1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 /// A convenience routine for creating a decayed reference to a function. 42 static ExprResult 43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 44 bool HadMultipleCandidates, 45 SourceLocation Loc = SourceLocation(), 46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 48 return ExprError(); 49 // If FoundDecl is different from Fn (such as if one is a template 50 // and the other a specialization), make sure DiagnoseUseOfDecl is 51 // called on both. 52 // FIXME: This would be more comprehensively addressed by modifying 53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 54 // being used. 55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 56 return ExprError(); 57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 58 VK_LValue, Loc, LocInfo); 59 if (HadMultipleCandidates) 60 DRE->setHadMultipleCandidates(true); 61 62 S.MarkDeclRefReferenced(DRE); 63 64 ExprResult E = DRE; 65 E = S.DefaultFunctionArrayConversion(E.get()); 66 if (E.isInvalid()) 67 return ExprError(); 68 return E; 69 } 70 71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 72 bool InOverloadResolution, 73 StandardConversionSequence &SCS, 74 bool CStyle, 75 bool AllowObjCWritebackConversion); 76 77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 78 QualType &ToType, 79 bool InOverloadResolution, 80 StandardConversionSequence &SCS, 81 bool CStyle); 82 static OverloadingResult 83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 84 UserDefinedConversionSequence& User, 85 OverloadCandidateSet& Conversions, 86 bool AllowExplicit, 87 bool AllowObjCConversionOnExplicit); 88 89 90 static ImplicitConversionSequence::CompareKind 91 CompareStandardConversionSequences(Sema &S, 92 const StandardConversionSequence& SCS1, 93 const StandardConversionSequence& SCS2); 94 95 static ImplicitConversionSequence::CompareKind 96 CompareQualificationConversions(Sema &S, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareDerivedToBaseConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 /// GetConversionRank - Retrieve the implicit conversion rank 106 /// corresponding to the given implicit conversion kind. 107 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 108 static const ImplicitConversionRank 109 Rank[(int)ICK_Num_Conversion_Kinds] = { 110 ICR_Exact_Match, 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Promotion, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Conversion, 120 ICR_Conversion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Complex_Real_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Writeback_Conversion 134 }; 135 return Rank[(int)Kind]; 136 } 137 138 /// GetImplicitConversionName - Return the name of this kind of 139 /// implicit conversion. 140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 142 "No conversion", 143 "Lvalue-to-rvalue", 144 "Array-to-pointer", 145 "Function-to-pointer", 146 "Noreturn adjustment", 147 "Qualification", 148 "Integral promotion", 149 "Floating point promotion", 150 "Complex promotion", 151 "Integral conversion", 152 "Floating conversion", 153 "Complex conversion", 154 "Floating-integral conversion", 155 "Pointer conversion", 156 "Pointer-to-member conversion", 157 "Boolean conversion", 158 "Compatible-types conversion", 159 "Derived-to-base conversion", 160 "Vector conversion", 161 "Vector splat", 162 "Complex-real conversion", 163 "Block Pointer conversion", 164 "Transparent Union Conversion", 165 "Writeback conversion" 166 }; 167 return Name[Kind]; 168 } 169 170 /// StandardConversionSequence - Set the standard conversion 171 /// sequence to the identity conversion. 172 void StandardConversionSequence::setAsIdentityConversion() { 173 First = ICK_Identity; 174 Second = ICK_Identity; 175 Third = ICK_Identity; 176 DeprecatedStringLiteralToCharPtr = false; 177 QualificationIncludesObjCLifetime = false; 178 ReferenceBinding = false; 179 DirectBinding = false; 180 IsLvalueReference = true; 181 BindsToFunctionLvalue = false; 182 BindsToRvalue = false; 183 BindsImplicitObjectArgumentWithoutRefQualifier = false; 184 ObjCLifetimeConversionBinding = false; 185 CopyConstructor = nullptr; 186 } 187 188 /// getRank - Retrieve the rank of this standard conversion sequence 189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 190 /// implicit conversions. 191 ImplicitConversionRank StandardConversionSequence::getRank() const { 192 ImplicitConversionRank Rank = ICR_Exact_Match; 193 if (GetConversionRank(First) > Rank) 194 Rank = GetConversionRank(First); 195 if (GetConversionRank(Second) > Rank) 196 Rank = GetConversionRank(Second); 197 if (GetConversionRank(Third) > Rank) 198 Rank = GetConversionRank(Third); 199 return Rank; 200 } 201 202 /// isPointerConversionToBool - Determines whether this conversion is 203 /// a conversion of a pointer or pointer-to-member to bool. This is 204 /// used as part of the ranking of standard conversion sequences 205 /// (C++ 13.3.3.2p4). 206 bool StandardConversionSequence::isPointerConversionToBool() const { 207 // Note that FromType has not necessarily been transformed by the 208 // array-to-pointer or function-to-pointer implicit conversions, so 209 // check for their presence as well as checking whether FromType is 210 // a pointer. 211 if (getToType(1)->isBooleanType() && 212 (getFromType()->isPointerType() || 213 getFromType()->isObjCObjectPointerType() || 214 getFromType()->isBlockPointerType() || 215 getFromType()->isNullPtrType() || 216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 217 return true; 218 219 return false; 220 } 221 222 /// isPointerConversionToVoidPointer - Determines whether this 223 /// conversion is a conversion of a pointer to a void pointer. This is 224 /// used as part of the ranking of standard conversion sequences (C++ 225 /// 13.3.3.2p4). 226 bool 227 StandardConversionSequence:: 228 isPointerConversionToVoidPointer(ASTContext& Context) const { 229 QualType FromType = getFromType(); 230 QualType ToType = getToType(1); 231 232 // Note that FromType has not necessarily been transformed by the 233 // array-to-pointer implicit conversion, so check for its presence 234 // and redo the conversion to get a pointer. 235 if (First == ICK_Array_To_Pointer) 236 FromType = Context.getArrayDecayedType(FromType); 237 238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 240 return ToPtrType->getPointeeType()->isVoidType(); 241 242 return false; 243 } 244 245 /// Skip any implicit casts which could be either part of a narrowing conversion 246 /// or after one in an implicit conversion. 247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 249 switch (ICE->getCastKind()) { 250 case CK_NoOp: 251 case CK_IntegralCast: 252 case CK_IntegralToBoolean: 253 case CK_IntegralToFloating: 254 case CK_FloatingToIntegral: 255 case CK_FloatingToBoolean: 256 case CK_FloatingCast: 257 Converted = ICE->getSubExpr(); 258 continue; 259 260 default: 261 return Converted; 262 } 263 } 264 265 return Converted; 266 } 267 268 /// Check if this standard conversion sequence represents a narrowing 269 /// conversion, according to C++11 [dcl.init.list]p7. 270 /// 271 /// \param Ctx The AST context. 272 /// \param Converted The result of applying this standard conversion sequence. 273 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 274 /// value of the expression prior to the narrowing conversion. 275 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 276 /// type of the expression prior to the narrowing conversion. 277 NarrowingKind 278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 279 const Expr *Converted, 280 APValue &ConstantValue, 281 QualType &ConstantType) const { 282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 283 284 // C++11 [dcl.init.list]p7: 285 // A narrowing conversion is an implicit conversion ... 286 QualType FromType = getToType(0); 287 QualType ToType = getToType(1); 288 switch (Second) { 289 // 'bool' is an integral type; dispatch to the right place to handle it. 290 case ICK_Boolean_Conversion: 291 if (FromType->isRealFloatingType()) 292 goto FloatingIntegralConversion; 293 if (FromType->isIntegralOrUnscopedEnumerationType()) 294 goto IntegralConversion; 295 // Boolean conversions can be from pointers and pointers to members 296 // [conv.bool], and those aren't considered narrowing conversions. 297 return NK_Not_Narrowing; 298 299 // -- from a floating-point type to an integer type, or 300 // 301 // -- from an integer type or unscoped enumeration type to a floating-point 302 // type, except where the source is a constant expression and the actual 303 // value after conversion will fit into the target type and will produce 304 // the original value when converted back to the original type, or 305 case ICK_Floating_Integral: 306 FloatingIntegralConversion: 307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 308 return NK_Type_Narrowing; 309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 310 llvm::APSInt IntConstantValue; 311 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 312 if (Initializer && 313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 314 // Convert the integer to the floating type. 315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 317 llvm::APFloat::rmNearestTiesToEven); 318 // And back. 319 llvm::APSInt ConvertedValue = IntConstantValue; 320 bool ignored; 321 Result.convertToInteger(ConvertedValue, 322 llvm::APFloat::rmTowardZero, &ignored); 323 // If the resulting value is different, this was a narrowing conversion. 324 if (IntConstantValue != ConvertedValue) { 325 ConstantValue = APValue(IntConstantValue); 326 ConstantType = Initializer->getType(); 327 return NK_Constant_Narrowing; 328 } 329 } else { 330 // Variables are always narrowings. 331 return NK_Variable_Narrowing; 332 } 333 } 334 return NK_Not_Narrowing; 335 336 // -- from long double to double or float, or from double to float, except 337 // where the source is a constant expression and the actual value after 338 // conversion is within the range of values that can be represented (even 339 // if it cannot be represented exactly), or 340 case ICK_Floating_Conversion: 341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 343 // FromType is larger than ToType. 344 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 346 // Constant! 347 assert(ConstantValue.isFloat()); 348 llvm::APFloat FloatVal = ConstantValue.getFloat(); 349 // Convert the source value into the target type. 350 bool ignored; 351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 352 Ctx.getFloatTypeSemantics(ToType), 353 llvm::APFloat::rmNearestTiesToEven, &ignored); 354 // If there was no overflow, the source value is within the range of 355 // values that can be represented. 356 if (ConvertStatus & llvm::APFloat::opOverflow) { 357 ConstantType = Initializer->getType(); 358 return NK_Constant_Narrowing; 359 } 360 } else { 361 return NK_Variable_Narrowing; 362 } 363 } 364 return NK_Not_Narrowing; 365 366 // -- from an integer type or unscoped enumeration type to an integer type 367 // that cannot represent all the values of the original type, except where 368 // the source is a constant expression and the actual value after 369 // conversion will fit into the target type and will produce the original 370 // value when converted back to the original type. 371 case ICK_Integral_Conversion: 372 IntegralConversion: { 373 assert(FromType->isIntegralOrUnscopedEnumerationType()); 374 assert(ToType->isIntegralOrUnscopedEnumerationType()); 375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 376 const unsigned FromWidth = Ctx.getIntWidth(FromType); 377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 378 const unsigned ToWidth = Ctx.getIntWidth(ToType); 379 380 if (FromWidth > ToWidth || 381 (FromWidth == ToWidth && FromSigned != ToSigned) || 382 (FromSigned && !ToSigned)) { 383 // Not all values of FromType can be represented in ToType. 384 llvm::APSInt InitializerValue; 385 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 387 // Such conversions on variables are always narrowing. 388 return NK_Variable_Narrowing; 389 } 390 bool Narrowing = false; 391 if (FromWidth < ToWidth) { 392 // Negative -> unsigned is narrowing. Otherwise, more bits is never 393 // narrowing. 394 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 395 Narrowing = true; 396 } else { 397 // Add a bit to the InitializerValue so we don't have to worry about 398 // signed vs. unsigned comparisons. 399 InitializerValue = InitializerValue.extend( 400 InitializerValue.getBitWidth() + 1); 401 // Convert the initializer to and from the target width and signed-ness. 402 llvm::APSInt ConvertedValue = InitializerValue; 403 ConvertedValue = ConvertedValue.trunc(ToWidth); 404 ConvertedValue.setIsSigned(ToSigned); 405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 406 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 407 // If the result is different, this was a narrowing conversion. 408 if (ConvertedValue != InitializerValue) 409 Narrowing = true; 410 } 411 if (Narrowing) { 412 ConstantType = Initializer->getType(); 413 ConstantValue = APValue(InitializerValue); 414 return NK_Constant_Narrowing; 415 } 416 } 417 return NK_Not_Narrowing; 418 } 419 420 default: 421 // Other kinds of conversions are not narrowings. 422 return NK_Not_Narrowing; 423 } 424 } 425 426 /// dump - Print this standard conversion sequence to standard 427 /// error. Useful for debugging overloading issues. 428 void StandardConversionSequence::dump() const { 429 raw_ostream &OS = llvm::errs(); 430 bool PrintedSomething = false; 431 if (First != ICK_Identity) { 432 OS << GetImplicitConversionName(First); 433 PrintedSomething = true; 434 } 435 436 if (Second != ICK_Identity) { 437 if (PrintedSomething) { 438 OS << " -> "; 439 } 440 OS << GetImplicitConversionName(Second); 441 442 if (CopyConstructor) { 443 OS << " (by copy constructor)"; 444 } else if (DirectBinding) { 445 OS << " (direct reference binding)"; 446 } else if (ReferenceBinding) { 447 OS << " (reference binding)"; 448 } 449 PrintedSomething = true; 450 } 451 452 if (Third != ICK_Identity) { 453 if (PrintedSomething) { 454 OS << " -> "; 455 } 456 OS << GetImplicitConversionName(Third); 457 PrintedSomething = true; 458 } 459 460 if (!PrintedSomething) { 461 OS << "No conversions required"; 462 } 463 } 464 465 /// dump - Print this user-defined conversion sequence to standard 466 /// error. Useful for debugging overloading issues. 467 void UserDefinedConversionSequence::dump() const { 468 raw_ostream &OS = llvm::errs(); 469 if (Before.First || Before.Second || Before.Third) { 470 Before.dump(); 471 OS << " -> "; 472 } 473 if (ConversionFunction) 474 OS << '\'' << *ConversionFunction << '\''; 475 else 476 OS << "aggregate initialization"; 477 if (After.First || After.Second || After.Third) { 478 OS << " -> "; 479 After.dump(); 480 } 481 } 482 483 /// dump - Print this implicit conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 void ImplicitConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 if (isStdInitializerListElement()) 488 OS << "Worst std::initializer_list element conversion: "; 489 switch (ConversionKind) { 490 case StandardConversion: 491 OS << "Standard conversion: "; 492 Standard.dump(); 493 break; 494 case UserDefinedConversion: 495 OS << "User-defined conversion: "; 496 UserDefined.dump(); 497 break; 498 case EllipsisConversion: 499 OS << "Ellipsis conversion"; 500 break; 501 case AmbiguousConversion: 502 OS << "Ambiguous conversion"; 503 break; 504 case BadConversion: 505 OS << "Bad conversion"; 506 break; 507 } 508 509 OS << "\n"; 510 } 511 512 void AmbiguousConversionSequence::construct() { 513 new (&conversions()) ConversionSet(); 514 } 515 516 void AmbiguousConversionSequence::destruct() { 517 conversions().~ConversionSet(); 518 } 519 520 void 521 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 522 FromTypePtr = O.FromTypePtr; 523 ToTypePtr = O.ToTypePtr; 524 new (&conversions()) ConversionSet(O.conversions()); 525 } 526 527 namespace { 528 // Structure used by DeductionFailureInfo to store 529 // template argument information. 530 struct DFIArguments { 531 TemplateArgument FirstArg; 532 TemplateArgument SecondArg; 533 }; 534 // Structure used by DeductionFailureInfo to store 535 // template parameter and template argument information. 536 struct DFIParamWithArguments : DFIArguments { 537 TemplateParameter Param; 538 }; 539 } 540 541 /// \brief Convert from Sema's representation of template deduction information 542 /// to the form used in overload-candidate information. 543 DeductionFailureInfo 544 clang::MakeDeductionFailureInfo(ASTContext &Context, 545 Sema::TemplateDeductionResult TDK, 546 TemplateDeductionInfo &Info) { 547 DeductionFailureInfo Result; 548 Result.Result = static_cast<unsigned>(TDK); 549 Result.HasDiagnostic = false; 550 Result.Data = nullptr; 551 switch (TDK) { 552 case Sema::TDK_Success: 553 case Sema::TDK_Invalid: 554 case Sema::TDK_InstantiationDepth: 555 case Sema::TDK_TooManyArguments: 556 case Sema::TDK_TooFewArguments: 557 break; 558 559 case Sema::TDK_Incomplete: 560 case Sema::TDK_InvalidExplicitArguments: 561 Result.Data = Info.Param.getOpaqueValue(); 562 break; 563 564 case Sema::TDK_NonDeducedMismatch: { 565 // FIXME: Should allocate from normal heap so that we can free this later. 566 DFIArguments *Saved = new (Context) DFIArguments; 567 Saved->FirstArg = Info.FirstArg; 568 Saved->SecondArg = Info.SecondArg; 569 Result.Data = Saved; 570 break; 571 } 572 573 case Sema::TDK_Inconsistent: 574 case Sema::TDK_Underqualified: { 575 // FIXME: Should allocate from normal heap so that we can free this later. 576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 577 Saved->Param = Info.Param; 578 Saved->FirstArg = Info.FirstArg; 579 Saved->SecondArg = Info.SecondArg; 580 Result.Data = Saved; 581 break; 582 } 583 584 case Sema::TDK_SubstitutionFailure: 585 Result.Data = Info.take(); 586 if (Info.hasSFINAEDiagnostic()) { 587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 588 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 589 Info.takeSFINAEDiagnostic(*Diag); 590 Result.HasDiagnostic = true; 591 } 592 break; 593 594 case Sema::TDK_FailedOverloadResolution: 595 Result.Data = Info.Expression; 596 break; 597 598 case Sema::TDK_MiscellaneousDeductionFailure: 599 break; 600 } 601 602 return Result; 603 } 604 605 void DeductionFailureInfo::Destroy() { 606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 607 case Sema::TDK_Success: 608 case Sema::TDK_Invalid: 609 case Sema::TDK_InstantiationDepth: 610 case Sema::TDK_Incomplete: 611 case Sema::TDK_TooManyArguments: 612 case Sema::TDK_TooFewArguments: 613 case Sema::TDK_InvalidExplicitArguments: 614 case Sema::TDK_FailedOverloadResolution: 615 break; 616 617 case Sema::TDK_Inconsistent: 618 case Sema::TDK_Underqualified: 619 case Sema::TDK_NonDeducedMismatch: 620 // FIXME: Destroy the data? 621 Data = nullptr; 622 break; 623 624 case Sema::TDK_SubstitutionFailure: 625 // FIXME: Destroy the template argument list? 626 Data = nullptr; 627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 628 Diag->~PartialDiagnosticAt(); 629 HasDiagnostic = false; 630 } 631 break; 632 633 // Unhandled 634 case Sema::TDK_MiscellaneousDeductionFailure: 635 break; 636 } 637 } 638 639 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 640 if (HasDiagnostic) 641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 642 return nullptr; 643 } 644 645 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 647 case Sema::TDK_Success: 648 case Sema::TDK_Invalid: 649 case Sema::TDK_InstantiationDepth: 650 case Sema::TDK_TooManyArguments: 651 case Sema::TDK_TooFewArguments: 652 case Sema::TDK_SubstitutionFailure: 653 case Sema::TDK_NonDeducedMismatch: 654 case Sema::TDK_FailedOverloadResolution: 655 return TemplateParameter(); 656 657 case Sema::TDK_Incomplete: 658 case Sema::TDK_InvalidExplicitArguments: 659 return TemplateParameter::getFromOpaqueValue(Data); 660 661 case Sema::TDK_Inconsistent: 662 case Sema::TDK_Underqualified: 663 return static_cast<DFIParamWithArguments*>(Data)->Param; 664 665 // Unhandled 666 case Sema::TDK_MiscellaneousDeductionFailure: 667 break; 668 } 669 670 return TemplateParameter(); 671 } 672 673 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 675 case Sema::TDK_Success: 676 case Sema::TDK_Invalid: 677 case Sema::TDK_InstantiationDepth: 678 case Sema::TDK_TooManyArguments: 679 case Sema::TDK_TooFewArguments: 680 case Sema::TDK_Incomplete: 681 case Sema::TDK_InvalidExplicitArguments: 682 case Sema::TDK_Inconsistent: 683 case Sema::TDK_Underqualified: 684 case Sema::TDK_NonDeducedMismatch: 685 case Sema::TDK_FailedOverloadResolution: 686 return nullptr; 687 688 case Sema::TDK_SubstitutionFailure: 689 return static_cast<TemplateArgumentList*>(Data); 690 691 // Unhandled 692 case Sema::TDK_MiscellaneousDeductionFailure: 693 break; 694 } 695 696 return nullptr; 697 } 698 699 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_Incomplete: 705 case Sema::TDK_TooManyArguments: 706 case Sema::TDK_TooFewArguments: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_SubstitutionFailure: 709 case Sema::TDK_FailedOverloadResolution: 710 return nullptr; 711 712 case Sema::TDK_Inconsistent: 713 case Sema::TDK_Underqualified: 714 case Sema::TDK_NonDeducedMismatch: 715 return &static_cast<DFIArguments*>(Data)->FirstArg; 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return nullptr; 723 } 724 725 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return nullptr; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->SecondArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return nullptr; 749 } 750 751 Expr *DeductionFailureInfo::getExpr() { 752 if (static_cast<Sema::TemplateDeductionResult>(Result) == 753 Sema::TDK_FailedOverloadResolution) 754 return static_cast<Expr*>(Data); 755 756 return nullptr; 757 } 758 759 void OverloadCandidateSet::destroyCandidates() { 760 for (iterator i = begin(), e = end(); i != e; ++i) { 761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 762 i->Conversions[ii].~ImplicitConversionSequence(); 763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 764 i->DeductionFailure.Destroy(); 765 } 766 } 767 768 void OverloadCandidateSet::clear() { 769 destroyCandidates(); 770 NumInlineSequences = 0; 771 Candidates.clear(); 772 Functions.clear(); 773 } 774 775 namespace { 776 class UnbridgedCastsSet { 777 struct Entry { 778 Expr **Addr; 779 Expr *Saved; 780 }; 781 SmallVector<Entry, 2> Entries; 782 783 public: 784 void save(Sema &S, Expr *&E) { 785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 786 Entry entry = { &E, E }; 787 Entries.push_back(entry); 788 E = S.stripARCUnbridgedCast(E); 789 } 790 791 void restore() { 792 for (SmallVectorImpl<Entry>::iterator 793 i = Entries.begin(), e = Entries.end(); i != e; ++i) 794 *i->Addr = i->Saved; 795 } 796 }; 797 } 798 799 /// checkPlaceholderForOverload - Do any interesting placeholder-like 800 /// preprocessing on the given expression. 801 /// 802 /// \param unbridgedCasts a collection to which to add unbridged casts; 803 /// without this, they will be immediately diagnosed as errors 804 /// 805 /// Return true on unrecoverable error. 806 static bool 807 checkPlaceholderForOverload(Sema &S, Expr *&E, 808 UnbridgedCastsSet *unbridgedCasts = nullptr) { 809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 810 // We can't handle overloaded expressions here because overload 811 // resolution might reasonably tweak them. 812 if (placeholder->getKind() == BuiltinType::Overload) return false; 813 814 // If the context potentially accepts unbridged ARC casts, strip 815 // the unbridged cast and add it to the collection for later restoration. 816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 817 unbridgedCasts) { 818 unbridgedCasts->save(S, E); 819 return false; 820 } 821 822 // Go ahead and check everything else. 823 ExprResult result = S.CheckPlaceholderExpr(E); 824 if (result.isInvalid()) 825 return true; 826 827 E = result.get(); 828 return false; 829 } 830 831 // Nothing to do. 832 return false; 833 } 834 835 /// checkArgPlaceholdersForOverload - Check a set of call operands for 836 /// placeholders. 837 static bool checkArgPlaceholdersForOverload(Sema &S, 838 MultiExprArg Args, 839 UnbridgedCastsSet &unbridged) { 840 for (unsigned i = 0, e = Args.size(); i != e; ++i) 841 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 842 return true; 843 844 return false; 845 } 846 847 // IsOverload - Determine whether the given New declaration is an 848 // overload of the declarations in Old. This routine returns false if 849 // New and Old cannot be overloaded, e.g., if New has the same 850 // signature as some function in Old (C++ 1.3.10) or if the Old 851 // declarations aren't functions (or function templates) at all. When 852 // it does return false, MatchedDecl will point to the decl that New 853 // cannot be overloaded with. This decl may be a UsingShadowDecl on 854 // top of the underlying declaration. 855 // 856 // Example: Given the following input: 857 // 858 // void f(int, float); // #1 859 // void f(int, int); // #2 860 // int f(int, int); // #3 861 // 862 // When we process #1, there is no previous declaration of "f", 863 // so IsOverload will not be used. 864 // 865 // When we process #2, Old contains only the FunctionDecl for #1. By 866 // comparing the parameter types, we see that #1 and #2 are overloaded 867 // (since they have different signatures), so this routine returns 868 // false; MatchedDecl is unchanged. 869 // 870 // When we process #3, Old is an overload set containing #1 and #2. We 871 // compare the signatures of #3 to #1 (they're overloaded, so we do 872 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 873 // identical (return types of functions are not part of the 874 // signature), IsOverload returns false and MatchedDecl will be set to 875 // point to the FunctionDecl for #2. 876 // 877 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 878 // into a class by a using declaration. The rules for whether to hide 879 // shadow declarations ignore some properties which otherwise figure 880 // into a function template's signature. 881 Sema::OverloadKind 882 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 883 NamedDecl *&Match, bool NewIsUsingDecl) { 884 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 885 I != E; ++I) { 886 NamedDecl *OldD = *I; 887 888 bool OldIsUsingDecl = false; 889 if (isa<UsingShadowDecl>(OldD)) { 890 OldIsUsingDecl = true; 891 892 // We can always introduce two using declarations into the same 893 // context, even if they have identical signatures. 894 if (NewIsUsingDecl) continue; 895 896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 897 } 898 899 // If either declaration was introduced by a using declaration, 900 // we'll need to use slightly different rules for matching. 901 // Essentially, these rules are the normal rules, except that 902 // function templates hide function templates with different 903 // return types or template parameter lists. 904 bool UseMemberUsingDeclRules = 905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 906 !New->getFriendObjectKind(); 907 908 if (FunctionDecl *OldF = OldD->getAsFunction()) { 909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 910 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 912 continue; 913 } 914 915 if (!isa<FunctionTemplateDecl>(OldD) && 916 !shouldLinkPossiblyHiddenDecl(*I, New)) 917 continue; 918 919 Match = *I; 920 return Ovl_Match; 921 } 922 } else if (isa<UsingDecl>(OldD)) { 923 // We can overload with these, which can show up when doing 924 // redeclaration checks for UsingDecls. 925 assert(Old.getLookupKind() == LookupUsingDeclName); 926 } else if (isa<TagDecl>(OldD)) { 927 // We can always overload with tags by hiding them. 928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 929 // Optimistically assume that an unresolved using decl will 930 // overload; if it doesn't, we'll have to diagnose during 931 // template instantiation. 932 } else { 933 // (C++ 13p1): 934 // Only function declarations can be overloaded; object and type 935 // declarations cannot be overloaded. 936 Match = *I; 937 return Ovl_NonFunction; 938 } 939 } 940 941 return Ovl_Overload; 942 } 943 944 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 945 bool UseUsingDeclRules) { 946 // C++ [basic.start.main]p2: This function shall not be overloaded. 947 if (New->isMain()) 948 return false; 949 950 // MSVCRT user defined entry points cannot be overloaded. 951 if (New->isMSVCRTEntryPoint()) 952 return false; 953 954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 956 957 // C++ [temp.fct]p2: 958 // A function template can be overloaded with other function templates 959 // and with normal (non-template) functions. 960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 961 return true; 962 963 // Is the function New an overload of the function Old? 964 QualType OldQType = Context.getCanonicalType(Old->getType()); 965 QualType NewQType = Context.getCanonicalType(New->getType()); 966 967 // Compare the signatures (C++ 1.3.10) of the two functions to 968 // determine whether they are overloads. If we find any mismatch 969 // in the signature, they are overloads. 970 971 // If either of these functions is a K&R-style function (no 972 // prototype), then we consider them to have matching signatures. 973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 974 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 975 return false; 976 977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 979 980 // The signature of a function includes the types of its 981 // parameters (C++ 1.3.10), which includes the presence or absence 982 // of the ellipsis; see C++ DR 357). 983 if (OldQType != NewQType && 984 (OldType->getNumParams() != NewType->getNumParams() || 985 OldType->isVariadic() != NewType->isVariadic() || 986 !FunctionParamTypesAreEqual(OldType, NewType))) 987 return true; 988 989 // C++ [temp.over.link]p4: 990 // The signature of a function template consists of its function 991 // signature, its return type and its template parameter list. The names 992 // of the template parameters are significant only for establishing the 993 // relationship between the template parameters and the rest of the 994 // signature. 995 // 996 // We check the return type and template parameter lists for function 997 // templates first; the remaining checks follow. 998 // 999 // However, we don't consider either of these when deciding whether 1000 // a member introduced by a shadow declaration is hidden. 1001 if (!UseUsingDeclRules && NewTemplate && 1002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1003 OldTemplate->getTemplateParameters(), 1004 false, TPL_TemplateMatch) || 1005 OldType->getReturnType() != NewType->getReturnType())) 1006 return true; 1007 1008 // If the function is a class member, its signature includes the 1009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1010 // 1011 // As part of this, also check whether one of the member functions 1012 // is static, in which case they are not overloads (C++ 1013 // 13.1p2). While not part of the definition of the signature, 1014 // this check is important to determine whether these functions 1015 // can be overloaded. 1016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1018 if (OldMethod && NewMethod && 1019 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1021 if (!UseUsingDeclRules && 1022 (OldMethod->getRefQualifier() == RQ_None || 1023 NewMethod->getRefQualifier() == RQ_None)) { 1024 // C++0x [over.load]p2: 1025 // - Member function declarations with the same name and the same 1026 // parameter-type-list as well as member function template 1027 // declarations with the same name, the same parameter-type-list, and 1028 // the same template parameter lists cannot be overloaded if any of 1029 // them, but not all, have a ref-qualifier (8.3.5). 1030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1032 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1033 } 1034 return true; 1035 } 1036 1037 // We may not have applied the implicit const for a constexpr member 1038 // function yet (because we haven't yet resolved whether this is a static 1039 // or non-static member function). Add it now, on the assumption that this 1040 // is a redeclaration of OldMethod. 1041 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1042 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1044 !isa<CXXConstructorDecl>(NewMethod)) 1045 NewQuals |= Qualifiers::Const; 1046 1047 // We do not allow overloading based off of '__restrict'. 1048 OldQuals &= ~Qualifiers::Restrict; 1049 NewQuals &= ~Qualifiers::Restrict; 1050 if (OldQuals != NewQuals) 1051 return true; 1052 } 1053 1054 // enable_if attributes are an order-sensitive part of the signature. 1055 for (specific_attr_iterator<EnableIfAttr> 1056 NewI = New->specific_attr_begin<EnableIfAttr>(), 1057 NewE = New->specific_attr_end<EnableIfAttr>(), 1058 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1059 OldE = Old->specific_attr_end<EnableIfAttr>(); 1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1061 if (NewI == NewE || OldI == OldE) 1062 return true; 1063 llvm::FoldingSetNodeID NewID, OldID; 1064 NewI->getCond()->Profile(NewID, Context, true); 1065 OldI->getCond()->Profile(OldID, Context, true); 1066 if (NewID != OldID) 1067 return true; 1068 } 1069 1070 // The signatures match; this is not an overload. 1071 return false; 1072 } 1073 1074 /// \brief Checks availability of the function depending on the current 1075 /// function context. Inside an unavailable function, unavailability is ignored. 1076 /// 1077 /// \returns true if \arg FD is unavailable and current context is inside 1078 /// an available function, false otherwise. 1079 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1081 } 1082 1083 /// \brief Tries a user-defined conversion from From to ToType. 1084 /// 1085 /// Produces an implicit conversion sequence for when a standard conversion 1086 /// is not an option. See TryImplicitConversion for more information. 1087 static ImplicitConversionSequence 1088 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1089 bool SuppressUserConversions, 1090 bool AllowExplicit, 1091 bool InOverloadResolution, 1092 bool CStyle, 1093 bool AllowObjCWritebackConversion, 1094 bool AllowObjCConversionOnExplicit) { 1095 ImplicitConversionSequence ICS; 1096 1097 if (SuppressUserConversions) { 1098 // We're not in the case above, so there is no conversion that 1099 // we can perform. 1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1101 return ICS; 1102 } 1103 1104 // Attempt user-defined conversion. 1105 OverloadCandidateSet Conversions(From->getExprLoc(), 1106 OverloadCandidateSet::CSK_Normal); 1107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1108 Conversions, AllowExplicit, 1109 AllowObjCConversionOnExplicit)) { 1110 case OR_Success: 1111 case OR_Deleted: 1112 ICS.setUserDefined(); 1113 ICS.UserDefined.Before.setAsIdentityConversion(); 1114 // C++ [over.ics.user]p4: 1115 // A conversion of an expression of class type to the same class 1116 // type is given Exact Match rank, and a conversion of an 1117 // expression of class type to a base class of that type is 1118 // given Conversion rank, in spite of the fact that a copy 1119 // constructor (i.e., a user-defined conversion function) is 1120 // called for those cases. 1121 if (CXXConstructorDecl *Constructor 1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1123 QualType FromCanon 1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1125 QualType ToCanon 1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1127 if (Constructor->isCopyConstructor() && 1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1129 // Turn this into a "standard" conversion sequence, so that it 1130 // gets ranked with standard conversion sequences. 1131 ICS.setStandard(); 1132 ICS.Standard.setAsIdentityConversion(); 1133 ICS.Standard.setFromType(From->getType()); 1134 ICS.Standard.setAllToTypes(ToType); 1135 ICS.Standard.CopyConstructor = Constructor; 1136 if (ToCanon != FromCanon) 1137 ICS.Standard.Second = ICK_Derived_To_Base; 1138 } 1139 } 1140 break; 1141 1142 case OR_Ambiguous: 1143 ICS.setAmbiguous(); 1144 ICS.Ambiguous.setFromType(From->getType()); 1145 ICS.Ambiguous.setToType(ToType); 1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1147 Cand != Conversions.end(); ++Cand) 1148 if (Cand->Viable) 1149 ICS.Ambiguous.addConversion(Cand->Function); 1150 break; 1151 1152 // Fall through. 1153 case OR_No_Viable_Function: 1154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1155 break; 1156 } 1157 1158 return ICS; 1159 } 1160 1161 /// TryImplicitConversion - Attempt to perform an implicit conversion 1162 /// from the given expression (Expr) to the given type (ToType). This 1163 /// function returns an implicit conversion sequence that can be used 1164 /// to perform the initialization. Given 1165 /// 1166 /// void f(float f); 1167 /// void g(int i) { f(i); } 1168 /// 1169 /// this routine would produce an implicit conversion sequence to 1170 /// describe the initialization of f from i, which will be a standard 1171 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1172 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1173 // 1174 /// Note that this routine only determines how the conversion can be 1175 /// performed; it does not actually perform the conversion. As such, 1176 /// it will not produce any diagnostics if no conversion is available, 1177 /// but will instead return an implicit conversion sequence of kind 1178 /// "BadConversion". 1179 /// 1180 /// If @p SuppressUserConversions, then user-defined conversions are 1181 /// not permitted. 1182 /// If @p AllowExplicit, then explicit user-defined conversions are 1183 /// permitted. 1184 /// 1185 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1186 /// writeback conversion, which allows __autoreleasing id* parameters to 1187 /// be initialized with __strong id* or __weak id* arguments. 1188 static ImplicitConversionSequence 1189 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1190 bool SuppressUserConversions, 1191 bool AllowExplicit, 1192 bool InOverloadResolution, 1193 bool CStyle, 1194 bool AllowObjCWritebackConversion, 1195 bool AllowObjCConversionOnExplicit) { 1196 ImplicitConversionSequence ICS; 1197 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1199 ICS.setStandard(); 1200 return ICS; 1201 } 1202 1203 if (!S.getLangOpts().CPlusPlus) { 1204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1205 return ICS; 1206 } 1207 1208 // C++ [over.ics.user]p4: 1209 // A conversion of an expression of class type to the same class 1210 // type is given Exact Match rank, and a conversion of an 1211 // expression of class type to a base class of that type is 1212 // given Conversion rank, in spite of the fact that a copy/move 1213 // constructor (i.e., a user-defined conversion function) is 1214 // called for those cases. 1215 QualType FromType = From->getType(); 1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1217 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1218 S.IsDerivedFrom(FromType, ToType))) { 1219 ICS.setStandard(); 1220 ICS.Standard.setAsIdentityConversion(); 1221 ICS.Standard.setFromType(FromType); 1222 ICS.Standard.setAllToTypes(ToType); 1223 1224 // We don't actually check at this point whether there is a valid 1225 // copy/move constructor, since overloading just assumes that it 1226 // exists. When we actually perform initialization, we'll find the 1227 // appropriate constructor to copy the returned object, if needed. 1228 ICS.Standard.CopyConstructor = nullptr; 1229 1230 // Determine whether this is considered a derived-to-base conversion. 1231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1232 ICS.Standard.Second = ICK_Derived_To_Base; 1233 1234 return ICS; 1235 } 1236 1237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1238 AllowExplicit, InOverloadResolution, CStyle, 1239 AllowObjCWritebackConversion, 1240 AllowObjCConversionOnExplicit); 1241 } 1242 1243 ImplicitConversionSequence 1244 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1245 bool SuppressUserConversions, 1246 bool AllowExplicit, 1247 bool InOverloadResolution, 1248 bool CStyle, 1249 bool AllowObjCWritebackConversion) { 1250 return ::TryImplicitConversion(*this, From, ToType, 1251 SuppressUserConversions, AllowExplicit, 1252 InOverloadResolution, CStyle, 1253 AllowObjCWritebackConversion, 1254 /*AllowObjCConversionOnExplicit=*/false); 1255 } 1256 1257 /// PerformImplicitConversion - Perform an implicit conversion of the 1258 /// expression From to the type ToType. Returns the 1259 /// converted expression. Flavor is the kind of conversion we're 1260 /// performing, used in the error message. If @p AllowExplicit, 1261 /// explicit user-defined conversions are permitted. 1262 ExprResult 1263 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1264 AssignmentAction Action, bool AllowExplicit) { 1265 ImplicitConversionSequence ICS; 1266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1267 } 1268 1269 ExprResult 1270 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1271 AssignmentAction Action, bool AllowExplicit, 1272 ImplicitConversionSequence& ICS) { 1273 if (checkPlaceholderForOverload(*this, From)) 1274 return ExprError(); 1275 1276 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1277 bool AllowObjCWritebackConversion 1278 = getLangOpts().ObjCAutoRefCount && 1279 (Action == AA_Passing || Action == AA_Sending); 1280 if (getLangOpts().ObjC1) 1281 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1282 ToType, From->getType(), From); 1283 ICS = ::TryImplicitConversion(*this, From, ToType, 1284 /*SuppressUserConversions=*/false, 1285 AllowExplicit, 1286 /*InOverloadResolution=*/false, 1287 /*CStyle=*/false, 1288 AllowObjCWritebackConversion, 1289 /*AllowObjCConversionOnExplicit=*/false); 1290 return PerformImplicitConversion(From, ToType, ICS, Action); 1291 } 1292 1293 /// \brief Determine whether the conversion from FromType to ToType is a valid 1294 /// conversion that strips "noreturn" off the nested function type. 1295 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1296 QualType &ResultTy) { 1297 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1298 return false; 1299 1300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1301 // where F adds one of the following at most once: 1302 // - a pointer 1303 // - a member pointer 1304 // - a block pointer 1305 CanQualType CanTo = Context.getCanonicalType(ToType); 1306 CanQualType CanFrom = Context.getCanonicalType(FromType); 1307 Type::TypeClass TyClass = CanTo->getTypeClass(); 1308 if (TyClass != CanFrom->getTypeClass()) return false; 1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1310 if (TyClass == Type::Pointer) { 1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1313 } else if (TyClass == Type::BlockPointer) { 1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1316 } else if (TyClass == Type::MemberPointer) { 1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1319 } else { 1320 return false; 1321 } 1322 1323 TyClass = CanTo->getTypeClass(); 1324 if (TyClass != CanFrom->getTypeClass()) return false; 1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1326 return false; 1327 } 1328 1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1331 if (!EInfo.getNoReturn()) return false; 1332 1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1334 assert(QualType(FromFn, 0).isCanonical()); 1335 if (QualType(FromFn, 0) != CanTo) return false; 1336 1337 ResultTy = ToType; 1338 return true; 1339 } 1340 1341 /// \brief Determine whether the conversion from FromType to ToType is a valid 1342 /// vector conversion. 1343 /// 1344 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1345 /// conversion. 1346 static bool IsVectorConversion(Sema &S, QualType FromType, 1347 QualType ToType, ImplicitConversionKind &ICK) { 1348 // We need at least one of these types to be a vector type to have a vector 1349 // conversion. 1350 if (!ToType->isVectorType() && !FromType->isVectorType()) 1351 return false; 1352 1353 // Identical types require no conversions. 1354 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1355 return false; 1356 1357 // There are no conversions between extended vector types, only identity. 1358 if (ToType->isExtVectorType()) { 1359 // There are no conversions between extended vector types other than the 1360 // identity conversion. 1361 if (FromType->isExtVectorType()) 1362 return false; 1363 1364 // Vector splat from any arithmetic type to a vector. 1365 if (FromType->isArithmeticType()) { 1366 ICK = ICK_Vector_Splat; 1367 return true; 1368 } 1369 } 1370 1371 // We can perform the conversion between vector types in the following cases: 1372 // 1)vector types are equivalent AltiVec and GCC vector types 1373 // 2)lax vector conversions are permitted and the vector types are of the 1374 // same size 1375 if (ToType->isVectorType() && FromType->isVectorType()) { 1376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1377 S.isLaxVectorConversion(FromType, ToType)) { 1378 ICK = ICK_Vector_Conversion; 1379 return true; 1380 } 1381 } 1382 1383 return false; 1384 } 1385 1386 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1387 bool InOverloadResolution, 1388 StandardConversionSequence &SCS, 1389 bool CStyle); 1390 1391 /// IsStandardConversion - Determines whether there is a standard 1392 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1393 /// expression From to the type ToType. Standard conversion sequences 1394 /// only consider non-class types; for conversions that involve class 1395 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1396 /// contain the standard conversion sequence required to perform this 1397 /// conversion and this routine will return true. Otherwise, this 1398 /// routine will return false and the value of SCS is unspecified. 1399 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1400 bool InOverloadResolution, 1401 StandardConversionSequence &SCS, 1402 bool CStyle, 1403 bool AllowObjCWritebackConversion) { 1404 QualType FromType = From->getType(); 1405 1406 // Standard conversions (C++ [conv]) 1407 SCS.setAsIdentityConversion(); 1408 SCS.IncompatibleObjC = false; 1409 SCS.setFromType(FromType); 1410 SCS.CopyConstructor = nullptr; 1411 1412 // There are no standard conversions for class types in C++, so 1413 // abort early. When overloading in C, however, we do permit 1414 if (FromType->isRecordType() || ToType->isRecordType()) { 1415 if (S.getLangOpts().CPlusPlus) 1416 return false; 1417 1418 // When we're overloading in C, we allow, as standard conversions, 1419 } 1420 1421 // The first conversion can be an lvalue-to-rvalue conversion, 1422 // array-to-pointer conversion, or function-to-pointer conversion 1423 // (C++ 4p1). 1424 1425 if (FromType == S.Context.OverloadTy) { 1426 DeclAccessPair AccessPair; 1427 if (FunctionDecl *Fn 1428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1429 AccessPair)) { 1430 // We were able to resolve the address of the overloaded function, 1431 // so we can convert to the type of that function. 1432 FromType = Fn->getType(); 1433 SCS.setFromType(FromType); 1434 1435 // we can sometimes resolve &foo<int> regardless of ToType, so check 1436 // if the type matches (identity) or we are converting to bool 1437 if (!S.Context.hasSameUnqualifiedType( 1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1439 QualType resultTy; 1440 // if the function type matches except for [[noreturn]], it's ok 1441 if (!S.IsNoReturnConversion(FromType, 1442 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1443 // otherwise, only a boolean conversion is standard 1444 if (!ToType->isBooleanType()) 1445 return false; 1446 } 1447 1448 // Check if the "from" expression is taking the address of an overloaded 1449 // function and recompute the FromType accordingly. Take advantage of the 1450 // fact that non-static member functions *must* have such an address-of 1451 // expression. 1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1453 if (Method && !Method->isStatic()) { 1454 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1455 "Non-unary operator on non-static member address"); 1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1457 == UO_AddrOf && 1458 "Non-address-of operator on non-static member address"); 1459 const Type *ClassType 1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1461 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1462 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1464 UO_AddrOf && 1465 "Non-address-of operator for overloaded function expression"); 1466 FromType = S.Context.getPointerType(FromType); 1467 } 1468 1469 // Check that we've computed the proper type after overload resolution. 1470 assert(S.Context.hasSameType( 1471 FromType, 1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1473 } else { 1474 return false; 1475 } 1476 } 1477 // Lvalue-to-rvalue conversion (C++11 4.1): 1478 // A glvalue (3.10) of a non-function, non-array type T can 1479 // be converted to a prvalue. 1480 bool argIsLValue = From->isGLValue(); 1481 if (argIsLValue && 1482 !FromType->isFunctionType() && !FromType->isArrayType() && 1483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1484 SCS.First = ICK_Lvalue_To_Rvalue; 1485 1486 // C11 6.3.2.1p2: 1487 // ... if the lvalue has atomic type, the value has the non-atomic version 1488 // of the type of the lvalue ... 1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1490 FromType = Atomic->getValueType(); 1491 1492 // If T is a non-class type, the type of the rvalue is the 1493 // cv-unqualified version of T. Otherwise, the type of the rvalue 1494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1495 // just strip the qualifiers because they don't matter. 1496 FromType = FromType.getUnqualifiedType(); 1497 } else if (FromType->isArrayType()) { 1498 // Array-to-pointer conversion (C++ 4.2) 1499 SCS.First = ICK_Array_To_Pointer; 1500 1501 // An lvalue or rvalue of type "array of N T" or "array of unknown 1502 // bound of T" can be converted to an rvalue of type "pointer to 1503 // T" (C++ 4.2p1). 1504 FromType = S.Context.getArrayDecayedType(FromType); 1505 1506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1507 // This conversion is deprecated in C++03 (D.4) 1508 SCS.DeprecatedStringLiteralToCharPtr = true; 1509 1510 // For the purpose of ranking in overload resolution 1511 // (13.3.3.1.1), this conversion is considered an 1512 // array-to-pointer conversion followed by a qualification 1513 // conversion (4.4). (C++ 4.2p2) 1514 SCS.Second = ICK_Identity; 1515 SCS.Third = ICK_Qualification; 1516 SCS.QualificationIncludesObjCLifetime = false; 1517 SCS.setAllToTypes(FromType); 1518 return true; 1519 } 1520 } else if (FromType->isFunctionType() && argIsLValue) { 1521 // Function-to-pointer conversion (C++ 4.3). 1522 SCS.First = ICK_Function_To_Pointer; 1523 1524 // An lvalue of function type T can be converted to an rvalue of 1525 // type "pointer to T." The result is a pointer to the 1526 // function. (C++ 4.3p1). 1527 FromType = S.Context.getPointerType(FromType); 1528 } else { 1529 // We don't require any conversions for the first step. 1530 SCS.First = ICK_Identity; 1531 } 1532 SCS.setToType(0, FromType); 1533 1534 // The second conversion can be an integral promotion, floating 1535 // point promotion, integral conversion, floating point conversion, 1536 // floating-integral conversion, pointer conversion, 1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1538 // For overloading in C, this can also be a "compatible-type" 1539 // conversion. 1540 bool IncompatibleObjC = false; 1541 ImplicitConversionKind SecondICK = ICK_Identity; 1542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1543 // The unqualified versions of the types are the same: there's no 1544 // conversion to do. 1545 SCS.Second = ICK_Identity; 1546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1547 // Integral promotion (C++ 4.5). 1548 SCS.Second = ICK_Integral_Promotion; 1549 FromType = ToType.getUnqualifiedType(); 1550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1551 // Floating point promotion (C++ 4.6). 1552 SCS.Second = ICK_Floating_Promotion; 1553 FromType = ToType.getUnqualifiedType(); 1554 } else if (S.IsComplexPromotion(FromType, ToType)) { 1555 // Complex promotion (Clang extension) 1556 SCS.Second = ICK_Complex_Promotion; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (ToType->isBooleanType() && 1559 (FromType->isArithmeticType() || 1560 FromType->isAnyPointerType() || 1561 FromType->isBlockPointerType() || 1562 FromType->isMemberPointerType() || 1563 FromType->isNullPtrType())) { 1564 // Boolean conversions (C++ 4.12). 1565 SCS.Second = ICK_Boolean_Conversion; 1566 FromType = S.Context.BoolTy; 1567 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1568 ToType->isIntegralType(S.Context)) { 1569 // Integral conversions (C++ 4.7). 1570 SCS.Second = ICK_Integral_Conversion; 1571 FromType = ToType.getUnqualifiedType(); 1572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1573 // Complex conversions (C99 6.3.1.6) 1574 SCS.Second = ICK_Complex_Conversion; 1575 FromType = ToType.getUnqualifiedType(); 1576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1578 // Complex-real conversions (C99 6.3.1.7) 1579 SCS.Second = ICK_Complex_Real; 1580 FromType = ToType.getUnqualifiedType(); 1581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1582 // Floating point conversions (C++ 4.8). 1583 SCS.Second = ICK_Floating_Conversion; 1584 FromType = ToType.getUnqualifiedType(); 1585 } else if ((FromType->isRealFloatingType() && 1586 ToType->isIntegralType(S.Context)) || 1587 (FromType->isIntegralOrUnscopedEnumerationType() && 1588 ToType->isRealFloatingType())) { 1589 // Floating-integral conversions (C++ 4.9). 1590 SCS.Second = ICK_Floating_Integral; 1591 FromType = ToType.getUnqualifiedType(); 1592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1593 SCS.Second = ICK_Block_Pointer_Conversion; 1594 } else if (AllowObjCWritebackConversion && 1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1596 SCS.Second = ICK_Writeback_Conversion; 1597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1598 FromType, IncompatibleObjC)) { 1599 // Pointer conversions (C++ 4.10). 1600 SCS.Second = ICK_Pointer_Conversion; 1601 SCS.IncompatibleObjC = IncompatibleObjC; 1602 FromType = FromType.getUnqualifiedType(); 1603 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1604 InOverloadResolution, FromType)) { 1605 // Pointer to member conversions (4.11). 1606 SCS.Second = ICK_Pointer_Member; 1607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1608 SCS.Second = SecondICK; 1609 FromType = ToType.getUnqualifiedType(); 1610 } else if (!S.getLangOpts().CPlusPlus && 1611 S.Context.typesAreCompatible(ToType, FromType)) { 1612 // Compatible conversions (Clang extension for C function overloading) 1613 SCS.Second = ICK_Compatible_Conversion; 1614 FromType = ToType.getUnqualifiedType(); 1615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1616 // Treat a conversion that strips "noreturn" as an identity conversion. 1617 SCS.Second = ICK_NoReturn_Adjustment; 1618 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1619 InOverloadResolution, 1620 SCS, CStyle)) { 1621 SCS.Second = ICK_TransparentUnionConversion; 1622 FromType = ToType; 1623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1624 CStyle)) { 1625 // tryAtomicConversion has updated the standard conversion sequence 1626 // appropriately. 1627 return true; 1628 } else if (ToType->isEventT() && 1629 From->isIntegerConstantExpr(S.getASTContext()) && 1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1631 SCS.Second = ICK_Zero_Event_Conversion; 1632 FromType = ToType; 1633 } else { 1634 // No second conversion required. 1635 SCS.Second = ICK_Identity; 1636 } 1637 SCS.setToType(1, FromType); 1638 1639 QualType CanonFrom; 1640 QualType CanonTo; 1641 // The third conversion can be a qualification conversion (C++ 4p1). 1642 bool ObjCLifetimeConversion; 1643 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1644 ObjCLifetimeConversion)) { 1645 SCS.Third = ICK_Qualification; 1646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1647 FromType = ToType; 1648 CanonFrom = S.Context.getCanonicalType(FromType); 1649 CanonTo = S.Context.getCanonicalType(ToType); 1650 } else { 1651 // No conversion required 1652 SCS.Third = ICK_Identity; 1653 1654 // C++ [over.best.ics]p6: 1655 // [...] Any difference in top-level cv-qualification is 1656 // subsumed by the initialization itself and does not constitute 1657 // a conversion. [...] 1658 CanonFrom = S.Context.getCanonicalType(FromType); 1659 CanonTo = S.Context.getCanonicalType(ToType); 1660 if (CanonFrom.getLocalUnqualifiedType() 1661 == CanonTo.getLocalUnqualifiedType() && 1662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1663 FromType = ToType; 1664 CanonFrom = CanonTo; 1665 } 1666 } 1667 SCS.setToType(2, FromType); 1668 1669 // If we have not converted the argument type to the parameter type, 1670 // this is a bad conversion sequence. 1671 if (CanonFrom != CanonTo) 1672 return false; 1673 1674 return true; 1675 } 1676 1677 static bool 1678 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1679 QualType &ToType, 1680 bool InOverloadResolution, 1681 StandardConversionSequence &SCS, 1682 bool CStyle) { 1683 1684 const RecordType *UT = ToType->getAsUnionType(); 1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1686 return false; 1687 // The field to initialize within the transparent union. 1688 RecordDecl *UD = UT->getDecl(); 1689 // It's compatible if the expression matches any of the fields. 1690 for (const auto *it : UD->fields()) { 1691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1692 CStyle, /*ObjCWritebackConversion=*/false)) { 1693 ToType = it->getType(); 1694 return true; 1695 } 1696 } 1697 return false; 1698 } 1699 1700 /// IsIntegralPromotion - Determines whether the conversion from the 1701 /// expression From (whose potentially-adjusted type is FromType) to 1702 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1703 /// sets PromotedType to the promoted type. 1704 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1705 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1706 // All integers are built-in. 1707 if (!To) { 1708 return false; 1709 } 1710 1711 // An rvalue of type char, signed char, unsigned char, short int, or 1712 // unsigned short int can be converted to an rvalue of type int if 1713 // int can represent all the values of the source type; otherwise, 1714 // the source rvalue can be converted to an rvalue of type unsigned 1715 // int (C++ 4.5p1). 1716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1717 !FromType->isEnumeralType()) { 1718 if (// We can promote any signed, promotable integer type to an int 1719 (FromType->isSignedIntegerType() || 1720 // We can promote any unsigned integer type whose size is 1721 // less than int to an int. 1722 (!FromType->isSignedIntegerType() && 1723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1724 return To->getKind() == BuiltinType::Int; 1725 } 1726 1727 return To->getKind() == BuiltinType::UInt; 1728 } 1729 1730 // C++11 [conv.prom]p3: 1731 // A prvalue of an unscoped enumeration type whose underlying type is not 1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1733 // following types that can represent all the values of the enumeration 1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1735 // unsigned int, long int, unsigned long int, long long int, or unsigned 1736 // long long int. If none of the types in that list can represent all the 1737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1738 // type can be converted to an rvalue a prvalue of the extended integer type 1739 // with lowest integer conversion rank (4.13) greater than the rank of long 1740 // long in which all the values of the enumeration can be represented. If 1741 // there are two such extended types, the signed one is chosen. 1742 // C++11 [conv.prom]p4: 1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1744 // can be converted to a prvalue of its underlying type. Moreover, if 1745 // integral promotion can be applied to its underlying type, a prvalue of an 1746 // unscoped enumeration type whose underlying type is fixed can also be 1747 // converted to a prvalue of the promoted underlying type. 1748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1750 // provided for a scoped enumeration. 1751 if (FromEnumType->getDecl()->isScoped()) 1752 return false; 1753 1754 // We can perform an integral promotion to the underlying type of the enum, 1755 // even if that's not the promoted type. Note that the check for promoting 1756 // the underlying type is based on the type alone, and does not consider 1757 // the bitfield-ness of the actual source expression. 1758 if (FromEnumType->getDecl()->isFixed()) { 1759 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1760 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1761 IsIntegralPromotion(nullptr, Underlying, ToType); 1762 } 1763 1764 // We have already pre-calculated the promotion type, so this is trivial. 1765 if (ToType->isIntegerType() && 1766 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1767 return Context.hasSameUnqualifiedType( 1768 ToType, FromEnumType->getDecl()->getPromotionType()); 1769 } 1770 1771 // C++0x [conv.prom]p2: 1772 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1773 // to an rvalue a prvalue of the first of the following types that can 1774 // represent all the values of its underlying type: int, unsigned int, 1775 // long int, unsigned long int, long long int, or unsigned long long int. 1776 // If none of the types in that list can represent all the values of its 1777 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1778 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1779 // type. 1780 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1781 ToType->isIntegerType()) { 1782 // Determine whether the type we're converting from is signed or 1783 // unsigned. 1784 bool FromIsSigned = FromType->isSignedIntegerType(); 1785 uint64_t FromSize = Context.getTypeSize(FromType); 1786 1787 // The types we'll try to promote to, in the appropriate 1788 // order. Try each of these types. 1789 QualType PromoteTypes[6] = { 1790 Context.IntTy, Context.UnsignedIntTy, 1791 Context.LongTy, Context.UnsignedLongTy , 1792 Context.LongLongTy, Context.UnsignedLongLongTy 1793 }; 1794 for (int Idx = 0; Idx < 6; ++Idx) { 1795 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1796 if (FromSize < ToSize || 1797 (FromSize == ToSize && 1798 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1799 // We found the type that we can promote to. If this is the 1800 // type we wanted, we have a promotion. Otherwise, no 1801 // promotion. 1802 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1803 } 1804 } 1805 } 1806 1807 // An rvalue for an integral bit-field (9.6) can be converted to an 1808 // rvalue of type int if int can represent all the values of the 1809 // bit-field; otherwise, it can be converted to unsigned int if 1810 // unsigned int can represent all the values of the bit-field. If 1811 // the bit-field is larger yet, no integral promotion applies to 1812 // it. If the bit-field has an enumerated type, it is treated as any 1813 // other value of that type for promotion purposes (C++ 4.5p3). 1814 // FIXME: We should delay checking of bit-fields until we actually perform the 1815 // conversion. 1816 if (From) { 1817 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1818 llvm::APSInt BitWidth; 1819 if (FromType->isIntegralType(Context) && 1820 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1821 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1822 ToSize = Context.getTypeSize(ToType); 1823 1824 // Are we promoting to an int from a bitfield that fits in an int? 1825 if (BitWidth < ToSize || 1826 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1827 return To->getKind() == BuiltinType::Int; 1828 } 1829 1830 // Are we promoting to an unsigned int from an unsigned bitfield 1831 // that fits into an unsigned int? 1832 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1833 return To->getKind() == BuiltinType::UInt; 1834 } 1835 1836 return false; 1837 } 1838 } 1839 } 1840 1841 // An rvalue of type bool can be converted to an rvalue of type int, 1842 // with false becoming zero and true becoming one (C++ 4.5p4). 1843 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1844 return true; 1845 } 1846 1847 return false; 1848 } 1849 1850 /// IsFloatingPointPromotion - Determines whether the conversion from 1851 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1852 /// returns true and sets PromotedType to the promoted type. 1853 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1854 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1855 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1856 /// An rvalue of type float can be converted to an rvalue of type 1857 /// double. (C++ 4.6p1). 1858 if (FromBuiltin->getKind() == BuiltinType::Float && 1859 ToBuiltin->getKind() == BuiltinType::Double) 1860 return true; 1861 1862 // C99 6.3.1.5p1: 1863 // When a float is promoted to double or long double, or a 1864 // double is promoted to long double [...]. 1865 if (!getLangOpts().CPlusPlus && 1866 (FromBuiltin->getKind() == BuiltinType::Float || 1867 FromBuiltin->getKind() == BuiltinType::Double) && 1868 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1869 return true; 1870 1871 // Half can be promoted to float. 1872 if (!getLangOpts().NativeHalfType && 1873 FromBuiltin->getKind() == BuiltinType::Half && 1874 ToBuiltin->getKind() == BuiltinType::Float) 1875 return true; 1876 } 1877 1878 return false; 1879 } 1880 1881 /// \brief Determine if a conversion is a complex promotion. 1882 /// 1883 /// A complex promotion is defined as a complex -> complex conversion 1884 /// where the conversion between the underlying real types is a 1885 /// floating-point or integral promotion. 1886 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1887 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1888 if (!FromComplex) 1889 return false; 1890 1891 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1892 if (!ToComplex) 1893 return false; 1894 1895 return IsFloatingPointPromotion(FromComplex->getElementType(), 1896 ToComplex->getElementType()) || 1897 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1898 ToComplex->getElementType()); 1899 } 1900 1901 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1902 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1903 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1904 /// if non-empty, will be a pointer to ToType that may or may not have 1905 /// the right set of qualifiers on its pointee. 1906 /// 1907 static QualType 1908 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1909 QualType ToPointee, QualType ToType, 1910 ASTContext &Context, 1911 bool StripObjCLifetime = false) { 1912 assert((FromPtr->getTypeClass() == Type::Pointer || 1913 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1914 "Invalid similarly-qualified pointer type"); 1915 1916 /// Conversions to 'id' subsume cv-qualifier conversions. 1917 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1918 return ToType.getUnqualifiedType(); 1919 1920 QualType CanonFromPointee 1921 = Context.getCanonicalType(FromPtr->getPointeeType()); 1922 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1923 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1924 1925 if (StripObjCLifetime) 1926 Quals.removeObjCLifetime(); 1927 1928 // Exact qualifier match -> return the pointer type we're converting to. 1929 if (CanonToPointee.getLocalQualifiers() == Quals) { 1930 // ToType is exactly what we need. Return it. 1931 if (!ToType.isNull()) 1932 return ToType.getUnqualifiedType(); 1933 1934 // Build a pointer to ToPointee. It has the right qualifiers 1935 // already. 1936 if (isa<ObjCObjectPointerType>(ToType)) 1937 return Context.getObjCObjectPointerType(ToPointee); 1938 return Context.getPointerType(ToPointee); 1939 } 1940 1941 // Just build a canonical type that has the right qualifiers. 1942 QualType QualifiedCanonToPointee 1943 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1944 1945 if (isa<ObjCObjectPointerType>(ToType)) 1946 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1947 return Context.getPointerType(QualifiedCanonToPointee); 1948 } 1949 1950 static bool isNullPointerConstantForConversion(Expr *Expr, 1951 bool InOverloadResolution, 1952 ASTContext &Context) { 1953 // Handle value-dependent integral null pointer constants correctly. 1954 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1955 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1956 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1957 return !InOverloadResolution; 1958 1959 return Expr->isNullPointerConstant(Context, 1960 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1961 : Expr::NPC_ValueDependentIsNull); 1962 } 1963 1964 /// IsPointerConversion - Determines whether the conversion of the 1965 /// expression From, which has the (possibly adjusted) type FromType, 1966 /// can be converted to the type ToType via a pointer conversion (C++ 1967 /// 4.10). If so, returns true and places the converted type (that 1968 /// might differ from ToType in its cv-qualifiers at some level) into 1969 /// ConvertedType. 1970 /// 1971 /// This routine also supports conversions to and from block pointers 1972 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1973 /// pointers to interfaces. FIXME: Once we've determined the 1974 /// appropriate overloading rules for Objective-C, we may want to 1975 /// split the Objective-C checks into a different routine; however, 1976 /// GCC seems to consider all of these conversions to be pointer 1977 /// conversions, so for now they live here. IncompatibleObjC will be 1978 /// set if the conversion is an allowed Objective-C conversion that 1979 /// should result in a warning. 1980 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1981 bool InOverloadResolution, 1982 QualType& ConvertedType, 1983 bool &IncompatibleObjC) { 1984 IncompatibleObjC = false; 1985 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1986 IncompatibleObjC)) 1987 return true; 1988 1989 // Conversion from a null pointer constant to any Objective-C pointer type. 1990 if (ToType->isObjCObjectPointerType() && 1991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1992 ConvertedType = ToType; 1993 return true; 1994 } 1995 1996 // Blocks: Block pointers can be converted to void*. 1997 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1998 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1999 ConvertedType = ToType; 2000 return true; 2001 } 2002 // Blocks: A null pointer constant can be converted to a block 2003 // pointer type. 2004 if (ToType->isBlockPointerType() && 2005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2006 ConvertedType = ToType; 2007 return true; 2008 } 2009 2010 // If the left-hand-side is nullptr_t, the right side can be a null 2011 // pointer constant. 2012 if (ToType->isNullPtrType() && 2013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2014 ConvertedType = ToType; 2015 return true; 2016 } 2017 2018 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2019 if (!ToTypePtr) 2020 return false; 2021 2022 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2023 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2024 ConvertedType = ToType; 2025 return true; 2026 } 2027 2028 // Beyond this point, both types need to be pointers 2029 // , including objective-c pointers. 2030 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2031 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2032 !getLangOpts().ObjCAutoRefCount) { 2033 ConvertedType = BuildSimilarlyQualifiedPointerType( 2034 FromType->getAs<ObjCObjectPointerType>(), 2035 ToPointeeType, 2036 ToType, Context); 2037 return true; 2038 } 2039 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2040 if (!FromTypePtr) 2041 return false; 2042 2043 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2044 2045 // If the unqualified pointee types are the same, this can't be a 2046 // pointer conversion, so don't do all of the work below. 2047 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2048 return false; 2049 2050 // An rvalue of type "pointer to cv T," where T is an object type, 2051 // can be converted to an rvalue of type "pointer to cv void" (C++ 2052 // 4.10p2). 2053 if (FromPointeeType->isIncompleteOrObjectType() && 2054 ToPointeeType->isVoidType()) { 2055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2056 ToPointeeType, 2057 ToType, Context, 2058 /*StripObjCLifetime=*/true); 2059 return true; 2060 } 2061 2062 // MSVC allows implicit function to void* type conversion. 2063 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2064 ToPointeeType->isVoidType()) { 2065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2066 ToPointeeType, 2067 ToType, Context); 2068 return true; 2069 } 2070 2071 // When we're overloading in C, we allow a special kind of pointer 2072 // conversion for compatible-but-not-identical pointee types. 2073 if (!getLangOpts().CPlusPlus && 2074 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2076 ToPointeeType, 2077 ToType, Context); 2078 return true; 2079 } 2080 2081 // C++ [conv.ptr]p3: 2082 // 2083 // An rvalue of type "pointer to cv D," where D is a class type, 2084 // can be converted to an rvalue of type "pointer to cv B," where 2085 // B is a base class (clause 10) of D. If B is an inaccessible 2086 // (clause 11) or ambiguous (10.2) base class of D, a program that 2087 // necessitates this conversion is ill-formed. The result of the 2088 // conversion is a pointer to the base class sub-object of the 2089 // derived class object. The null pointer value is converted to 2090 // the null pointer value of the destination type. 2091 // 2092 // Note that we do not check for ambiguity or inaccessibility 2093 // here. That is handled by CheckPointerConversion. 2094 if (getLangOpts().CPlusPlus && 2095 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2096 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2097 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2098 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2100 ToPointeeType, 2101 ToType, Context); 2102 return true; 2103 } 2104 2105 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2106 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2108 ToPointeeType, 2109 ToType, Context); 2110 return true; 2111 } 2112 2113 return false; 2114 } 2115 2116 /// \brief Adopt the given qualifiers for the given type. 2117 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2118 Qualifiers TQs = T.getQualifiers(); 2119 2120 // Check whether qualifiers already match. 2121 if (TQs == Qs) 2122 return T; 2123 2124 if (Qs.compatiblyIncludes(TQs)) 2125 return Context.getQualifiedType(T, Qs); 2126 2127 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2128 } 2129 2130 /// isObjCPointerConversion - Determines whether this is an 2131 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2132 /// with the same arguments and return values. 2133 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2134 QualType& ConvertedType, 2135 bool &IncompatibleObjC) { 2136 if (!getLangOpts().ObjC1) 2137 return false; 2138 2139 // The set of qualifiers on the type we're converting from. 2140 Qualifiers FromQualifiers = FromType.getQualifiers(); 2141 2142 // First, we handle all conversions on ObjC object pointer types. 2143 const ObjCObjectPointerType* ToObjCPtr = 2144 ToType->getAs<ObjCObjectPointerType>(); 2145 const ObjCObjectPointerType *FromObjCPtr = 2146 FromType->getAs<ObjCObjectPointerType>(); 2147 2148 if (ToObjCPtr && FromObjCPtr) { 2149 // If the pointee types are the same (ignoring qualifications), 2150 // then this is not a pointer conversion. 2151 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2152 FromObjCPtr->getPointeeType())) 2153 return false; 2154 2155 // Check for compatible 2156 // Objective C++: We're able to convert between "id" or "Class" and a 2157 // pointer to any interface (in both directions). 2158 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2159 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2160 return true; 2161 } 2162 // Conversions with Objective-C's id<...>. 2163 if ((FromObjCPtr->isObjCQualifiedIdType() || 2164 ToObjCPtr->isObjCQualifiedIdType()) && 2165 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2166 /*compare=*/false)) { 2167 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2168 return true; 2169 } 2170 // Objective C++: We're able to convert from a pointer to an 2171 // interface to a pointer to a different interface. 2172 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2173 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2174 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2175 if (getLangOpts().CPlusPlus && LHS && RHS && 2176 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2177 FromObjCPtr->getPointeeType())) 2178 return false; 2179 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2180 ToObjCPtr->getPointeeType(), 2181 ToType, Context); 2182 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2183 return true; 2184 } 2185 2186 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2187 // Okay: this is some kind of implicit downcast of Objective-C 2188 // interfaces, which is permitted. However, we're going to 2189 // complain about it. 2190 IncompatibleObjC = true; 2191 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2192 ToObjCPtr->getPointeeType(), 2193 ToType, Context); 2194 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2195 return true; 2196 } 2197 } 2198 // Beyond this point, both types need to be C pointers or block pointers. 2199 QualType ToPointeeType; 2200 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2201 ToPointeeType = ToCPtr->getPointeeType(); 2202 else if (const BlockPointerType *ToBlockPtr = 2203 ToType->getAs<BlockPointerType>()) { 2204 // Objective C++: We're able to convert from a pointer to any object 2205 // to a block pointer type. 2206 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2207 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2208 return true; 2209 } 2210 ToPointeeType = ToBlockPtr->getPointeeType(); 2211 } 2212 else if (FromType->getAs<BlockPointerType>() && 2213 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2214 // Objective C++: We're able to convert from a block pointer type to a 2215 // pointer to any object. 2216 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2217 return true; 2218 } 2219 else 2220 return false; 2221 2222 QualType FromPointeeType; 2223 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2224 FromPointeeType = FromCPtr->getPointeeType(); 2225 else if (const BlockPointerType *FromBlockPtr = 2226 FromType->getAs<BlockPointerType>()) 2227 FromPointeeType = FromBlockPtr->getPointeeType(); 2228 else 2229 return false; 2230 2231 // If we have pointers to pointers, recursively check whether this 2232 // is an Objective-C conversion. 2233 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2234 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2235 IncompatibleObjC)) { 2236 // We always complain about this conversion. 2237 IncompatibleObjC = true; 2238 ConvertedType = Context.getPointerType(ConvertedType); 2239 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2240 return true; 2241 } 2242 // Allow conversion of pointee being objective-c pointer to another one; 2243 // as in I* to id. 2244 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2245 ToPointeeType->getAs<ObjCObjectPointerType>() && 2246 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2247 IncompatibleObjC)) { 2248 2249 ConvertedType = Context.getPointerType(ConvertedType); 2250 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2251 return true; 2252 } 2253 2254 // If we have pointers to functions or blocks, check whether the only 2255 // differences in the argument and result types are in Objective-C 2256 // pointer conversions. If so, we permit the conversion (but 2257 // complain about it). 2258 const FunctionProtoType *FromFunctionType 2259 = FromPointeeType->getAs<FunctionProtoType>(); 2260 const FunctionProtoType *ToFunctionType 2261 = ToPointeeType->getAs<FunctionProtoType>(); 2262 if (FromFunctionType && ToFunctionType) { 2263 // If the function types are exactly the same, this isn't an 2264 // Objective-C pointer conversion. 2265 if (Context.getCanonicalType(FromPointeeType) 2266 == Context.getCanonicalType(ToPointeeType)) 2267 return false; 2268 2269 // Perform the quick checks that will tell us whether these 2270 // function types are obviously different. 2271 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2272 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2273 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2274 return false; 2275 2276 bool HasObjCConversion = false; 2277 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2278 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2279 // Okay, the types match exactly. Nothing to do. 2280 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2281 ToFunctionType->getReturnType(), 2282 ConvertedType, IncompatibleObjC)) { 2283 // Okay, we have an Objective-C pointer conversion. 2284 HasObjCConversion = true; 2285 } else { 2286 // Function types are too different. Abort. 2287 return false; 2288 } 2289 2290 // Check argument types. 2291 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2292 ArgIdx != NumArgs; ++ArgIdx) { 2293 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2294 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2295 if (Context.getCanonicalType(FromArgType) 2296 == Context.getCanonicalType(ToArgType)) { 2297 // Okay, the types match exactly. Nothing to do. 2298 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2299 ConvertedType, IncompatibleObjC)) { 2300 // Okay, we have an Objective-C pointer conversion. 2301 HasObjCConversion = true; 2302 } else { 2303 // Argument types are too different. Abort. 2304 return false; 2305 } 2306 } 2307 2308 if (HasObjCConversion) { 2309 // We had an Objective-C conversion. Allow this pointer 2310 // conversion, but complain about it. 2311 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2312 IncompatibleObjC = true; 2313 return true; 2314 } 2315 } 2316 2317 return false; 2318 } 2319 2320 /// \brief Determine whether this is an Objective-C writeback conversion, 2321 /// used for parameter passing when performing automatic reference counting. 2322 /// 2323 /// \param FromType The type we're converting form. 2324 /// 2325 /// \param ToType The type we're converting to. 2326 /// 2327 /// \param ConvertedType The type that will be produced after applying 2328 /// this conversion. 2329 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2330 QualType &ConvertedType) { 2331 if (!getLangOpts().ObjCAutoRefCount || 2332 Context.hasSameUnqualifiedType(FromType, ToType)) 2333 return false; 2334 2335 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2336 QualType ToPointee; 2337 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2338 ToPointee = ToPointer->getPointeeType(); 2339 else 2340 return false; 2341 2342 Qualifiers ToQuals = ToPointee.getQualifiers(); 2343 if (!ToPointee->isObjCLifetimeType() || 2344 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2345 !ToQuals.withoutObjCLifetime().empty()) 2346 return false; 2347 2348 // Argument must be a pointer to __strong to __weak. 2349 QualType FromPointee; 2350 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2351 FromPointee = FromPointer->getPointeeType(); 2352 else 2353 return false; 2354 2355 Qualifiers FromQuals = FromPointee.getQualifiers(); 2356 if (!FromPointee->isObjCLifetimeType() || 2357 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2358 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2359 return false; 2360 2361 // Make sure that we have compatible qualifiers. 2362 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2363 if (!ToQuals.compatiblyIncludes(FromQuals)) 2364 return false; 2365 2366 // Remove qualifiers from the pointee type we're converting from; they 2367 // aren't used in the compatibility check belong, and we'll be adding back 2368 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2369 FromPointee = FromPointee.getUnqualifiedType(); 2370 2371 // The unqualified form of the pointee types must be compatible. 2372 ToPointee = ToPointee.getUnqualifiedType(); 2373 bool IncompatibleObjC; 2374 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2375 FromPointee = ToPointee; 2376 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2377 IncompatibleObjC)) 2378 return false; 2379 2380 /// \brief Construct the type we're converting to, which is a pointer to 2381 /// __autoreleasing pointee. 2382 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2383 ConvertedType = Context.getPointerType(FromPointee); 2384 return true; 2385 } 2386 2387 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2388 QualType& ConvertedType) { 2389 QualType ToPointeeType; 2390 if (const BlockPointerType *ToBlockPtr = 2391 ToType->getAs<BlockPointerType>()) 2392 ToPointeeType = ToBlockPtr->getPointeeType(); 2393 else 2394 return false; 2395 2396 QualType FromPointeeType; 2397 if (const BlockPointerType *FromBlockPtr = 2398 FromType->getAs<BlockPointerType>()) 2399 FromPointeeType = FromBlockPtr->getPointeeType(); 2400 else 2401 return false; 2402 // We have pointer to blocks, check whether the only 2403 // differences in the argument and result types are in Objective-C 2404 // pointer conversions. If so, we permit the conversion. 2405 2406 const FunctionProtoType *FromFunctionType 2407 = FromPointeeType->getAs<FunctionProtoType>(); 2408 const FunctionProtoType *ToFunctionType 2409 = ToPointeeType->getAs<FunctionProtoType>(); 2410 2411 if (!FromFunctionType || !ToFunctionType) 2412 return false; 2413 2414 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2415 return true; 2416 2417 // Perform the quick checks that will tell us whether these 2418 // function types are obviously different. 2419 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2420 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2421 return false; 2422 2423 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2424 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2425 if (FromEInfo != ToEInfo) 2426 return false; 2427 2428 bool IncompatibleObjC = false; 2429 if (Context.hasSameType(FromFunctionType->getReturnType(), 2430 ToFunctionType->getReturnType())) { 2431 // Okay, the types match exactly. Nothing to do. 2432 } else { 2433 QualType RHS = FromFunctionType->getReturnType(); 2434 QualType LHS = ToFunctionType->getReturnType(); 2435 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2436 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2437 LHS = LHS.getUnqualifiedType(); 2438 2439 if (Context.hasSameType(RHS,LHS)) { 2440 // OK exact match. 2441 } else if (isObjCPointerConversion(RHS, LHS, 2442 ConvertedType, IncompatibleObjC)) { 2443 if (IncompatibleObjC) 2444 return false; 2445 // Okay, we have an Objective-C pointer conversion. 2446 } 2447 else 2448 return false; 2449 } 2450 2451 // Check argument types. 2452 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2453 ArgIdx != NumArgs; ++ArgIdx) { 2454 IncompatibleObjC = false; 2455 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2456 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2457 if (Context.hasSameType(FromArgType, ToArgType)) { 2458 // Okay, the types match exactly. Nothing to do. 2459 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2460 ConvertedType, IncompatibleObjC)) { 2461 if (IncompatibleObjC) 2462 return false; 2463 // Okay, we have an Objective-C pointer conversion. 2464 } else 2465 // Argument types are too different. Abort. 2466 return false; 2467 } 2468 if (LangOpts.ObjCAutoRefCount && 2469 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2470 ToFunctionType)) 2471 return false; 2472 2473 ConvertedType = ToType; 2474 return true; 2475 } 2476 2477 enum { 2478 ft_default, 2479 ft_different_class, 2480 ft_parameter_arity, 2481 ft_parameter_mismatch, 2482 ft_return_type, 2483 ft_qualifer_mismatch 2484 }; 2485 2486 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2487 /// function types. Catches different number of parameter, mismatch in 2488 /// parameter types, and different return types. 2489 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2490 QualType FromType, QualType ToType) { 2491 // If either type is not valid, include no extra info. 2492 if (FromType.isNull() || ToType.isNull()) { 2493 PDiag << ft_default; 2494 return; 2495 } 2496 2497 // Get the function type from the pointers. 2498 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2499 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2500 *ToMember = ToType->getAs<MemberPointerType>(); 2501 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2502 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2503 << QualType(FromMember->getClass(), 0); 2504 return; 2505 } 2506 FromType = FromMember->getPointeeType(); 2507 ToType = ToMember->getPointeeType(); 2508 } 2509 2510 if (FromType->isPointerType()) 2511 FromType = FromType->getPointeeType(); 2512 if (ToType->isPointerType()) 2513 ToType = ToType->getPointeeType(); 2514 2515 // Remove references. 2516 FromType = FromType.getNonReferenceType(); 2517 ToType = ToType.getNonReferenceType(); 2518 2519 // Don't print extra info for non-specialized template functions. 2520 if (FromType->isInstantiationDependentType() && 2521 !FromType->getAs<TemplateSpecializationType>()) { 2522 PDiag << ft_default; 2523 return; 2524 } 2525 2526 // No extra info for same types. 2527 if (Context.hasSameType(FromType, ToType)) { 2528 PDiag << ft_default; 2529 return; 2530 } 2531 2532 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2533 *ToFunction = ToType->getAs<FunctionProtoType>(); 2534 2535 // Both types need to be function types. 2536 if (!FromFunction || !ToFunction) { 2537 PDiag << ft_default; 2538 return; 2539 } 2540 2541 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2542 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2543 << FromFunction->getNumParams(); 2544 return; 2545 } 2546 2547 // Handle different parameter types. 2548 unsigned ArgPos; 2549 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2550 PDiag << ft_parameter_mismatch << ArgPos + 1 2551 << ToFunction->getParamType(ArgPos) 2552 << FromFunction->getParamType(ArgPos); 2553 return; 2554 } 2555 2556 // Handle different return type. 2557 if (!Context.hasSameType(FromFunction->getReturnType(), 2558 ToFunction->getReturnType())) { 2559 PDiag << ft_return_type << ToFunction->getReturnType() 2560 << FromFunction->getReturnType(); 2561 return; 2562 } 2563 2564 unsigned FromQuals = FromFunction->getTypeQuals(), 2565 ToQuals = ToFunction->getTypeQuals(); 2566 if (FromQuals != ToQuals) { 2567 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2568 return; 2569 } 2570 2571 // Unable to find a difference, so add no extra info. 2572 PDiag << ft_default; 2573 } 2574 2575 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2576 /// for equality of their argument types. Caller has already checked that 2577 /// they have same number of arguments. If the parameters are different, 2578 /// ArgPos will have the parameter index of the first different parameter. 2579 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2580 const FunctionProtoType *NewType, 2581 unsigned *ArgPos) { 2582 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2583 N = NewType->param_type_begin(), 2584 E = OldType->param_type_end(); 2585 O && (O != E); ++O, ++N) { 2586 if (!Context.hasSameType(O->getUnqualifiedType(), 2587 N->getUnqualifiedType())) { 2588 if (ArgPos) 2589 *ArgPos = O - OldType->param_type_begin(); 2590 return false; 2591 } 2592 } 2593 return true; 2594 } 2595 2596 /// CheckPointerConversion - Check the pointer conversion from the 2597 /// expression From to the type ToType. This routine checks for 2598 /// ambiguous or inaccessible derived-to-base pointer 2599 /// conversions for which IsPointerConversion has already returned 2600 /// true. It returns true and produces a diagnostic if there was an 2601 /// error, or returns false otherwise. 2602 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2603 CastKind &Kind, 2604 CXXCastPath& BasePath, 2605 bool IgnoreBaseAccess) { 2606 QualType FromType = From->getType(); 2607 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2608 2609 Kind = CK_BitCast; 2610 2611 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2612 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2613 Expr::NPCK_ZeroExpression) { 2614 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2615 DiagRuntimeBehavior(From->getExprLoc(), From, 2616 PDiag(diag::warn_impcast_bool_to_null_pointer) 2617 << ToType << From->getSourceRange()); 2618 else if (!isUnevaluatedContext()) 2619 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2620 << ToType << From->getSourceRange(); 2621 } 2622 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2623 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2624 QualType FromPointeeType = FromPtrType->getPointeeType(), 2625 ToPointeeType = ToPtrType->getPointeeType(); 2626 2627 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2628 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2629 // We must have a derived-to-base conversion. Check an 2630 // ambiguous or inaccessible conversion. 2631 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2632 From->getExprLoc(), 2633 From->getSourceRange(), &BasePath, 2634 IgnoreBaseAccess)) 2635 return true; 2636 2637 // The conversion was successful. 2638 Kind = CK_DerivedToBase; 2639 } 2640 } 2641 } else if (const ObjCObjectPointerType *ToPtrType = 2642 ToType->getAs<ObjCObjectPointerType>()) { 2643 if (const ObjCObjectPointerType *FromPtrType = 2644 FromType->getAs<ObjCObjectPointerType>()) { 2645 // Objective-C++ conversions are always okay. 2646 // FIXME: We should have a different class of conversions for the 2647 // Objective-C++ implicit conversions. 2648 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2649 return false; 2650 } else if (FromType->isBlockPointerType()) { 2651 Kind = CK_BlockPointerToObjCPointerCast; 2652 } else { 2653 Kind = CK_CPointerToObjCPointerCast; 2654 } 2655 } else if (ToType->isBlockPointerType()) { 2656 if (!FromType->isBlockPointerType()) 2657 Kind = CK_AnyPointerToBlockPointerCast; 2658 } 2659 2660 // We shouldn't fall into this case unless it's valid for other 2661 // reasons. 2662 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2663 Kind = CK_NullToPointer; 2664 2665 return false; 2666 } 2667 2668 /// IsMemberPointerConversion - Determines whether the conversion of the 2669 /// expression From, which has the (possibly adjusted) type FromType, can be 2670 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2671 /// If so, returns true and places the converted type (that might differ from 2672 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2673 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2674 QualType ToType, 2675 bool InOverloadResolution, 2676 QualType &ConvertedType) { 2677 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2678 if (!ToTypePtr) 2679 return false; 2680 2681 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2682 if (From->isNullPointerConstant(Context, 2683 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2684 : Expr::NPC_ValueDependentIsNull)) { 2685 ConvertedType = ToType; 2686 return true; 2687 } 2688 2689 // Otherwise, both types have to be member pointers. 2690 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2691 if (!FromTypePtr) 2692 return false; 2693 2694 // A pointer to member of B can be converted to a pointer to member of D, 2695 // where D is derived from B (C++ 4.11p2). 2696 QualType FromClass(FromTypePtr->getClass(), 0); 2697 QualType ToClass(ToTypePtr->getClass(), 0); 2698 2699 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2700 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2701 IsDerivedFrom(ToClass, FromClass)) { 2702 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2703 ToClass.getTypePtr()); 2704 return true; 2705 } 2706 2707 return false; 2708 } 2709 2710 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2711 /// expression From to the type ToType. This routine checks for ambiguous or 2712 /// virtual or inaccessible base-to-derived member pointer conversions 2713 /// for which IsMemberPointerConversion has already returned true. It returns 2714 /// true and produces a diagnostic if there was an error, or returns false 2715 /// otherwise. 2716 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2717 CastKind &Kind, 2718 CXXCastPath &BasePath, 2719 bool IgnoreBaseAccess) { 2720 QualType FromType = From->getType(); 2721 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2722 if (!FromPtrType) { 2723 // This must be a null pointer to member pointer conversion 2724 assert(From->isNullPointerConstant(Context, 2725 Expr::NPC_ValueDependentIsNull) && 2726 "Expr must be null pointer constant!"); 2727 Kind = CK_NullToMemberPointer; 2728 return false; 2729 } 2730 2731 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2732 assert(ToPtrType && "No member pointer cast has a target type " 2733 "that is not a member pointer."); 2734 2735 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2736 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2737 2738 // FIXME: What about dependent types? 2739 assert(FromClass->isRecordType() && "Pointer into non-class."); 2740 assert(ToClass->isRecordType() && "Pointer into non-class."); 2741 2742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2743 /*DetectVirtual=*/true); 2744 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2745 assert(DerivationOkay && 2746 "Should not have been called if derivation isn't OK."); 2747 (void)DerivationOkay; 2748 2749 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2750 getUnqualifiedType())) { 2751 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2752 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2753 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2754 return true; 2755 } 2756 2757 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2758 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2759 << FromClass << ToClass << QualType(VBase, 0) 2760 << From->getSourceRange(); 2761 return true; 2762 } 2763 2764 if (!IgnoreBaseAccess) 2765 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2766 Paths.front(), 2767 diag::err_downcast_from_inaccessible_base); 2768 2769 // Must be a base to derived member conversion. 2770 BuildBasePathArray(Paths, BasePath); 2771 Kind = CK_BaseToDerivedMemberPointer; 2772 return false; 2773 } 2774 2775 /// Determine whether the lifetime conversion between the two given 2776 /// qualifiers sets is nontrivial. 2777 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2778 Qualifiers ToQuals) { 2779 // Converting anything to const __unsafe_unretained is trivial. 2780 if (ToQuals.hasConst() && 2781 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2782 return false; 2783 2784 return true; 2785 } 2786 2787 /// IsQualificationConversion - Determines whether the conversion from 2788 /// an rvalue of type FromType to ToType is a qualification conversion 2789 /// (C++ 4.4). 2790 /// 2791 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2792 /// when the qualification conversion involves a change in the Objective-C 2793 /// object lifetime. 2794 bool 2795 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2796 bool CStyle, bool &ObjCLifetimeConversion) { 2797 FromType = Context.getCanonicalType(FromType); 2798 ToType = Context.getCanonicalType(ToType); 2799 ObjCLifetimeConversion = false; 2800 2801 // If FromType and ToType are the same type, this is not a 2802 // qualification conversion. 2803 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2804 return false; 2805 2806 // (C++ 4.4p4): 2807 // A conversion can add cv-qualifiers at levels other than the first 2808 // in multi-level pointers, subject to the following rules: [...] 2809 bool PreviousToQualsIncludeConst = true; 2810 bool UnwrappedAnyPointer = false; 2811 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2812 // Within each iteration of the loop, we check the qualifiers to 2813 // determine if this still looks like a qualification 2814 // conversion. Then, if all is well, we unwrap one more level of 2815 // pointers or pointers-to-members and do it all again 2816 // until there are no more pointers or pointers-to-members left to 2817 // unwrap. 2818 UnwrappedAnyPointer = true; 2819 2820 Qualifiers FromQuals = FromType.getQualifiers(); 2821 Qualifiers ToQuals = ToType.getQualifiers(); 2822 2823 // Objective-C ARC: 2824 // Check Objective-C lifetime conversions. 2825 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2826 UnwrappedAnyPointer) { 2827 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2828 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2829 ObjCLifetimeConversion = true; 2830 FromQuals.removeObjCLifetime(); 2831 ToQuals.removeObjCLifetime(); 2832 } else { 2833 // Qualification conversions cannot cast between different 2834 // Objective-C lifetime qualifiers. 2835 return false; 2836 } 2837 } 2838 2839 // Allow addition/removal of GC attributes but not changing GC attributes. 2840 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2841 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2842 FromQuals.removeObjCGCAttr(); 2843 ToQuals.removeObjCGCAttr(); 2844 } 2845 2846 // -- for every j > 0, if const is in cv 1,j then const is in cv 2847 // 2,j, and similarly for volatile. 2848 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2849 return false; 2850 2851 // -- if the cv 1,j and cv 2,j are different, then const is in 2852 // every cv for 0 < k < j. 2853 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2854 && !PreviousToQualsIncludeConst) 2855 return false; 2856 2857 // Keep track of whether all prior cv-qualifiers in the "to" type 2858 // include const. 2859 PreviousToQualsIncludeConst 2860 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2861 } 2862 2863 // We are left with FromType and ToType being the pointee types 2864 // after unwrapping the original FromType and ToType the same number 2865 // of types. If we unwrapped any pointers, and if FromType and 2866 // ToType have the same unqualified type (since we checked 2867 // qualifiers above), then this is a qualification conversion. 2868 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2869 } 2870 2871 /// \brief - Determine whether this is a conversion from a scalar type to an 2872 /// atomic type. 2873 /// 2874 /// If successful, updates \c SCS's second and third steps in the conversion 2875 /// sequence to finish the conversion. 2876 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2877 bool InOverloadResolution, 2878 StandardConversionSequence &SCS, 2879 bool CStyle) { 2880 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2881 if (!ToAtomic) 2882 return false; 2883 2884 StandardConversionSequence InnerSCS; 2885 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2886 InOverloadResolution, InnerSCS, 2887 CStyle, /*AllowObjCWritebackConversion=*/false)) 2888 return false; 2889 2890 SCS.Second = InnerSCS.Second; 2891 SCS.setToType(1, InnerSCS.getToType(1)); 2892 SCS.Third = InnerSCS.Third; 2893 SCS.QualificationIncludesObjCLifetime 2894 = InnerSCS.QualificationIncludesObjCLifetime; 2895 SCS.setToType(2, InnerSCS.getToType(2)); 2896 return true; 2897 } 2898 2899 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2900 CXXConstructorDecl *Constructor, 2901 QualType Type) { 2902 const FunctionProtoType *CtorType = 2903 Constructor->getType()->getAs<FunctionProtoType>(); 2904 if (CtorType->getNumParams() > 0) { 2905 QualType FirstArg = CtorType->getParamType(0); 2906 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2907 return true; 2908 } 2909 return false; 2910 } 2911 2912 static OverloadingResult 2913 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2914 CXXRecordDecl *To, 2915 UserDefinedConversionSequence &User, 2916 OverloadCandidateSet &CandidateSet, 2917 bool AllowExplicit) { 2918 DeclContext::lookup_result R = S.LookupConstructors(To); 2919 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2920 Con != ConEnd; ++Con) { 2921 NamedDecl *D = *Con; 2922 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2923 2924 // Find the constructor (which may be a template). 2925 CXXConstructorDecl *Constructor = nullptr; 2926 FunctionTemplateDecl *ConstructorTmpl 2927 = dyn_cast<FunctionTemplateDecl>(D); 2928 if (ConstructorTmpl) 2929 Constructor 2930 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2931 else 2932 Constructor = cast<CXXConstructorDecl>(D); 2933 2934 bool Usable = !Constructor->isInvalidDecl() && 2935 S.isInitListConstructor(Constructor) && 2936 (AllowExplicit || !Constructor->isExplicit()); 2937 if (Usable) { 2938 // If the first argument is (a reference to) the target type, 2939 // suppress conversions. 2940 bool SuppressUserConversions = 2941 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2942 if (ConstructorTmpl) 2943 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2944 /*ExplicitArgs*/ nullptr, 2945 From, CandidateSet, 2946 SuppressUserConversions); 2947 else 2948 S.AddOverloadCandidate(Constructor, FoundDecl, 2949 From, CandidateSet, 2950 SuppressUserConversions); 2951 } 2952 } 2953 2954 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2955 2956 OverloadCandidateSet::iterator Best; 2957 switch (auto Result = 2958 CandidateSet.BestViableFunction(S, From->getLocStart(), 2959 Best, true)) { 2960 case OR_Deleted: 2961 case OR_Success: { 2962 // Record the standard conversion we used and the conversion function. 2963 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2964 QualType ThisType = Constructor->getThisType(S.Context); 2965 // Initializer lists don't have conversions as such. 2966 User.Before.setAsIdentityConversion(); 2967 User.HadMultipleCandidates = HadMultipleCandidates; 2968 User.ConversionFunction = Constructor; 2969 User.FoundConversionFunction = Best->FoundDecl; 2970 User.After.setAsIdentityConversion(); 2971 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2972 User.After.setAllToTypes(ToType); 2973 return Result; 2974 } 2975 2976 case OR_No_Viable_Function: 2977 return OR_No_Viable_Function; 2978 case OR_Ambiguous: 2979 return OR_Ambiguous; 2980 } 2981 2982 llvm_unreachable("Invalid OverloadResult!"); 2983 } 2984 2985 /// Determines whether there is a user-defined conversion sequence 2986 /// (C++ [over.ics.user]) that converts expression From to the type 2987 /// ToType. If such a conversion exists, User will contain the 2988 /// user-defined conversion sequence that performs such a conversion 2989 /// and this routine will return true. Otherwise, this routine returns 2990 /// false and User is unspecified. 2991 /// 2992 /// \param AllowExplicit true if the conversion should consider C++0x 2993 /// "explicit" conversion functions as well as non-explicit conversion 2994 /// functions (C++0x [class.conv.fct]p2). 2995 /// 2996 /// \param AllowObjCConversionOnExplicit true if the conversion should 2997 /// allow an extra Objective-C pointer conversion on uses of explicit 2998 /// constructors. Requires \c AllowExplicit to also be set. 2999 static OverloadingResult 3000 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3001 UserDefinedConversionSequence &User, 3002 OverloadCandidateSet &CandidateSet, 3003 bool AllowExplicit, 3004 bool AllowObjCConversionOnExplicit) { 3005 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3006 3007 // Whether we will only visit constructors. 3008 bool ConstructorsOnly = false; 3009 3010 // If the type we are conversion to is a class type, enumerate its 3011 // constructors. 3012 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3013 // C++ [over.match.ctor]p1: 3014 // When objects of class type are direct-initialized (8.5), or 3015 // copy-initialized from an expression of the same or a 3016 // derived class type (8.5), overload resolution selects the 3017 // constructor. [...] For copy-initialization, the candidate 3018 // functions are all the converting constructors (12.3.1) of 3019 // that class. The argument list is the expression-list within 3020 // the parentheses of the initializer. 3021 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3022 (From->getType()->getAs<RecordType>() && 3023 S.IsDerivedFrom(From->getType(), ToType))) 3024 ConstructorsOnly = true; 3025 3026 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3027 // RequireCompleteType may have returned true due to some invalid decl 3028 // during template instantiation, but ToType may be complete enough now 3029 // to try to recover. 3030 if (ToType->isIncompleteType()) { 3031 // We're not going to find any constructors. 3032 } else if (CXXRecordDecl *ToRecordDecl 3033 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3034 3035 Expr **Args = &From; 3036 unsigned NumArgs = 1; 3037 bool ListInitializing = false; 3038 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3039 // But first, see if there is an init-list-constructor that will work. 3040 OverloadingResult Result = IsInitializerListConstructorConversion( 3041 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3042 if (Result != OR_No_Viable_Function) 3043 return Result; 3044 // Never mind. 3045 CandidateSet.clear(); 3046 3047 // If we're list-initializing, we pass the individual elements as 3048 // arguments, not the entire list. 3049 Args = InitList->getInits(); 3050 NumArgs = InitList->getNumInits(); 3051 ListInitializing = true; 3052 } 3053 3054 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3055 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3056 Con != ConEnd; ++Con) { 3057 NamedDecl *D = *Con; 3058 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3059 3060 // Find the constructor (which may be a template). 3061 CXXConstructorDecl *Constructor = nullptr; 3062 FunctionTemplateDecl *ConstructorTmpl 3063 = dyn_cast<FunctionTemplateDecl>(D); 3064 if (ConstructorTmpl) 3065 Constructor 3066 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3067 else 3068 Constructor = cast<CXXConstructorDecl>(D); 3069 3070 bool Usable = !Constructor->isInvalidDecl(); 3071 if (ListInitializing) 3072 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3073 else 3074 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3075 if (Usable) { 3076 bool SuppressUserConversions = !ConstructorsOnly; 3077 if (SuppressUserConversions && ListInitializing) { 3078 SuppressUserConversions = false; 3079 if (NumArgs == 1) { 3080 // If the first argument is (a reference to) the target type, 3081 // suppress conversions. 3082 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3083 S.Context, Constructor, ToType); 3084 } 3085 } 3086 if (ConstructorTmpl) 3087 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3088 /*ExplicitArgs*/ nullptr, 3089 llvm::makeArrayRef(Args, NumArgs), 3090 CandidateSet, SuppressUserConversions); 3091 else 3092 // Allow one user-defined conversion when user specifies a 3093 // From->ToType conversion via an static cast (c-style, etc). 3094 S.AddOverloadCandidate(Constructor, FoundDecl, 3095 llvm::makeArrayRef(Args, NumArgs), 3096 CandidateSet, SuppressUserConversions); 3097 } 3098 } 3099 } 3100 } 3101 3102 // Enumerate conversion functions, if we're allowed to. 3103 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3104 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3105 // No conversion functions from incomplete types. 3106 } else if (const RecordType *FromRecordType 3107 = From->getType()->getAs<RecordType>()) { 3108 if (CXXRecordDecl *FromRecordDecl 3109 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3110 // Add all of the conversion functions as candidates. 3111 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3112 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3113 DeclAccessPair FoundDecl = I.getPair(); 3114 NamedDecl *D = FoundDecl.getDecl(); 3115 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3116 if (isa<UsingShadowDecl>(D)) 3117 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3118 3119 CXXConversionDecl *Conv; 3120 FunctionTemplateDecl *ConvTemplate; 3121 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3122 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3123 else 3124 Conv = cast<CXXConversionDecl>(D); 3125 3126 if (AllowExplicit || !Conv->isExplicit()) { 3127 if (ConvTemplate) 3128 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3129 ActingContext, From, ToType, 3130 CandidateSet, 3131 AllowObjCConversionOnExplicit); 3132 else 3133 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3134 From, ToType, CandidateSet, 3135 AllowObjCConversionOnExplicit); 3136 } 3137 } 3138 } 3139 } 3140 3141 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3142 3143 OverloadCandidateSet::iterator Best; 3144 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3145 Best, true)) { 3146 case OR_Success: 3147 case OR_Deleted: 3148 // Record the standard conversion we used and the conversion function. 3149 if (CXXConstructorDecl *Constructor 3150 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3151 // C++ [over.ics.user]p1: 3152 // If the user-defined conversion is specified by a 3153 // constructor (12.3.1), the initial standard conversion 3154 // sequence converts the source type to the type required by 3155 // the argument of the constructor. 3156 // 3157 QualType ThisType = Constructor->getThisType(S.Context); 3158 if (isa<InitListExpr>(From)) { 3159 // Initializer lists don't have conversions as such. 3160 User.Before.setAsIdentityConversion(); 3161 } else { 3162 if (Best->Conversions[0].isEllipsis()) 3163 User.EllipsisConversion = true; 3164 else { 3165 User.Before = Best->Conversions[0].Standard; 3166 User.EllipsisConversion = false; 3167 } 3168 } 3169 User.HadMultipleCandidates = HadMultipleCandidates; 3170 User.ConversionFunction = Constructor; 3171 User.FoundConversionFunction = Best->FoundDecl; 3172 User.After.setAsIdentityConversion(); 3173 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3174 User.After.setAllToTypes(ToType); 3175 return Result; 3176 } 3177 if (CXXConversionDecl *Conversion 3178 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3179 // C++ [over.ics.user]p1: 3180 // 3181 // [...] If the user-defined conversion is specified by a 3182 // conversion function (12.3.2), the initial standard 3183 // conversion sequence converts the source type to the 3184 // implicit object parameter of the conversion function. 3185 User.Before = Best->Conversions[0].Standard; 3186 User.HadMultipleCandidates = HadMultipleCandidates; 3187 User.ConversionFunction = Conversion; 3188 User.FoundConversionFunction = Best->FoundDecl; 3189 User.EllipsisConversion = false; 3190 3191 // C++ [over.ics.user]p2: 3192 // The second standard conversion sequence converts the 3193 // result of the user-defined conversion to the target type 3194 // for the sequence. Since an implicit conversion sequence 3195 // is an initialization, the special rules for 3196 // initialization by user-defined conversion apply when 3197 // selecting the best user-defined conversion for a 3198 // user-defined conversion sequence (see 13.3.3 and 3199 // 13.3.3.1). 3200 User.After = Best->FinalConversion; 3201 return Result; 3202 } 3203 llvm_unreachable("Not a constructor or conversion function?"); 3204 3205 case OR_No_Viable_Function: 3206 return OR_No_Viable_Function; 3207 3208 case OR_Ambiguous: 3209 return OR_Ambiguous; 3210 } 3211 3212 llvm_unreachable("Invalid OverloadResult!"); 3213 } 3214 3215 bool 3216 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3217 ImplicitConversionSequence ICS; 3218 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3219 OverloadCandidateSet::CSK_Normal); 3220 OverloadingResult OvResult = 3221 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3222 CandidateSet, false, false); 3223 if (OvResult == OR_Ambiguous) 3224 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3225 << From->getType() << ToType << From->getSourceRange(); 3226 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3227 if (!RequireCompleteType(From->getLocStart(), ToType, 3228 diag::err_typecheck_nonviable_condition_incomplete, 3229 From->getType(), From->getSourceRange())) 3230 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3231 << From->getType() << From->getSourceRange() << ToType; 3232 } else 3233 return false; 3234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3235 return true; 3236 } 3237 3238 /// \brief Compare the user-defined conversion functions or constructors 3239 /// of two user-defined conversion sequences to determine whether any ordering 3240 /// is possible. 3241 static ImplicitConversionSequence::CompareKind 3242 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3243 FunctionDecl *Function2) { 3244 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3245 return ImplicitConversionSequence::Indistinguishable; 3246 3247 // Objective-C++: 3248 // If both conversion functions are implicitly-declared conversions from 3249 // a lambda closure type to a function pointer and a block pointer, 3250 // respectively, always prefer the conversion to a function pointer, 3251 // because the function pointer is more lightweight and is more likely 3252 // to keep code working. 3253 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3254 if (!Conv1) 3255 return ImplicitConversionSequence::Indistinguishable; 3256 3257 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3258 if (!Conv2) 3259 return ImplicitConversionSequence::Indistinguishable; 3260 3261 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3262 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3263 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3264 if (Block1 != Block2) 3265 return Block1 ? ImplicitConversionSequence::Worse 3266 : ImplicitConversionSequence::Better; 3267 } 3268 3269 return ImplicitConversionSequence::Indistinguishable; 3270 } 3271 3272 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3273 const ImplicitConversionSequence &ICS) { 3274 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3275 (ICS.isUserDefined() && 3276 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3277 } 3278 3279 /// CompareImplicitConversionSequences - Compare two implicit 3280 /// conversion sequences to determine whether one is better than the 3281 /// other or if they are indistinguishable (C++ 13.3.3.2). 3282 static ImplicitConversionSequence::CompareKind 3283 CompareImplicitConversionSequences(Sema &S, 3284 const ImplicitConversionSequence& ICS1, 3285 const ImplicitConversionSequence& ICS2) 3286 { 3287 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3288 // conversion sequences (as defined in 13.3.3.1) 3289 // -- a standard conversion sequence (13.3.3.1.1) is a better 3290 // conversion sequence than a user-defined conversion sequence or 3291 // an ellipsis conversion sequence, and 3292 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3293 // conversion sequence than an ellipsis conversion sequence 3294 // (13.3.3.1.3). 3295 // 3296 // C++0x [over.best.ics]p10: 3297 // For the purpose of ranking implicit conversion sequences as 3298 // described in 13.3.3.2, the ambiguous conversion sequence is 3299 // treated as a user-defined sequence that is indistinguishable 3300 // from any other user-defined conversion sequence. 3301 3302 // String literal to 'char *' conversion has been deprecated in C++03. It has 3303 // been removed from C++11. We still accept this conversion, if it happens at 3304 // the best viable function. Otherwise, this conversion is considered worse 3305 // than ellipsis conversion. Consider this as an extension; this is not in the 3306 // standard. For example: 3307 // 3308 // int &f(...); // #1 3309 // void f(char*); // #2 3310 // void g() { int &r = f("foo"); } 3311 // 3312 // In C++03, we pick #2 as the best viable function. 3313 // In C++11, we pick #1 as the best viable function, because ellipsis 3314 // conversion is better than string-literal to char* conversion (since there 3315 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3316 // convert arguments, #2 would be the best viable function in C++11. 3317 // If the best viable function has this conversion, a warning will be issued 3318 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3319 3320 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3321 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3322 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3323 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3324 ? ImplicitConversionSequence::Worse 3325 : ImplicitConversionSequence::Better; 3326 3327 if (ICS1.getKindRank() < ICS2.getKindRank()) 3328 return ImplicitConversionSequence::Better; 3329 if (ICS2.getKindRank() < ICS1.getKindRank()) 3330 return ImplicitConversionSequence::Worse; 3331 3332 // The following checks require both conversion sequences to be of 3333 // the same kind. 3334 if (ICS1.getKind() != ICS2.getKind()) 3335 return ImplicitConversionSequence::Indistinguishable; 3336 3337 ImplicitConversionSequence::CompareKind Result = 3338 ImplicitConversionSequence::Indistinguishable; 3339 3340 // Two implicit conversion sequences of the same form are 3341 // indistinguishable conversion sequences unless one of the 3342 // following rules apply: (C++ 13.3.3.2p3): 3343 3344 // List-initialization sequence L1 is a better conversion sequence than 3345 // list-initialization sequence L2 if: 3346 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3347 // if not that, 3348 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3349 // and N1 is smaller than N2., 3350 // even if one of the other rules in this paragraph would otherwise apply. 3351 if (!ICS1.isBad()) { 3352 if (ICS1.isStdInitializerListElement() && 3353 !ICS2.isStdInitializerListElement()) 3354 return ImplicitConversionSequence::Better; 3355 if (!ICS1.isStdInitializerListElement() && 3356 ICS2.isStdInitializerListElement()) 3357 return ImplicitConversionSequence::Worse; 3358 } 3359 3360 if (ICS1.isStandard()) 3361 // Standard conversion sequence S1 is a better conversion sequence than 3362 // standard conversion sequence S2 if [...] 3363 Result = CompareStandardConversionSequences(S, 3364 ICS1.Standard, ICS2.Standard); 3365 else if (ICS1.isUserDefined()) { 3366 // User-defined conversion sequence U1 is a better conversion 3367 // sequence than another user-defined conversion sequence U2 if 3368 // they contain the same user-defined conversion function or 3369 // constructor and if the second standard conversion sequence of 3370 // U1 is better than the second standard conversion sequence of 3371 // U2 (C++ 13.3.3.2p3). 3372 if (ICS1.UserDefined.ConversionFunction == 3373 ICS2.UserDefined.ConversionFunction) 3374 Result = CompareStandardConversionSequences(S, 3375 ICS1.UserDefined.After, 3376 ICS2.UserDefined.After); 3377 else 3378 Result = compareConversionFunctions(S, 3379 ICS1.UserDefined.ConversionFunction, 3380 ICS2.UserDefined.ConversionFunction); 3381 } 3382 3383 return Result; 3384 } 3385 3386 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3387 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3388 Qualifiers Quals; 3389 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3390 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3391 } 3392 3393 return Context.hasSameUnqualifiedType(T1, T2); 3394 } 3395 3396 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3397 // determine if one is a proper subset of the other. 3398 static ImplicitConversionSequence::CompareKind 3399 compareStandardConversionSubsets(ASTContext &Context, 3400 const StandardConversionSequence& SCS1, 3401 const StandardConversionSequence& SCS2) { 3402 ImplicitConversionSequence::CompareKind Result 3403 = ImplicitConversionSequence::Indistinguishable; 3404 3405 // the identity conversion sequence is considered to be a subsequence of 3406 // any non-identity conversion sequence 3407 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3408 return ImplicitConversionSequence::Better; 3409 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3410 return ImplicitConversionSequence::Worse; 3411 3412 if (SCS1.Second != SCS2.Second) { 3413 if (SCS1.Second == ICK_Identity) 3414 Result = ImplicitConversionSequence::Better; 3415 else if (SCS2.Second == ICK_Identity) 3416 Result = ImplicitConversionSequence::Worse; 3417 else 3418 return ImplicitConversionSequence::Indistinguishable; 3419 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3420 return ImplicitConversionSequence::Indistinguishable; 3421 3422 if (SCS1.Third == SCS2.Third) { 3423 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3424 : ImplicitConversionSequence::Indistinguishable; 3425 } 3426 3427 if (SCS1.Third == ICK_Identity) 3428 return Result == ImplicitConversionSequence::Worse 3429 ? ImplicitConversionSequence::Indistinguishable 3430 : ImplicitConversionSequence::Better; 3431 3432 if (SCS2.Third == ICK_Identity) 3433 return Result == ImplicitConversionSequence::Better 3434 ? ImplicitConversionSequence::Indistinguishable 3435 : ImplicitConversionSequence::Worse; 3436 3437 return ImplicitConversionSequence::Indistinguishable; 3438 } 3439 3440 /// \brief Determine whether one of the given reference bindings is better 3441 /// than the other based on what kind of bindings they are. 3442 static bool 3443 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3444 const StandardConversionSequence &SCS2) { 3445 // C++0x [over.ics.rank]p3b4: 3446 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3447 // implicit object parameter of a non-static member function declared 3448 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3449 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3450 // lvalue reference to a function lvalue and S2 binds an rvalue 3451 // reference*. 3452 // 3453 // FIXME: Rvalue references. We're going rogue with the above edits, 3454 // because the semantics in the current C++0x working paper (N3225 at the 3455 // time of this writing) break the standard definition of std::forward 3456 // and std::reference_wrapper when dealing with references to functions. 3457 // Proposed wording changes submitted to CWG for consideration. 3458 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3459 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3460 return false; 3461 3462 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3463 SCS2.IsLvalueReference) || 3464 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3465 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3466 } 3467 3468 /// CompareStandardConversionSequences - Compare two standard 3469 /// conversion sequences to determine whether one is better than the 3470 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3471 static ImplicitConversionSequence::CompareKind 3472 CompareStandardConversionSequences(Sema &S, 3473 const StandardConversionSequence& SCS1, 3474 const StandardConversionSequence& SCS2) 3475 { 3476 // Standard conversion sequence S1 is a better conversion sequence 3477 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3478 3479 // -- S1 is a proper subsequence of S2 (comparing the conversion 3480 // sequences in the canonical form defined by 13.3.3.1.1, 3481 // excluding any Lvalue Transformation; the identity conversion 3482 // sequence is considered to be a subsequence of any 3483 // non-identity conversion sequence) or, if not that, 3484 if (ImplicitConversionSequence::CompareKind CK 3485 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3486 return CK; 3487 3488 // -- the rank of S1 is better than the rank of S2 (by the rules 3489 // defined below), or, if not that, 3490 ImplicitConversionRank Rank1 = SCS1.getRank(); 3491 ImplicitConversionRank Rank2 = SCS2.getRank(); 3492 if (Rank1 < Rank2) 3493 return ImplicitConversionSequence::Better; 3494 else if (Rank2 < Rank1) 3495 return ImplicitConversionSequence::Worse; 3496 3497 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3498 // are indistinguishable unless one of the following rules 3499 // applies: 3500 3501 // A conversion that is not a conversion of a pointer, or 3502 // pointer to member, to bool is better than another conversion 3503 // that is such a conversion. 3504 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3505 return SCS2.isPointerConversionToBool() 3506 ? ImplicitConversionSequence::Better 3507 : ImplicitConversionSequence::Worse; 3508 3509 // C++ [over.ics.rank]p4b2: 3510 // 3511 // If class B is derived directly or indirectly from class A, 3512 // conversion of B* to A* is better than conversion of B* to 3513 // void*, and conversion of A* to void* is better than conversion 3514 // of B* to void*. 3515 bool SCS1ConvertsToVoid 3516 = SCS1.isPointerConversionToVoidPointer(S.Context); 3517 bool SCS2ConvertsToVoid 3518 = SCS2.isPointerConversionToVoidPointer(S.Context); 3519 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3520 // Exactly one of the conversion sequences is a conversion to 3521 // a void pointer; it's the worse conversion. 3522 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3523 : ImplicitConversionSequence::Worse; 3524 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3525 // Neither conversion sequence converts to a void pointer; compare 3526 // their derived-to-base conversions. 3527 if (ImplicitConversionSequence::CompareKind DerivedCK 3528 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3529 return DerivedCK; 3530 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3531 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3532 // Both conversion sequences are conversions to void 3533 // pointers. Compare the source types to determine if there's an 3534 // inheritance relationship in their sources. 3535 QualType FromType1 = SCS1.getFromType(); 3536 QualType FromType2 = SCS2.getFromType(); 3537 3538 // Adjust the types we're converting from via the array-to-pointer 3539 // conversion, if we need to. 3540 if (SCS1.First == ICK_Array_To_Pointer) 3541 FromType1 = S.Context.getArrayDecayedType(FromType1); 3542 if (SCS2.First == ICK_Array_To_Pointer) 3543 FromType2 = S.Context.getArrayDecayedType(FromType2); 3544 3545 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3546 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3547 3548 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3549 return ImplicitConversionSequence::Better; 3550 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3551 return ImplicitConversionSequence::Worse; 3552 3553 // Objective-C++: If one interface is more specific than the 3554 // other, it is the better one. 3555 const ObjCObjectPointerType* FromObjCPtr1 3556 = FromType1->getAs<ObjCObjectPointerType>(); 3557 const ObjCObjectPointerType* FromObjCPtr2 3558 = FromType2->getAs<ObjCObjectPointerType>(); 3559 if (FromObjCPtr1 && FromObjCPtr2) { 3560 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3561 FromObjCPtr2); 3562 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3563 FromObjCPtr1); 3564 if (AssignLeft != AssignRight) { 3565 return AssignLeft? ImplicitConversionSequence::Better 3566 : ImplicitConversionSequence::Worse; 3567 } 3568 } 3569 } 3570 3571 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3572 // bullet 3). 3573 if (ImplicitConversionSequence::CompareKind QualCK 3574 = CompareQualificationConversions(S, SCS1, SCS2)) 3575 return QualCK; 3576 3577 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3578 // Check for a better reference binding based on the kind of bindings. 3579 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3580 return ImplicitConversionSequence::Better; 3581 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3582 return ImplicitConversionSequence::Worse; 3583 3584 // C++ [over.ics.rank]p3b4: 3585 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3586 // which the references refer are the same type except for 3587 // top-level cv-qualifiers, and the type to which the reference 3588 // initialized by S2 refers is more cv-qualified than the type 3589 // to which the reference initialized by S1 refers. 3590 QualType T1 = SCS1.getToType(2); 3591 QualType T2 = SCS2.getToType(2); 3592 T1 = S.Context.getCanonicalType(T1); 3593 T2 = S.Context.getCanonicalType(T2); 3594 Qualifiers T1Quals, T2Quals; 3595 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3596 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3597 if (UnqualT1 == UnqualT2) { 3598 // Objective-C++ ARC: If the references refer to objects with different 3599 // lifetimes, prefer bindings that don't change lifetime. 3600 if (SCS1.ObjCLifetimeConversionBinding != 3601 SCS2.ObjCLifetimeConversionBinding) { 3602 return SCS1.ObjCLifetimeConversionBinding 3603 ? ImplicitConversionSequence::Worse 3604 : ImplicitConversionSequence::Better; 3605 } 3606 3607 // If the type is an array type, promote the element qualifiers to the 3608 // type for comparison. 3609 if (isa<ArrayType>(T1) && T1Quals) 3610 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3611 if (isa<ArrayType>(T2) && T2Quals) 3612 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3613 if (T2.isMoreQualifiedThan(T1)) 3614 return ImplicitConversionSequence::Better; 3615 else if (T1.isMoreQualifiedThan(T2)) 3616 return ImplicitConversionSequence::Worse; 3617 } 3618 } 3619 3620 // In Microsoft mode, prefer an integral conversion to a 3621 // floating-to-integral conversion if the integral conversion 3622 // is between types of the same size. 3623 // For example: 3624 // void f(float); 3625 // void f(int); 3626 // int main { 3627 // long a; 3628 // f(a); 3629 // } 3630 // Here, MSVC will call f(int) instead of generating a compile error 3631 // as clang will do in standard mode. 3632 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3633 SCS2.Second == ICK_Floating_Integral && 3634 S.Context.getTypeSize(SCS1.getFromType()) == 3635 S.Context.getTypeSize(SCS1.getToType(2))) 3636 return ImplicitConversionSequence::Better; 3637 3638 return ImplicitConversionSequence::Indistinguishable; 3639 } 3640 3641 /// CompareQualificationConversions - Compares two standard conversion 3642 /// sequences to determine whether they can be ranked based on their 3643 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3644 static ImplicitConversionSequence::CompareKind 3645 CompareQualificationConversions(Sema &S, 3646 const StandardConversionSequence& SCS1, 3647 const StandardConversionSequence& SCS2) { 3648 // C++ 13.3.3.2p3: 3649 // -- S1 and S2 differ only in their qualification conversion and 3650 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3651 // cv-qualification signature of type T1 is a proper subset of 3652 // the cv-qualification signature of type T2, and S1 is not the 3653 // deprecated string literal array-to-pointer conversion (4.2). 3654 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3655 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3656 return ImplicitConversionSequence::Indistinguishable; 3657 3658 // FIXME: the example in the standard doesn't use a qualification 3659 // conversion (!) 3660 QualType T1 = SCS1.getToType(2); 3661 QualType T2 = SCS2.getToType(2); 3662 T1 = S.Context.getCanonicalType(T1); 3663 T2 = S.Context.getCanonicalType(T2); 3664 Qualifiers T1Quals, T2Quals; 3665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3667 3668 // If the types are the same, we won't learn anything by unwrapped 3669 // them. 3670 if (UnqualT1 == UnqualT2) 3671 return ImplicitConversionSequence::Indistinguishable; 3672 3673 // If the type is an array type, promote the element qualifiers to the type 3674 // for comparison. 3675 if (isa<ArrayType>(T1) && T1Quals) 3676 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3677 if (isa<ArrayType>(T2) && T2Quals) 3678 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3679 3680 ImplicitConversionSequence::CompareKind Result 3681 = ImplicitConversionSequence::Indistinguishable; 3682 3683 // Objective-C++ ARC: 3684 // Prefer qualification conversions not involving a change in lifetime 3685 // to qualification conversions that do not change lifetime. 3686 if (SCS1.QualificationIncludesObjCLifetime != 3687 SCS2.QualificationIncludesObjCLifetime) { 3688 Result = SCS1.QualificationIncludesObjCLifetime 3689 ? ImplicitConversionSequence::Worse 3690 : ImplicitConversionSequence::Better; 3691 } 3692 3693 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3694 // Within each iteration of the loop, we check the qualifiers to 3695 // determine if this still looks like a qualification 3696 // conversion. Then, if all is well, we unwrap one more level of 3697 // pointers or pointers-to-members and do it all again 3698 // until there are no more pointers or pointers-to-members left 3699 // to unwrap. This essentially mimics what 3700 // IsQualificationConversion does, but here we're checking for a 3701 // strict subset of qualifiers. 3702 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3703 // The qualifiers are the same, so this doesn't tell us anything 3704 // about how the sequences rank. 3705 ; 3706 else if (T2.isMoreQualifiedThan(T1)) { 3707 // T1 has fewer qualifiers, so it could be the better sequence. 3708 if (Result == ImplicitConversionSequence::Worse) 3709 // Neither has qualifiers that are a subset of the other's 3710 // qualifiers. 3711 return ImplicitConversionSequence::Indistinguishable; 3712 3713 Result = ImplicitConversionSequence::Better; 3714 } else if (T1.isMoreQualifiedThan(T2)) { 3715 // T2 has fewer qualifiers, so it could be the better sequence. 3716 if (Result == ImplicitConversionSequence::Better) 3717 // Neither has qualifiers that are a subset of the other's 3718 // qualifiers. 3719 return ImplicitConversionSequence::Indistinguishable; 3720 3721 Result = ImplicitConversionSequence::Worse; 3722 } else { 3723 // Qualifiers are disjoint. 3724 return ImplicitConversionSequence::Indistinguishable; 3725 } 3726 3727 // If the types after this point are equivalent, we're done. 3728 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3729 break; 3730 } 3731 3732 // Check that the winning standard conversion sequence isn't using 3733 // the deprecated string literal array to pointer conversion. 3734 switch (Result) { 3735 case ImplicitConversionSequence::Better: 3736 if (SCS1.DeprecatedStringLiteralToCharPtr) 3737 Result = ImplicitConversionSequence::Indistinguishable; 3738 break; 3739 3740 case ImplicitConversionSequence::Indistinguishable: 3741 break; 3742 3743 case ImplicitConversionSequence::Worse: 3744 if (SCS2.DeprecatedStringLiteralToCharPtr) 3745 Result = ImplicitConversionSequence::Indistinguishable; 3746 break; 3747 } 3748 3749 return Result; 3750 } 3751 3752 /// CompareDerivedToBaseConversions - Compares two standard conversion 3753 /// sequences to determine whether they can be ranked based on their 3754 /// various kinds of derived-to-base conversions (C++ 3755 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3756 /// conversions between Objective-C interface types. 3757 static ImplicitConversionSequence::CompareKind 3758 CompareDerivedToBaseConversions(Sema &S, 3759 const StandardConversionSequence& SCS1, 3760 const StandardConversionSequence& SCS2) { 3761 QualType FromType1 = SCS1.getFromType(); 3762 QualType ToType1 = SCS1.getToType(1); 3763 QualType FromType2 = SCS2.getFromType(); 3764 QualType ToType2 = SCS2.getToType(1); 3765 3766 // Adjust the types we're converting from via the array-to-pointer 3767 // conversion, if we need to. 3768 if (SCS1.First == ICK_Array_To_Pointer) 3769 FromType1 = S.Context.getArrayDecayedType(FromType1); 3770 if (SCS2.First == ICK_Array_To_Pointer) 3771 FromType2 = S.Context.getArrayDecayedType(FromType2); 3772 3773 // Canonicalize all of the types. 3774 FromType1 = S.Context.getCanonicalType(FromType1); 3775 ToType1 = S.Context.getCanonicalType(ToType1); 3776 FromType2 = S.Context.getCanonicalType(FromType2); 3777 ToType2 = S.Context.getCanonicalType(ToType2); 3778 3779 // C++ [over.ics.rank]p4b3: 3780 // 3781 // If class B is derived directly or indirectly from class A and 3782 // class C is derived directly or indirectly from B, 3783 // 3784 // Compare based on pointer conversions. 3785 if (SCS1.Second == ICK_Pointer_Conversion && 3786 SCS2.Second == ICK_Pointer_Conversion && 3787 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3788 FromType1->isPointerType() && FromType2->isPointerType() && 3789 ToType1->isPointerType() && ToType2->isPointerType()) { 3790 QualType FromPointee1 3791 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3792 QualType ToPointee1 3793 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3794 QualType FromPointee2 3795 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3796 QualType ToPointee2 3797 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3798 3799 // -- conversion of C* to B* is better than conversion of C* to A*, 3800 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3801 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3802 return ImplicitConversionSequence::Better; 3803 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3804 return ImplicitConversionSequence::Worse; 3805 } 3806 3807 // -- conversion of B* to A* is better than conversion of C* to A*, 3808 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3809 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3810 return ImplicitConversionSequence::Better; 3811 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3812 return ImplicitConversionSequence::Worse; 3813 } 3814 } else if (SCS1.Second == ICK_Pointer_Conversion && 3815 SCS2.Second == ICK_Pointer_Conversion) { 3816 const ObjCObjectPointerType *FromPtr1 3817 = FromType1->getAs<ObjCObjectPointerType>(); 3818 const ObjCObjectPointerType *FromPtr2 3819 = FromType2->getAs<ObjCObjectPointerType>(); 3820 const ObjCObjectPointerType *ToPtr1 3821 = ToType1->getAs<ObjCObjectPointerType>(); 3822 const ObjCObjectPointerType *ToPtr2 3823 = ToType2->getAs<ObjCObjectPointerType>(); 3824 3825 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3826 // Apply the same conversion ranking rules for Objective-C pointer types 3827 // that we do for C++ pointers to class types. However, we employ the 3828 // Objective-C pseudo-subtyping relationship used for assignment of 3829 // Objective-C pointer types. 3830 bool FromAssignLeft 3831 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3832 bool FromAssignRight 3833 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3834 bool ToAssignLeft 3835 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3836 bool ToAssignRight 3837 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3838 3839 // A conversion to an a non-id object pointer type or qualified 'id' 3840 // type is better than a conversion to 'id'. 3841 if (ToPtr1->isObjCIdType() && 3842 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3843 return ImplicitConversionSequence::Worse; 3844 if (ToPtr2->isObjCIdType() && 3845 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3846 return ImplicitConversionSequence::Better; 3847 3848 // A conversion to a non-id object pointer type is better than a 3849 // conversion to a qualified 'id' type 3850 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3851 return ImplicitConversionSequence::Worse; 3852 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3853 return ImplicitConversionSequence::Better; 3854 3855 // A conversion to an a non-Class object pointer type or qualified 'Class' 3856 // type is better than a conversion to 'Class'. 3857 if (ToPtr1->isObjCClassType() && 3858 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3859 return ImplicitConversionSequence::Worse; 3860 if (ToPtr2->isObjCClassType() && 3861 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3862 return ImplicitConversionSequence::Better; 3863 3864 // A conversion to a non-Class object pointer type is better than a 3865 // conversion to a qualified 'Class' type. 3866 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3867 return ImplicitConversionSequence::Worse; 3868 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3869 return ImplicitConversionSequence::Better; 3870 3871 // -- "conversion of C* to B* is better than conversion of C* to A*," 3872 if (S.Context.hasSameType(FromType1, FromType2) && 3873 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3874 (ToAssignLeft != ToAssignRight)) 3875 return ToAssignLeft? ImplicitConversionSequence::Worse 3876 : ImplicitConversionSequence::Better; 3877 3878 // -- "conversion of B* to A* is better than conversion of C* to A*," 3879 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3880 (FromAssignLeft != FromAssignRight)) 3881 return FromAssignLeft? ImplicitConversionSequence::Better 3882 : ImplicitConversionSequence::Worse; 3883 } 3884 } 3885 3886 // Ranking of member-pointer types. 3887 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3888 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3889 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3890 const MemberPointerType * FromMemPointer1 = 3891 FromType1->getAs<MemberPointerType>(); 3892 const MemberPointerType * ToMemPointer1 = 3893 ToType1->getAs<MemberPointerType>(); 3894 const MemberPointerType * FromMemPointer2 = 3895 FromType2->getAs<MemberPointerType>(); 3896 const MemberPointerType * ToMemPointer2 = 3897 ToType2->getAs<MemberPointerType>(); 3898 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3899 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3900 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3901 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3902 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3903 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3904 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3905 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3906 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3907 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3908 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3909 return ImplicitConversionSequence::Worse; 3910 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3911 return ImplicitConversionSequence::Better; 3912 } 3913 // conversion of B::* to C::* is better than conversion of A::* to C::* 3914 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3915 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3916 return ImplicitConversionSequence::Better; 3917 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3918 return ImplicitConversionSequence::Worse; 3919 } 3920 } 3921 3922 if (SCS1.Second == ICK_Derived_To_Base) { 3923 // -- conversion of C to B is better than conversion of C to A, 3924 // -- binding of an expression of type C to a reference of type 3925 // B& is better than binding an expression of type C to a 3926 // reference of type A&, 3927 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3928 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3929 if (S.IsDerivedFrom(ToType1, ToType2)) 3930 return ImplicitConversionSequence::Better; 3931 else if (S.IsDerivedFrom(ToType2, ToType1)) 3932 return ImplicitConversionSequence::Worse; 3933 } 3934 3935 // -- conversion of B to A is better than conversion of C to A. 3936 // -- binding of an expression of type B to a reference of type 3937 // A& is better than binding an expression of type C to a 3938 // reference of type A&, 3939 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3940 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3941 if (S.IsDerivedFrom(FromType2, FromType1)) 3942 return ImplicitConversionSequence::Better; 3943 else if (S.IsDerivedFrom(FromType1, FromType2)) 3944 return ImplicitConversionSequence::Worse; 3945 } 3946 } 3947 3948 return ImplicitConversionSequence::Indistinguishable; 3949 } 3950 3951 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3952 /// C++ class. 3953 static bool isTypeValid(QualType T) { 3954 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3955 return !Record->isInvalidDecl(); 3956 3957 return true; 3958 } 3959 3960 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3961 /// determine whether they are reference-related, 3962 /// reference-compatible, reference-compatible with added 3963 /// qualification, or incompatible, for use in C++ initialization by 3964 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3965 /// type, and the first type (T1) is the pointee type of the reference 3966 /// type being initialized. 3967 Sema::ReferenceCompareResult 3968 Sema::CompareReferenceRelationship(SourceLocation Loc, 3969 QualType OrigT1, QualType OrigT2, 3970 bool &DerivedToBase, 3971 bool &ObjCConversion, 3972 bool &ObjCLifetimeConversion) { 3973 assert(!OrigT1->isReferenceType() && 3974 "T1 must be the pointee type of the reference type"); 3975 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3976 3977 QualType T1 = Context.getCanonicalType(OrigT1); 3978 QualType T2 = Context.getCanonicalType(OrigT2); 3979 Qualifiers T1Quals, T2Quals; 3980 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3981 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3982 3983 // C++ [dcl.init.ref]p4: 3984 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3985 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3986 // T1 is a base class of T2. 3987 DerivedToBase = false; 3988 ObjCConversion = false; 3989 ObjCLifetimeConversion = false; 3990 if (UnqualT1 == UnqualT2) { 3991 // Nothing to do. 3992 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3993 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3994 IsDerivedFrom(UnqualT2, UnqualT1)) 3995 DerivedToBase = true; 3996 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3997 UnqualT2->isObjCObjectOrInterfaceType() && 3998 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3999 ObjCConversion = true; 4000 else 4001 return Ref_Incompatible; 4002 4003 // At this point, we know that T1 and T2 are reference-related (at 4004 // least). 4005 4006 // If the type is an array type, promote the element qualifiers to the type 4007 // for comparison. 4008 if (isa<ArrayType>(T1) && T1Quals) 4009 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4010 if (isa<ArrayType>(T2) && T2Quals) 4011 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4012 4013 // C++ [dcl.init.ref]p4: 4014 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4015 // reference-related to T2 and cv1 is the same cv-qualification 4016 // as, or greater cv-qualification than, cv2. For purposes of 4017 // overload resolution, cases for which cv1 is greater 4018 // cv-qualification than cv2 are identified as 4019 // reference-compatible with added qualification (see 13.3.3.2). 4020 // 4021 // Note that we also require equivalence of Objective-C GC and address-space 4022 // qualifiers when performing these computations, so that e.g., an int in 4023 // address space 1 is not reference-compatible with an int in address 4024 // space 2. 4025 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4026 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4027 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4028 ObjCLifetimeConversion = true; 4029 4030 T1Quals.removeObjCLifetime(); 4031 T2Quals.removeObjCLifetime(); 4032 } 4033 4034 if (T1Quals == T2Quals) 4035 return Ref_Compatible; 4036 else if (T1Quals.compatiblyIncludes(T2Quals)) 4037 return Ref_Compatible_With_Added_Qualification; 4038 else 4039 return Ref_Related; 4040 } 4041 4042 /// \brief Look for a user-defined conversion to an value reference-compatible 4043 /// with DeclType. Return true if something definite is found. 4044 static bool 4045 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4046 QualType DeclType, SourceLocation DeclLoc, 4047 Expr *Init, QualType T2, bool AllowRvalues, 4048 bool AllowExplicit) { 4049 assert(T2->isRecordType() && "Can only find conversions of record types."); 4050 CXXRecordDecl *T2RecordDecl 4051 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4052 4053 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4054 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4055 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4056 NamedDecl *D = *I; 4057 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4058 if (isa<UsingShadowDecl>(D)) 4059 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4060 4061 FunctionTemplateDecl *ConvTemplate 4062 = dyn_cast<FunctionTemplateDecl>(D); 4063 CXXConversionDecl *Conv; 4064 if (ConvTemplate) 4065 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4066 else 4067 Conv = cast<CXXConversionDecl>(D); 4068 4069 // If this is an explicit conversion, and we're not allowed to consider 4070 // explicit conversions, skip it. 4071 if (!AllowExplicit && Conv->isExplicit()) 4072 continue; 4073 4074 if (AllowRvalues) { 4075 bool DerivedToBase = false; 4076 bool ObjCConversion = false; 4077 bool ObjCLifetimeConversion = false; 4078 4079 // If we are initializing an rvalue reference, don't permit conversion 4080 // functions that return lvalues. 4081 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4082 const ReferenceType *RefType 4083 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4084 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4085 continue; 4086 } 4087 4088 if (!ConvTemplate && 4089 S.CompareReferenceRelationship( 4090 DeclLoc, 4091 Conv->getConversionType().getNonReferenceType() 4092 .getUnqualifiedType(), 4093 DeclType.getNonReferenceType().getUnqualifiedType(), 4094 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4095 Sema::Ref_Incompatible) 4096 continue; 4097 } else { 4098 // If the conversion function doesn't return a reference type, 4099 // it can't be considered for this conversion. An rvalue reference 4100 // is only acceptable if its referencee is a function type. 4101 4102 const ReferenceType *RefType = 4103 Conv->getConversionType()->getAs<ReferenceType>(); 4104 if (!RefType || 4105 (!RefType->isLValueReferenceType() && 4106 !RefType->getPointeeType()->isFunctionType())) 4107 continue; 4108 } 4109 4110 if (ConvTemplate) 4111 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4112 Init, DeclType, CandidateSet, 4113 /*AllowObjCConversionOnExplicit=*/false); 4114 else 4115 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4116 DeclType, CandidateSet, 4117 /*AllowObjCConversionOnExplicit=*/false); 4118 } 4119 4120 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4121 4122 OverloadCandidateSet::iterator Best; 4123 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4124 case OR_Success: 4125 // C++ [over.ics.ref]p1: 4126 // 4127 // [...] If the parameter binds directly to the result of 4128 // applying a conversion function to the argument 4129 // expression, the implicit conversion sequence is a 4130 // user-defined conversion sequence (13.3.3.1.2), with the 4131 // second standard conversion sequence either an identity 4132 // conversion or, if the conversion function returns an 4133 // entity of a type that is a derived class of the parameter 4134 // type, a derived-to-base Conversion. 4135 if (!Best->FinalConversion.DirectBinding) 4136 return false; 4137 4138 ICS.setUserDefined(); 4139 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4140 ICS.UserDefined.After = Best->FinalConversion; 4141 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4142 ICS.UserDefined.ConversionFunction = Best->Function; 4143 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4144 ICS.UserDefined.EllipsisConversion = false; 4145 assert(ICS.UserDefined.After.ReferenceBinding && 4146 ICS.UserDefined.After.DirectBinding && 4147 "Expected a direct reference binding!"); 4148 return true; 4149 4150 case OR_Ambiguous: 4151 ICS.setAmbiguous(); 4152 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4153 Cand != CandidateSet.end(); ++Cand) 4154 if (Cand->Viable) 4155 ICS.Ambiguous.addConversion(Cand->Function); 4156 return true; 4157 4158 case OR_No_Viable_Function: 4159 case OR_Deleted: 4160 // There was no suitable conversion, or we found a deleted 4161 // conversion; continue with other checks. 4162 return false; 4163 } 4164 4165 llvm_unreachable("Invalid OverloadResult!"); 4166 } 4167 4168 /// \brief Compute an implicit conversion sequence for reference 4169 /// initialization. 4170 static ImplicitConversionSequence 4171 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4172 SourceLocation DeclLoc, 4173 bool SuppressUserConversions, 4174 bool AllowExplicit) { 4175 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4176 4177 // Most paths end in a failed conversion. 4178 ImplicitConversionSequence ICS; 4179 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4180 4181 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4182 QualType T2 = Init->getType(); 4183 4184 // If the initializer is the address of an overloaded function, try 4185 // to resolve the overloaded function. If all goes well, T2 is the 4186 // type of the resulting function. 4187 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4188 DeclAccessPair Found; 4189 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4190 false, Found)) 4191 T2 = Fn->getType(); 4192 } 4193 4194 // Compute some basic properties of the types and the initializer. 4195 bool isRValRef = DeclType->isRValueReferenceType(); 4196 bool DerivedToBase = false; 4197 bool ObjCConversion = false; 4198 bool ObjCLifetimeConversion = false; 4199 Expr::Classification InitCategory = Init->Classify(S.Context); 4200 Sema::ReferenceCompareResult RefRelationship 4201 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4202 ObjCConversion, ObjCLifetimeConversion); 4203 4204 4205 // C++0x [dcl.init.ref]p5: 4206 // A reference to type "cv1 T1" is initialized by an expression 4207 // of type "cv2 T2" as follows: 4208 4209 // -- If reference is an lvalue reference and the initializer expression 4210 if (!isRValRef) { 4211 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4212 // reference-compatible with "cv2 T2," or 4213 // 4214 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4215 if (InitCategory.isLValue() && 4216 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4217 // C++ [over.ics.ref]p1: 4218 // When a parameter of reference type binds directly (8.5.3) 4219 // to an argument expression, the implicit conversion sequence 4220 // is the identity conversion, unless the argument expression 4221 // has a type that is a derived class of the parameter type, 4222 // in which case the implicit conversion sequence is a 4223 // derived-to-base Conversion (13.3.3.1). 4224 ICS.setStandard(); 4225 ICS.Standard.First = ICK_Identity; 4226 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4227 : ObjCConversion? ICK_Compatible_Conversion 4228 : ICK_Identity; 4229 ICS.Standard.Third = ICK_Identity; 4230 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4231 ICS.Standard.setToType(0, T2); 4232 ICS.Standard.setToType(1, T1); 4233 ICS.Standard.setToType(2, T1); 4234 ICS.Standard.ReferenceBinding = true; 4235 ICS.Standard.DirectBinding = true; 4236 ICS.Standard.IsLvalueReference = !isRValRef; 4237 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4238 ICS.Standard.BindsToRvalue = false; 4239 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4240 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4241 ICS.Standard.CopyConstructor = nullptr; 4242 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4243 4244 // Nothing more to do: the inaccessibility/ambiguity check for 4245 // derived-to-base conversions is suppressed when we're 4246 // computing the implicit conversion sequence (C++ 4247 // [over.best.ics]p2). 4248 return ICS; 4249 } 4250 4251 // -- has a class type (i.e., T2 is a class type), where T1 is 4252 // not reference-related to T2, and can be implicitly 4253 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4254 // is reference-compatible with "cv3 T3" 92) (this 4255 // conversion is selected by enumerating the applicable 4256 // conversion functions (13.3.1.6) and choosing the best 4257 // one through overload resolution (13.3)), 4258 if (!SuppressUserConversions && T2->isRecordType() && 4259 !S.RequireCompleteType(DeclLoc, T2, 0) && 4260 RefRelationship == Sema::Ref_Incompatible) { 4261 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4262 Init, T2, /*AllowRvalues=*/false, 4263 AllowExplicit)) 4264 return ICS; 4265 } 4266 } 4267 4268 // -- Otherwise, the reference shall be an lvalue reference to a 4269 // non-volatile const type (i.e., cv1 shall be const), or the reference 4270 // shall be an rvalue reference. 4271 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4272 return ICS; 4273 4274 // -- If the initializer expression 4275 // 4276 // -- is an xvalue, class prvalue, array prvalue or function 4277 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4278 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4279 (InitCategory.isXValue() || 4280 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4281 (InitCategory.isLValue() && T2->isFunctionType()))) { 4282 ICS.setStandard(); 4283 ICS.Standard.First = ICK_Identity; 4284 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4285 : ObjCConversion? ICK_Compatible_Conversion 4286 : ICK_Identity; 4287 ICS.Standard.Third = ICK_Identity; 4288 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4289 ICS.Standard.setToType(0, T2); 4290 ICS.Standard.setToType(1, T1); 4291 ICS.Standard.setToType(2, T1); 4292 ICS.Standard.ReferenceBinding = true; 4293 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4294 // binding unless we're binding to a class prvalue. 4295 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4296 // allow the use of rvalue references in C++98/03 for the benefit of 4297 // standard library implementors; therefore, we need the xvalue check here. 4298 ICS.Standard.DirectBinding = 4299 S.getLangOpts().CPlusPlus11 || 4300 !(InitCategory.isPRValue() || T2->isRecordType()); 4301 ICS.Standard.IsLvalueReference = !isRValRef; 4302 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4303 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4304 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4305 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4306 ICS.Standard.CopyConstructor = nullptr; 4307 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4308 return ICS; 4309 } 4310 4311 // -- has a class type (i.e., T2 is a class type), where T1 is not 4312 // reference-related to T2, and can be implicitly converted to 4313 // an xvalue, class prvalue, or function lvalue of type 4314 // "cv3 T3", where "cv1 T1" is reference-compatible with 4315 // "cv3 T3", 4316 // 4317 // then the reference is bound to the value of the initializer 4318 // expression in the first case and to the result of the conversion 4319 // in the second case (or, in either case, to an appropriate base 4320 // class subobject). 4321 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4322 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4323 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4324 Init, T2, /*AllowRvalues=*/true, 4325 AllowExplicit)) { 4326 // In the second case, if the reference is an rvalue reference 4327 // and the second standard conversion sequence of the 4328 // user-defined conversion sequence includes an lvalue-to-rvalue 4329 // conversion, the program is ill-formed. 4330 if (ICS.isUserDefined() && isRValRef && 4331 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4332 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4333 4334 return ICS; 4335 } 4336 4337 // A temporary of function type cannot be created; don't even try. 4338 if (T1->isFunctionType()) 4339 return ICS; 4340 4341 // -- Otherwise, a temporary of type "cv1 T1" is created and 4342 // initialized from the initializer expression using the 4343 // rules for a non-reference copy initialization (8.5). The 4344 // reference is then bound to the temporary. If T1 is 4345 // reference-related to T2, cv1 must be the same 4346 // cv-qualification as, or greater cv-qualification than, 4347 // cv2; otherwise, the program is ill-formed. 4348 if (RefRelationship == Sema::Ref_Related) { 4349 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4350 // we would be reference-compatible or reference-compatible with 4351 // added qualification. But that wasn't the case, so the reference 4352 // initialization fails. 4353 // 4354 // Note that we only want to check address spaces and cvr-qualifiers here. 4355 // ObjC GC and lifetime qualifiers aren't important. 4356 Qualifiers T1Quals = T1.getQualifiers(); 4357 Qualifiers T2Quals = T2.getQualifiers(); 4358 T1Quals.removeObjCGCAttr(); 4359 T1Quals.removeObjCLifetime(); 4360 T2Quals.removeObjCGCAttr(); 4361 T2Quals.removeObjCLifetime(); 4362 if (!T1Quals.compatiblyIncludes(T2Quals)) 4363 return ICS; 4364 } 4365 4366 // If at least one of the types is a class type, the types are not 4367 // related, and we aren't allowed any user conversions, the 4368 // reference binding fails. This case is important for breaking 4369 // recursion, since TryImplicitConversion below will attempt to 4370 // create a temporary through the use of a copy constructor. 4371 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4372 (T1->isRecordType() || T2->isRecordType())) 4373 return ICS; 4374 4375 // If T1 is reference-related to T2 and the reference is an rvalue 4376 // reference, the initializer expression shall not be an lvalue. 4377 if (RefRelationship >= Sema::Ref_Related && 4378 isRValRef && Init->Classify(S.Context).isLValue()) 4379 return ICS; 4380 4381 // C++ [over.ics.ref]p2: 4382 // When a parameter of reference type is not bound directly to 4383 // an argument expression, the conversion sequence is the one 4384 // required to convert the argument expression to the 4385 // underlying type of the reference according to 4386 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4387 // to copy-initializing a temporary of the underlying type with 4388 // the argument expression. Any difference in top-level 4389 // cv-qualification is subsumed by the initialization itself 4390 // and does not constitute a conversion. 4391 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4392 /*AllowExplicit=*/false, 4393 /*InOverloadResolution=*/false, 4394 /*CStyle=*/false, 4395 /*AllowObjCWritebackConversion=*/false, 4396 /*AllowObjCConversionOnExplicit=*/false); 4397 4398 // Of course, that's still a reference binding. 4399 if (ICS.isStandard()) { 4400 ICS.Standard.ReferenceBinding = true; 4401 ICS.Standard.IsLvalueReference = !isRValRef; 4402 ICS.Standard.BindsToFunctionLvalue = false; 4403 ICS.Standard.BindsToRvalue = true; 4404 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4405 ICS.Standard.ObjCLifetimeConversionBinding = false; 4406 } else if (ICS.isUserDefined()) { 4407 const ReferenceType *LValRefType = 4408 ICS.UserDefined.ConversionFunction->getReturnType() 4409 ->getAs<LValueReferenceType>(); 4410 4411 // C++ [over.ics.ref]p3: 4412 // Except for an implicit object parameter, for which see 13.3.1, a 4413 // standard conversion sequence cannot be formed if it requires [...] 4414 // binding an rvalue reference to an lvalue other than a function 4415 // lvalue. 4416 // Note that the function case is not possible here. 4417 if (DeclType->isRValueReferenceType() && LValRefType) { 4418 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4419 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4420 // reference to an rvalue! 4421 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4422 return ICS; 4423 } 4424 4425 ICS.UserDefined.Before.setAsIdentityConversion(); 4426 ICS.UserDefined.After.ReferenceBinding = true; 4427 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4428 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4429 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4430 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4431 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4432 } 4433 4434 return ICS; 4435 } 4436 4437 static ImplicitConversionSequence 4438 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4439 bool SuppressUserConversions, 4440 bool InOverloadResolution, 4441 bool AllowObjCWritebackConversion, 4442 bool AllowExplicit = false); 4443 4444 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4445 /// initializer list From. 4446 static ImplicitConversionSequence 4447 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4448 bool SuppressUserConversions, 4449 bool InOverloadResolution, 4450 bool AllowObjCWritebackConversion) { 4451 // C++11 [over.ics.list]p1: 4452 // When an argument is an initializer list, it is not an expression and 4453 // special rules apply for converting it to a parameter type. 4454 4455 ImplicitConversionSequence Result; 4456 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4457 4458 // We need a complete type for what follows. Incomplete types can never be 4459 // initialized from init lists. 4460 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4461 return Result; 4462 4463 // Per DR1467: 4464 // If the parameter type is a class X and the initializer list has a single 4465 // element of type cv U, where U is X or a class derived from X, the 4466 // implicit conversion sequence is the one required to convert the element 4467 // to the parameter type. 4468 // 4469 // Otherwise, if the parameter type is a character array [... ] 4470 // and the initializer list has a single element that is an 4471 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4472 // implicit conversion sequence is the identity conversion. 4473 if (From->getNumInits() == 1) { 4474 if (ToType->isRecordType()) { 4475 QualType InitType = From->getInit(0)->getType(); 4476 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4477 S.IsDerivedFrom(InitType, ToType)) 4478 return TryCopyInitialization(S, From->getInit(0), ToType, 4479 SuppressUserConversions, 4480 InOverloadResolution, 4481 AllowObjCWritebackConversion); 4482 } 4483 // FIXME: Check the other conditions here: array of character type, 4484 // initializer is a string literal. 4485 if (ToType->isArrayType()) { 4486 InitializedEntity Entity = 4487 InitializedEntity::InitializeParameter(S.Context, ToType, 4488 /*Consumed=*/false); 4489 if (S.CanPerformCopyInitialization(Entity, From)) { 4490 Result.setStandard(); 4491 Result.Standard.setAsIdentityConversion(); 4492 Result.Standard.setFromType(ToType); 4493 Result.Standard.setAllToTypes(ToType); 4494 return Result; 4495 } 4496 } 4497 } 4498 4499 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4500 // C++11 [over.ics.list]p2: 4501 // If the parameter type is std::initializer_list<X> or "array of X" and 4502 // all the elements can be implicitly converted to X, the implicit 4503 // conversion sequence is the worst conversion necessary to convert an 4504 // element of the list to X. 4505 // 4506 // C++14 [over.ics.list]p3: 4507 // Otherwise, if the parameter type is "array of N X", if the initializer 4508 // list has exactly N elements or if it has fewer than N elements and X is 4509 // default-constructible, and if all the elements of the initializer list 4510 // can be implicitly converted to X, the implicit conversion sequence is 4511 // the worst conversion necessary to convert an element of the list to X. 4512 // 4513 // FIXME: We're missing a lot of these checks. 4514 bool toStdInitializerList = false; 4515 QualType X; 4516 if (ToType->isArrayType()) 4517 X = S.Context.getAsArrayType(ToType)->getElementType(); 4518 else 4519 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4520 if (!X.isNull()) { 4521 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4522 Expr *Init = From->getInit(i); 4523 ImplicitConversionSequence ICS = 4524 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4525 InOverloadResolution, 4526 AllowObjCWritebackConversion); 4527 // If a single element isn't convertible, fail. 4528 if (ICS.isBad()) { 4529 Result = ICS; 4530 break; 4531 } 4532 // Otherwise, look for the worst conversion. 4533 if (Result.isBad() || 4534 CompareImplicitConversionSequences(S, ICS, Result) == 4535 ImplicitConversionSequence::Worse) 4536 Result = ICS; 4537 } 4538 4539 // For an empty list, we won't have computed any conversion sequence. 4540 // Introduce the identity conversion sequence. 4541 if (From->getNumInits() == 0) { 4542 Result.setStandard(); 4543 Result.Standard.setAsIdentityConversion(); 4544 Result.Standard.setFromType(ToType); 4545 Result.Standard.setAllToTypes(ToType); 4546 } 4547 4548 Result.setStdInitializerListElement(toStdInitializerList); 4549 return Result; 4550 } 4551 4552 // C++14 [over.ics.list]p4: 4553 // C++11 [over.ics.list]p3: 4554 // Otherwise, if the parameter is a non-aggregate class X and overload 4555 // resolution chooses a single best constructor [...] the implicit 4556 // conversion sequence is a user-defined conversion sequence. If multiple 4557 // constructors are viable but none is better than the others, the 4558 // implicit conversion sequence is a user-defined conversion sequence. 4559 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4560 // This function can deal with initializer lists. 4561 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4562 /*AllowExplicit=*/false, 4563 InOverloadResolution, /*CStyle=*/false, 4564 AllowObjCWritebackConversion, 4565 /*AllowObjCConversionOnExplicit=*/false); 4566 } 4567 4568 // C++14 [over.ics.list]p5: 4569 // C++11 [over.ics.list]p4: 4570 // Otherwise, if the parameter has an aggregate type which can be 4571 // initialized from the initializer list [...] the implicit conversion 4572 // sequence is a user-defined conversion sequence. 4573 if (ToType->isAggregateType()) { 4574 // Type is an aggregate, argument is an init list. At this point it comes 4575 // down to checking whether the initialization works. 4576 // FIXME: Find out whether this parameter is consumed or not. 4577 InitializedEntity Entity = 4578 InitializedEntity::InitializeParameter(S.Context, ToType, 4579 /*Consumed=*/false); 4580 if (S.CanPerformCopyInitialization(Entity, From)) { 4581 Result.setUserDefined(); 4582 Result.UserDefined.Before.setAsIdentityConversion(); 4583 // Initializer lists don't have a type. 4584 Result.UserDefined.Before.setFromType(QualType()); 4585 Result.UserDefined.Before.setAllToTypes(QualType()); 4586 4587 Result.UserDefined.After.setAsIdentityConversion(); 4588 Result.UserDefined.After.setFromType(ToType); 4589 Result.UserDefined.After.setAllToTypes(ToType); 4590 Result.UserDefined.ConversionFunction = nullptr; 4591 } 4592 return Result; 4593 } 4594 4595 // C++14 [over.ics.list]p6: 4596 // C++11 [over.ics.list]p5: 4597 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4598 if (ToType->isReferenceType()) { 4599 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4600 // mention initializer lists in any way. So we go by what list- 4601 // initialization would do and try to extrapolate from that. 4602 4603 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4604 4605 // If the initializer list has a single element that is reference-related 4606 // to the parameter type, we initialize the reference from that. 4607 if (From->getNumInits() == 1) { 4608 Expr *Init = From->getInit(0); 4609 4610 QualType T2 = Init->getType(); 4611 4612 // If the initializer is the address of an overloaded function, try 4613 // to resolve the overloaded function. If all goes well, T2 is the 4614 // type of the resulting function. 4615 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4616 DeclAccessPair Found; 4617 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4618 Init, ToType, false, Found)) 4619 T2 = Fn->getType(); 4620 } 4621 4622 // Compute some basic properties of the types and the initializer. 4623 bool dummy1 = false; 4624 bool dummy2 = false; 4625 bool dummy3 = false; 4626 Sema::ReferenceCompareResult RefRelationship 4627 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4628 dummy2, dummy3); 4629 4630 if (RefRelationship >= Sema::Ref_Related) { 4631 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4632 SuppressUserConversions, 4633 /*AllowExplicit=*/false); 4634 } 4635 } 4636 4637 // Otherwise, we bind the reference to a temporary created from the 4638 // initializer list. 4639 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4640 InOverloadResolution, 4641 AllowObjCWritebackConversion); 4642 if (Result.isFailure()) 4643 return Result; 4644 assert(!Result.isEllipsis() && 4645 "Sub-initialization cannot result in ellipsis conversion."); 4646 4647 // Can we even bind to a temporary? 4648 if (ToType->isRValueReferenceType() || 4649 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4650 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4651 Result.UserDefined.After; 4652 SCS.ReferenceBinding = true; 4653 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4654 SCS.BindsToRvalue = true; 4655 SCS.BindsToFunctionLvalue = false; 4656 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4657 SCS.ObjCLifetimeConversionBinding = false; 4658 } else 4659 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4660 From, ToType); 4661 return Result; 4662 } 4663 4664 // C++14 [over.ics.list]p7: 4665 // C++11 [over.ics.list]p6: 4666 // Otherwise, if the parameter type is not a class: 4667 if (!ToType->isRecordType()) { 4668 // - if the initializer list has one element that is not itself an 4669 // initializer list, the implicit conversion sequence is the one 4670 // required to convert the element to the parameter type. 4671 unsigned NumInits = From->getNumInits(); 4672 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4673 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4674 SuppressUserConversions, 4675 InOverloadResolution, 4676 AllowObjCWritebackConversion); 4677 // - if the initializer list has no elements, the implicit conversion 4678 // sequence is the identity conversion. 4679 else if (NumInits == 0) { 4680 Result.setStandard(); 4681 Result.Standard.setAsIdentityConversion(); 4682 Result.Standard.setFromType(ToType); 4683 Result.Standard.setAllToTypes(ToType); 4684 } 4685 return Result; 4686 } 4687 4688 // C++14 [over.ics.list]p8: 4689 // C++11 [over.ics.list]p7: 4690 // In all cases other than those enumerated above, no conversion is possible 4691 return Result; 4692 } 4693 4694 /// TryCopyInitialization - Try to copy-initialize a value of type 4695 /// ToType from the expression From. Return the implicit conversion 4696 /// sequence required to pass this argument, which may be a bad 4697 /// conversion sequence (meaning that the argument cannot be passed to 4698 /// a parameter of this type). If @p SuppressUserConversions, then we 4699 /// do not permit any user-defined conversion sequences. 4700 static ImplicitConversionSequence 4701 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4702 bool SuppressUserConversions, 4703 bool InOverloadResolution, 4704 bool AllowObjCWritebackConversion, 4705 bool AllowExplicit) { 4706 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4707 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4708 InOverloadResolution,AllowObjCWritebackConversion); 4709 4710 if (ToType->isReferenceType()) 4711 return TryReferenceInit(S, From, ToType, 4712 /*FIXME:*/From->getLocStart(), 4713 SuppressUserConversions, 4714 AllowExplicit); 4715 4716 return TryImplicitConversion(S, From, ToType, 4717 SuppressUserConversions, 4718 /*AllowExplicit=*/false, 4719 InOverloadResolution, 4720 /*CStyle=*/false, 4721 AllowObjCWritebackConversion, 4722 /*AllowObjCConversionOnExplicit=*/false); 4723 } 4724 4725 static bool TryCopyInitialization(const CanQualType FromQTy, 4726 const CanQualType ToQTy, 4727 Sema &S, 4728 SourceLocation Loc, 4729 ExprValueKind FromVK) { 4730 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4731 ImplicitConversionSequence ICS = 4732 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4733 4734 return !ICS.isBad(); 4735 } 4736 4737 /// TryObjectArgumentInitialization - Try to initialize the object 4738 /// parameter of the given member function (@c Method) from the 4739 /// expression @p From. 4740 static ImplicitConversionSequence 4741 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4742 Expr::Classification FromClassification, 4743 CXXMethodDecl *Method, 4744 CXXRecordDecl *ActingContext) { 4745 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4746 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4747 // const volatile object. 4748 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4749 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4750 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4751 4752 // Set up the conversion sequence as a "bad" conversion, to allow us 4753 // to exit early. 4754 ImplicitConversionSequence ICS; 4755 4756 // We need to have an object of class type. 4757 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4758 FromType = PT->getPointeeType(); 4759 4760 // When we had a pointer, it's implicitly dereferenced, so we 4761 // better have an lvalue. 4762 assert(FromClassification.isLValue()); 4763 } 4764 4765 assert(FromType->isRecordType()); 4766 4767 // C++0x [over.match.funcs]p4: 4768 // For non-static member functions, the type of the implicit object 4769 // parameter is 4770 // 4771 // - "lvalue reference to cv X" for functions declared without a 4772 // ref-qualifier or with the & ref-qualifier 4773 // - "rvalue reference to cv X" for functions declared with the && 4774 // ref-qualifier 4775 // 4776 // where X is the class of which the function is a member and cv is the 4777 // cv-qualification on the member function declaration. 4778 // 4779 // However, when finding an implicit conversion sequence for the argument, we 4780 // are not allowed to create temporaries or perform user-defined conversions 4781 // (C++ [over.match.funcs]p5). We perform a simplified version of 4782 // reference binding here, that allows class rvalues to bind to 4783 // non-constant references. 4784 4785 // First check the qualifiers. 4786 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4787 if (ImplicitParamType.getCVRQualifiers() 4788 != FromTypeCanon.getLocalCVRQualifiers() && 4789 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4790 ICS.setBad(BadConversionSequence::bad_qualifiers, 4791 FromType, ImplicitParamType); 4792 return ICS; 4793 } 4794 4795 // Check that we have either the same type or a derived type. It 4796 // affects the conversion rank. 4797 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4798 ImplicitConversionKind SecondKind; 4799 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4800 SecondKind = ICK_Identity; 4801 } else if (S.IsDerivedFrom(FromType, ClassType)) 4802 SecondKind = ICK_Derived_To_Base; 4803 else { 4804 ICS.setBad(BadConversionSequence::unrelated_class, 4805 FromType, ImplicitParamType); 4806 return ICS; 4807 } 4808 4809 // Check the ref-qualifier. 4810 switch (Method->getRefQualifier()) { 4811 case RQ_None: 4812 // Do nothing; we don't care about lvalueness or rvalueness. 4813 break; 4814 4815 case RQ_LValue: 4816 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4817 // non-const lvalue reference cannot bind to an rvalue 4818 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4819 ImplicitParamType); 4820 return ICS; 4821 } 4822 break; 4823 4824 case RQ_RValue: 4825 if (!FromClassification.isRValue()) { 4826 // rvalue reference cannot bind to an lvalue 4827 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4828 ImplicitParamType); 4829 return ICS; 4830 } 4831 break; 4832 } 4833 4834 // Success. Mark this as a reference binding. 4835 ICS.setStandard(); 4836 ICS.Standard.setAsIdentityConversion(); 4837 ICS.Standard.Second = SecondKind; 4838 ICS.Standard.setFromType(FromType); 4839 ICS.Standard.setAllToTypes(ImplicitParamType); 4840 ICS.Standard.ReferenceBinding = true; 4841 ICS.Standard.DirectBinding = true; 4842 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4843 ICS.Standard.BindsToFunctionLvalue = false; 4844 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4845 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4846 = (Method->getRefQualifier() == RQ_None); 4847 return ICS; 4848 } 4849 4850 /// PerformObjectArgumentInitialization - Perform initialization of 4851 /// the implicit object parameter for the given Method with the given 4852 /// expression. 4853 ExprResult 4854 Sema::PerformObjectArgumentInitialization(Expr *From, 4855 NestedNameSpecifier *Qualifier, 4856 NamedDecl *FoundDecl, 4857 CXXMethodDecl *Method) { 4858 QualType FromRecordType, DestType; 4859 QualType ImplicitParamRecordType = 4860 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4861 4862 Expr::Classification FromClassification; 4863 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4864 FromRecordType = PT->getPointeeType(); 4865 DestType = Method->getThisType(Context); 4866 FromClassification = Expr::Classification::makeSimpleLValue(); 4867 } else { 4868 FromRecordType = From->getType(); 4869 DestType = ImplicitParamRecordType; 4870 FromClassification = From->Classify(Context); 4871 } 4872 4873 // Note that we always use the true parent context when performing 4874 // the actual argument initialization. 4875 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4876 *this, From->getType(), FromClassification, Method, Method->getParent()); 4877 if (ICS.isBad()) { 4878 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4879 Qualifiers FromQs = FromRecordType.getQualifiers(); 4880 Qualifiers ToQs = DestType.getQualifiers(); 4881 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4882 if (CVR) { 4883 Diag(From->getLocStart(), 4884 diag::err_member_function_call_bad_cvr) 4885 << Method->getDeclName() << FromRecordType << (CVR - 1) 4886 << From->getSourceRange(); 4887 Diag(Method->getLocation(), diag::note_previous_decl) 4888 << Method->getDeclName(); 4889 return ExprError(); 4890 } 4891 } 4892 4893 return Diag(From->getLocStart(), 4894 diag::err_implicit_object_parameter_init) 4895 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4896 } 4897 4898 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4899 ExprResult FromRes = 4900 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4901 if (FromRes.isInvalid()) 4902 return ExprError(); 4903 From = FromRes.get(); 4904 } 4905 4906 if (!Context.hasSameType(From->getType(), DestType)) 4907 From = ImpCastExprToType(From, DestType, CK_NoOp, 4908 From->getValueKind()).get(); 4909 return From; 4910 } 4911 4912 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4913 /// expression From to bool (C++0x [conv]p3). 4914 static ImplicitConversionSequence 4915 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4916 return TryImplicitConversion(S, From, S.Context.BoolTy, 4917 /*SuppressUserConversions=*/false, 4918 /*AllowExplicit=*/true, 4919 /*InOverloadResolution=*/false, 4920 /*CStyle=*/false, 4921 /*AllowObjCWritebackConversion=*/false, 4922 /*AllowObjCConversionOnExplicit=*/false); 4923 } 4924 4925 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4926 /// of the expression From to bool (C++0x [conv]p3). 4927 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4928 if (checkPlaceholderForOverload(*this, From)) 4929 return ExprError(); 4930 4931 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4932 if (!ICS.isBad()) 4933 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4934 4935 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4936 return Diag(From->getLocStart(), 4937 diag::err_typecheck_bool_condition) 4938 << From->getType() << From->getSourceRange(); 4939 return ExprError(); 4940 } 4941 4942 /// Check that the specified conversion is permitted in a converted constant 4943 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4944 /// is acceptable. 4945 static bool CheckConvertedConstantConversions(Sema &S, 4946 StandardConversionSequence &SCS) { 4947 // Since we know that the target type is an integral or unscoped enumeration 4948 // type, most conversion kinds are impossible. All possible First and Third 4949 // conversions are fine. 4950 switch (SCS.Second) { 4951 case ICK_Identity: 4952 case ICK_NoReturn_Adjustment: 4953 case ICK_Integral_Promotion: 4954 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4955 return true; 4956 4957 case ICK_Boolean_Conversion: 4958 // Conversion from an integral or unscoped enumeration type to bool is 4959 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4960 // conversion, so we allow it in a converted constant expression. 4961 // 4962 // FIXME: Per core issue 1407, we should not allow this, but that breaks 4963 // a lot of popular code. We should at least add a warning for this 4964 // (non-conforming) extension. 4965 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4966 SCS.getToType(2)->isBooleanType(); 4967 4968 case ICK_Pointer_Conversion: 4969 case ICK_Pointer_Member: 4970 // C++1z: null pointer conversions and null member pointer conversions are 4971 // only permitted if the source type is std::nullptr_t. 4972 return SCS.getFromType()->isNullPtrType(); 4973 4974 case ICK_Floating_Promotion: 4975 case ICK_Complex_Promotion: 4976 case ICK_Floating_Conversion: 4977 case ICK_Complex_Conversion: 4978 case ICK_Floating_Integral: 4979 case ICK_Compatible_Conversion: 4980 case ICK_Derived_To_Base: 4981 case ICK_Vector_Conversion: 4982 case ICK_Vector_Splat: 4983 case ICK_Complex_Real: 4984 case ICK_Block_Pointer_Conversion: 4985 case ICK_TransparentUnionConversion: 4986 case ICK_Writeback_Conversion: 4987 case ICK_Zero_Event_Conversion: 4988 return false; 4989 4990 case ICK_Lvalue_To_Rvalue: 4991 case ICK_Array_To_Pointer: 4992 case ICK_Function_To_Pointer: 4993 llvm_unreachable("found a first conversion kind in Second"); 4994 4995 case ICK_Qualification: 4996 llvm_unreachable("found a third conversion kind in Second"); 4997 4998 case ICK_Num_Conversion_Kinds: 4999 break; 5000 } 5001 5002 llvm_unreachable("unknown conversion kind"); 5003 } 5004 5005 /// CheckConvertedConstantExpression - Check that the expression From is a 5006 /// converted constant expression of type T, perform the conversion and produce 5007 /// the converted expression, per C++11 [expr.const]p3. 5008 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5009 QualType T, APValue &Value, 5010 Sema::CCEKind CCE, 5011 bool RequireInt) { 5012 assert(S.getLangOpts().CPlusPlus11 && 5013 "converted constant expression outside C++11"); 5014 5015 if (checkPlaceholderForOverload(S, From)) 5016 return ExprError(); 5017 5018 // C++1z [expr.const]p3: 5019 // A converted constant expression of type T is an expression, 5020 // implicitly converted to type T, where the converted 5021 // expression is a constant expression and the implicit conversion 5022 // sequence contains only [... list of conversions ...]. 5023 ImplicitConversionSequence ICS = 5024 TryCopyInitialization(S, From, T, 5025 /*SuppressUserConversions=*/false, 5026 /*InOverloadResolution=*/false, 5027 /*AllowObjcWritebackConversion=*/false, 5028 /*AllowExplicit=*/false); 5029 StandardConversionSequence *SCS = nullptr; 5030 switch (ICS.getKind()) { 5031 case ImplicitConversionSequence::StandardConversion: 5032 SCS = &ICS.Standard; 5033 break; 5034 case ImplicitConversionSequence::UserDefinedConversion: 5035 // We are converting to a non-class type, so the Before sequence 5036 // must be trivial. 5037 SCS = &ICS.UserDefined.After; 5038 break; 5039 case ImplicitConversionSequence::AmbiguousConversion: 5040 case ImplicitConversionSequence::BadConversion: 5041 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5042 return S.Diag(From->getLocStart(), 5043 diag::err_typecheck_converted_constant_expression) 5044 << From->getType() << From->getSourceRange() << T; 5045 return ExprError(); 5046 5047 case ImplicitConversionSequence::EllipsisConversion: 5048 llvm_unreachable("ellipsis conversion in converted constant expression"); 5049 } 5050 5051 // Check that we would only use permitted conversions. 5052 if (!CheckConvertedConstantConversions(S, *SCS)) { 5053 return S.Diag(From->getLocStart(), 5054 diag::err_typecheck_converted_constant_expression_disallowed) 5055 << From->getType() << From->getSourceRange() << T; 5056 } 5057 // [...] and where the reference binding (if any) binds directly. 5058 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5059 return S.Diag(From->getLocStart(), 5060 diag::err_typecheck_converted_constant_expression_indirect) 5061 << From->getType() << From->getSourceRange() << T; 5062 } 5063 5064 ExprResult Result = 5065 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5066 if (Result.isInvalid()) 5067 return Result; 5068 5069 // Check for a narrowing implicit conversion. 5070 APValue PreNarrowingValue; 5071 QualType PreNarrowingType; 5072 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5073 PreNarrowingType)) { 5074 case NK_Variable_Narrowing: 5075 // Implicit conversion to a narrower type, and the value is not a constant 5076 // expression. We'll diagnose this in a moment. 5077 case NK_Not_Narrowing: 5078 break; 5079 5080 case NK_Constant_Narrowing: 5081 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5082 << CCE << /*Constant*/1 5083 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5084 break; 5085 5086 case NK_Type_Narrowing: 5087 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5088 << CCE << /*Constant*/0 << From->getType() << T; 5089 break; 5090 } 5091 5092 // Check the expression is a constant expression. 5093 SmallVector<PartialDiagnosticAt, 8> Notes; 5094 Expr::EvalResult Eval; 5095 Eval.Diag = &Notes; 5096 5097 if ((T->isReferenceType() 5098 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5099 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5100 (RequireInt && !Eval.Val.isInt())) { 5101 // The expression can't be folded, so we can't keep it at this position in 5102 // the AST. 5103 Result = ExprError(); 5104 } else { 5105 Value = Eval.Val; 5106 5107 if (Notes.empty()) { 5108 // It's a constant expression. 5109 return Result; 5110 } 5111 } 5112 5113 // It's not a constant expression. Produce an appropriate diagnostic. 5114 if (Notes.size() == 1 && 5115 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5116 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5117 else { 5118 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5119 << CCE << From->getSourceRange(); 5120 for (unsigned I = 0; I < Notes.size(); ++I) 5121 S.Diag(Notes[I].first, Notes[I].second); 5122 } 5123 return ExprError(); 5124 } 5125 5126 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5127 APValue &Value, CCEKind CCE) { 5128 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5129 } 5130 5131 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5132 llvm::APSInt &Value, 5133 CCEKind CCE) { 5134 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5135 5136 APValue V; 5137 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5138 if (!R.isInvalid()) 5139 Value = V.getInt(); 5140 return R; 5141 } 5142 5143 5144 /// dropPointerConversions - If the given standard conversion sequence 5145 /// involves any pointer conversions, remove them. This may change 5146 /// the result type of the conversion sequence. 5147 static void dropPointerConversion(StandardConversionSequence &SCS) { 5148 if (SCS.Second == ICK_Pointer_Conversion) { 5149 SCS.Second = ICK_Identity; 5150 SCS.Third = ICK_Identity; 5151 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5152 } 5153 } 5154 5155 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5156 /// convert the expression From to an Objective-C pointer type. 5157 static ImplicitConversionSequence 5158 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5159 // Do an implicit conversion to 'id'. 5160 QualType Ty = S.Context.getObjCIdType(); 5161 ImplicitConversionSequence ICS 5162 = TryImplicitConversion(S, From, Ty, 5163 // FIXME: Are these flags correct? 5164 /*SuppressUserConversions=*/false, 5165 /*AllowExplicit=*/true, 5166 /*InOverloadResolution=*/false, 5167 /*CStyle=*/false, 5168 /*AllowObjCWritebackConversion=*/false, 5169 /*AllowObjCConversionOnExplicit=*/true); 5170 5171 // Strip off any final conversions to 'id'. 5172 switch (ICS.getKind()) { 5173 case ImplicitConversionSequence::BadConversion: 5174 case ImplicitConversionSequence::AmbiguousConversion: 5175 case ImplicitConversionSequence::EllipsisConversion: 5176 break; 5177 5178 case ImplicitConversionSequence::UserDefinedConversion: 5179 dropPointerConversion(ICS.UserDefined.After); 5180 break; 5181 5182 case ImplicitConversionSequence::StandardConversion: 5183 dropPointerConversion(ICS.Standard); 5184 break; 5185 } 5186 5187 return ICS; 5188 } 5189 5190 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5191 /// conversion of the expression From to an Objective-C pointer type. 5192 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5193 if (checkPlaceholderForOverload(*this, From)) 5194 return ExprError(); 5195 5196 QualType Ty = Context.getObjCIdType(); 5197 ImplicitConversionSequence ICS = 5198 TryContextuallyConvertToObjCPointer(*this, From); 5199 if (!ICS.isBad()) 5200 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5201 return ExprError(); 5202 } 5203 5204 /// Determine whether the provided type is an integral type, or an enumeration 5205 /// type of a permitted flavor. 5206 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5207 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5208 : T->isIntegralOrUnscopedEnumerationType(); 5209 } 5210 5211 static ExprResult 5212 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5213 Sema::ContextualImplicitConverter &Converter, 5214 QualType T, UnresolvedSetImpl &ViableConversions) { 5215 5216 if (Converter.Suppress) 5217 return ExprError(); 5218 5219 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5220 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5221 CXXConversionDecl *Conv = 5222 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5223 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5224 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5225 } 5226 return From; 5227 } 5228 5229 static bool 5230 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5231 Sema::ContextualImplicitConverter &Converter, 5232 QualType T, bool HadMultipleCandidates, 5233 UnresolvedSetImpl &ExplicitConversions) { 5234 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5235 DeclAccessPair Found = ExplicitConversions[0]; 5236 CXXConversionDecl *Conversion = 5237 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5238 5239 // The user probably meant to invoke the given explicit 5240 // conversion; use it. 5241 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5242 std::string TypeStr; 5243 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5244 5245 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5246 << FixItHint::CreateInsertion(From->getLocStart(), 5247 "static_cast<" + TypeStr + ">(") 5248 << FixItHint::CreateInsertion( 5249 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5250 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5251 5252 // If we aren't in a SFINAE context, build a call to the 5253 // explicit conversion function. 5254 if (SemaRef.isSFINAEContext()) 5255 return true; 5256 5257 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5258 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5259 HadMultipleCandidates); 5260 if (Result.isInvalid()) 5261 return true; 5262 // Record usage of conversion in an implicit cast. 5263 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5264 CK_UserDefinedConversion, Result.get(), 5265 nullptr, Result.get()->getValueKind()); 5266 } 5267 return false; 5268 } 5269 5270 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5271 Sema::ContextualImplicitConverter &Converter, 5272 QualType T, bool HadMultipleCandidates, 5273 DeclAccessPair &Found) { 5274 CXXConversionDecl *Conversion = 5275 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5276 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5277 5278 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5279 if (!Converter.SuppressConversion) { 5280 if (SemaRef.isSFINAEContext()) 5281 return true; 5282 5283 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5284 << From->getSourceRange(); 5285 } 5286 5287 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5288 HadMultipleCandidates); 5289 if (Result.isInvalid()) 5290 return true; 5291 // Record usage of conversion in an implicit cast. 5292 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5293 CK_UserDefinedConversion, Result.get(), 5294 nullptr, Result.get()->getValueKind()); 5295 return false; 5296 } 5297 5298 static ExprResult finishContextualImplicitConversion( 5299 Sema &SemaRef, SourceLocation Loc, Expr *From, 5300 Sema::ContextualImplicitConverter &Converter) { 5301 if (!Converter.match(From->getType()) && !Converter.Suppress) 5302 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5303 << From->getSourceRange(); 5304 5305 return SemaRef.DefaultLvalueConversion(From); 5306 } 5307 5308 static void 5309 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5310 UnresolvedSetImpl &ViableConversions, 5311 OverloadCandidateSet &CandidateSet) { 5312 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5313 DeclAccessPair FoundDecl = ViableConversions[I]; 5314 NamedDecl *D = FoundDecl.getDecl(); 5315 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5316 if (isa<UsingShadowDecl>(D)) 5317 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5318 5319 CXXConversionDecl *Conv; 5320 FunctionTemplateDecl *ConvTemplate; 5321 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5322 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5323 else 5324 Conv = cast<CXXConversionDecl>(D); 5325 5326 if (ConvTemplate) 5327 SemaRef.AddTemplateConversionCandidate( 5328 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5329 /*AllowObjCConversionOnExplicit=*/false); 5330 else 5331 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5332 ToType, CandidateSet, 5333 /*AllowObjCConversionOnExplicit=*/false); 5334 } 5335 } 5336 5337 /// \brief Attempt to convert the given expression to a type which is accepted 5338 /// by the given converter. 5339 /// 5340 /// This routine will attempt to convert an expression of class type to a 5341 /// type accepted by the specified converter. In C++11 and before, the class 5342 /// must have a single non-explicit conversion function converting to a matching 5343 /// type. In C++1y, there can be multiple such conversion functions, but only 5344 /// one target type. 5345 /// 5346 /// \param Loc The source location of the construct that requires the 5347 /// conversion. 5348 /// 5349 /// \param From The expression we're converting from. 5350 /// 5351 /// \param Converter Used to control and diagnose the conversion process. 5352 /// 5353 /// \returns The expression, converted to an integral or enumeration type if 5354 /// successful. 5355 ExprResult Sema::PerformContextualImplicitConversion( 5356 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5357 // We can't perform any more checking for type-dependent expressions. 5358 if (From->isTypeDependent()) 5359 return From; 5360 5361 // Process placeholders immediately. 5362 if (From->hasPlaceholderType()) { 5363 ExprResult result = CheckPlaceholderExpr(From); 5364 if (result.isInvalid()) 5365 return result; 5366 From = result.get(); 5367 } 5368 5369 // If the expression already has a matching type, we're golden. 5370 QualType T = From->getType(); 5371 if (Converter.match(T)) 5372 return DefaultLvalueConversion(From); 5373 5374 // FIXME: Check for missing '()' if T is a function type? 5375 5376 // We can only perform contextual implicit conversions on objects of class 5377 // type. 5378 const RecordType *RecordTy = T->getAs<RecordType>(); 5379 if (!RecordTy || !getLangOpts().CPlusPlus) { 5380 if (!Converter.Suppress) 5381 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5382 return From; 5383 } 5384 5385 // We must have a complete class type. 5386 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5387 ContextualImplicitConverter &Converter; 5388 Expr *From; 5389 5390 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5391 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5392 5393 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5394 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5395 } 5396 } IncompleteDiagnoser(Converter, From); 5397 5398 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5399 return From; 5400 5401 // Look for a conversion to an integral or enumeration type. 5402 UnresolvedSet<4> 5403 ViableConversions; // These are *potentially* viable in C++1y. 5404 UnresolvedSet<4> ExplicitConversions; 5405 const auto &Conversions = 5406 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5407 5408 bool HadMultipleCandidates = 5409 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5410 5411 // To check that there is only one target type, in C++1y: 5412 QualType ToType; 5413 bool HasUniqueTargetType = true; 5414 5415 // Collect explicit or viable (potentially in C++1y) conversions. 5416 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5417 NamedDecl *D = (*I)->getUnderlyingDecl(); 5418 CXXConversionDecl *Conversion; 5419 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5420 if (ConvTemplate) { 5421 if (getLangOpts().CPlusPlus14) 5422 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5423 else 5424 continue; // C++11 does not consider conversion operator templates(?). 5425 } else 5426 Conversion = cast<CXXConversionDecl>(D); 5427 5428 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5429 "Conversion operator templates are considered potentially " 5430 "viable in C++1y"); 5431 5432 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5433 if (Converter.match(CurToType) || ConvTemplate) { 5434 5435 if (Conversion->isExplicit()) { 5436 // FIXME: For C++1y, do we need this restriction? 5437 // cf. diagnoseNoViableConversion() 5438 if (!ConvTemplate) 5439 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5440 } else { 5441 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5442 if (ToType.isNull()) 5443 ToType = CurToType.getUnqualifiedType(); 5444 else if (HasUniqueTargetType && 5445 (CurToType.getUnqualifiedType() != ToType)) 5446 HasUniqueTargetType = false; 5447 } 5448 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5449 } 5450 } 5451 } 5452 5453 if (getLangOpts().CPlusPlus14) { 5454 // C++1y [conv]p6: 5455 // ... An expression e of class type E appearing in such a context 5456 // is said to be contextually implicitly converted to a specified 5457 // type T and is well-formed if and only if e can be implicitly 5458 // converted to a type T that is determined as follows: E is searched 5459 // for conversion functions whose return type is cv T or reference to 5460 // cv T such that T is allowed by the context. There shall be 5461 // exactly one such T. 5462 5463 // If no unique T is found: 5464 if (ToType.isNull()) { 5465 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5466 HadMultipleCandidates, 5467 ExplicitConversions)) 5468 return ExprError(); 5469 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5470 } 5471 5472 // If more than one unique Ts are found: 5473 if (!HasUniqueTargetType) 5474 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5475 ViableConversions); 5476 5477 // If one unique T is found: 5478 // First, build a candidate set from the previously recorded 5479 // potentially viable conversions. 5480 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5481 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5482 CandidateSet); 5483 5484 // Then, perform overload resolution over the candidate set. 5485 OverloadCandidateSet::iterator Best; 5486 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5487 case OR_Success: { 5488 // Apply this conversion. 5489 DeclAccessPair Found = 5490 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5491 if (recordConversion(*this, Loc, From, Converter, T, 5492 HadMultipleCandidates, Found)) 5493 return ExprError(); 5494 break; 5495 } 5496 case OR_Ambiguous: 5497 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5498 ViableConversions); 5499 case OR_No_Viable_Function: 5500 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5501 HadMultipleCandidates, 5502 ExplicitConversions)) 5503 return ExprError(); 5504 // fall through 'OR_Deleted' case. 5505 case OR_Deleted: 5506 // We'll complain below about a non-integral condition type. 5507 break; 5508 } 5509 } else { 5510 switch (ViableConversions.size()) { 5511 case 0: { 5512 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5513 HadMultipleCandidates, 5514 ExplicitConversions)) 5515 return ExprError(); 5516 5517 // We'll complain below about a non-integral condition type. 5518 break; 5519 } 5520 case 1: { 5521 // Apply this conversion. 5522 DeclAccessPair Found = ViableConversions[0]; 5523 if (recordConversion(*this, Loc, From, Converter, T, 5524 HadMultipleCandidates, Found)) 5525 return ExprError(); 5526 break; 5527 } 5528 default: 5529 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5530 ViableConversions); 5531 } 5532 } 5533 5534 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5535 } 5536 5537 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5538 /// an acceptable non-member overloaded operator for a call whose 5539 /// arguments have types T1 (and, if non-empty, T2). This routine 5540 /// implements the check in C++ [over.match.oper]p3b2 concerning 5541 /// enumeration types. 5542 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5543 FunctionDecl *Fn, 5544 ArrayRef<Expr *> Args) { 5545 QualType T1 = Args[0]->getType(); 5546 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5547 5548 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5549 return true; 5550 5551 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5552 return true; 5553 5554 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5555 if (Proto->getNumParams() < 1) 5556 return false; 5557 5558 if (T1->isEnumeralType()) { 5559 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5560 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5561 return true; 5562 } 5563 5564 if (Proto->getNumParams() < 2) 5565 return false; 5566 5567 if (!T2.isNull() && T2->isEnumeralType()) { 5568 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5569 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5570 return true; 5571 } 5572 5573 return false; 5574 } 5575 5576 /// AddOverloadCandidate - Adds the given function to the set of 5577 /// candidate functions, using the given function call arguments. If 5578 /// @p SuppressUserConversions, then don't allow user-defined 5579 /// conversions via constructors or conversion operators. 5580 /// 5581 /// \param PartialOverloading true if we are performing "partial" overloading 5582 /// based on an incomplete set of function arguments. This feature is used by 5583 /// code completion. 5584 void 5585 Sema::AddOverloadCandidate(FunctionDecl *Function, 5586 DeclAccessPair FoundDecl, 5587 ArrayRef<Expr *> Args, 5588 OverloadCandidateSet &CandidateSet, 5589 bool SuppressUserConversions, 5590 bool PartialOverloading, 5591 bool AllowExplicit) { 5592 const FunctionProtoType *Proto 5593 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5594 assert(Proto && "Functions without a prototype cannot be overloaded"); 5595 assert(!Function->getDescribedFunctionTemplate() && 5596 "Use AddTemplateOverloadCandidate for function templates"); 5597 5598 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5599 if (!isa<CXXConstructorDecl>(Method)) { 5600 // If we get here, it's because we're calling a member function 5601 // that is named without a member access expression (e.g., 5602 // "this->f") that was either written explicitly or created 5603 // implicitly. This can happen with a qualified call to a member 5604 // function, e.g., X::f(). We use an empty type for the implied 5605 // object argument (C++ [over.call.func]p3), and the acting context 5606 // is irrelevant. 5607 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5608 QualType(), Expr::Classification::makeSimpleLValue(), 5609 Args, CandidateSet, SuppressUserConversions, 5610 PartialOverloading); 5611 return; 5612 } 5613 // We treat a constructor like a non-member function, since its object 5614 // argument doesn't participate in overload resolution. 5615 } 5616 5617 if (!CandidateSet.isNewCandidate(Function)) 5618 return; 5619 5620 // C++ [over.match.oper]p3: 5621 // if no operand has a class type, only those non-member functions in the 5622 // lookup set that have a first parameter of type T1 or "reference to 5623 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5624 // is a right operand) a second parameter of type T2 or "reference to 5625 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5626 // candidate functions. 5627 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5628 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5629 return; 5630 5631 // C++11 [class.copy]p11: [DR1402] 5632 // A defaulted move constructor that is defined as deleted is ignored by 5633 // overload resolution. 5634 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5635 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5636 Constructor->isMoveConstructor()) 5637 return; 5638 5639 // Overload resolution is always an unevaluated context. 5640 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5641 5642 // Add this candidate 5643 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5644 Candidate.FoundDecl = FoundDecl; 5645 Candidate.Function = Function; 5646 Candidate.Viable = true; 5647 Candidate.IsSurrogate = false; 5648 Candidate.IgnoreObjectArgument = false; 5649 Candidate.ExplicitCallArguments = Args.size(); 5650 5651 if (Constructor) { 5652 // C++ [class.copy]p3: 5653 // A member function template is never instantiated to perform the copy 5654 // of a class object to an object of its class type. 5655 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5656 if (Args.size() == 1 && 5657 Constructor->isSpecializationCopyingObject() && 5658 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5659 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5660 Candidate.Viable = false; 5661 Candidate.FailureKind = ovl_fail_illegal_constructor; 5662 return; 5663 } 5664 } 5665 5666 unsigned NumParams = Proto->getNumParams(); 5667 5668 // (C++ 13.3.2p2): A candidate function having fewer than m 5669 // parameters is viable only if it has an ellipsis in its parameter 5670 // list (8.3.5). 5671 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5672 !Proto->isVariadic()) { 5673 Candidate.Viable = false; 5674 Candidate.FailureKind = ovl_fail_too_many_arguments; 5675 return; 5676 } 5677 5678 // (C++ 13.3.2p2): A candidate function having more than m parameters 5679 // is viable only if the (m+1)st parameter has a default argument 5680 // (8.3.6). For the purposes of overload resolution, the 5681 // parameter list is truncated on the right, so that there are 5682 // exactly m parameters. 5683 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5684 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5685 // Not enough arguments. 5686 Candidate.Viable = false; 5687 Candidate.FailureKind = ovl_fail_too_few_arguments; 5688 return; 5689 } 5690 5691 // (CUDA B.1): Check for invalid calls between targets. 5692 if (getLangOpts().CUDA) 5693 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5694 // Skip the check for callers that are implicit members, because in this 5695 // case we may not yet know what the member's target is; the target is 5696 // inferred for the member automatically, based on the bases and fields of 5697 // the class. 5698 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5699 Candidate.Viable = false; 5700 Candidate.FailureKind = ovl_fail_bad_target; 5701 return; 5702 } 5703 5704 // Determine the implicit conversion sequences for each of the 5705 // arguments. 5706 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5707 if (ArgIdx < NumParams) { 5708 // (C++ 13.3.2p3): for F to be a viable function, there shall 5709 // exist for each argument an implicit conversion sequence 5710 // (13.3.3.1) that converts that argument to the corresponding 5711 // parameter of F. 5712 QualType ParamType = Proto->getParamType(ArgIdx); 5713 Candidate.Conversions[ArgIdx] 5714 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5715 SuppressUserConversions, 5716 /*InOverloadResolution=*/true, 5717 /*AllowObjCWritebackConversion=*/ 5718 getLangOpts().ObjCAutoRefCount, 5719 AllowExplicit); 5720 if (Candidate.Conversions[ArgIdx].isBad()) { 5721 Candidate.Viable = false; 5722 Candidate.FailureKind = ovl_fail_bad_conversion; 5723 return; 5724 } 5725 } else { 5726 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5727 // argument for which there is no corresponding parameter is 5728 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5729 Candidate.Conversions[ArgIdx].setEllipsis(); 5730 } 5731 } 5732 5733 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5734 Candidate.Viable = false; 5735 Candidate.FailureKind = ovl_fail_enable_if; 5736 Candidate.DeductionFailure.Data = FailedAttr; 5737 return; 5738 } 5739 } 5740 5741 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5742 bool IsInstance) { 5743 SmallVector<ObjCMethodDecl*, 4> Methods; 5744 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5745 return nullptr; 5746 5747 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5748 bool Match = true; 5749 ObjCMethodDecl *Method = Methods[b]; 5750 unsigned NumNamedArgs = Sel.getNumArgs(); 5751 // Method might have more arguments than selector indicates. This is due 5752 // to addition of c-style arguments in method. 5753 if (Method->param_size() > NumNamedArgs) 5754 NumNamedArgs = Method->param_size(); 5755 if (Args.size() < NumNamedArgs) 5756 continue; 5757 5758 for (unsigned i = 0; i < NumNamedArgs; i++) { 5759 // We can't do any type-checking on a type-dependent argument. 5760 if (Args[i]->isTypeDependent()) { 5761 Match = false; 5762 break; 5763 } 5764 5765 ParmVarDecl *param = Method->parameters()[i]; 5766 Expr *argExpr = Args[i]; 5767 assert(argExpr && "SelectBestMethod(): missing expression"); 5768 5769 // Strip the unbridged-cast placeholder expression off unless it's 5770 // a consumed argument. 5771 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5772 !param->hasAttr<CFConsumedAttr>()) 5773 argExpr = stripARCUnbridgedCast(argExpr); 5774 5775 // If the parameter is __unknown_anytype, move on to the next method. 5776 if (param->getType() == Context.UnknownAnyTy) { 5777 Match = false; 5778 break; 5779 } 5780 5781 ImplicitConversionSequence ConversionState 5782 = TryCopyInitialization(*this, argExpr, param->getType(), 5783 /*SuppressUserConversions*/false, 5784 /*InOverloadResolution=*/true, 5785 /*AllowObjCWritebackConversion=*/ 5786 getLangOpts().ObjCAutoRefCount, 5787 /*AllowExplicit*/false); 5788 if (ConversionState.isBad()) { 5789 Match = false; 5790 break; 5791 } 5792 } 5793 // Promote additional arguments to variadic methods. 5794 if (Match && Method->isVariadic()) { 5795 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5796 if (Args[i]->isTypeDependent()) { 5797 Match = false; 5798 break; 5799 } 5800 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5801 nullptr); 5802 if (Arg.isInvalid()) { 5803 Match = false; 5804 break; 5805 } 5806 } 5807 } else { 5808 // Check for extra arguments to non-variadic methods. 5809 if (Args.size() != NumNamedArgs) 5810 Match = false; 5811 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5812 // Special case when selectors have no argument. In this case, select 5813 // one with the most general result type of 'id'. 5814 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5815 QualType ReturnT = Methods[b]->getReturnType(); 5816 if (ReturnT->isObjCIdType()) 5817 return Methods[b]; 5818 } 5819 } 5820 } 5821 5822 if (Match) 5823 return Method; 5824 } 5825 return nullptr; 5826 } 5827 5828 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5829 5830 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5831 bool MissingImplicitThis) { 5832 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5833 // we need to find the first failing one. 5834 if (!Function->hasAttrs()) 5835 return nullptr; 5836 AttrVec Attrs = Function->getAttrs(); 5837 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5838 IsNotEnableIfAttr); 5839 if (Attrs.begin() == E) 5840 return nullptr; 5841 std::reverse(Attrs.begin(), E); 5842 5843 SFINAETrap Trap(*this); 5844 5845 // Convert the arguments. 5846 SmallVector<Expr *, 16> ConvertedArgs; 5847 bool InitializationFailed = false; 5848 bool ContainsValueDependentExpr = false; 5849 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5850 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5851 !cast<CXXMethodDecl>(Function)->isStatic() && 5852 !isa<CXXConstructorDecl>(Function)) { 5853 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5854 ExprResult R = 5855 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5856 Method, Method); 5857 if (R.isInvalid()) { 5858 InitializationFailed = true; 5859 break; 5860 } 5861 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5862 ConvertedArgs.push_back(R.get()); 5863 } else { 5864 ExprResult R = 5865 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5866 Context, 5867 Function->getParamDecl(i)), 5868 SourceLocation(), 5869 Args[i]); 5870 if (R.isInvalid()) { 5871 InitializationFailed = true; 5872 break; 5873 } 5874 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5875 ConvertedArgs.push_back(R.get()); 5876 } 5877 } 5878 5879 if (InitializationFailed || Trap.hasErrorOccurred()) 5880 return cast<EnableIfAttr>(Attrs[0]); 5881 5882 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5883 APValue Result; 5884 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5885 if (EIA->getCond()->isValueDependent()) { 5886 // Don't even try now, we'll examine it after instantiation. 5887 continue; 5888 } 5889 5890 if (!EIA->getCond()->EvaluateWithSubstitution( 5891 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5892 if (!ContainsValueDependentExpr) 5893 return EIA; 5894 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5895 return EIA; 5896 } 5897 } 5898 return nullptr; 5899 } 5900 5901 /// \brief Add all of the function declarations in the given function set to 5902 /// the overload candidate set. 5903 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5904 ArrayRef<Expr *> Args, 5905 OverloadCandidateSet& CandidateSet, 5906 TemplateArgumentListInfo *ExplicitTemplateArgs, 5907 bool SuppressUserConversions, 5908 bool PartialOverloading) { 5909 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5910 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5911 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5912 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5913 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5914 cast<CXXMethodDecl>(FD)->getParent(), 5915 Args[0]->getType(), Args[0]->Classify(Context), 5916 Args.slice(1), CandidateSet, 5917 SuppressUserConversions, PartialOverloading); 5918 else 5919 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5920 SuppressUserConversions, PartialOverloading); 5921 } else { 5922 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5923 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5924 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5925 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5926 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5927 ExplicitTemplateArgs, 5928 Args[0]->getType(), 5929 Args[0]->Classify(Context), Args.slice(1), 5930 CandidateSet, SuppressUserConversions, 5931 PartialOverloading); 5932 else 5933 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5934 ExplicitTemplateArgs, Args, 5935 CandidateSet, SuppressUserConversions, 5936 PartialOverloading); 5937 } 5938 } 5939 } 5940 5941 /// AddMethodCandidate - Adds a named decl (which is some kind of 5942 /// method) as a method candidate to the given overload set. 5943 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5944 QualType ObjectType, 5945 Expr::Classification ObjectClassification, 5946 ArrayRef<Expr *> Args, 5947 OverloadCandidateSet& CandidateSet, 5948 bool SuppressUserConversions) { 5949 NamedDecl *Decl = FoundDecl.getDecl(); 5950 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5951 5952 if (isa<UsingShadowDecl>(Decl)) 5953 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5954 5955 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5956 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5957 "Expected a member function template"); 5958 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5959 /*ExplicitArgs*/ nullptr, 5960 ObjectType, ObjectClassification, 5961 Args, CandidateSet, 5962 SuppressUserConversions); 5963 } else { 5964 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5965 ObjectType, ObjectClassification, 5966 Args, 5967 CandidateSet, SuppressUserConversions); 5968 } 5969 } 5970 5971 /// AddMethodCandidate - Adds the given C++ member function to the set 5972 /// of candidate functions, using the given function call arguments 5973 /// and the object argument (@c Object). For example, in a call 5974 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5975 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5976 /// allow user-defined conversions via constructors or conversion 5977 /// operators. 5978 void 5979 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5980 CXXRecordDecl *ActingContext, QualType ObjectType, 5981 Expr::Classification ObjectClassification, 5982 ArrayRef<Expr *> Args, 5983 OverloadCandidateSet &CandidateSet, 5984 bool SuppressUserConversions, 5985 bool PartialOverloading) { 5986 const FunctionProtoType *Proto 5987 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5988 assert(Proto && "Methods without a prototype cannot be overloaded"); 5989 assert(!isa<CXXConstructorDecl>(Method) && 5990 "Use AddOverloadCandidate for constructors"); 5991 5992 if (!CandidateSet.isNewCandidate(Method)) 5993 return; 5994 5995 // C++11 [class.copy]p23: [DR1402] 5996 // A defaulted move assignment operator that is defined as deleted is 5997 // ignored by overload resolution. 5998 if (Method->isDefaulted() && Method->isDeleted() && 5999 Method->isMoveAssignmentOperator()) 6000 return; 6001 6002 // Overload resolution is always an unevaluated context. 6003 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6004 6005 // Add this candidate 6006 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6007 Candidate.FoundDecl = FoundDecl; 6008 Candidate.Function = Method; 6009 Candidate.IsSurrogate = false; 6010 Candidate.IgnoreObjectArgument = false; 6011 Candidate.ExplicitCallArguments = Args.size(); 6012 6013 unsigned NumParams = Proto->getNumParams(); 6014 6015 // (C++ 13.3.2p2): A candidate function having fewer than m 6016 // parameters is viable only if it has an ellipsis in its parameter 6017 // list (8.3.5). 6018 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6019 !Proto->isVariadic()) { 6020 Candidate.Viable = false; 6021 Candidate.FailureKind = ovl_fail_too_many_arguments; 6022 return; 6023 } 6024 6025 // (C++ 13.3.2p2): A candidate function having more than m parameters 6026 // is viable only if the (m+1)st parameter has a default argument 6027 // (8.3.6). For the purposes of overload resolution, the 6028 // parameter list is truncated on the right, so that there are 6029 // exactly m parameters. 6030 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6031 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6032 // Not enough arguments. 6033 Candidate.Viable = false; 6034 Candidate.FailureKind = ovl_fail_too_few_arguments; 6035 return; 6036 } 6037 6038 Candidate.Viable = true; 6039 6040 if (Method->isStatic() || ObjectType.isNull()) 6041 // The implicit object argument is ignored. 6042 Candidate.IgnoreObjectArgument = true; 6043 else { 6044 // Determine the implicit conversion sequence for the object 6045 // parameter. 6046 Candidate.Conversions[0] 6047 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6048 Method, ActingContext); 6049 if (Candidate.Conversions[0].isBad()) { 6050 Candidate.Viable = false; 6051 Candidate.FailureKind = ovl_fail_bad_conversion; 6052 return; 6053 } 6054 } 6055 6056 // (CUDA B.1): Check for invalid calls between targets. 6057 if (getLangOpts().CUDA) 6058 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6059 if (CheckCUDATarget(Caller, Method)) { 6060 Candidate.Viable = false; 6061 Candidate.FailureKind = ovl_fail_bad_target; 6062 return; 6063 } 6064 6065 // Determine the implicit conversion sequences for each of the 6066 // arguments. 6067 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6068 if (ArgIdx < NumParams) { 6069 // (C++ 13.3.2p3): for F to be a viable function, there shall 6070 // exist for each argument an implicit conversion sequence 6071 // (13.3.3.1) that converts that argument to the corresponding 6072 // parameter of F. 6073 QualType ParamType = Proto->getParamType(ArgIdx); 6074 Candidate.Conversions[ArgIdx + 1] 6075 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6076 SuppressUserConversions, 6077 /*InOverloadResolution=*/true, 6078 /*AllowObjCWritebackConversion=*/ 6079 getLangOpts().ObjCAutoRefCount); 6080 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6081 Candidate.Viable = false; 6082 Candidate.FailureKind = ovl_fail_bad_conversion; 6083 return; 6084 } 6085 } else { 6086 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6087 // argument for which there is no corresponding parameter is 6088 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6089 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6090 } 6091 } 6092 6093 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6094 Candidate.Viable = false; 6095 Candidate.FailureKind = ovl_fail_enable_if; 6096 Candidate.DeductionFailure.Data = FailedAttr; 6097 return; 6098 } 6099 } 6100 6101 /// \brief Add a C++ member function template as a candidate to the candidate 6102 /// set, using template argument deduction to produce an appropriate member 6103 /// function template specialization. 6104 void 6105 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6106 DeclAccessPair FoundDecl, 6107 CXXRecordDecl *ActingContext, 6108 TemplateArgumentListInfo *ExplicitTemplateArgs, 6109 QualType ObjectType, 6110 Expr::Classification ObjectClassification, 6111 ArrayRef<Expr *> Args, 6112 OverloadCandidateSet& CandidateSet, 6113 bool SuppressUserConversions, 6114 bool PartialOverloading) { 6115 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6116 return; 6117 6118 // C++ [over.match.funcs]p7: 6119 // In each case where a candidate is a function template, candidate 6120 // function template specializations are generated using template argument 6121 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6122 // candidate functions in the usual way.113) A given name can refer to one 6123 // or more function templates and also to a set of overloaded non-template 6124 // functions. In such a case, the candidate functions generated from each 6125 // function template are combined with the set of non-template candidate 6126 // functions. 6127 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6128 FunctionDecl *Specialization = nullptr; 6129 if (TemplateDeductionResult Result 6130 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6131 Specialization, Info, PartialOverloading)) { 6132 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6133 Candidate.FoundDecl = FoundDecl; 6134 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6135 Candidate.Viable = false; 6136 Candidate.FailureKind = ovl_fail_bad_deduction; 6137 Candidate.IsSurrogate = false; 6138 Candidate.IgnoreObjectArgument = false; 6139 Candidate.ExplicitCallArguments = Args.size(); 6140 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6141 Info); 6142 return; 6143 } 6144 6145 // Add the function template specialization produced by template argument 6146 // deduction as a candidate. 6147 assert(Specialization && "Missing member function template specialization?"); 6148 assert(isa<CXXMethodDecl>(Specialization) && 6149 "Specialization is not a member function?"); 6150 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6151 ActingContext, ObjectType, ObjectClassification, Args, 6152 CandidateSet, SuppressUserConversions, PartialOverloading); 6153 } 6154 6155 /// \brief Add a C++ function template specialization as a candidate 6156 /// in the candidate set, using template argument deduction to produce 6157 /// an appropriate function template specialization. 6158 void 6159 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6160 DeclAccessPair FoundDecl, 6161 TemplateArgumentListInfo *ExplicitTemplateArgs, 6162 ArrayRef<Expr *> Args, 6163 OverloadCandidateSet& CandidateSet, 6164 bool SuppressUserConversions, 6165 bool PartialOverloading) { 6166 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6167 return; 6168 6169 // C++ [over.match.funcs]p7: 6170 // In each case where a candidate is a function template, candidate 6171 // function template specializations are generated using template argument 6172 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6173 // candidate functions in the usual way.113) A given name can refer to one 6174 // or more function templates and also to a set of overloaded non-template 6175 // functions. In such a case, the candidate functions generated from each 6176 // function template are combined with the set of non-template candidate 6177 // functions. 6178 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6179 FunctionDecl *Specialization = nullptr; 6180 if (TemplateDeductionResult Result 6181 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6182 Specialization, Info, PartialOverloading)) { 6183 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6184 Candidate.FoundDecl = FoundDecl; 6185 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6186 Candidate.Viable = false; 6187 Candidate.FailureKind = ovl_fail_bad_deduction; 6188 Candidate.IsSurrogate = false; 6189 Candidate.IgnoreObjectArgument = false; 6190 Candidate.ExplicitCallArguments = Args.size(); 6191 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6192 Info); 6193 return; 6194 } 6195 6196 // Add the function template specialization produced by template argument 6197 // deduction as a candidate. 6198 assert(Specialization && "Missing function template specialization?"); 6199 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6200 SuppressUserConversions, PartialOverloading); 6201 } 6202 6203 /// Determine whether this is an allowable conversion from the result 6204 /// of an explicit conversion operator to the expected type, per C++ 6205 /// [over.match.conv]p1 and [over.match.ref]p1. 6206 /// 6207 /// \param ConvType The return type of the conversion function. 6208 /// 6209 /// \param ToType The type we are converting to. 6210 /// 6211 /// \param AllowObjCPointerConversion Allow a conversion from one 6212 /// Objective-C pointer to another. 6213 /// 6214 /// \returns true if the conversion is allowable, false otherwise. 6215 static bool isAllowableExplicitConversion(Sema &S, 6216 QualType ConvType, QualType ToType, 6217 bool AllowObjCPointerConversion) { 6218 QualType ToNonRefType = ToType.getNonReferenceType(); 6219 6220 // Easy case: the types are the same. 6221 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6222 return true; 6223 6224 // Allow qualification conversions. 6225 bool ObjCLifetimeConversion; 6226 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6227 ObjCLifetimeConversion)) 6228 return true; 6229 6230 // If we're not allowed to consider Objective-C pointer conversions, 6231 // we're done. 6232 if (!AllowObjCPointerConversion) 6233 return false; 6234 6235 // Is this an Objective-C pointer conversion? 6236 bool IncompatibleObjC = false; 6237 QualType ConvertedType; 6238 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6239 IncompatibleObjC); 6240 } 6241 6242 /// AddConversionCandidate - Add a C++ conversion function as a 6243 /// candidate in the candidate set (C++ [over.match.conv], 6244 /// C++ [over.match.copy]). From is the expression we're converting from, 6245 /// and ToType is the type that we're eventually trying to convert to 6246 /// (which may or may not be the same type as the type that the 6247 /// conversion function produces). 6248 void 6249 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6250 DeclAccessPair FoundDecl, 6251 CXXRecordDecl *ActingContext, 6252 Expr *From, QualType ToType, 6253 OverloadCandidateSet& CandidateSet, 6254 bool AllowObjCConversionOnExplicit) { 6255 assert(!Conversion->getDescribedFunctionTemplate() && 6256 "Conversion function templates use AddTemplateConversionCandidate"); 6257 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6258 if (!CandidateSet.isNewCandidate(Conversion)) 6259 return; 6260 6261 // If the conversion function has an undeduced return type, trigger its 6262 // deduction now. 6263 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6264 if (DeduceReturnType(Conversion, From->getExprLoc())) 6265 return; 6266 ConvType = Conversion->getConversionType().getNonReferenceType(); 6267 } 6268 6269 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6270 // operator is only a candidate if its return type is the target type or 6271 // can be converted to the target type with a qualification conversion. 6272 if (Conversion->isExplicit() && 6273 !isAllowableExplicitConversion(*this, ConvType, ToType, 6274 AllowObjCConversionOnExplicit)) 6275 return; 6276 6277 // Overload resolution is always an unevaluated context. 6278 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6279 6280 // Add this candidate 6281 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6282 Candidate.FoundDecl = FoundDecl; 6283 Candidate.Function = Conversion; 6284 Candidate.IsSurrogate = false; 6285 Candidate.IgnoreObjectArgument = false; 6286 Candidate.FinalConversion.setAsIdentityConversion(); 6287 Candidate.FinalConversion.setFromType(ConvType); 6288 Candidate.FinalConversion.setAllToTypes(ToType); 6289 Candidate.Viable = true; 6290 Candidate.ExplicitCallArguments = 1; 6291 6292 // C++ [over.match.funcs]p4: 6293 // For conversion functions, the function is considered to be a member of 6294 // the class of the implicit implied object argument for the purpose of 6295 // defining the type of the implicit object parameter. 6296 // 6297 // Determine the implicit conversion sequence for the implicit 6298 // object parameter. 6299 QualType ImplicitParamType = From->getType(); 6300 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6301 ImplicitParamType = FromPtrType->getPointeeType(); 6302 CXXRecordDecl *ConversionContext 6303 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6304 6305 Candidate.Conversions[0] 6306 = TryObjectArgumentInitialization(*this, From->getType(), 6307 From->Classify(Context), 6308 Conversion, ConversionContext); 6309 6310 if (Candidate.Conversions[0].isBad()) { 6311 Candidate.Viable = false; 6312 Candidate.FailureKind = ovl_fail_bad_conversion; 6313 return; 6314 } 6315 6316 // We won't go through a user-defined type conversion function to convert a 6317 // derived to base as such conversions are given Conversion Rank. They only 6318 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6319 QualType FromCanon 6320 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6321 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6322 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6323 Candidate.Viable = false; 6324 Candidate.FailureKind = ovl_fail_trivial_conversion; 6325 return; 6326 } 6327 6328 // To determine what the conversion from the result of calling the 6329 // conversion function to the type we're eventually trying to 6330 // convert to (ToType), we need to synthesize a call to the 6331 // conversion function and attempt copy initialization from it. This 6332 // makes sure that we get the right semantics with respect to 6333 // lvalues/rvalues and the type. Fortunately, we can allocate this 6334 // call on the stack and we don't need its arguments to be 6335 // well-formed. 6336 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6337 VK_LValue, From->getLocStart()); 6338 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6339 Context.getPointerType(Conversion->getType()), 6340 CK_FunctionToPointerDecay, 6341 &ConversionRef, VK_RValue); 6342 6343 QualType ConversionType = Conversion->getConversionType(); 6344 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6345 Candidate.Viable = false; 6346 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6347 return; 6348 } 6349 6350 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6351 6352 // Note that it is safe to allocate CallExpr on the stack here because 6353 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6354 // allocator). 6355 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6356 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6357 From->getLocStart()); 6358 ImplicitConversionSequence ICS = 6359 TryCopyInitialization(*this, &Call, ToType, 6360 /*SuppressUserConversions=*/true, 6361 /*InOverloadResolution=*/false, 6362 /*AllowObjCWritebackConversion=*/false); 6363 6364 switch (ICS.getKind()) { 6365 case ImplicitConversionSequence::StandardConversion: 6366 Candidate.FinalConversion = ICS.Standard; 6367 6368 // C++ [over.ics.user]p3: 6369 // If the user-defined conversion is specified by a specialization of a 6370 // conversion function template, the second standard conversion sequence 6371 // shall have exact match rank. 6372 if (Conversion->getPrimaryTemplate() && 6373 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6374 Candidate.Viable = false; 6375 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6376 return; 6377 } 6378 6379 // C++0x [dcl.init.ref]p5: 6380 // In the second case, if the reference is an rvalue reference and 6381 // the second standard conversion sequence of the user-defined 6382 // conversion sequence includes an lvalue-to-rvalue conversion, the 6383 // program is ill-formed. 6384 if (ToType->isRValueReferenceType() && 6385 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6386 Candidate.Viable = false; 6387 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6388 return; 6389 } 6390 break; 6391 6392 case ImplicitConversionSequence::BadConversion: 6393 Candidate.Viable = false; 6394 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6395 return; 6396 6397 default: 6398 llvm_unreachable( 6399 "Can only end up with a standard conversion sequence or failure"); 6400 } 6401 6402 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6403 Candidate.Viable = false; 6404 Candidate.FailureKind = ovl_fail_enable_if; 6405 Candidate.DeductionFailure.Data = FailedAttr; 6406 return; 6407 } 6408 } 6409 6410 /// \brief Adds a conversion function template specialization 6411 /// candidate to the overload set, using template argument deduction 6412 /// to deduce the template arguments of the conversion function 6413 /// template from the type that we are converting to (C++ 6414 /// [temp.deduct.conv]). 6415 void 6416 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6417 DeclAccessPair FoundDecl, 6418 CXXRecordDecl *ActingDC, 6419 Expr *From, QualType ToType, 6420 OverloadCandidateSet &CandidateSet, 6421 bool AllowObjCConversionOnExplicit) { 6422 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6423 "Only conversion function templates permitted here"); 6424 6425 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6426 return; 6427 6428 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6429 CXXConversionDecl *Specialization = nullptr; 6430 if (TemplateDeductionResult Result 6431 = DeduceTemplateArguments(FunctionTemplate, ToType, 6432 Specialization, Info)) { 6433 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6434 Candidate.FoundDecl = FoundDecl; 6435 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6436 Candidate.Viable = false; 6437 Candidate.FailureKind = ovl_fail_bad_deduction; 6438 Candidate.IsSurrogate = false; 6439 Candidate.IgnoreObjectArgument = false; 6440 Candidate.ExplicitCallArguments = 1; 6441 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6442 Info); 6443 return; 6444 } 6445 6446 // Add the conversion function template specialization produced by 6447 // template argument deduction as a candidate. 6448 assert(Specialization && "Missing function template specialization?"); 6449 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6450 CandidateSet, AllowObjCConversionOnExplicit); 6451 } 6452 6453 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6454 /// converts the given @c Object to a function pointer via the 6455 /// conversion function @c Conversion, and then attempts to call it 6456 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6457 /// the type of function that we'll eventually be calling. 6458 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6459 DeclAccessPair FoundDecl, 6460 CXXRecordDecl *ActingContext, 6461 const FunctionProtoType *Proto, 6462 Expr *Object, 6463 ArrayRef<Expr *> Args, 6464 OverloadCandidateSet& CandidateSet) { 6465 if (!CandidateSet.isNewCandidate(Conversion)) 6466 return; 6467 6468 // Overload resolution is always an unevaluated context. 6469 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6470 6471 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6472 Candidate.FoundDecl = FoundDecl; 6473 Candidate.Function = nullptr; 6474 Candidate.Surrogate = Conversion; 6475 Candidate.Viable = true; 6476 Candidate.IsSurrogate = true; 6477 Candidate.IgnoreObjectArgument = false; 6478 Candidate.ExplicitCallArguments = Args.size(); 6479 6480 // Determine the implicit conversion sequence for the implicit 6481 // object parameter. 6482 ImplicitConversionSequence ObjectInit 6483 = TryObjectArgumentInitialization(*this, Object->getType(), 6484 Object->Classify(Context), 6485 Conversion, ActingContext); 6486 if (ObjectInit.isBad()) { 6487 Candidate.Viable = false; 6488 Candidate.FailureKind = ovl_fail_bad_conversion; 6489 Candidate.Conversions[0] = ObjectInit; 6490 return; 6491 } 6492 6493 // The first conversion is actually a user-defined conversion whose 6494 // first conversion is ObjectInit's standard conversion (which is 6495 // effectively a reference binding). Record it as such. 6496 Candidate.Conversions[0].setUserDefined(); 6497 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6498 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6499 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6500 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6501 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6502 Candidate.Conversions[0].UserDefined.After 6503 = Candidate.Conversions[0].UserDefined.Before; 6504 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6505 6506 // Find the 6507 unsigned NumParams = Proto->getNumParams(); 6508 6509 // (C++ 13.3.2p2): A candidate function having fewer than m 6510 // parameters is viable only if it has an ellipsis in its parameter 6511 // list (8.3.5). 6512 if (Args.size() > NumParams && !Proto->isVariadic()) { 6513 Candidate.Viable = false; 6514 Candidate.FailureKind = ovl_fail_too_many_arguments; 6515 return; 6516 } 6517 6518 // Function types don't have any default arguments, so just check if 6519 // we have enough arguments. 6520 if (Args.size() < NumParams) { 6521 // Not enough arguments. 6522 Candidate.Viable = false; 6523 Candidate.FailureKind = ovl_fail_too_few_arguments; 6524 return; 6525 } 6526 6527 // Determine the implicit conversion sequences for each of the 6528 // arguments. 6529 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6530 if (ArgIdx < NumParams) { 6531 // (C++ 13.3.2p3): for F to be a viable function, there shall 6532 // exist for each argument an implicit conversion sequence 6533 // (13.3.3.1) that converts that argument to the corresponding 6534 // parameter of F. 6535 QualType ParamType = Proto->getParamType(ArgIdx); 6536 Candidate.Conversions[ArgIdx + 1] 6537 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6538 /*SuppressUserConversions=*/false, 6539 /*InOverloadResolution=*/false, 6540 /*AllowObjCWritebackConversion=*/ 6541 getLangOpts().ObjCAutoRefCount); 6542 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6543 Candidate.Viable = false; 6544 Candidate.FailureKind = ovl_fail_bad_conversion; 6545 return; 6546 } 6547 } else { 6548 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6549 // argument for which there is no corresponding parameter is 6550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6551 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6552 } 6553 } 6554 6555 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6556 Candidate.Viable = false; 6557 Candidate.FailureKind = ovl_fail_enable_if; 6558 Candidate.DeductionFailure.Data = FailedAttr; 6559 return; 6560 } 6561 } 6562 6563 /// \brief Add overload candidates for overloaded operators that are 6564 /// member functions. 6565 /// 6566 /// Add the overloaded operator candidates that are member functions 6567 /// for the operator Op that was used in an operator expression such 6568 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6569 /// CandidateSet will store the added overload candidates. (C++ 6570 /// [over.match.oper]). 6571 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6572 SourceLocation OpLoc, 6573 ArrayRef<Expr *> Args, 6574 OverloadCandidateSet& CandidateSet, 6575 SourceRange OpRange) { 6576 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6577 6578 // C++ [over.match.oper]p3: 6579 // For a unary operator @ with an operand of a type whose 6580 // cv-unqualified version is T1, and for a binary operator @ with 6581 // a left operand of a type whose cv-unqualified version is T1 and 6582 // a right operand of a type whose cv-unqualified version is T2, 6583 // three sets of candidate functions, designated member 6584 // candidates, non-member candidates and built-in candidates, are 6585 // constructed as follows: 6586 QualType T1 = Args[0]->getType(); 6587 6588 // -- If T1 is a complete class type or a class currently being 6589 // defined, the set of member candidates is the result of the 6590 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6591 // the set of member candidates is empty. 6592 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6593 // Complete the type if it can be completed. 6594 RequireCompleteType(OpLoc, T1, 0); 6595 // If the type is neither complete nor being defined, bail out now. 6596 if (!T1Rec->getDecl()->getDefinition()) 6597 return; 6598 6599 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6600 LookupQualifiedName(Operators, T1Rec->getDecl()); 6601 Operators.suppressDiagnostics(); 6602 6603 for (LookupResult::iterator Oper = Operators.begin(), 6604 OperEnd = Operators.end(); 6605 Oper != OperEnd; 6606 ++Oper) 6607 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6608 Args[0]->Classify(Context), 6609 Args.slice(1), 6610 CandidateSet, 6611 /* SuppressUserConversions = */ false); 6612 } 6613 } 6614 6615 /// AddBuiltinCandidate - Add a candidate for a built-in 6616 /// operator. ResultTy and ParamTys are the result and parameter types 6617 /// of the built-in candidate, respectively. Args and NumArgs are the 6618 /// arguments being passed to the candidate. IsAssignmentOperator 6619 /// should be true when this built-in candidate is an assignment 6620 /// operator. NumContextualBoolArguments is the number of arguments 6621 /// (at the beginning of the argument list) that will be contextually 6622 /// converted to bool. 6623 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6624 ArrayRef<Expr *> Args, 6625 OverloadCandidateSet& CandidateSet, 6626 bool IsAssignmentOperator, 6627 unsigned NumContextualBoolArguments) { 6628 // Overload resolution is always an unevaluated context. 6629 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6630 6631 // Add this candidate 6632 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6633 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6634 Candidate.Function = nullptr; 6635 Candidate.IsSurrogate = false; 6636 Candidate.IgnoreObjectArgument = false; 6637 Candidate.BuiltinTypes.ResultTy = ResultTy; 6638 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6639 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6640 6641 // Determine the implicit conversion sequences for each of the 6642 // arguments. 6643 Candidate.Viable = true; 6644 Candidate.ExplicitCallArguments = Args.size(); 6645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6646 // C++ [over.match.oper]p4: 6647 // For the built-in assignment operators, conversions of the 6648 // left operand are restricted as follows: 6649 // -- no temporaries are introduced to hold the left operand, and 6650 // -- no user-defined conversions are applied to the left 6651 // operand to achieve a type match with the left-most 6652 // parameter of a built-in candidate. 6653 // 6654 // We block these conversions by turning off user-defined 6655 // conversions, since that is the only way that initialization of 6656 // a reference to a non-class type can occur from something that 6657 // is not of the same type. 6658 if (ArgIdx < NumContextualBoolArguments) { 6659 assert(ParamTys[ArgIdx] == Context.BoolTy && 6660 "Contextual conversion to bool requires bool type"); 6661 Candidate.Conversions[ArgIdx] 6662 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6663 } else { 6664 Candidate.Conversions[ArgIdx] 6665 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6666 ArgIdx == 0 && IsAssignmentOperator, 6667 /*InOverloadResolution=*/false, 6668 /*AllowObjCWritebackConversion=*/ 6669 getLangOpts().ObjCAutoRefCount); 6670 } 6671 if (Candidate.Conversions[ArgIdx].isBad()) { 6672 Candidate.Viable = false; 6673 Candidate.FailureKind = ovl_fail_bad_conversion; 6674 break; 6675 } 6676 } 6677 } 6678 6679 namespace { 6680 6681 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6682 /// candidate operator functions for built-in operators (C++ 6683 /// [over.built]). The types are separated into pointer types and 6684 /// enumeration types. 6685 class BuiltinCandidateTypeSet { 6686 /// TypeSet - A set of types. 6687 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6688 6689 /// PointerTypes - The set of pointer types that will be used in the 6690 /// built-in candidates. 6691 TypeSet PointerTypes; 6692 6693 /// MemberPointerTypes - The set of member pointer types that will be 6694 /// used in the built-in candidates. 6695 TypeSet MemberPointerTypes; 6696 6697 /// EnumerationTypes - The set of enumeration types that will be 6698 /// used in the built-in candidates. 6699 TypeSet EnumerationTypes; 6700 6701 /// \brief The set of vector types that will be used in the built-in 6702 /// candidates. 6703 TypeSet VectorTypes; 6704 6705 /// \brief A flag indicating non-record types are viable candidates 6706 bool HasNonRecordTypes; 6707 6708 /// \brief A flag indicating whether either arithmetic or enumeration types 6709 /// were present in the candidate set. 6710 bool HasArithmeticOrEnumeralTypes; 6711 6712 /// \brief A flag indicating whether the nullptr type was present in the 6713 /// candidate set. 6714 bool HasNullPtrType; 6715 6716 /// Sema - The semantic analysis instance where we are building the 6717 /// candidate type set. 6718 Sema &SemaRef; 6719 6720 /// Context - The AST context in which we will build the type sets. 6721 ASTContext &Context; 6722 6723 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6724 const Qualifiers &VisibleQuals); 6725 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6726 6727 public: 6728 /// iterator - Iterates through the types that are part of the set. 6729 typedef TypeSet::iterator iterator; 6730 6731 BuiltinCandidateTypeSet(Sema &SemaRef) 6732 : HasNonRecordTypes(false), 6733 HasArithmeticOrEnumeralTypes(false), 6734 HasNullPtrType(false), 6735 SemaRef(SemaRef), 6736 Context(SemaRef.Context) { } 6737 6738 void AddTypesConvertedFrom(QualType Ty, 6739 SourceLocation Loc, 6740 bool AllowUserConversions, 6741 bool AllowExplicitConversions, 6742 const Qualifiers &VisibleTypeConversionsQuals); 6743 6744 /// pointer_begin - First pointer type found; 6745 iterator pointer_begin() { return PointerTypes.begin(); } 6746 6747 /// pointer_end - Past the last pointer type found; 6748 iterator pointer_end() { return PointerTypes.end(); } 6749 6750 /// member_pointer_begin - First member pointer type found; 6751 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6752 6753 /// member_pointer_end - Past the last member pointer type found; 6754 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6755 6756 /// enumeration_begin - First enumeration type found; 6757 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6758 6759 /// enumeration_end - Past the last enumeration type found; 6760 iterator enumeration_end() { return EnumerationTypes.end(); } 6761 6762 iterator vector_begin() { return VectorTypes.begin(); } 6763 iterator vector_end() { return VectorTypes.end(); } 6764 6765 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6766 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6767 bool hasNullPtrType() const { return HasNullPtrType; } 6768 }; 6769 6770 } // end anonymous namespace 6771 6772 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6773 /// the set of pointer types along with any more-qualified variants of 6774 /// that type. For example, if @p Ty is "int const *", this routine 6775 /// will add "int const *", "int const volatile *", "int const 6776 /// restrict *", and "int const volatile restrict *" to the set of 6777 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6778 /// false otherwise. 6779 /// 6780 /// FIXME: what to do about extended qualifiers? 6781 bool 6782 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6783 const Qualifiers &VisibleQuals) { 6784 6785 // Insert this type. 6786 if (!PointerTypes.insert(Ty).second) 6787 return false; 6788 6789 QualType PointeeTy; 6790 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6791 bool buildObjCPtr = false; 6792 if (!PointerTy) { 6793 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6794 PointeeTy = PTy->getPointeeType(); 6795 buildObjCPtr = true; 6796 } else { 6797 PointeeTy = PointerTy->getPointeeType(); 6798 } 6799 6800 // Don't add qualified variants of arrays. For one, they're not allowed 6801 // (the qualifier would sink to the element type), and for another, the 6802 // only overload situation where it matters is subscript or pointer +- int, 6803 // and those shouldn't have qualifier variants anyway. 6804 if (PointeeTy->isArrayType()) 6805 return true; 6806 6807 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6808 bool hasVolatile = VisibleQuals.hasVolatile(); 6809 bool hasRestrict = VisibleQuals.hasRestrict(); 6810 6811 // Iterate through all strict supersets of BaseCVR. 6812 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6813 if ((CVR | BaseCVR) != CVR) continue; 6814 // Skip over volatile if no volatile found anywhere in the types. 6815 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6816 6817 // Skip over restrict if no restrict found anywhere in the types, or if 6818 // the type cannot be restrict-qualified. 6819 if ((CVR & Qualifiers::Restrict) && 6820 (!hasRestrict || 6821 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6822 continue; 6823 6824 // Build qualified pointee type. 6825 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6826 6827 // Build qualified pointer type. 6828 QualType QPointerTy; 6829 if (!buildObjCPtr) 6830 QPointerTy = Context.getPointerType(QPointeeTy); 6831 else 6832 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6833 6834 // Insert qualified pointer type. 6835 PointerTypes.insert(QPointerTy); 6836 } 6837 6838 return true; 6839 } 6840 6841 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6842 /// to the set of pointer types along with any more-qualified variants of 6843 /// that type. For example, if @p Ty is "int const *", this routine 6844 /// will add "int const *", "int const volatile *", "int const 6845 /// restrict *", and "int const volatile restrict *" to the set of 6846 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6847 /// false otherwise. 6848 /// 6849 /// FIXME: what to do about extended qualifiers? 6850 bool 6851 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6852 QualType Ty) { 6853 // Insert this type. 6854 if (!MemberPointerTypes.insert(Ty).second) 6855 return false; 6856 6857 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6858 assert(PointerTy && "type was not a member pointer type!"); 6859 6860 QualType PointeeTy = PointerTy->getPointeeType(); 6861 // Don't add qualified variants of arrays. For one, they're not allowed 6862 // (the qualifier would sink to the element type), and for another, the 6863 // only overload situation where it matters is subscript or pointer +- int, 6864 // and those shouldn't have qualifier variants anyway. 6865 if (PointeeTy->isArrayType()) 6866 return true; 6867 const Type *ClassTy = PointerTy->getClass(); 6868 6869 // Iterate through all strict supersets of the pointee type's CVR 6870 // qualifiers. 6871 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6872 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6873 if ((CVR | BaseCVR) != CVR) continue; 6874 6875 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6876 MemberPointerTypes.insert( 6877 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6878 } 6879 6880 return true; 6881 } 6882 6883 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6884 /// Ty can be implicit converted to the given set of @p Types. We're 6885 /// primarily interested in pointer types and enumeration types. We also 6886 /// take member pointer types, for the conditional operator. 6887 /// AllowUserConversions is true if we should look at the conversion 6888 /// functions of a class type, and AllowExplicitConversions if we 6889 /// should also include the explicit conversion functions of a class 6890 /// type. 6891 void 6892 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6893 SourceLocation Loc, 6894 bool AllowUserConversions, 6895 bool AllowExplicitConversions, 6896 const Qualifiers &VisibleQuals) { 6897 // Only deal with canonical types. 6898 Ty = Context.getCanonicalType(Ty); 6899 6900 // Look through reference types; they aren't part of the type of an 6901 // expression for the purposes of conversions. 6902 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6903 Ty = RefTy->getPointeeType(); 6904 6905 // If we're dealing with an array type, decay to the pointer. 6906 if (Ty->isArrayType()) 6907 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6908 6909 // Otherwise, we don't care about qualifiers on the type. 6910 Ty = Ty.getLocalUnqualifiedType(); 6911 6912 // Flag if we ever add a non-record type. 6913 const RecordType *TyRec = Ty->getAs<RecordType>(); 6914 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6915 6916 // Flag if we encounter an arithmetic type. 6917 HasArithmeticOrEnumeralTypes = 6918 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6919 6920 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6921 PointerTypes.insert(Ty); 6922 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6923 // Insert our type, and its more-qualified variants, into the set 6924 // of types. 6925 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6926 return; 6927 } else if (Ty->isMemberPointerType()) { 6928 // Member pointers are far easier, since the pointee can't be converted. 6929 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6930 return; 6931 } else if (Ty->isEnumeralType()) { 6932 HasArithmeticOrEnumeralTypes = true; 6933 EnumerationTypes.insert(Ty); 6934 } else if (Ty->isVectorType()) { 6935 // We treat vector types as arithmetic types in many contexts as an 6936 // extension. 6937 HasArithmeticOrEnumeralTypes = true; 6938 VectorTypes.insert(Ty); 6939 } else if (Ty->isNullPtrType()) { 6940 HasNullPtrType = true; 6941 } else if (AllowUserConversions && TyRec) { 6942 // No conversion functions in incomplete types. 6943 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6944 return; 6945 6946 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6947 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 6948 if (isa<UsingShadowDecl>(D)) 6949 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6950 6951 // Skip conversion function templates; they don't tell us anything 6952 // about which builtin types we can convert to. 6953 if (isa<FunctionTemplateDecl>(D)) 6954 continue; 6955 6956 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6957 if (AllowExplicitConversions || !Conv->isExplicit()) { 6958 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6959 VisibleQuals); 6960 } 6961 } 6962 } 6963 } 6964 6965 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6966 /// the volatile- and non-volatile-qualified assignment operators for the 6967 /// given type to the candidate set. 6968 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6969 QualType T, 6970 ArrayRef<Expr *> Args, 6971 OverloadCandidateSet &CandidateSet) { 6972 QualType ParamTypes[2]; 6973 6974 // T& operator=(T&, T) 6975 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6976 ParamTypes[1] = T; 6977 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6978 /*IsAssignmentOperator=*/true); 6979 6980 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6981 // volatile T& operator=(volatile T&, T) 6982 ParamTypes[0] 6983 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6984 ParamTypes[1] = T; 6985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6986 /*IsAssignmentOperator=*/true); 6987 } 6988 } 6989 6990 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6991 /// if any, found in visible type conversion functions found in ArgExpr's type. 6992 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6993 Qualifiers VRQuals; 6994 const RecordType *TyRec; 6995 if (const MemberPointerType *RHSMPType = 6996 ArgExpr->getType()->getAs<MemberPointerType>()) 6997 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6998 else 6999 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7000 if (!TyRec) { 7001 // Just to be safe, assume the worst case. 7002 VRQuals.addVolatile(); 7003 VRQuals.addRestrict(); 7004 return VRQuals; 7005 } 7006 7007 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7008 if (!ClassDecl->hasDefinition()) 7009 return VRQuals; 7010 7011 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7012 if (isa<UsingShadowDecl>(D)) 7013 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7014 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7015 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7016 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7017 CanTy = ResTypeRef->getPointeeType(); 7018 // Need to go down the pointer/mempointer chain and add qualifiers 7019 // as see them. 7020 bool done = false; 7021 while (!done) { 7022 if (CanTy.isRestrictQualified()) 7023 VRQuals.addRestrict(); 7024 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7025 CanTy = ResTypePtr->getPointeeType(); 7026 else if (const MemberPointerType *ResTypeMPtr = 7027 CanTy->getAs<MemberPointerType>()) 7028 CanTy = ResTypeMPtr->getPointeeType(); 7029 else 7030 done = true; 7031 if (CanTy.isVolatileQualified()) 7032 VRQuals.addVolatile(); 7033 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7034 return VRQuals; 7035 } 7036 } 7037 } 7038 return VRQuals; 7039 } 7040 7041 namespace { 7042 7043 /// \brief Helper class to manage the addition of builtin operator overload 7044 /// candidates. It provides shared state and utility methods used throughout 7045 /// the process, as well as a helper method to add each group of builtin 7046 /// operator overloads from the standard to a candidate set. 7047 class BuiltinOperatorOverloadBuilder { 7048 // Common instance state available to all overload candidate addition methods. 7049 Sema &S; 7050 ArrayRef<Expr *> Args; 7051 Qualifiers VisibleTypeConversionsQuals; 7052 bool HasArithmeticOrEnumeralCandidateType; 7053 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7054 OverloadCandidateSet &CandidateSet; 7055 7056 // Define some constants used to index and iterate over the arithemetic types 7057 // provided via the getArithmeticType() method below. 7058 // The "promoted arithmetic types" are the arithmetic 7059 // types are that preserved by promotion (C++ [over.built]p2). 7060 static const unsigned FirstIntegralType = 3; 7061 static const unsigned LastIntegralType = 20; 7062 static const unsigned FirstPromotedIntegralType = 3, 7063 LastPromotedIntegralType = 11; 7064 static const unsigned FirstPromotedArithmeticType = 0, 7065 LastPromotedArithmeticType = 11; 7066 static const unsigned NumArithmeticTypes = 20; 7067 7068 /// \brief Get the canonical type for a given arithmetic type index. 7069 CanQualType getArithmeticType(unsigned index) { 7070 assert(index < NumArithmeticTypes); 7071 static CanQualType ASTContext::* const 7072 ArithmeticTypes[NumArithmeticTypes] = { 7073 // Start of promoted types. 7074 &ASTContext::FloatTy, 7075 &ASTContext::DoubleTy, 7076 &ASTContext::LongDoubleTy, 7077 7078 // Start of integral types. 7079 &ASTContext::IntTy, 7080 &ASTContext::LongTy, 7081 &ASTContext::LongLongTy, 7082 &ASTContext::Int128Ty, 7083 &ASTContext::UnsignedIntTy, 7084 &ASTContext::UnsignedLongTy, 7085 &ASTContext::UnsignedLongLongTy, 7086 &ASTContext::UnsignedInt128Ty, 7087 // End of promoted types. 7088 7089 &ASTContext::BoolTy, 7090 &ASTContext::CharTy, 7091 &ASTContext::WCharTy, 7092 &ASTContext::Char16Ty, 7093 &ASTContext::Char32Ty, 7094 &ASTContext::SignedCharTy, 7095 &ASTContext::ShortTy, 7096 &ASTContext::UnsignedCharTy, 7097 &ASTContext::UnsignedShortTy, 7098 // End of integral types. 7099 // FIXME: What about complex? What about half? 7100 }; 7101 return S.Context.*ArithmeticTypes[index]; 7102 } 7103 7104 /// \brief Gets the canonical type resulting from the usual arithemetic 7105 /// converions for the given arithmetic types. 7106 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7107 // Accelerator table for performing the usual arithmetic conversions. 7108 // The rules are basically: 7109 // - if either is floating-point, use the wider floating-point 7110 // - if same signedness, use the higher rank 7111 // - if same size, use unsigned of the higher rank 7112 // - use the larger type 7113 // These rules, together with the axiom that higher ranks are 7114 // never smaller, are sufficient to precompute all of these results 7115 // *except* when dealing with signed types of higher rank. 7116 // (we could precompute SLL x UI for all known platforms, but it's 7117 // better not to make any assumptions). 7118 // We assume that int128 has a higher rank than long long on all platforms. 7119 enum PromotedType { 7120 Dep=-1, 7121 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7122 }; 7123 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7124 [LastPromotedArithmeticType] = { 7125 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7126 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7127 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7128 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7129 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7130 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7131 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7132 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7133 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7134 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7135 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7136 }; 7137 7138 assert(L < LastPromotedArithmeticType); 7139 assert(R < LastPromotedArithmeticType); 7140 int Idx = ConversionsTable[L][R]; 7141 7142 // Fast path: the table gives us a concrete answer. 7143 if (Idx != Dep) return getArithmeticType(Idx); 7144 7145 // Slow path: we need to compare widths. 7146 // An invariant is that the signed type has higher rank. 7147 CanQualType LT = getArithmeticType(L), 7148 RT = getArithmeticType(R); 7149 unsigned LW = S.Context.getIntWidth(LT), 7150 RW = S.Context.getIntWidth(RT); 7151 7152 // If they're different widths, use the signed type. 7153 if (LW > RW) return LT; 7154 else if (LW < RW) return RT; 7155 7156 // Otherwise, use the unsigned type of the signed type's rank. 7157 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7158 assert(L == SLL || R == SLL); 7159 return S.Context.UnsignedLongLongTy; 7160 } 7161 7162 /// \brief Helper method to factor out the common pattern of adding overloads 7163 /// for '++' and '--' builtin operators. 7164 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7165 bool HasVolatile, 7166 bool HasRestrict) { 7167 QualType ParamTypes[2] = { 7168 S.Context.getLValueReferenceType(CandidateTy), 7169 S.Context.IntTy 7170 }; 7171 7172 // Non-volatile version. 7173 if (Args.size() == 1) 7174 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7175 else 7176 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7177 7178 // Use a heuristic to reduce number of builtin candidates in the set: 7179 // add volatile version only if there are conversions to a volatile type. 7180 if (HasVolatile) { 7181 ParamTypes[0] = 7182 S.Context.getLValueReferenceType( 7183 S.Context.getVolatileType(CandidateTy)); 7184 if (Args.size() == 1) 7185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7186 else 7187 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7188 } 7189 7190 // Add restrict version only if there are conversions to a restrict type 7191 // and our candidate type is a non-restrict-qualified pointer. 7192 if (HasRestrict && CandidateTy->isAnyPointerType() && 7193 !CandidateTy.isRestrictQualified()) { 7194 ParamTypes[0] 7195 = S.Context.getLValueReferenceType( 7196 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7197 if (Args.size() == 1) 7198 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7199 else 7200 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7201 7202 if (HasVolatile) { 7203 ParamTypes[0] 7204 = S.Context.getLValueReferenceType( 7205 S.Context.getCVRQualifiedType(CandidateTy, 7206 (Qualifiers::Volatile | 7207 Qualifiers::Restrict))); 7208 if (Args.size() == 1) 7209 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7210 else 7211 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7212 } 7213 } 7214 7215 } 7216 7217 public: 7218 BuiltinOperatorOverloadBuilder( 7219 Sema &S, ArrayRef<Expr *> Args, 7220 Qualifiers VisibleTypeConversionsQuals, 7221 bool HasArithmeticOrEnumeralCandidateType, 7222 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7223 OverloadCandidateSet &CandidateSet) 7224 : S(S), Args(Args), 7225 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7226 HasArithmeticOrEnumeralCandidateType( 7227 HasArithmeticOrEnumeralCandidateType), 7228 CandidateTypes(CandidateTypes), 7229 CandidateSet(CandidateSet) { 7230 // Validate some of our static helper constants in debug builds. 7231 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7232 "Invalid first promoted integral type"); 7233 assert(getArithmeticType(LastPromotedIntegralType - 1) 7234 == S.Context.UnsignedInt128Ty && 7235 "Invalid last promoted integral type"); 7236 assert(getArithmeticType(FirstPromotedArithmeticType) 7237 == S.Context.FloatTy && 7238 "Invalid first promoted arithmetic type"); 7239 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7240 == S.Context.UnsignedInt128Ty && 7241 "Invalid last promoted arithmetic type"); 7242 } 7243 7244 // C++ [over.built]p3: 7245 // 7246 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7247 // is either volatile or empty, there exist candidate operator 7248 // functions of the form 7249 // 7250 // VQ T& operator++(VQ T&); 7251 // T operator++(VQ T&, int); 7252 // 7253 // C++ [over.built]p4: 7254 // 7255 // For every pair (T, VQ), where T is an arithmetic type other 7256 // than bool, and VQ is either volatile or empty, there exist 7257 // candidate operator functions of the form 7258 // 7259 // VQ T& operator--(VQ T&); 7260 // T operator--(VQ T&, int); 7261 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7262 if (!HasArithmeticOrEnumeralCandidateType) 7263 return; 7264 7265 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7266 Arith < NumArithmeticTypes; ++Arith) { 7267 addPlusPlusMinusMinusStyleOverloads( 7268 getArithmeticType(Arith), 7269 VisibleTypeConversionsQuals.hasVolatile(), 7270 VisibleTypeConversionsQuals.hasRestrict()); 7271 } 7272 } 7273 7274 // C++ [over.built]p5: 7275 // 7276 // For every pair (T, VQ), where T is a cv-qualified or 7277 // cv-unqualified object type, and VQ is either volatile or 7278 // empty, there exist candidate operator functions of the form 7279 // 7280 // T*VQ& operator++(T*VQ&); 7281 // T*VQ& operator--(T*VQ&); 7282 // T* operator++(T*VQ&, int); 7283 // T* operator--(T*VQ&, int); 7284 void addPlusPlusMinusMinusPointerOverloads() { 7285 for (BuiltinCandidateTypeSet::iterator 7286 Ptr = CandidateTypes[0].pointer_begin(), 7287 PtrEnd = CandidateTypes[0].pointer_end(); 7288 Ptr != PtrEnd; ++Ptr) { 7289 // Skip pointer types that aren't pointers to object types. 7290 if (!(*Ptr)->getPointeeType()->isObjectType()) 7291 continue; 7292 7293 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7294 (!(*Ptr).isVolatileQualified() && 7295 VisibleTypeConversionsQuals.hasVolatile()), 7296 (!(*Ptr).isRestrictQualified() && 7297 VisibleTypeConversionsQuals.hasRestrict())); 7298 } 7299 } 7300 7301 // C++ [over.built]p6: 7302 // For every cv-qualified or cv-unqualified object type T, there 7303 // exist candidate operator functions of the form 7304 // 7305 // T& operator*(T*); 7306 // 7307 // C++ [over.built]p7: 7308 // For every function type T that does not have cv-qualifiers or a 7309 // ref-qualifier, there exist candidate operator functions of the form 7310 // T& operator*(T*); 7311 void addUnaryStarPointerOverloads() { 7312 for (BuiltinCandidateTypeSet::iterator 7313 Ptr = CandidateTypes[0].pointer_begin(), 7314 PtrEnd = CandidateTypes[0].pointer_end(); 7315 Ptr != PtrEnd; ++Ptr) { 7316 QualType ParamTy = *Ptr; 7317 QualType PointeeTy = ParamTy->getPointeeType(); 7318 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7319 continue; 7320 7321 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7322 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7323 continue; 7324 7325 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7326 &ParamTy, Args, CandidateSet); 7327 } 7328 } 7329 7330 // C++ [over.built]p9: 7331 // For every promoted arithmetic type T, there exist candidate 7332 // operator functions of the form 7333 // 7334 // T operator+(T); 7335 // T operator-(T); 7336 void addUnaryPlusOrMinusArithmeticOverloads() { 7337 if (!HasArithmeticOrEnumeralCandidateType) 7338 return; 7339 7340 for (unsigned Arith = FirstPromotedArithmeticType; 7341 Arith < LastPromotedArithmeticType; ++Arith) { 7342 QualType ArithTy = getArithmeticType(Arith); 7343 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7344 } 7345 7346 // Extension: We also add these operators for vector types. 7347 for (BuiltinCandidateTypeSet::iterator 7348 Vec = CandidateTypes[0].vector_begin(), 7349 VecEnd = CandidateTypes[0].vector_end(); 7350 Vec != VecEnd; ++Vec) { 7351 QualType VecTy = *Vec; 7352 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7353 } 7354 } 7355 7356 // C++ [over.built]p8: 7357 // For every type T, there exist candidate operator functions of 7358 // the form 7359 // 7360 // T* operator+(T*); 7361 void addUnaryPlusPointerOverloads() { 7362 for (BuiltinCandidateTypeSet::iterator 7363 Ptr = CandidateTypes[0].pointer_begin(), 7364 PtrEnd = CandidateTypes[0].pointer_end(); 7365 Ptr != PtrEnd; ++Ptr) { 7366 QualType ParamTy = *Ptr; 7367 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7368 } 7369 } 7370 7371 // C++ [over.built]p10: 7372 // For every promoted integral type T, there exist candidate 7373 // operator functions of the form 7374 // 7375 // T operator~(T); 7376 void addUnaryTildePromotedIntegralOverloads() { 7377 if (!HasArithmeticOrEnumeralCandidateType) 7378 return; 7379 7380 for (unsigned Int = FirstPromotedIntegralType; 7381 Int < LastPromotedIntegralType; ++Int) { 7382 QualType IntTy = getArithmeticType(Int); 7383 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7384 } 7385 7386 // Extension: We also add this operator for vector types. 7387 for (BuiltinCandidateTypeSet::iterator 7388 Vec = CandidateTypes[0].vector_begin(), 7389 VecEnd = CandidateTypes[0].vector_end(); 7390 Vec != VecEnd; ++Vec) { 7391 QualType VecTy = *Vec; 7392 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7393 } 7394 } 7395 7396 // C++ [over.match.oper]p16: 7397 // For every pointer to member type T, there exist candidate operator 7398 // functions of the form 7399 // 7400 // bool operator==(T,T); 7401 // bool operator!=(T,T); 7402 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7403 /// Set of (canonical) types that we've already handled. 7404 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7405 7406 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7407 for (BuiltinCandidateTypeSet::iterator 7408 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7409 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7410 MemPtr != MemPtrEnd; 7411 ++MemPtr) { 7412 // Don't add the same builtin candidate twice. 7413 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7414 continue; 7415 7416 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7417 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7418 } 7419 } 7420 } 7421 7422 // C++ [over.built]p15: 7423 // 7424 // For every T, where T is an enumeration type, a pointer type, or 7425 // std::nullptr_t, there exist candidate operator functions of the form 7426 // 7427 // bool operator<(T, T); 7428 // bool operator>(T, T); 7429 // bool operator<=(T, T); 7430 // bool operator>=(T, T); 7431 // bool operator==(T, T); 7432 // bool operator!=(T, T); 7433 void addRelationalPointerOrEnumeralOverloads() { 7434 // C++ [over.match.oper]p3: 7435 // [...]the built-in candidates include all of the candidate operator 7436 // functions defined in 13.6 that, compared to the given operator, [...] 7437 // do not have the same parameter-type-list as any non-template non-member 7438 // candidate. 7439 // 7440 // Note that in practice, this only affects enumeration types because there 7441 // aren't any built-in candidates of record type, and a user-defined operator 7442 // must have an operand of record or enumeration type. Also, the only other 7443 // overloaded operator with enumeration arguments, operator=, 7444 // cannot be overloaded for enumeration types, so this is the only place 7445 // where we must suppress candidates like this. 7446 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7447 UserDefinedBinaryOperators; 7448 7449 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7450 if (CandidateTypes[ArgIdx].enumeration_begin() != 7451 CandidateTypes[ArgIdx].enumeration_end()) { 7452 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7453 CEnd = CandidateSet.end(); 7454 C != CEnd; ++C) { 7455 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7456 continue; 7457 7458 if (C->Function->isFunctionTemplateSpecialization()) 7459 continue; 7460 7461 QualType FirstParamType = 7462 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7463 QualType SecondParamType = 7464 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7465 7466 // Skip if either parameter isn't of enumeral type. 7467 if (!FirstParamType->isEnumeralType() || 7468 !SecondParamType->isEnumeralType()) 7469 continue; 7470 7471 // Add this operator to the set of known user-defined operators. 7472 UserDefinedBinaryOperators.insert( 7473 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7474 S.Context.getCanonicalType(SecondParamType))); 7475 } 7476 } 7477 } 7478 7479 /// Set of (canonical) types that we've already handled. 7480 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7481 7482 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7483 for (BuiltinCandidateTypeSet::iterator 7484 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7485 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7486 Ptr != PtrEnd; ++Ptr) { 7487 // Don't add the same builtin candidate twice. 7488 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7489 continue; 7490 7491 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7492 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7493 } 7494 for (BuiltinCandidateTypeSet::iterator 7495 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7496 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7497 Enum != EnumEnd; ++Enum) { 7498 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7499 7500 // Don't add the same builtin candidate twice, or if a user defined 7501 // candidate exists. 7502 if (!AddedTypes.insert(CanonType).second || 7503 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7504 CanonType))) 7505 continue; 7506 7507 QualType ParamTypes[2] = { *Enum, *Enum }; 7508 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7509 } 7510 7511 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7512 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7513 if (AddedTypes.insert(NullPtrTy).second && 7514 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7515 NullPtrTy))) { 7516 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7517 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7518 CandidateSet); 7519 } 7520 } 7521 } 7522 } 7523 7524 // C++ [over.built]p13: 7525 // 7526 // For every cv-qualified or cv-unqualified object type T 7527 // there exist candidate operator functions of the form 7528 // 7529 // T* operator+(T*, ptrdiff_t); 7530 // T& operator[](T*, ptrdiff_t); [BELOW] 7531 // T* operator-(T*, ptrdiff_t); 7532 // T* operator+(ptrdiff_t, T*); 7533 // T& operator[](ptrdiff_t, T*); [BELOW] 7534 // 7535 // C++ [over.built]p14: 7536 // 7537 // For every T, where T is a pointer to object type, there 7538 // exist candidate operator functions of the form 7539 // 7540 // ptrdiff_t operator-(T, T); 7541 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7542 /// Set of (canonical) types that we've already handled. 7543 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7544 7545 for (int Arg = 0; Arg < 2; ++Arg) { 7546 QualType AsymetricParamTypes[2] = { 7547 S.Context.getPointerDiffType(), 7548 S.Context.getPointerDiffType(), 7549 }; 7550 for (BuiltinCandidateTypeSet::iterator 7551 Ptr = CandidateTypes[Arg].pointer_begin(), 7552 PtrEnd = CandidateTypes[Arg].pointer_end(); 7553 Ptr != PtrEnd; ++Ptr) { 7554 QualType PointeeTy = (*Ptr)->getPointeeType(); 7555 if (!PointeeTy->isObjectType()) 7556 continue; 7557 7558 AsymetricParamTypes[Arg] = *Ptr; 7559 if (Arg == 0 || Op == OO_Plus) { 7560 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7561 // T* operator+(ptrdiff_t, T*); 7562 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7563 } 7564 if (Op == OO_Minus) { 7565 // ptrdiff_t operator-(T, T); 7566 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7567 continue; 7568 7569 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7570 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7571 Args, CandidateSet); 7572 } 7573 } 7574 } 7575 } 7576 7577 // C++ [over.built]p12: 7578 // 7579 // For every pair of promoted arithmetic types L and R, there 7580 // exist candidate operator functions of the form 7581 // 7582 // LR operator*(L, R); 7583 // LR operator/(L, R); 7584 // LR operator+(L, R); 7585 // LR operator-(L, R); 7586 // bool operator<(L, R); 7587 // bool operator>(L, R); 7588 // bool operator<=(L, R); 7589 // bool operator>=(L, R); 7590 // bool operator==(L, R); 7591 // bool operator!=(L, R); 7592 // 7593 // where LR is the result of the usual arithmetic conversions 7594 // between types L and R. 7595 // 7596 // C++ [over.built]p24: 7597 // 7598 // For every pair of promoted arithmetic types L and R, there exist 7599 // candidate operator functions of the form 7600 // 7601 // LR operator?(bool, L, R); 7602 // 7603 // where LR is the result of the usual arithmetic conversions 7604 // between types L and R. 7605 // Our candidates ignore the first parameter. 7606 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7607 if (!HasArithmeticOrEnumeralCandidateType) 7608 return; 7609 7610 for (unsigned Left = FirstPromotedArithmeticType; 7611 Left < LastPromotedArithmeticType; ++Left) { 7612 for (unsigned Right = FirstPromotedArithmeticType; 7613 Right < LastPromotedArithmeticType; ++Right) { 7614 QualType LandR[2] = { getArithmeticType(Left), 7615 getArithmeticType(Right) }; 7616 QualType Result = 7617 isComparison ? S.Context.BoolTy 7618 : getUsualArithmeticConversions(Left, Right); 7619 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7620 } 7621 } 7622 7623 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7624 // conditional operator for vector types. 7625 for (BuiltinCandidateTypeSet::iterator 7626 Vec1 = CandidateTypes[0].vector_begin(), 7627 Vec1End = CandidateTypes[0].vector_end(); 7628 Vec1 != Vec1End; ++Vec1) { 7629 for (BuiltinCandidateTypeSet::iterator 7630 Vec2 = CandidateTypes[1].vector_begin(), 7631 Vec2End = CandidateTypes[1].vector_end(); 7632 Vec2 != Vec2End; ++Vec2) { 7633 QualType LandR[2] = { *Vec1, *Vec2 }; 7634 QualType Result = S.Context.BoolTy; 7635 if (!isComparison) { 7636 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7637 Result = *Vec1; 7638 else 7639 Result = *Vec2; 7640 } 7641 7642 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7643 } 7644 } 7645 } 7646 7647 // C++ [over.built]p17: 7648 // 7649 // For every pair of promoted integral types L and R, there 7650 // exist candidate operator functions of the form 7651 // 7652 // LR operator%(L, R); 7653 // LR operator&(L, R); 7654 // LR operator^(L, R); 7655 // LR operator|(L, R); 7656 // L operator<<(L, R); 7657 // L operator>>(L, R); 7658 // 7659 // where LR is the result of the usual arithmetic conversions 7660 // between types L and R. 7661 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7662 if (!HasArithmeticOrEnumeralCandidateType) 7663 return; 7664 7665 for (unsigned Left = FirstPromotedIntegralType; 7666 Left < LastPromotedIntegralType; ++Left) { 7667 for (unsigned Right = FirstPromotedIntegralType; 7668 Right < LastPromotedIntegralType; ++Right) { 7669 QualType LandR[2] = { getArithmeticType(Left), 7670 getArithmeticType(Right) }; 7671 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7672 ? LandR[0] 7673 : getUsualArithmeticConversions(Left, Right); 7674 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7675 } 7676 } 7677 } 7678 7679 // C++ [over.built]p20: 7680 // 7681 // For every pair (T, VQ), where T is an enumeration or 7682 // pointer to member type and VQ is either volatile or 7683 // empty, there exist candidate operator functions of the form 7684 // 7685 // VQ T& operator=(VQ T&, T); 7686 void addAssignmentMemberPointerOrEnumeralOverloads() { 7687 /// Set of (canonical) types that we've already handled. 7688 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7689 7690 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7691 for (BuiltinCandidateTypeSet::iterator 7692 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7693 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7694 Enum != EnumEnd; ++Enum) { 7695 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7696 continue; 7697 7698 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7699 } 7700 7701 for (BuiltinCandidateTypeSet::iterator 7702 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7703 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7704 MemPtr != MemPtrEnd; ++MemPtr) { 7705 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7706 continue; 7707 7708 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7709 } 7710 } 7711 } 7712 7713 // C++ [over.built]p19: 7714 // 7715 // For every pair (T, VQ), where T is any type and VQ is either 7716 // volatile or empty, there exist candidate operator functions 7717 // of the form 7718 // 7719 // T*VQ& operator=(T*VQ&, T*); 7720 // 7721 // C++ [over.built]p21: 7722 // 7723 // For every pair (T, VQ), where T is a cv-qualified or 7724 // cv-unqualified object type and VQ is either volatile or 7725 // empty, there exist candidate operator functions of the form 7726 // 7727 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7728 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7729 void addAssignmentPointerOverloads(bool isEqualOp) { 7730 /// Set of (canonical) types that we've already handled. 7731 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7732 7733 for (BuiltinCandidateTypeSet::iterator 7734 Ptr = CandidateTypes[0].pointer_begin(), 7735 PtrEnd = CandidateTypes[0].pointer_end(); 7736 Ptr != PtrEnd; ++Ptr) { 7737 // If this is operator=, keep track of the builtin candidates we added. 7738 if (isEqualOp) 7739 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7740 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7741 continue; 7742 7743 // non-volatile version 7744 QualType ParamTypes[2] = { 7745 S.Context.getLValueReferenceType(*Ptr), 7746 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7747 }; 7748 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7749 /*IsAssigmentOperator=*/ isEqualOp); 7750 7751 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7752 VisibleTypeConversionsQuals.hasVolatile(); 7753 if (NeedVolatile) { 7754 // volatile version 7755 ParamTypes[0] = 7756 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7757 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7758 /*IsAssigmentOperator=*/isEqualOp); 7759 } 7760 7761 if (!(*Ptr).isRestrictQualified() && 7762 VisibleTypeConversionsQuals.hasRestrict()) { 7763 // restrict version 7764 ParamTypes[0] 7765 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7766 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7767 /*IsAssigmentOperator=*/isEqualOp); 7768 7769 if (NeedVolatile) { 7770 // volatile restrict version 7771 ParamTypes[0] 7772 = S.Context.getLValueReferenceType( 7773 S.Context.getCVRQualifiedType(*Ptr, 7774 (Qualifiers::Volatile | 7775 Qualifiers::Restrict))); 7776 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7777 /*IsAssigmentOperator=*/isEqualOp); 7778 } 7779 } 7780 } 7781 7782 if (isEqualOp) { 7783 for (BuiltinCandidateTypeSet::iterator 7784 Ptr = CandidateTypes[1].pointer_begin(), 7785 PtrEnd = CandidateTypes[1].pointer_end(); 7786 Ptr != PtrEnd; ++Ptr) { 7787 // Make sure we don't add the same candidate twice. 7788 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7789 continue; 7790 7791 QualType ParamTypes[2] = { 7792 S.Context.getLValueReferenceType(*Ptr), 7793 *Ptr, 7794 }; 7795 7796 // non-volatile version 7797 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7798 /*IsAssigmentOperator=*/true); 7799 7800 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7801 VisibleTypeConversionsQuals.hasVolatile(); 7802 if (NeedVolatile) { 7803 // volatile version 7804 ParamTypes[0] = 7805 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7806 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7807 /*IsAssigmentOperator=*/true); 7808 } 7809 7810 if (!(*Ptr).isRestrictQualified() && 7811 VisibleTypeConversionsQuals.hasRestrict()) { 7812 // restrict version 7813 ParamTypes[0] 7814 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7815 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7816 /*IsAssigmentOperator=*/true); 7817 7818 if (NeedVolatile) { 7819 // volatile restrict version 7820 ParamTypes[0] 7821 = S.Context.getLValueReferenceType( 7822 S.Context.getCVRQualifiedType(*Ptr, 7823 (Qualifiers::Volatile | 7824 Qualifiers::Restrict))); 7825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7826 /*IsAssigmentOperator=*/true); 7827 } 7828 } 7829 } 7830 } 7831 } 7832 7833 // C++ [over.built]p18: 7834 // 7835 // For every triple (L, VQ, R), where L is an arithmetic type, 7836 // VQ is either volatile or empty, and R is a promoted 7837 // arithmetic type, there exist candidate operator functions of 7838 // the form 7839 // 7840 // VQ L& operator=(VQ L&, R); 7841 // VQ L& operator*=(VQ L&, R); 7842 // VQ L& operator/=(VQ L&, R); 7843 // VQ L& operator+=(VQ L&, R); 7844 // VQ L& operator-=(VQ L&, R); 7845 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7846 if (!HasArithmeticOrEnumeralCandidateType) 7847 return; 7848 7849 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7850 for (unsigned Right = FirstPromotedArithmeticType; 7851 Right < LastPromotedArithmeticType; ++Right) { 7852 QualType ParamTypes[2]; 7853 ParamTypes[1] = getArithmeticType(Right); 7854 7855 // Add this built-in operator as a candidate (VQ is empty). 7856 ParamTypes[0] = 7857 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7858 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7859 /*IsAssigmentOperator=*/isEqualOp); 7860 7861 // Add this built-in operator as a candidate (VQ is 'volatile'). 7862 if (VisibleTypeConversionsQuals.hasVolatile()) { 7863 ParamTypes[0] = 7864 S.Context.getVolatileType(getArithmeticType(Left)); 7865 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7866 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7867 /*IsAssigmentOperator=*/isEqualOp); 7868 } 7869 } 7870 } 7871 7872 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7873 for (BuiltinCandidateTypeSet::iterator 7874 Vec1 = CandidateTypes[0].vector_begin(), 7875 Vec1End = CandidateTypes[0].vector_end(); 7876 Vec1 != Vec1End; ++Vec1) { 7877 for (BuiltinCandidateTypeSet::iterator 7878 Vec2 = CandidateTypes[1].vector_begin(), 7879 Vec2End = CandidateTypes[1].vector_end(); 7880 Vec2 != Vec2End; ++Vec2) { 7881 QualType ParamTypes[2]; 7882 ParamTypes[1] = *Vec2; 7883 // Add this built-in operator as a candidate (VQ is empty). 7884 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7885 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7886 /*IsAssigmentOperator=*/isEqualOp); 7887 7888 // Add this built-in operator as a candidate (VQ is 'volatile'). 7889 if (VisibleTypeConversionsQuals.hasVolatile()) { 7890 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7891 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7893 /*IsAssigmentOperator=*/isEqualOp); 7894 } 7895 } 7896 } 7897 } 7898 7899 // C++ [over.built]p22: 7900 // 7901 // For every triple (L, VQ, R), where L is an integral type, VQ 7902 // is either volatile or empty, and R is a promoted integral 7903 // type, there exist candidate operator functions of the form 7904 // 7905 // VQ L& operator%=(VQ L&, R); 7906 // VQ L& operator<<=(VQ L&, R); 7907 // VQ L& operator>>=(VQ L&, R); 7908 // VQ L& operator&=(VQ L&, R); 7909 // VQ L& operator^=(VQ L&, R); 7910 // VQ L& operator|=(VQ L&, R); 7911 void addAssignmentIntegralOverloads() { 7912 if (!HasArithmeticOrEnumeralCandidateType) 7913 return; 7914 7915 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7916 for (unsigned Right = FirstPromotedIntegralType; 7917 Right < LastPromotedIntegralType; ++Right) { 7918 QualType ParamTypes[2]; 7919 ParamTypes[1] = getArithmeticType(Right); 7920 7921 // Add this built-in operator as a candidate (VQ is empty). 7922 ParamTypes[0] = 7923 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7924 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7925 if (VisibleTypeConversionsQuals.hasVolatile()) { 7926 // Add this built-in operator as a candidate (VQ is 'volatile'). 7927 ParamTypes[0] = getArithmeticType(Left); 7928 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7929 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7930 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7931 } 7932 } 7933 } 7934 } 7935 7936 // C++ [over.operator]p23: 7937 // 7938 // There also exist candidate operator functions of the form 7939 // 7940 // bool operator!(bool); 7941 // bool operator&&(bool, bool); 7942 // bool operator||(bool, bool); 7943 void addExclaimOverload() { 7944 QualType ParamTy = S.Context.BoolTy; 7945 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7946 /*IsAssignmentOperator=*/false, 7947 /*NumContextualBoolArguments=*/1); 7948 } 7949 void addAmpAmpOrPipePipeOverload() { 7950 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7951 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7952 /*IsAssignmentOperator=*/false, 7953 /*NumContextualBoolArguments=*/2); 7954 } 7955 7956 // C++ [over.built]p13: 7957 // 7958 // For every cv-qualified or cv-unqualified object type T there 7959 // exist candidate operator functions of the form 7960 // 7961 // T* operator+(T*, ptrdiff_t); [ABOVE] 7962 // T& operator[](T*, ptrdiff_t); 7963 // T* operator-(T*, ptrdiff_t); [ABOVE] 7964 // T* operator+(ptrdiff_t, T*); [ABOVE] 7965 // T& operator[](ptrdiff_t, T*); 7966 void addSubscriptOverloads() { 7967 for (BuiltinCandidateTypeSet::iterator 7968 Ptr = CandidateTypes[0].pointer_begin(), 7969 PtrEnd = CandidateTypes[0].pointer_end(); 7970 Ptr != PtrEnd; ++Ptr) { 7971 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7972 QualType PointeeType = (*Ptr)->getPointeeType(); 7973 if (!PointeeType->isObjectType()) 7974 continue; 7975 7976 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7977 7978 // T& operator[](T*, ptrdiff_t) 7979 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7980 } 7981 7982 for (BuiltinCandidateTypeSet::iterator 7983 Ptr = CandidateTypes[1].pointer_begin(), 7984 PtrEnd = CandidateTypes[1].pointer_end(); 7985 Ptr != PtrEnd; ++Ptr) { 7986 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7987 QualType PointeeType = (*Ptr)->getPointeeType(); 7988 if (!PointeeType->isObjectType()) 7989 continue; 7990 7991 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7992 7993 // T& operator[](ptrdiff_t, T*) 7994 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7995 } 7996 } 7997 7998 // C++ [over.built]p11: 7999 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8000 // C1 is the same type as C2 or is a derived class of C2, T is an object 8001 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8002 // there exist candidate operator functions of the form 8003 // 8004 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8005 // 8006 // where CV12 is the union of CV1 and CV2. 8007 void addArrowStarOverloads() { 8008 for (BuiltinCandidateTypeSet::iterator 8009 Ptr = CandidateTypes[0].pointer_begin(), 8010 PtrEnd = CandidateTypes[0].pointer_end(); 8011 Ptr != PtrEnd; ++Ptr) { 8012 QualType C1Ty = (*Ptr); 8013 QualType C1; 8014 QualifierCollector Q1; 8015 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8016 if (!isa<RecordType>(C1)) 8017 continue; 8018 // heuristic to reduce number of builtin candidates in the set. 8019 // Add volatile/restrict version only if there are conversions to a 8020 // volatile/restrict type. 8021 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8022 continue; 8023 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8024 continue; 8025 for (BuiltinCandidateTypeSet::iterator 8026 MemPtr = CandidateTypes[1].member_pointer_begin(), 8027 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8028 MemPtr != MemPtrEnd; ++MemPtr) { 8029 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8030 QualType C2 = QualType(mptr->getClass(), 0); 8031 C2 = C2.getUnqualifiedType(); 8032 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8033 break; 8034 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8035 // build CV12 T& 8036 QualType T = mptr->getPointeeType(); 8037 if (!VisibleTypeConversionsQuals.hasVolatile() && 8038 T.isVolatileQualified()) 8039 continue; 8040 if (!VisibleTypeConversionsQuals.hasRestrict() && 8041 T.isRestrictQualified()) 8042 continue; 8043 T = Q1.apply(S.Context, T); 8044 QualType ResultTy = S.Context.getLValueReferenceType(T); 8045 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8046 } 8047 } 8048 } 8049 8050 // Note that we don't consider the first argument, since it has been 8051 // contextually converted to bool long ago. The candidates below are 8052 // therefore added as binary. 8053 // 8054 // C++ [over.built]p25: 8055 // For every type T, where T is a pointer, pointer-to-member, or scoped 8056 // enumeration type, there exist candidate operator functions of the form 8057 // 8058 // T operator?(bool, T, T); 8059 // 8060 void addConditionalOperatorOverloads() { 8061 /// Set of (canonical) types that we've already handled. 8062 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8063 8064 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8065 for (BuiltinCandidateTypeSet::iterator 8066 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8067 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8068 Ptr != PtrEnd; ++Ptr) { 8069 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8070 continue; 8071 8072 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8073 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8074 } 8075 8076 for (BuiltinCandidateTypeSet::iterator 8077 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8078 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8079 MemPtr != MemPtrEnd; ++MemPtr) { 8080 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8081 continue; 8082 8083 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8084 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8085 } 8086 8087 if (S.getLangOpts().CPlusPlus11) { 8088 for (BuiltinCandidateTypeSet::iterator 8089 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8090 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8091 Enum != EnumEnd; ++Enum) { 8092 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8093 continue; 8094 8095 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8096 continue; 8097 8098 QualType ParamTypes[2] = { *Enum, *Enum }; 8099 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8100 } 8101 } 8102 } 8103 } 8104 }; 8105 8106 } // end anonymous namespace 8107 8108 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8109 /// operator overloads to the candidate set (C++ [over.built]), based 8110 /// on the operator @p Op and the arguments given. For example, if the 8111 /// operator is a binary '+', this routine might add "int 8112 /// operator+(int, int)" to cover integer addition. 8113 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8114 SourceLocation OpLoc, 8115 ArrayRef<Expr *> Args, 8116 OverloadCandidateSet &CandidateSet) { 8117 // Find all of the types that the arguments can convert to, but only 8118 // if the operator we're looking at has built-in operator candidates 8119 // that make use of these types. Also record whether we encounter non-record 8120 // candidate types or either arithmetic or enumeral candidate types. 8121 Qualifiers VisibleTypeConversionsQuals; 8122 VisibleTypeConversionsQuals.addConst(); 8123 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8124 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8125 8126 bool HasNonRecordCandidateType = false; 8127 bool HasArithmeticOrEnumeralCandidateType = false; 8128 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8129 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8130 CandidateTypes.emplace_back(*this); 8131 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8132 OpLoc, 8133 true, 8134 (Op == OO_Exclaim || 8135 Op == OO_AmpAmp || 8136 Op == OO_PipePipe), 8137 VisibleTypeConversionsQuals); 8138 HasNonRecordCandidateType = HasNonRecordCandidateType || 8139 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8140 HasArithmeticOrEnumeralCandidateType = 8141 HasArithmeticOrEnumeralCandidateType || 8142 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8143 } 8144 8145 // Exit early when no non-record types have been added to the candidate set 8146 // for any of the arguments to the operator. 8147 // 8148 // We can't exit early for !, ||, or &&, since there we have always have 8149 // 'bool' overloads. 8150 if (!HasNonRecordCandidateType && 8151 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8152 return; 8153 8154 // Setup an object to manage the common state for building overloads. 8155 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8156 VisibleTypeConversionsQuals, 8157 HasArithmeticOrEnumeralCandidateType, 8158 CandidateTypes, CandidateSet); 8159 8160 // Dispatch over the operation to add in only those overloads which apply. 8161 switch (Op) { 8162 case OO_None: 8163 case NUM_OVERLOADED_OPERATORS: 8164 llvm_unreachable("Expected an overloaded operator"); 8165 8166 case OO_New: 8167 case OO_Delete: 8168 case OO_Array_New: 8169 case OO_Array_Delete: 8170 case OO_Call: 8171 llvm_unreachable( 8172 "Special operators don't use AddBuiltinOperatorCandidates"); 8173 8174 case OO_Comma: 8175 case OO_Arrow: 8176 // C++ [over.match.oper]p3: 8177 // -- For the operator ',', the unary operator '&', or the 8178 // operator '->', the built-in candidates set is empty. 8179 break; 8180 8181 case OO_Plus: // '+' is either unary or binary 8182 if (Args.size() == 1) 8183 OpBuilder.addUnaryPlusPointerOverloads(); 8184 // Fall through. 8185 8186 case OO_Minus: // '-' is either unary or binary 8187 if (Args.size() == 1) { 8188 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8189 } else { 8190 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8191 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8192 } 8193 break; 8194 8195 case OO_Star: // '*' is either unary or binary 8196 if (Args.size() == 1) 8197 OpBuilder.addUnaryStarPointerOverloads(); 8198 else 8199 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8200 break; 8201 8202 case OO_Slash: 8203 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8204 break; 8205 8206 case OO_PlusPlus: 8207 case OO_MinusMinus: 8208 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8209 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8210 break; 8211 8212 case OO_EqualEqual: 8213 case OO_ExclaimEqual: 8214 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8215 // Fall through. 8216 8217 case OO_Less: 8218 case OO_Greater: 8219 case OO_LessEqual: 8220 case OO_GreaterEqual: 8221 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8222 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8223 break; 8224 8225 case OO_Percent: 8226 case OO_Caret: 8227 case OO_Pipe: 8228 case OO_LessLess: 8229 case OO_GreaterGreater: 8230 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8231 break; 8232 8233 case OO_Amp: // '&' is either unary or binary 8234 if (Args.size() == 1) 8235 // C++ [over.match.oper]p3: 8236 // -- For the operator ',', the unary operator '&', or the 8237 // operator '->', the built-in candidates set is empty. 8238 break; 8239 8240 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8241 break; 8242 8243 case OO_Tilde: 8244 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8245 break; 8246 8247 case OO_Equal: 8248 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8249 // Fall through. 8250 8251 case OO_PlusEqual: 8252 case OO_MinusEqual: 8253 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8254 // Fall through. 8255 8256 case OO_StarEqual: 8257 case OO_SlashEqual: 8258 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8259 break; 8260 8261 case OO_PercentEqual: 8262 case OO_LessLessEqual: 8263 case OO_GreaterGreaterEqual: 8264 case OO_AmpEqual: 8265 case OO_CaretEqual: 8266 case OO_PipeEqual: 8267 OpBuilder.addAssignmentIntegralOverloads(); 8268 break; 8269 8270 case OO_Exclaim: 8271 OpBuilder.addExclaimOverload(); 8272 break; 8273 8274 case OO_AmpAmp: 8275 case OO_PipePipe: 8276 OpBuilder.addAmpAmpOrPipePipeOverload(); 8277 break; 8278 8279 case OO_Subscript: 8280 OpBuilder.addSubscriptOverloads(); 8281 break; 8282 8283 case OO_ArrowStar: 8284 OpBuilder.addArrowStarOverloads(); 8285 break; 8286 8287 case OO_Conditional: 8288 OpBuilder.addConditionalOperatorOverloads(); 8289 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8290 break; 8291 } 8292 } 8293 8294 /// \brief Add function candidates found via argument-dependent lookup 8295 /// to the set of overloading candidates. 8296 /// 8297 /// This routine performs argument-dependent name lookup based on the 8298 /// given function name (which may also be an operator name) and adds 8299 /// all of the overload candidates found by ADL to the overload 8300 /// candidate set (C++ [basic.lookup.argdep]). 8301 void 8302 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8303 SourceLocation Loc, 8304 ArrayRef<Expr *> Args, 8305 TemplateArgumentListInfo *ExplicitTemplateArgs, 8306 OverloadCandidateSet& CandidateSet, 8307 bool PartialOverloading) { 8308 ADLResult Fns; 8309 8310 // FIXME: This approach for uniquing ADL results (and removing 8311 // redundant candidates from the set) relies on pointer-equality, 8312 // which means we need to key off the canonical decl. However, 8313 // always going back to the canonical decl might not get us the 8314 // right set of default arguments. What default arguments are 8315 // we supposed to consider on ADL candidates, anyway? 8316 8317 // FIXME: Pass in the explicit template arguments? 8318 ArgumentDependentLookup(Name, Loc, Args, Fns); 8319 8320 // Erase all of the candidates we already knew about. 8321 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8322 CandEnd = CandidateSet.end(); 8323 Cand != CandEnd; ++Cand) 8324 if (Cand->Function) { 8325 Fns.erase(Cand->Function); 8326 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8327 Fns.erase(FunTmpl); 8328 } 8329 8330 // For each of the ADL candidates we found, add it to the overload 8331 // set. 8332 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8333 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8334 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8335 if (ExplicitTemplateArgs) 8336 continue; 8337 8338 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8339 PartialOverloading); 8340 } else 8341 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8342 FoundDecl, ExplicitTemplateArgs, 8343 Args, CandidateSet, PartialOverloading); 8344 } 8345 } 8346 8347 /// isBetterOverloadCandidate - Determines whether the first overload 8348 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8349 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8350 const OverloadCandidate &Cand2, 8351 SourceLocation Loc, 8352 bool UserDefinedConversion) { 8353 // Define viable functions to be better candidates than non-viable 8354 // functions. 8355 if (!Cand2.Viable) 8356 return Cand1.Viable; 8357 else if (!Cand1.Viable) 8358 return false; 8359 8360 // C++ [over.match.best]p1: 8361 // 8362 // -- if F is a static member function, ICS1(F) is defined such 8363 // that ICS1(F) is neither better nor worse than ICS1(G) for 8364 // any function G, and, symmetrically, ICS1(G) is neither 8365 // better nor worse than ICS1(F). 8366 unsigned StartArg = 0; 8367 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8368 StartArg = 1; 8369 8370 // C++ [over.match.best]p1: 8371 // A viable function F1 is defined to be a better function than another 8372 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8373 // conversion sequence than ICSi(F2), and then... 8374 unsigned NumArgs = Cand1.NumConversions; 8375 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8376 bool HasBetterConversion = false; 8377 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8378 switch (CompareImplicitConversionSequences(S, 8379 Cand1.Conversions[ArgIdx], 8380 Cand2.Conversions[ArgIdx])) { 8381 case ImplicitConversionSequence::Better: 8382 // Cand1 has a better conversion sequence. 8383 HasBetterConversion = true; 8384 break; 8385 8386 case ImplicitConversionSequence::Worse: 8387 // Cand1 can't be better than Cand2. 8388 return false; 8389 8390 case ImplicitConversionSequence::Indistinguishable: 8391 // Do nothing. 8392 break; 8393 } 8394 } 8395 8396 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8397 // ICSj(F2), or, if not that, 8398 if (HasBetterConversion) 8399 return true; 8400 8401 // -- the context is an initialization by user-defined conversion 8402 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8403 // from the return type of F1 to the destination type (i.e., 8404 // the type of the entity being initialized) is a better 8405 // conversion sequence than the standard conversion sequence 8406 // from the return type of F2 to the destination type. 8407 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8408 isa<CXXConversionDecl>(Cand1.Function) && 8409 isa<CXXConversionDecl>(Cand2.Function)) { 8410 // First check whether we prefer one of the conversion functions over the 8411 // other. This only distinguishes the results in non-standard, extension 8412 // cases such as the conversion from a lambda closure type to a function 8413 // pointer or block. 8414 ImplicitConversionSequence::CompareKind Result = 8415 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8416 if (Result == ImplicitConversionSequence::Indistinguishable) 8417 Result = CompareStandardConversionSequences(S, 8418 Cand1.FinalConversion, 8419 Cand2.FinalConversion); 8420 8421 if (Result != ImplicitConversionSequence::Indistinguishable) 8422 return Result == ImplicitConversionSequence::Better; 8423 8424 // FIXME: Compare kind of reference binding if conversion functions 8425 // convert to a reference type used in direct reference binding, per 8426 // C++14 [over.match.best]p1 section 2 bullet 3. 8427 } 8428 8429 // -- F1 is a non-template function and F2 is a function template 8430 // specialization, or, if not that, 8431 bool Cand1IsSpecialization = Cand1.Function && 8432 Cand1.Function->getPrimaryTemplate(); 8433 bool Cand2IsSpecialization = Cand2.Function && 8434 Cand2.Function->getPrimaryTemplate(); 8435 if (Cand1IsSpecialization != Cand2IsSpecialization) 8436 return Cand2IsSpecialization; 8437 8438 // -- F1 and F2 are function template specializations, and the function 8439 // template for F1 is more specialized than the template for F2 8440 // according to the partial ordering rules described in 14.5.5.2, or, 8441 // if not that, 8442 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8443 if (FunctionTemplateDecl *BetterTemplate 8444 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8445 Cand2.Function->getPrimaryTemplate(), 8446 Loc, 8447 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8448 : TPOC_Call, 8449 Cand1.ExplicitCallArguments, 8450 Cand2.ExplicitCallArguments)) 8451 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8452 } 8453 8454 // Check for enable_if value-based overload resolution. 8455 if (Cand1.Function && Cand2.Function && 8456 (Cand1.Function->hasAttr<EnableIfAttr>() || 8457 Cand2.Function->hasAttr<EnableIfAttr>())) { 8458 // FIXME: The next several lines are just 8459 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8460 // instead of reverse order which is how they're stored in the AST. 8461 AttrVec Cand1Attrs; 8462 if (Cand1.Function->hasAttrs()) { 8463 Cand1Attrs = Cand1.Function->getAttrs(); 8464 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8465 IsNotEnableIfAttr), 8466 Cand1Attrs.end()); 8467 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end()); 8468 } 8469 8470 AttrVec Cand2Attrs; 8471 if (Cand2.Function->hasAttrs()) { 8472 Cand2Attrs = Cand2.Function->getAttrs(); 8473 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8474 IsNotEnableIfAttr), 8475 Cand2Attrs.end()); 8476 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end()); 8477 } 8478 8479 // Candidate 1 is better if it has strictly more attributes and 8480 // the common sequence is identical. 8481 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8482 return false; 8483 8484 auto Cand1I = Cand1Attrs.begin(); 8485 for (auto &Cand2A : Cand2Attrs) { 8486 auto &Cand1A = *Cand1I++; 8487 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8488 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID, 8489 S.getASTContext(), true); 8490 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID, 8491 S.getASTContext(), true); 8492 if (Cand1ID != Cand2ID) 8493 return false; 8494 } 8495 8496 return true; 8497 } 8498 8499 return false; 8500 } 8501 8502 /// \brief Computes the best viable function (C++ 13.3.3) 8503 /// within an overload candidate set. 8504 /// 8505 /// \param Loc The location of the function name (or operator symbol) for 8506 /// which overload resolution occurs. 8507 /// 8508 /// \param Best If overload resolution was successful or found a deleted 8509 /// function, \p Best points to the candidate function found. 8510 /// 8511 /// \returns The result of overload resolution. 8512 OverloadingResult 8513 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8514 iterator &Best, 8515 bool UserDefinedConversion) { 8516 // Find the best viable function. 8517 Best = end(); 8518 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8519 if (Cand->Viable) 8520 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8521 UserDefinedConversion)) 8522 Best = Cand; 8523 } 8524 8525 // If we didn't find any viable functions, abort. 8526 if (Best == end()) 8527 return OR_No_Viable_Function; 8528 8529 // Make sure that this function is better than every other viable 8530 // function. If not, we have an ambiguity. 8531 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8532 if (Cand->Viable && 8533 Cand != Best && 8534 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8535 UserDefinedConversion)) { 8536 Best = end(); 8537 return OR_Ambiguous; 8538 } 8539 } 8540 8541 // Best is the best viable function. 8542 if (Best->Function && 8543 (Best->Function->isDeleted() || 8544 S.isFunctionConsideredUnavailable(Best->Function))) 8545 return OR_Deleted; 8546 8547 return OR_Success; 8548 } 8549 8550 namespace { 8551 8552 enum OverloadCandidateKind { 8553 oc_function, 8554 oc_method, 8555 oc_constructor, 8556 oc_function_template, 8557 oc_method_template, 8558 oc_constructor_template, 8559 oc_implicit_default_constructor, 8560 oc_implicit_copy_constructor, 8561 oc_implicit_move_constructor, 8562 oc_implicit_copy_assignment, 8563 oc_implicit_move_assignment, 8564 oc_implicit_inherited_constructor 8565 }; 8566 8567 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8568 FunctionDecl *Fn, 8569 std::string &Description) { 8570 bool isTemplate = false; 8571 8572 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8573 isTemplate = true; 8574 Description = S.getTemplateArgumentBindingsText( 8575 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8576 } 8577 8578 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8579 if (!Ctor->isImplicit()) 8580 return isTemplate ? oc_constructor_template : oc_constructor; 8581 8582 if (Ctor->getInheritedConstructor()) 8583 return oc_implicit_inherited_constructor; 8584 8585 if (Ctor->isDefaultConstructor()) 8586 return oc_implicit_default_constructor; 8587 8588 if (Ctor->isMoveConstructor()) 8589 return oc_implicit_move_constructor; 8590 8591 assert(Ctor->isCopyConstructor() && 8592 "unexpected sort of implicit constructor"); 8593 return oc_implicit_copy_constructor; 8594 } 8595 8596 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8597 // This actually gets spelled 'candidate function' for now, but 8598 // it doesn't hurt to split it out. 8599 if (!Meth->isImplicit()) 8600 return isTemplate ? oc_method_template : oc_method; 8601 8602 if (Meth->isMoveAssignmentOperator()) 8603 return oc_implicit_move_assignment; 8604 8605 if (Meth->isCopyAssignmentOperator()) 8606 return oc_implicit_copy_assignment; 8607 8608 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8609 return oc_method; 8610 } 8611 8612 return isTemplate ? oc_function_template : oc_function; 8613 } 8614 8615 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8616 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8617 if (!Ctor) return; 8618 8619 Ctor = Ctor->getInheritedConstructor(); 8620 if (!Ctor) return; 8621 8622 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8623 } 8624 8625 } // end anonymous namespace 8626 8627 // Notes the location of an overload candidate. 8628 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8629 std::string FnDesc; 8630 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8631 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8632 << (unsigned) K << FnDesc; 8633 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8634 Diag(Fn->getLocation(), PD); 8635 MaybeEmitInheritedConstructorNote(*this, Fn); 8636 } 8637 8638 // Notes the location of all overload candidates designated through 8639 // OverloadedExpr 8640 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8641 assert(OverloadedExpr->getType() == Context.OverloadTy); 8642 8643 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8644 OverloadExpr *OvlExpr = Ovl.Expression; 8645 8646 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8647 IEnd = OvlExpr->decls_end(); 8648 I != IEnd; ++I) { 8649 if (FunctionTemplateDecl *FunTmpl = 8650 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8651 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8652 } else if (FunctionDecl *Fun 8653 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8654 NoteOverloadCandidate(Fun, DestType); 8655 } 8656 } 8657 } 8658 8659 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8660 /// "lead" diagnostic; it will be given two arguments, the source and 8661 /// target types of the conversion. 8662 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8663 Sema &S, 8664 SourceLocation CaretLoc, 8665 const PartialDiagnostic &PDiag) const { 8666 S.Diag(CaretLoc, PDiag) 8667 << Ambiguous.getFromType() << Ambiguous.getToType(); 8668 // FIXME: The note limiting machinery is borrowed from 8669 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8670 // refactoring here. 8671 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8672 unsigned CandsShown = 0; 8673 AmbiguousConversionSequence::const_iterator I, E; 8674 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8675 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8676 break; 8677 ++CandsShown; 8678 S.NoteOverloadCandidate(*I); 8679 } 8680 if (I != E) 8681 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8682 } 8683 8684 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8685 unsigned I) { 8686 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8687 assert(Conv.isBad()); 8688 assert(Cand->Function && "for now, candidate must be a function"); 8689 FunctionDecl *Fn = Cand->Function; 8690 8691 // There's a conversion slot for the object argument if this is a 8692 // non-constructor method. Note that 'I' corresponds the 8693 // conversion-slot index. 8694 bool isObjectArgument = false; 8695 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8696 if (I == 0) 8697 isObjectArgument = true; 8698 else 8699 I--; 8700 } 8701 8702 std::string FnDesc; 8703 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8704 8705 Expr *FromExpr = Conv.Bad.FromExpr; 8706 QualType FromTy = Conv.Bad.getFromType(); 8707 QualType ToTy = Conv.Bad.getToType(); 8708 8709 if (FromTy == S.Context.OverloadTy) { 8710 assert(FromExpr && "overload set argument came from implicit argument?"); 8711 Expr *E = FromExpr->IgnoreParens(); 8712 if (isa<UnaryOperator>(E)) 8713 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8714 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8715 8716 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8717 << (unsigned) FnKind << FnDesc 8718 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8719 << ToTy << Name << I+1; 8720 MaybeEmitInheritedConstructorNote(S, Fn); 8721 return; 8722 } 8723 8724 // Do some hand-waving analysis to see if the non-viability is due 8725 // to a qualifier mismatch. 8726 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8727 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8728 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8729 CToTy = RT->getPointeeType(); 8730 else { 8731 // TODO: detect and diagnose the full richness of const mismatches. 8732 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8733 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8734 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8735 } 8736 8737 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8738 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8739 Qualifiers FromQs = CFromTy.getQualifiers(); 8740 Qualifiers ToQs = CToTy.getQualifiers(); 8741 8742 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8743 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8744 << (unsigned) FnKind << FnDesc 8745 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8746 << FromTy 8747 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8748 << (unsigned) isObjectArgument << I+1; 8749 MaybeEmitInheritedConstructorNote(S, Fn); 8750 return; 8751 } 8752 8753 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8755 << (unsigned) FnKind << FnDesc 8756 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8757 << FromTy 8758 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8759 << (unsigned) isObjectArgument << I+1; 8760 MaybeEmitInheritedConstructorNote(S, Fn); 8761 return; 8762 } 8763 8764 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8765 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8766 << (unsigned) FnKind << FnDesc 8767 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8768 << FromTy 8769 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8770 << (unsigned) isObjectArgument << I+1; 8771 MaybeEmitInheritedConstructorNote(S, Fn); 8772 return; 8773 } 8774 8775 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8776 assert(CVR && "unexpected qualifiers mismatch"); 8777 8778 if (isObjectArgument) { 8779 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8780 << (unsigned) FnKind << FnDesc 8781 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8782 << FromTy << (CVR - 1); 8783 } else { 8784 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8785 << (unsigned) FnKind << FnDesc 8786 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8787 << FromTy << (CVR - 1) << I+1; 8788 } 8789 MaybeEmitInheritedConstructorNote(S, Fn); 8790 return; 8791 } 8792 8793 // Special diagnostic for failure to convert an initializer list, since 8794 // telling the user that it has type void is not useful. 8795 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8797 << (unsigned) FnKind << FnDesc 8798 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8799 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8800 MaybeEmitInheritedConstructorNote(S, Fn); 8801 return; 8802 } 8803 8804 // Diagnose references or pointers to incomplete types differently, 8805 // since it's far from impossible that the incompleteness triggered 8806 // the failure. 8807 QualType TempFromTy = FromTy.getNonReferenceType(); 8808 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8809 TempFromTy = PTy->getPointeeType(); 8810 if (TempFromTy->isIncompleteType()) { 8811 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8812 << (unsigned) FnKind << FnDesc 8813 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8814 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8815 MaybeEmitInheritedConstructorNote(S, Fn); 8816 return; 8817 } 8818 8819 // Diagnose base -> derived pointer conversions. 8820 unsigned BaseToDerivedConversion = 0; 8821 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8822 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8823 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8824 FromPtrTy->getPointeeType()) && 8825 !FromPtrTy->getPointeeType()->isIncompleteType() && 8826 !ToPtrTy->getPointeeType()->isIncompleteType() && 8827 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8828 FromPtrTy->getPointeeType())) 8829 BaseToDerivedConversion = 1; 8830 } 8831 } else if (const ObjCObjectPointerType *FromPtrTy 8832 = FromTy->getAs<ObjCObjectPointerType>()) { 8833 if (const ObjCObjectPointerType *ToPtrTy 8834 = ToTy->getAs<ObjCObjectPointerType>()) 8835 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8836 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8837 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8838 FromPtrTy->getPointeeType()) && 8839 FromIface->isSuperClassOf(ToIface)) 8840 BaseToDerivedConversion = 2; 8841 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8842 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8843 !FromTy->isIncompleteType() && 8844 !ToRefTy->getPointeeType()->isIncompleteType() && 8845 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8846 BaseToDerivedConversion = 3; 8847 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8848 ToTy.getNonReferenceType().getCanonicalType() == 8849 FromTy.getNonReferenceType().getCanonicalType()) { 8850 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8851 << (unsigned) FnKind << FnDesc 8852 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8853 << (unsigned) isObjectArgument << I + 1; 8854 MaybeEmitInheritedConstructorNote(S, Fn); 8855 return; 8856 } 8857 } 8858 8859 if (BaseToDerivedConversion) { 8860 S.Diag(Fn->getLocation(), 8861 diag::note_ovl_candidate_bad_base_to_derived_conv) 8862 << (unsigned) FnKind << FnDesc 8863 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8864 << (BaseToDerivedConversion - 1) 8865 << FromTy << ToTy << I+1; 8866 MaybeEmitInheritedConstructorNote(S, Fn); 8867 return; 8868 } 8869 8870 if (isa<ObjCObjectPointerType>(CFromTy) && 8871 isa<PointerType>(CToTy)) { 8872 Qualifiers FromQs = CFromTy.getQualifiers(); 8873 Qualifiers ToQs = CToTy.getQualifiers(); 8874 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8876 << (unsigned) FnKind << FnDesc 8877 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8878 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8879 MaybeEmitInheritedConstructorNote(S, Fn); 8880 return; 8881 } 8882 } 8883 8884 // Emit the generic diagnostic and, optionally, add the hints to it. 8885 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8886 FDiag << (unsigned) FnKind << FnDesc 8887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8888 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8889 << (unsigned) (Cand->Fix.Kind); 8890 8891 // If we can fix the conversion, suggest the FixIts. 8892 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8893 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8894 FDiag << *HI; 8895 S.Diag(Fn->getLocation(), FDiag); 8896 8897 MaybeEmitInheritedConstructorNote(S, Fn); 8898 } 8899 8900 /// Additional arity mismatch diagnosis specific to a function overload 8901 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8902 /// over a candidate in any candidate set. 8903 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8904 unsigned NumArgs) { 8905 FunctionDecl *Fn = Cand->Function; 8906 unsigned MinParams = Fn->getMinRequiredArguments(); 8907 8908 // With invalid overloaded operators, it's possible that we think we 8909 // have an arity mismatch when in fact it looks like we have the 8910 // right number of arguments, because only overloaded operators have 8911 // the weird behavior of overloading member and non-member functions. 8912 // Just don't report anything. 8913 if (Fn->isInvalidDecl() && 8914 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8915 return true; 8916 8917 if (NumArgs < MinParams) { 8918 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8919 (Cand->FailureKind == ovl_fail_bad_deduction && 8920 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8921 } else { 8922 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8923 (Cand->FailureKind == ovl_fail_bad_deduction && 8924 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8925 } 8926 8927 return false; 8928 } 8929 8930 /// General arity mismatch diagnosis over a candidate in a candidate set. 8931 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8932 assert(isa<FunctionDecl>(D) && 8933 "The templated declaration should at least be a function" 8934 " when diagnosing bad template argument deduction due to too many" 8935 " or too few arguments"); 8936 8937 FunctionDecl *Fn = cast<FunctionDecl>(D); 8938 8939 // TODO: treat calls to a missing default constructor as a special case 8940 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8941 unsigned MinParams = Fn->getMinRequiredArguments(); 8942 8943 // at least / at most / exactly 8944 unsigned mode, modeCount; 8945 if (NumFormalArgs < MinParams) { 8946 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8947 FnTy->isTemplateVariadic()) 8948 mode = 0; // "at least" 8949 else 8950 mode = 2; // "exactly" 8951 modeCount = MinParams; 8952 } else { 8953 if (MinParams != FnTy->getNumParams()) 8954 mode = 1; // "at most" 8955 else 8956 mode = 2; // "exactly" 8957 modeCount = FnTy->getNumParams(); 8958 } 8959 8960 std::string Description; 8961 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8962 8963 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8964 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8965 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8966 << mode << Fn->getParamDecl(0) << NumFormalArgs; 8967 else 8968 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8969 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8970 << mode << modeCount << NumFormalArgs; 8971 MaybeEmitInheritedConstructorNote(S, Fn); 8972 } 8973 8974 /// Arity mismatch diagnosis specific to a function overload candidate. 8975 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8976 unsigned NumFormalArgs) { 8977 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8978 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8979 } 8980 8981 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 8982 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8983 return FD->getDescribedFunctionTemplate(); 8984 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8985 return RD->getDescribedClassTemplate(); 8986 8987 llvm_unreachable("Unsupported: Getting the described template declaration" 8988 " for bad deduction diagnosis"); 8989 } 8990 8991 /// Diagnose a failed template-argument deduction. 8992 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8993 DeductionFailureInfo &DeductionFailure, 8994 unsigned NumArgs) { 8995 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8996 NamedDecl *ParamD; 8997 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8998 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8999 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9000 switch (DeductionFailure.Result) { 9001 case Sema::TDK_Success: 9002 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9003 9004 case Sema::TDK_Incomplete: { 9005 assert(ParamD && "no parameter found for incomplete deduction result"); 9006 S.Diag(Templated->getLocation(), 9007 diag::note_ovl_candidate_incomplete_deduction) 9008 << ParamD->getDeclName(); 9009 MaybeEmitInheritedConstructorNote(S, Templated); 9010 return; 9011 } 9012 9013 case Sema::TDK_Underqualified: { 9014 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9015 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9016 9017 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9018 9019 // Param will have been canonicalized, but it should just be a 9020 // qualified version of ParamD, so move the qualifiers to that. 9021 QualifierCollector Qs; 9022 Qs.strip(Param); 9023 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9024 assert(S.Context.hasSameType(Param, NonCanonParam)); 9025 9026 // Arg has also been canonicalized, but there's nothing we can do 9027 // about that. It also doesn't matter as much, because it won't 9028 // have any template parameters in it (because deduction isn't 9029 // done on dependent types). 9030 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9031 9032 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9033 << ParamD->getDeclName() << Arg << NonCanonParam; 9034 MaybeEmitInheritedConstructorNote(S, Templated); 9035 return; 9036 } 9037 9038 case Sema::TDK_Inconsistent: { 9039 assert(ParamD && "no parameter found for inconsistent deduction result"); 9040 int which = 0; 9041 if (isa<TemplateTypeParmDecl>(ParamD)) 9042 which = 0; 9043 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9044 which = 1; 9045 else { 9046 which = 2; 9047 } 9048 9049 S.Diag(Templated->getLocation(), 9050 diag::note_ovl_candidate_inconsistent_deduction) 9051 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9052 << *DeductionFailure.getSecondArg(); 9053 MaybeEmitInheritedConstructorNote(S, Templated); 9054 return; 9055 } 9056 9057 case Sema::TDK_InvalidExplicitArguments: 9058 assert(ParamD && "no parameter found for invalid explicit arguments"); 9059 if (ParamD->getDeclName()) 9060 S.Diag(Templated->getLocation(), 9061 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9062 << ParamD->getDeclName(); 9063 else { 9064 int index = 0; 9065 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9066 index = TTP->getIndex(); 9067 else if (NonTypeTemplateParmDecl *NTTP 9068 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9069 index = NTTP->getIndex(); 9070 else 9071 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9072 S.Diag(Templated->getLocation(), 9073 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9074 << (index + 1); 9075 } 9076 MaybeEmitInheritedConstructorNote(S, Templated); 9077 return; 9078 9079 case Sema::TDK_TooManyArguments: 9080 case Sema::TDK_TooFewArguments: 9081 DiagnoseArityMismatch(S, Templated, NumArgs); 9082 return; 9083 9084 case Sema::TDK_InstantiationDepth: 9085 S.Diag(Templated->getLocation(), 9086 diag::note_ovl_candidate_instantiation_depth); 9087 MaybeEmitInheritedConstructorNote(S, Templated); 9088 return; 9089 9090 case Sema::TDK_SubstitutionFailure: { 9091 // Format the template argument list into the argument string. 9092 SmallString<128> TemplateArgString; 9093 if (TemplateArgumentList *Args = 9094 DeductionFailure.getTemplateArgumentList()) { 9095 TemplateArgString = " "; 9096 TemplateArgString += S.getTemplateArgumentBindingsText( 9097 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9098 } 9099 9100 // If this candidate was disabled by enable_if, say so. 9101 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9102 if (PDiag && PDiag->second.getDiagID() == 9103 diag::err_typename_nested_not_found_enable_if) { 9104 // FIXME: Use the source range of the condition, and the fully-qualified 9105 // name of the enable_if template. These are both present in PDiag. 9106 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9107 << "'enable_if'" << TemplateArgString; 9108 return; 9109 } 9110 9111 // Format the SFINAE diagnostic into the argument string. 9112 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9113 // formatted message in another diagnostic. 9114 SmallString<128> SFINAEArgString; 9115 SourceRange R; 9116 if (PDiag) { 9117 SFINAEArgString = ": "; 9118 R = SourceRange(PDiag->first, PDiag->first); 9119 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9120 } 9121 9122 S.Diag(Templated->getLocation(), 9123 diag::note_ovl_candidate_substitution_failure) 9124 << TemplateArgString << SFINAEArgString << R; 9125 MaybeEmitInheritedConstructorNote(S, Templated); 9126 return; 9127 } 9128 9129 case Sema::TDK_FailedOverloadResolution: { 9130 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9131 S.Diag(Templated->getLocation(), 9132 diag::note_ovl_candidate_failed_overload_resolution) 9133 << R.Expression->getName(); 9134 return; 9135 } 9136 9137 case Sema::TDK_NonDeducedMismatch: { 9138 // FIXME: Provide a source location to indicate what we couldn't match. 9139 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9140 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9141 if (FirstTA.getKind() == TemplateArgument::Template && 9142 SecondTA.getKind() == TemplateArgument::Template) { 9143 TemplateName FirstTN = FirstTA.getAsTemplate(); 9144 TemplateName SecondTN = SecondTA.getAsTemplate(); 9145 if (FirstTN.getKind() == TemplateName::Template && 9146 SecondTN.getKind() == TemplateName::Template) { 9147 if (FirstTN.getAsTemplateDecl()->getName() == 9148 SecondTN.getAsTemplateDecl()->getName()) { 9149 // FIXME: This fixes a bad diagnostic where both templates are named 9150 // the same. This particular case is a bit difficult since: 9151 // 1) It is passed as a string to the diagnostic printer. 9152 // 2) The diagnostic printer only attempts to find a better 9153 // name for types, not decls. 9154 // Ideally, this should folded into the diagnostic printer. 9155 S.Diag(Templated->getLocation(), 9156 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9157 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9158 return; 9159 } 9160 } 9161 } 9162 // FIXME: For generic lambda parameters, check if the function is a lambda 9163 // call operator, and if so, emit a prettier and more informative 9164 // diagnostic that mentions 'auto' and lambda in addition to 9165 // (or instead of?) the canonical template type parameters. 9166 S.Diag(Templated->getLocation(), 9167 diag::note_ovl_candidate_non_deduced_mismatch) 9168 << FirstTA << SecondTA; 9169 return; 9170 } 9171 // TODO: diagnose these individually, then kill off 9172 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9173 case Sema::TDK_MiscellaneousDeductionFailure: 9174 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9175 MaybeEmitInheritedConstructorNote(S, Templated); 9176 return; 9177 } 9178 } 9179 9180 /// Diagnose a failed template-argument deduction, for function calls. 9181 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9182 unsigned NumArgs) { 9183 unsigned TDK = Cand->DeductionFailure.Result; 9184 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9185 if (CheckArityMismatch(S, Cand, NumArgs)) 9186 return; 9187 } 9188 DiagnoseBadDeduction(S, Cand->Function, // pattern 9189 Cand->DeductionFailure, NumArgs); 9190 } 9191 9192 /// CUDA: diagnose an invalid call across targets. 9193 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9194 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9195 FunctionDecl *Callee = Cand->Function; 9196 9197 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9198 CalleeTarget = S.IdentifyCUDATarget(Callee); 9199 9200 std::string FnDesc; 9201 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9202 9203 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9204 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9205 9206 // This could be an implicit constructor for which we could not infer the 9207 // target due to a collsion. Diagnose that case. 9208 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9209 if (Meth != nullptr && Meth->isImplicit()) { 9210 CXXRecordDecl *ParentClass = Meth->getParent(); 9211 Sema::CXXSpecialMember CSM; 9212 9213 switch (FnKind) { 9214 default: 9215 return; 9216 case oc_implicit_default_constructor: 9217 CSM = Sema::CXXDefaultConstructor; 9218 break; 9219 case oc_implicit_copy_constructor: 9220 CSM = Sema::CXXCopyConstructor; 9221 break; 9222 case oc_implicit_move_constructor: 9223 CSM = Sema::CXXMoveConstructor; 9224 break; 9225 case oc_implicit_copy_assignment: 9226 CSM = Sema::CXXCopyAssignment; 9227 break; 9228 case oc_implicit_move_assignment: 9229 CSM = Sema::CXXMoveAssignment; 9230 break; 9231 }; 9232 9233 bool ConstRHS = false; 9234 if (Meth->getNumParams()) { 9235 if (const ReferenceType *RT = 9236 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9237 ConstRHS = RT->getPointeeType().isConstQualified(); 9238 } 9239 } 9240 9241 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9242 /* ConstRHS */ ConstRHS, 9243 /* Diagnose */ true); 9244 } 9245 } 9246 9247 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9248 FunctionDecl *Callee = Cand->Function; 9249 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9250 9251 S.Diag(Callee->getLocation(), 9252 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9253 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9254 } 9255 9256 /// Generates a 'note' diagnostic for an overload candidate. We've 9257 /// already generated a primary error at the call site. 9258 /// 9259 /// It really does need to be a single diagnostic with its caret 9260 /// pointed at the candidate declaration. Yes, this creates some 9261 /// major challenges of technical writing. Yes, this makes pointing 9262 /// out problems with specific arguments quite awkward. It's still 9263 /// better than generating twenty screens of text for every failed 9264 /// overload. 9265 /// 9266 /// It would be great to be able to express per-candidate problems 9267 /// more richly for those diagnostic clients that cared, but we'd 9268 /// still have to be just as careful with the default diagnostics. 9269 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9270 unsigned NumArgs) { 9271 FunctionDecl *Fn = Cand->Function; 9272 9273 // Note deleted candidates, but only if they're viable. 9274 if (Cand->Viable && (Fn->isDeleted() || 9275 S.isFunctionConsideredUnavailable(Fn))) { 9276 std::string FnDesc; 9277 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9278 9279 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9280 << FnKind << FnDesc 9281 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9282 MaybeEmitInheritedConstructorNote(S, Fn); 9283 return; 9284 } 9285 9286 // We don't really have anything else to say about viable candidates. 9287 if (Cand->Viable) { 9288 S.NoteOverloadCandidate(Fn); 9289 return; 9290 } 9291 9292 switch (Cand->FailureKind) { 9293 case ovl_fail_too_many_arguments: 9294 case ovl_fail_too_few_arguments: 9295 return DiagnoseArityMismatch(S, Cand, NumArgs); 9296 9297 case ovl_fail_bad_deduction: 9298 return DiagnoseBadDeduction(S, Cand, NumArgs); 9299 9300 case ovl_fail_illegal_constructor: { 9301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9302 << (Fn->getPrimaryTemplate() ? 1 : 0); 9303 MaybeEmitInheritedConstructorNote(S, Fn); 9304 return; 9305 } 9306 9307 case ovl_fail_trivial_conversion: 9308 case ovl_fail_bad_final_conversion: 9309 case ovl_fail_final_conversion_not_exact: 9310 return S.NoteOverloadCandidate(Fn); 9311 9312 case ovl_fail_bad_conversion: { 9313 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9314 for (unsigned N = Cand->NumConversions; I != N; ++I) 9315 if (Cand->Conversions[I].isBad()) 9316 return DiagnoseBadConversion(S, Cand, I); 9317 9318 // FIXME: this currently happens when we're called from SemaInit 9319 // when user-conversion overload fails. Figure out how to handle 9320 // those conditions and diagnose them well. 9321 return S.NoteOverloadCandidate(Fn); 9322 } 9323 9324 case ovl_fail_bad_target: 9325 return DiagnoseBadTarget(S, Cand); 9326 9327 case ovl_fail_enable_if: 9328 return DiagnoseFailedEnableIfAttr(S, Cand); 9329 } 9330 } 9331 9332 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9333 // Desugar the type of the surrogate down to a function type, 9334 // retaining as many typedefs as possible while still showing 9335 // the function type (and, therefore, its parameter types). 9336 QualType FnType = Cand->Surrogate->getConversionType(); 9337 bool isLValueReference = false; 9338 bool isRValueReference = false; 9339 bool isPointer = false; 9340 if (const LValueReferenceType *FnTypeRef = 9341 FnType->getAs<LValueReferenceType>()) { 9342 FnType = FnTypeRef->getPointeeType(); 9343 isLValueReference = true; 9344 } else if (const RValueReferenceType *FnTypeRef = 9345 FnType->getAs<RValueReferenceType>()) { 9346 FnType = FnTypeRef->getPointeeType(); 9347 isRValueReference = true; 9348 } 9349 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9350 FnType = FnTypePtr->getPointeeType(); 9351 isPointer = true; 9352 } 9353 // Desugar down to a function type. 9354 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9355 // Reconstruct the pointer/reference as appropriate. 9356 if (isPointer) FnType = S.Context.getPointerType(FnType); 9357 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9358 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9359 9360 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9361 << FnType; 9362 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9363 } 9364 9365 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9366 SourceLocation OpLoc, 9367 OverloadCandidate *Cand) { 9368 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9369 std::string TypeStr("operator"); 9370 TypeStr += Opc; 9371 TypeStr += "("; 9372 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9373 if (Cand->NumConversions == 1) { 9374 TypeStr += ")"; 9375 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9376 } else { 9377 TypeStr += ", "; 9378 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9379 TypeStr += ")"; 9380 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9381 } 9382 } 9383 9384 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9385 OverloadCandidate *Cand) { 9386 unsigned NoOperands = Cand->NumConversions; 9387 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9388 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9389 if (ICS.isBad()) break; // all meaningless after first invalid 9390 if (!ICS.isAmbiguous()) continue; 9391 9392 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9393 S.PDiag(diag::note_ambiguous_type_conversion)); 9394 } 9395 } 9396 9397 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9398 if (Cand->Function) 9399 return Cand->Function->getLocation(); 9400 if (Cand->IsSurrogate) 9401 return Cand->Surrogate->getLocation(); 9402 return SourceLocation(); 9403 } 9404 9405 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9406 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9407 case Sema::TDK_Success: 9408 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9409 9410 case Sema::TDK_Invalid: 9411 case Sema::TDK_Incomplete: 9412 return 1; 9413 9414 case Sema::TDK_Underqualified: 9415 case Sema::TDK_Inconsistent: 9416 return 2; 9417 9418 case Sema::TDK_SubstitutionFailure: 9419 case Sema::TDK_NonDeducedMismatch: 9420 case Sema::TDK_MiscellaneousDeductionFailure: 9421 return 3; 9422 9423 case Sema::TDK_InstantiationDepth: 9424 case Sema::TDK_FailedOverloadResolution: 9425 return 4; 9426 9427 case Sema::TDK_InvalidExplicitArguments: 9428 return 5; 9429 9430 case Sema::TDK_TooManyArguments: 9431 case Sema::TDK_TooFewArguments: 9432 return 6; 9433 } 9434 llvm_unreachable("Unhandled deduction result"); 9435 } 9436 9437 namespace { 9438 struct CompareOverloadCandidatesForDisplay { 9439 Sema &S; 9440 size_t NumArgs; 9441 9442 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9443 : S(S), NumArgs(nArgs) {} 9444 9445 bool operator()(const OverloadCandidate *L, 9446 const OverloadCandidate *R) { 9447 // Fast-path this check. 9448 if (L == R) return false; 9449 9450 // Order first by viability. 9451 if (L->Viable) { 9452 if (!R->Viable) return true; 9453 9454 // TODO: introduce a tri-valued comparison for overload 9455 // candidates. Would be more worthwhile if we had a sort 9456 // that could exploit it. 9457 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9458 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9459 } else if (R->Viable) 9460 return false; 9461 9462 assert(L->Viable == R->Viable); 9463 9464 // Criteria by which we can sort non-viable candidates: 9465 if (!L->Viable) { 9466 // 1. Arity mismatches come after other candidates. 9467 if (L->FailureKind == ovl_fail_too_many_arguments || 9468 L->FailureKind == ovl_fail_too_few_arguments) { 9469 if (R->FailureKind == ovl_fail_too_many_arguments || 9470 R->FailureKind == ovl_fail_too_few_arguments) { 9471 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9472 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9473 if (LDist == RDist) { 9474 if (L->FailureKind == R->FailureKind) 9475 // Sort non-surrogates before surrogates. 9476 return !L->IsSurrogate && R->IsSurrogate; 9477 // Sort candidates requiring fewer parameters than there were 9478 // arguments given after candidates requiring more parameters 9479 // than there were arguments given. 9480 return L->FailureKind == ovl_fail_too_many_arguments; 9481 } 9482 return LDist < RDist; 9483 } 9484 return false; 9485 } 9486 if (R->FailureKind == ovl_fail_too_many_arguments || 9487 R->FailureKind == ovl_fail_too_few_arguments) 9488 return true; 9489 9490 // 2. Bad conversions come first and are ordered by the number 9491 // of bad conversions and quality of good conversions. 9492 if (L->FailureKind == ovl_fail_bad_conversion) { 9493 if (R->FailureKind != ovl_fail_bad_conversion) 9494 return true; 9495 9496 // The conversion that can be fixed with a smaller number of changes, 9497 // comes first. 9498 unsigned numLFixes = L->Fix.NumConversionsFixed; 9499 unsigned numRFixes = R->Fix.NumConversionsFixed; 9500 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9501 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9502 if (numLFixes != numRFixes) { 9503 return numLFixes < numRFixes; 9504 } 9505 9506 // If there's any ordering between the defined conversions... 9507 // FIXME: this might not be transitive. 9508 assert(L->NumConversions == R->NumConversions); 9509 9510 int leftBetter = 0; 9511 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9512 for (unsigned E = L->NumConversions; I != E; ++I) { 9513 switch (CompareImplicitConversionSequences(S, 9514 L->Conversions[I], 9515 R->Conversions[I])) { 9516 case ImplicitConversionSequence::Better: 9517 leftBetter++; 9518 break; 9519 9520 case ImplicitConversionSequence::Worse: 9521 leftBetter--; 9522 break; 9523 9524 case ImplicitConversionSequence::Indistinguishable: 9525 break; 9526 } 9527 } 9528 if (leftBetter > 0) return true; 9529 if (leftBetter < 0) return false; 9530 9531 } else if (R->FailureKind == ovl_fail_bad_conversion) 9532 return false; 9533 9534 if (L->FailureKind == ovl_fail_bad_deduction) { 9535 if (R->FailureKind != ovl_fail_bad_deduction) 9536 return true; 9537 9538 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9539 return RankDeductionFailure(L->DeductionFailure) 9540 < RankDeductionFailure(R->DeductionFailure); 9541 } else if (R->FailureKind == ovl_fail_bad_deduction) 9542 return false; 9543 9544 // TODO: others? 9545 } 9546 9547 // Sort everything else by location. 9548 SourceLocation LLoc = GetLocationForCandidate(L); 9549 SourceLocation RLoc = GetLocationForCandidate(R); 9550 9551 // Put candidates without locations (e.g. builtins) at the end. 9552 if (LLoc.isInvalid()) return false; 9553 if (RLoc.isInvalid()) return true; 9554 9555 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9556 } 9557 }; 9558 } 9559 9560 /// CompleteNonViableCandidate - Normally, overload resolution only 9561 /// computes up to the first. Produces the FixIt set if possible. 9562 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9563 ArrayRef<Expr *> Args) { 9564 assert(!Cand->Viable); 9565 9566 // Don't do anything on failures other than bad conversion. 9567 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9568 9569 // We only want the FixIts if all the arguments can be corrected. 9570 bool Unfixable = false; 9571 // Use a implicit copy initialization to check conversion fixes. 9572 Cand->Fix.setConversionChecker(TryCopyInitialization); 9573 9574 // Skip forward to the first bad conversion. 9575 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9576 unsigned ConvCount = Cand->NumConversions; 9577 while (true) { 9578 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9579 ConvIdx++; 9580 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9581 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9582 break; 9583 } 9584 } 9585 9586 if (ConvIdx == ConvCount) 9587 return; 9588 9589 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9590 "remaining conversion is initialized?"); 9591 9592 // FIXME: this should probably be preserved from the overload 9593 // operation somehow. 9594 bool SuppressUserConversions = false; 9595 9596 const FunctionProtoType* Proto; 9597 unsigned ArgIdx = ConvIdx; 9598 9599 if (Cand->IsSurrogate) { 9600 QualType ConvType 9601 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9602 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9603 ConvType = ConvPtrType->getPointeeType(); 9604 Proto = ConvType->getAs<FunctionProtoType>(); 9605 ArgIdx--; 9606 } else if (Cand->Function) { 9607 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9608 if (isa<CXXMethodDecl>(Cand->Function) && 9609 !isa<CXXConstructorDecl>(Cand->Function)) 9610 ArgIdx--; 9611 } else { 9612 // Builtin binary operator with a bad first conversion. 9613 assert(ConvCount <= 3); 9614 for (; ConvIdx != ConvCount; ++ConvIdx) 9615 Cand->Conversions[ConvIdx] 9616 = TryCopyInitialization(S, Args[ConvIdx], 9617 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9618 SuppressUserConversions, 9619 /*InOverloadResolution*/ true, 9620 /*AllowObjCWritebackConversion=*/ 9621 S.getLangOpts().ObjCAutoRefCount); 9622 return; 9623 } 9624 9625 // Fill in the rest of the conversions. 9626 unsigned NumParams = Proto->getNumParams(); 9627 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9628 if (ArgIdx < NumParams) { 9629 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9630 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9631 /*InOverloadResolution=*/true, 9632 /*AllowObjCWritebackConversion=*/ 9633 S.getLangOpts().ObjCAutoRefCount); 9634 // Store the FixIt in the candidate if it exists. 9635 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9636 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9637 } 9638 else 9639 Cand->Conversions[ConvIdx].setEllipsis(); 9640 } 9641 } 9642 9643 /// PrintOverloadCandidates - When overload resolution fails, prints 9644 /// diagnostic messages containing the candidates in the candidate 9645 /// set. 9646 void OverloadCandidateSet::NoteCandidates(Sema &S, 9647 OverloadCandidateDisplayKind OCD, 9648 ArrayRef<Expr *> Args, 9649 StringRef Opc, 9650 SourceLocation OpLoc) { 9651 // Sort the candidates by viability and position. Sorting directly would 9652 // be prohibitive, so we make a set of pointers and sort those. 9653 SmallVector<OverloadCandidate*, 32> Cands; 9654 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9655 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9656 if (Cand->Viable) 9657 Cands.push_back(Cand); 9658 else if (OCD == OCD_AllCandidates) { 9659 CompleteNonViableCandidate(S, Cand, Args); 9660 if (Cand->Function || Cand->IsSurrogate) 9661 Cands.push_back(Cand); 9662 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9663 // want to list every possible builtin candidate. 9664 } 9665 } 9666 9667 std::sort(Cands.begin(), Cands.end(), 9668 CompareOverloadCandidatesForDisplay(S, Args.size())); 9669 9670 bool ReportedAmbiguousConversions = false; 9671 9672 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9673 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9674 unsigned CandsShown = 0; 9675 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9676 OverloadCandidate *Cand = *I; 9677 9678 // Set an arbitrary limit on the number of candidate functions we'll spam 9679 // the user with. FIXME: This limit should depend on details of the 9680 // candidate list. 9681 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9682 break; 9683 } 9684 ++CandsShown; 9685 9686 if (Cand->Function) 9687 NoteFunctionCandidate(S, Cand, Args.size()); 9688 else if (Cand->IsSurrogate) 9689 NoteSurrogateCandidate(S, Cand); 9690 else { 9691 assert(Cand->Viable && 9692 "Non-viable built-in candidates are not added to Cands."); 9693 // Generally we only see ambiguities including viable builtin 9694 // operators if overload resolution got screwed up by an 9695 // ambiguous user-defined conversion. 9696 // 9697 // FIXME: It's quite possible for different conversions to see 9698 // different ambiguities, though. 9699 if (!ReportedAmbiguousConversions) { 9700 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9701 ReportedAmbiguousConversions = true; 9702 } 9703 9704 // If this is a viable builtin, print it. 9705 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9706 } 9707 } 9708 9709 if (I != E) 9710 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9711 } 9712 9713 static SourceLocation 9714 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9715 return Cand->Specialization ? Cand->Specialization->getLocation() 9716 : SourceLocation(); 9717 } 9718 9719 namespace { 9720 struct CompareTemplateSpecCandidatesForDisplay { 9721 Sema &S; 9722 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9723 9724 bool operator()(const TemplateSpecCandidate *L, 9725 const TemplateSpecCandidate *R) { 9726 // Fast-path this check. 9727 if (L == R) 9728 return false; 9729 9730 // Assuming that both candidates are not matches... 9731 9732 // Sort by the ranking of deduction failures. 9733 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9734 return RankDeductionFailure(L->DeductionFailure) < 9735 RankDeductionFailure(R->DeductionFailure); 9736 9737 // Sort everything else by location. 9738 SourceLocation LLoc = GetLocationForCandidate(L); 9739 SourceLocation RLoc = GetLocationForCandidate(R); 9740 9741 // Put candidates without locations (e.g. builtins) at the end. 9742 if (LLoc.isInvalid()) 9743 return false; 9744 if (RLoc.isInvalid()) 9745 return true; 9746 9747 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9748 } 9749 }; 9750 } 9751 9752 /// Diagnose a template argument deduction failure. 9753 /// We are treating these failures as overload failures due to bad 9754 /// deductions. 9755 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9756 DiagnoseBadDeduction(S, Specialization, // pattern 9757 DeductionFailure, /*NumArgs=*/0); 9758 } 9759 9760 void TemplateSpecCandidateSet::destroyCandidates() { 9761 for (iterator i = begin(), e = end(); i != e; ++i) { 9762 i->DeductionFailure.Destroy(); 9763 } 9764 } 9765 9766 void TemplateSpecCandidateSet::clear() { 9767 destroyCandidates(); 9768 Candidates.clear(); 9769 } 9770 9771 /// NoteCandidates - When no template specialization match is found, prints 9772 /// diagnostic messages containing the non-matching specializations that form 9773 /// the candidate set. 9774 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9775 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9776 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9777 // Sort the candidates by position (assuming no candidate is a match). 9778 // Sorting directly would be prohibitive, so we make a set of pointers 9779 // and sort those. 9780 SmallVector<TemplateSpecCandidate *, 32> Cands; 9781 Cands.reserve(size()); 9782 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9783 if (Cand->Specialization) 9784 Cands.push_back(Cand); 9785 // Otherwise, this is a non-matching builtin candidate. We do not, 9786 // in general, want to list every possible builtin candidate. 9787 } 9788 9789 std::sort(Cands.begin(), Cands.end(), 9790 CompareTemplateSpecCandidatesForDisplay(S)); 9791 9792 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9793 // for generalization purposes (?). 9794 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9795 9796 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9797 unsigned CandsShown = 0; 9798 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9799 TemplateSpecCandidate *Cand = *I; 9800 9801 // Set an arbitrary limit on the number of candidates we'll spam 9802 // the user with. FIXME: This limit should depend on details of the 9803 // candidate list. 9804 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9805 break; 9806 ++CandsShown; 9807 9808 assert(Cand->Specialization && 9809 "Non-matching built-in candidates are not added to Cands."); 9810 Cand->NoteDeductionFailure(S); 9811 } 9812 9813 if (I != E) 9814 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9815 } 9816 9817 // [PossiblyAFunctionType] --> [Return] 9818 // NonFunctionType --> NonFunctionType 9819 // R (A) --> R(A) 9820 // R (*)(A) --> R (A) 9821 // R (&)(A) --> R (A) 9822 // R (S::*)(A) --> R (A) 9823 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9824 QualType Ret = PossiblyAFunctionType; 9825 if (const PointerType *ToTypePtr = 9826 PossiblyAFunctionType->getAs<PointerType>()) 9827 Ret = ToTypePtr->getPointeeType(); 9828 else if (const ReferenceType *ToTypeRef = 9829 PossiblyAFunctionType->getAs<ReferenceType>()) 9830 Ret = ToTypeRef->getPointeeType(); 9831 else if (const MemberPointerType *MemTypePtr = 9832 PossiblyAFunctionType->getAs<MemberPointerType>()) 9833 Ret = MemTypePtr->getPointeeType(); 9834 Ret = 9835 Context.getCanonicalType(Ret).getUnqualifiedType(); 9836 return Ret; 9837 } 9838 9839 namespace { 9840 // A helper class to help with address of function resolution 9841 // - allows us to avoid passing around all those ugly parameters 9842 class AddressOfFunctionResolver { 9843 Sema& S; 9844 Expr* SourceExpr; 9845 const QualType& TargetType; 9846 QualType TargetFunctionType; // Extracted function type from target type 9847 9848 bool Complain; 9849 //DeclAccessPair& ResultFunctionAccessPair; 9850 ASTContext& Context; 9851 9852 bool TargetTypeIsNonStaticMemberFunction; 9853 bool FoundNonTemplateFunction; 9854 bool StaticMemberFunctionFromBoundPointer; 9855 9856 OverloadExpr::FindResult OvlExprInfo; 9857 OverloadExpr *OvlExpr; 9858 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9859 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9860 TemplateSpecCandidateSet FailedCandidates; 9861 9862 public: 9863 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9864 const QualType &TargetType, bool Complain) 9865 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9866 Complain(Complain), Context(S.getASTContext()), 9867 TargetTypeIsNonStaticMemberFunction( 9868 !!TargetType->getAs<MemberPointerType>()), 9869 FoundNonTemplateFunction(false), 9870 StaticMemberFunctionFromBoundPointer(false), 9871 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9872 OvlExpr(OvlExprInfo.Expression), 9873 FailedCandidates(OvlExpr->getNameLoc()) { 9874 ExtractUnqualifiedFunctionTypeFromTargetType(); 9875 9876 if (TargetFunctionType->isFunctionType()) { 9877 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9878 if (!UME->isImplicitAccess() && 9879 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9880 StaticMemberFunctionFromBoundPointer = true; 9881 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9882 DeclAccessPair dap; 9883 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9884 OvlExpr, false, &dap)) { 9885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9886 if (!Method->isStatic()) { 9887 // If the target type is a non-function type and the function found 9888 // is a non-static member function, pretend as if that was the 9889 // target, it's the only possible type to end up with. 9890 TargetTypeIsNonStaticMemberFunction = true; 9891 9892 // And skip adding the function if its not in the proper form. 9893 // We'll diagnose this due to an empty set of functions. 9894 if (!OvlExprInfo.HasFormOfMemberPointer) 9895 return; 9896 } 9897 9898 Matches.push_back(std::make_pair(dap, Fn)); 9899 } 9900 return; 9901 } 9902 9903 if (OvlExpr->hasExplicitTemplateArgs()) 9904 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9905 9906 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9907 // C++ [over.over]p4: 9908 // If more than one function is selected, [...] 9909 if (Matches.size() > 1) { 9910 if (FoundNonTemplateFunction) 9911 EliminateAllTemplateMatches(); 9912 else 9913 EliminateAllExceptMostSpecializedTemplate(); 9914 } 9915 } 9916 } 9917 9918 private: 9919 bool isTargetTypeAFunction() const { 9920 return TargetFunctionType->isFunctionType(); 9921 } 9922 9923 // [ToType] [Return] 9924 9925 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9926 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9927 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9928 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9929 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9930 } 9931 9932 // return true if any matching specializations were found 9933 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9934 const DeclAccessPair& CurAccessFunPair) { 9935 if (CXXMethodDecl *Method 9936 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9937 // Skip non-static function templates when converting to pointer, and 9938 // static when converting to member pointer. 9939 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9940 return false; 9941 } 9942 else if (TargetTypeIsNonStaticMemberFunction) 9943 return false; 9944 9945 // C++ [over.over]p2: 9946 // If the name is a function template, template argument deduction is 9947 // done (14.8.2.2), and if the argument deduction succeeds, the 9948 // resulting template argument list is used to generate a single 9949 // function template specialization, which is added to the set of 9950 // overloaded functions considered. 9951 FunctionDecl *Specialization = nullptr; 9952 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9953 if (Sema::TemplateDeductionResult Result 9954 = S.DeduceTemplateArguments(FunctionTemplate, 9955 &OvlExplicitTemplateArgs, 9956 TargetFunctionType, Specialization, 9957 Info, /*InOverloadResolution=*/true)) { 9958 // Make a note of the failed deduction for diagnostics. 9959 FailedCandidates.addCandidate() 9960 .set(FunctionTemplate->getTemplatedDecl(), 9961 MakeDeductionFailureInfo(Context, Result, Info)); 9962 return false; 9963 } 9964 9965 // Template argument deduction ensures that we have an exact match or 9966 // compatible pointer-to-function arguments that would be adjusted by ICS. 9967 // This function template specicalization works. 9968 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9969 assert(S.isSameOrCompatibleFunctionType( 9970 Context.getCanonicalType(Specialization->getType()), 9971 Context.getCanonicalType(TargetFunctionType))); 9972 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9973 return true; 9974 } 9975 9976 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9977 const DeclAccessPair& CurAccessFunPair) { 9978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9979 // Skip non-static functions when converting to pointer, and static 9980 // when converting to member pointer. 9981 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9982 return false; 9983 } 9984 else if (TargetTypeIsNonStaticMemberFunction) 9985 return false; 9986 9987 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9988 if (S.getLangOpts().CUDA) 9989 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9990 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 9991 return false; 9992 9993 // If any candidate has a placeholder return type, trigger its deduction 9994 // now. 9995 if (S.getLangOpts().CPlusPlus14 && 9996 FunDecl->getReturnType()->isUndeducedType() && 9997 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9998 return false; 9999 10000 QualType ResultTy; 10001 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10002 FunDecl->getType()) || 10003 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10004 ResultTy)) { 10005 Matches.push_back(std::make_pair(CurAccessFunPair, 10006 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10007 FoundNonTemplateFunction = true; 10008 return true; 10009 } 10010 } 10011 10012 return false; 10013 } 10014 10015 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10016 bool Ret = false; 10017 10018 // If the overload expression doesn't have the form of a pointer to 10019 // member, don't try to convert it to a pointer-to-member type. 10020 if (IsInvalidFormOfPointerToMemberFunction()) 10021 return false; 10022 10023 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10024 E = OvlExpr->decls_end(); 10025 I != E; ++I) { 10026 // Look through any using declarations to find the underlying function. 10027 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10028 10029 // C++ [over.over]p3: 10030 // Non-member functions and static member functions match 10031 // targets of type "pointer-to-function" or "reference-to-function." 10032 // Nonstatic member functions match targets of 10033 // type "pointer-to-member-function." 10034 // Note that according to DR 247, the containing class does not matter. 10035 if (FunctionTemplateDecl *FunctionTemplate 10036 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10037 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10038 Ret = true; 10039 } 10040 // If we have explicit template arguments supplied, skip non-templates. 10041 else if (!OvlExpr->hasExplicitTemplateArgs() && 10042 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10043 Ret = true; 10044 } 10045 assert(Ret || Matches.empty()); 10046 return Ret; 10047 } 10048 10049 void EliminateAllExceptMostSpecializedTemplate() { 10050 // [...] and any given function template specialization F1 is 10051 // eliminated if the set contains a second function template 10052 // specialization whose function template is more specialized 10053 // than the function template of F1 according to the partial 10054 // ordering rules of 14.5.5.2. 10055 10056 // The algorithm specified above is quadratic. We instead use a 10057 // two-pass algorithm (similar to the one used to identify the 10058 // best viable function in an overload set) that identifies the 10059 // best function template (if it exists). 10060 10061 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10062 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10063 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10064 10065 // TODO: It looks like FailedCandidates does not serve much purpose 10066 // here, since the no_viable diagnostic has index 0. 10067 UnresolvedSetIterator Result = S.getMostSpecialized( 10068 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10069 SourceExpr->getLocStart(), S.PDiag(), 10070 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10071 .second->getDeclName(), 10072 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10073 Complain, TargetFunctionType); 10074 10075 if (Result != MatchesCopy.end()) { 10076 // Make it the first and only element 10077 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10078 Matches[0].second = cast<FunctionDecl>(*Result); 10079 Matches.resize(1); 10080 } 10081 } 10082 10083 void EliminateAllTemplateMatches() { 10084 // [...] any function template specializations in the set are 10085 // eliminated if the set also contains a non-template function, [...] 10086 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10087 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10088 ++I; 10089 else { 10090 Matches[I] = Matches[--N]; 10091 Matches.set_size(N); 10092 } 10093 } 10094 } 10095 10096 public: 10097 void ComplainNoMatchesFound() const { 10098 assert(Matches.empty()); 10099 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10100 << OvlExpr->getName() << TargetFunctionType 10101 << OvlExpr->getSourceRange(); 10102 if (FailedCandidates.empty()) 10103 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10104 else { 10105 // We have some deduction failure messages. Use them to diagnose 10106 // the function templates, and diagnose the non-template candidates 10107 // normally. 10108 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10109 IEnd = OvlExpr->decls_end(); 10110 I != IEnd; ++I) 10111 if (FunctionDecl *Fun = 10112 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10113 S.NoteOverloadCandidate(Fun, TargetFunctionType); 10114 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10115 } 10116 } 10117 10118 bool IsInvalidFormOfPointerToMemberFunction() const { 10119 return TargetTypeIsNonStaticMemberFunction && 10120 !OvlExprInfo.HasFormOfMemberPointer; 10121 } 10122 10123 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10124 // TODO: Should we condition this on whether any functions might 10125 // have matched, or is it more appropriate to do that in callers? 10126 // TODO: a fixit wouldn't hurt. 10127 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10128 << TargetType << OvlExpr->getSourceRange(); 10129 } 10130 10131 bool IsStaticMemberFunctionFromBoundPointer() const { 10132 return StaticMemberFunctionFromBoundPointer; 10133 } 10134 10135 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10136 S.Diag(OvlExpr->getLocStart(), 10137 diag::err_invalid_form_pointer_member_function) 10138 << OvlExpr->getSourceRange(); 10139 } 10140 10141 void ComplainOfInvalidConversion() const { 10142 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10143 << OvlExpr->getName() << TargetType; 10144 } 10145 10146 void ComplainMultipleMatchesFound() const { 10147 assert(Matches.size() > 1); 10148 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10149 << OvlExpr->getName() 10150 << OvlExpr->getSourceRange(); 10151 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10152 } 10153 10154 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10155 10156 int getNumMatches() const { return Matches.size(); } 10157 10158 FunctionDecl* getMatchingFunctionDecl() const { 10159 if (Matches.size() != 1) return nullptr; 10160 return Matches[0].second; 10161 } 10162 10163 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10164 if (Matches.size() != 1) return nullptr; 10165 return &Matches[0].first; 10166 } 10167 }; 10168 } 10169 10170 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10171 /// an overloaded function (C++ [over.over]), where @p From is an 10172 /// expression with overloaded function type and @p ToType is the type 10173 /// we're trying to resolve to. For example: 10174 /// 10175 /// @code 10176 /// int f(double); 10177 /// int f(int); 10178 /// 10179 /// int (*pfd)(double) = f; // selects f(double) 10180 /// @endcode 10181 /// 10182 /// This routine returns the resulting FunctionDecl if it could be 10183 /// resolved, and NULL otherwise. When @p Complain is true, this 10184 /// routine will emit diagnostics if there is an error. 10185 FunctionDecl * 10186 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10187 QualType TargetType, 10188 bool Complain, 10189 DeclAccessPair &FoundResult, 10190 bool *pHadMultipleCandidates) { 10191 assert(AddressOfExpr->getType() == Context.OverloadTy); 10192 10193 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10194 Complain); 10195 int NumMatches = Resolver.getNumMatches(); 10196 FunctionDecl *Fn = nullptr; 10197 if (NumMatches == 0 && Complain) { 10198 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10199 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10200 else 10201 Resolver.ComplainNoMatchesFound(); 10202 } 10203 else if (NumMatches > 1 && Complain) 10204 Resolver.ComplainMultipleMatchesFound(); 10205 else if (NumMatches == 1) { 10206 Fn = Resolver.getMatchingFunctionDecl(); 10207 assert(Fn); 10208 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10209 if (Complain) { 10210 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10211 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10212 else 10213 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10214 } 10215 } 10216 10217 if (pHadMultipleCandidates) 10218 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10219 return Fn; 10220 } 10221 10222 /// \brief Given an expression that refers to an overloaded function, try to 10223 /// resolve that overloaded function expression down to a single function. 10224 /// 10225 /// This routine can only resolve template-ids that refer to a single function 10226 /// template, where that template-id refers to a single template whose template 10227 /// arguments are either provided by the template-id or have defaults, 10228 /// as described in C++0x [temp.arg.explicit]p3. 10229 /// 10230 /// If no template-ids are found, no diagnostics are emitted and NULL is 10231 /// returned. 10232 FunctionDecl * 10233 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10234 bool Complain, 10235 DeclAccessPair *FoundResult) { 10236 // C++ [over.over]p1: 10237 // [...] [Note: any redundant set of parentheses surrounding the 10238 // overloaded function name is ignored (5.1). ] 10239 // C++ [over.over]p1: 10240 // [...] The overloaded function name can be preceded by the & 10241 // operator. 10242 10243 // If we didn't actually find any template-ids, we're done. 10244 if (!ovl->hasExplicitTemplateArgs()) 10245 return nullptr; 10246 10247 TemplateArgumentListInfo ExplicitTemplateArgs; 10248 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10249 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10250 10251 // Look through all of the overloaded functions, searching for one 10252 // whose type matches exactly. 10253 FunctionDecl *Matched = nullptr; 10254 for (UnresolvedSetIterator I = ovl->decls_begin(), 10255 E = ovl->decls_end(); I != E; ++I) { 10256 // C++0x [temp.arg.explicit]p3: 10257 // [...] In contexts where deduction is done and fails, or in contexts 10258 // where deduction is not done, if a template argument list is 10259 // specified and it, along with any default template arguments, 10260 // identifies a single function template specialization, then the 10261 // template-id is an lvalue for the function template specialization. 10262 FunctionTemplateDecl *FunctionTemplate 10263 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10264 10265 // C++ [over.over]p2: 10266 // If the name is a function template, template argument deduction is 10267 // done (14.8.2.2), and if the argument deduction succeeds, the 10268 // resulting template argument list is used to generate a single 10269 // function template specialization, which is added to the set of 10270 // overloaded functions considered. 10271 FunctionDecl *Specialization = nullptr; 10272 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10273 if (TemplateDeductionResult Result 10274 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10275 Specialization, Info, 10276 /*InOverloadResolution=*/true)) { 10277 // Make a note of the failed deduction for diagnostics. 10278 // TODO: Actually use the failed-deduction info? 10279 FailedCandidates.addCandidate() 10280 .set(FunctionTemplate->getTemplatedDecl(), 10281 MakeDeductionFailureInfo(Context, Result, Info)); 10282 continue; 10283 } 10284 10285 assert(Specialization && "no specialization and no error?"); 10286 10287 // Multiple matches; we can't resolve to a single declaration. 10288 if (Matched) { 10289 if (Complain) { 10290 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10291 << ovl->getName(); 10292 NoteAllOverloadCandidates(ovl); 10293 } 10294 return nullptr; 10295 } 10296 10297 Matched = Specialization; 10298 if (FoundResult) *FoundResult = I.getPair(); 10299 } 10300 10301 if (Matched && getLangOpts().CPlusPlus14 && 10302 Matched->getReturnType()->isUndeducedType() && 10303 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10304 return nullptr; 10305 10306 return Matched; 10307 } 10308 10309 10310 10311 10312 // Resolve and fix an overloaded expression that can be resolved 10313 // because it identifies a single function template specialization. 10314 // 10315 // Last three arguments should only be supplied if Complain = true 10316 // 10317 // Return true if it was logically possible to so resolve the 10318 // expression, regardless of whether or not it succeeded. Always 10319 // returns true if 'complain' is set. 10320 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10321 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10322 bool complain, const SourceRange& OpRangeForComplaining, 10323 QualType DestTypeForComplaining, 10324 unsigned DiagIDForComplaining) { 10325 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10326 10327 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10328 10329 DeclAccessPair found; 10330 ExprResult SingleFunctionExpression; 10331 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10332 ovl.Expression, /*complain*/ false, &found)) { 10333 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10334 SrcExpr = ExprError(); 10335 return true; 10336 } 10337 10338 // It is only correct to resolve to an instance method if we're 10339 // resolving a form that's permitted to be a pointer to member. 10340 // Otherwise we'll end up making a bound member expression, which 10341 // is illegal in all the contexts we resolve like this. 10342 if (!ovl.HasFormOfMemberPointer && 10343 isa<CXXMethodDecl>(fn) && 10344 cast<CXXMethodDecl>(fn)->isInstance()) { 10345 if (!complain) return false; 10346 10347 Diag(ovl.Expression->getExprLoc(), 10348 diag::err_bound_member_function) 10349 << 0 << ovl.Expression->getSourceRange(); 10350 10351 // TODO: I believe we only end up here if there's a mix of 10352 // static and non-static candidates (otherwise the expression 10353 // would have 'bound member' type, not 'overload' type). 10354 // Ideally we would note which candidate was chosen and why 10355 // the static candidates were rejected. 10356 SrcExpr = ExprError(); 10357 return true; 10358 } 10359 10360 // Fix the expression to refer to 'fn'. 10361 SingleFunctionExpression = 10362 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10363 10364 // If desired, do function-to-pointer decay. 10365 if (doFunctionPointerConverion) { 10366 SingleFunctionExpression = 10367 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10368 if (SingleFunctionExpression.isInvalid()) { 10369 SrcExpr = ExprError(); 10370 return true; 10371 } 10372 } 10373 } 10374 10375 if (!SingleFunctionExpression.isUsable()) { 10376 if (complain) { 10377 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10378 << ovl.Expression->getName() 10379 << DestTypeForComplaining 10380 << OpRangeForComplaining 10381 << ovl.Expression->getQualifierLoc().getSourceRange(); 10382 NoteAllOverloadCandidates(SrcExpr.get()); 10383 10384 SrcExpr = ExprError(); 10385 return true; 10386 } 10387 10388 return false; 10389 } 10390 10391 SrcExpr = SingleFunctionExpression; 10392 return true; 10393 } 10394 10395 /// \brief Add a single candidate to the overload set. 10396 static void AddOverloadedCallCandidate(Sema &S, 10397 DeclAccessPair FoundDecl, 10398 TemplateArgumentListInfo *ExplicitTemplateArgs, 10399 ArrayRef<Expr *> Args, 10400 OverloadCandidateSet &CandidateSet, 10401 bool PartialOverloading, 10402 bool KnownValid) { 10403 NamedDecl *Callee = FoundDecl.getDecl(); 10404 if (isa<UsingShadowDecl>(Callee)) 10405 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10406 10407 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10408 if (ExplicitTemplateArgs) { 10409 assert(!KnownValid && "Explicit template arguments?"); 10410 return; 10411 } 10412 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10413 /*SuppressUsedConversions=*/false, 10414 PartialOverloading); 10415 return; 10416 } 10417 10418 if (FunctionTemplateDecl *FuncTemplate 10419 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10420 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10421 ExplicitTemplateArgs, Args, CandidateSet, 10422 /*SuppressUsedConversions=*/false, 10423 PartialOverloading); 10424 return; 10425 } 10426 10427 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10428 } 10429 10430 /// \brief Add the overload candidates named by callee and/or found by argument 10431 /// dependent lookup to the given overload set. 10432 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10433 ArrayRef<Expr *> Args, 10434 OverloadCandidateSet &CandidateSet, 10435 bool PartialOverloading) { 10436 10437 #ifndef NDEBUG 10438 // Verify that ArgumentDependentLookup is consistent with the rules 10439 // in C++0x [basic.lookup.argdep]p3: 10440 // 10441 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10442 // and let Y be the lookup set produced by argument dependent 10443 // lookup (defined as follows). If X contains 10444 // 10445 // -- a declaration of a class member, or 10446 // 10447 // -- a block-scope function declaration that is not a 10448 // using-declaration, or 10449 // 10450 // -- a declaration that is neither a function or a function 10451 // template 10452 // 10453 // then Y is empty. 10454 10455 if (ULE->requiresADL()) { 10456 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10457 E = ULE->decls_end(); I != E; ++I) { 10458 assert(!(*I)->getDeclContext()->isRecord()); 10459 assert(isa<UsingShadowDecl>(*I) || 10460 !(*I)->getDeclContext()->isFunctionOrMethod()); 10461 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10462 } 10463 } 10464 #endif 10465 10466 // It would be nice to avoid this copy. 10467 TemplateArgumentListInfo TABuffer; 10468 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10469 if (ULE->hasExplicitTemplateArgs()) { 10470 ULE->copyTemplateArgumentsInto(TABuffer); 10471 ExplicitTemplateArgs = &TABuffer; 10472 } 10473 10474 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10475 E = ULE->decls_end(); I != E; ++I) 10476 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10477 CandidateSet, PartialOverloading, 10478 /*KnownValid*/ true); 10479 10480 if (ULE->requiresADL()) 10481 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10482 Args, ExplicitTemplateArgs, 10483 CandidateSet, PartialOverloading); 10484 } 10485 10486 /// Determine whether a declaration with the specified name could be moved into 10487 /// a different namespace. 10488 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10489 switch (Name.getCXXOverloadedOperator()) { 10490 case OO_New: case OO_Array_New: 10491 case OO_Delete: case OO_Array_Delete: 10492 return false; 10493 10494 default: 10495 return true; 10496 } 10497 } 10498 10499 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10500 /// template, where the non-dependent name was declared after the template 10501 /// was defined. This is common in code written for a compilers which do not 10502 /// correctly implement two-stage name lookup. 10503 /// 10504 /// Returns true if a viable candidate was found and a diagnostic was issued. 10505 static bool 10506 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10507 const CXXScopeSpec &SS, LookupResult &R, 10508 OverloadCandidateSet::CandidateSetKind CSK, 10509 TemplateArgumentListInfo *ExplicitTemplateArgs, 10510 ArrayRef<Expr *> Args) { 10511 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10512 return false; 10513 10514 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10515 if (DC->isTransparentContext()) 10516 continue; 10517 10518 SemaRef.LookupQualifiedName(R, DC); 10519 10520 if (!R.empty()) { 10521 R.suppressDiagnostics(); 10522 10523 if (isa<CXXRecordDecl>(DC)) { 10524 // Don't diagnose names we find in classes; we get much better 10525 // diagnostics for these from DiagnoseEmptyLookup. 10526 R.clear(); 10527 return false; 10528 } 10529 10530 OverloadCandidateSet Candidates(FnLoc, CSK); 10531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10532 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10533 ExplicitTemplateArgs, Args, 10534 Candidates, false, /*KnownValid*/ false); 10535 10536 OverloadCandidateSet::iterator Best; 10537 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10538 // No viable functions. Don't bother the user with notes for functions 10539 // which don't work and shouldn't be found anyway. 10540 R.clear(); 10541 return false; 10542 } 10543 10544 // Find the namespaces where ADL would have looked, and suggest 10545 // declaring the function there instead. 10546 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10547 Sema::AssociatedClassSet AssociatedClasses; 10548 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10549 AssociatedNamespaces, 10550 AssociatedClasses); 10551 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10552 if (canBeDeclaredInNamespace(R.getLookupName())) { 10553 DeclContext *Std = SemaRef.getStdNamespace(); 10554 for (Sema::AssociatedNamespaceSet::iterator 10555 it = AssociatedNamespaces.begin(), 10556 end = AssociatedNamespaces.end(); it != end; ++it) { 10557 // Never suggest declaring a function within namespace 'std'. 10558 if (Std && Std->Encloses(*it)) 10559 continue; 10560 10561 // Never suggest declaring a function within a namespace with a 10562 // reserved name, like __gnu_cxx. 10563 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10564 if (NS && 10565 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10566 continue; 10567 10568 SuggestedNamespaces.insert(*it); 10569 } 10570 } 10571 10572 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10573 << R.getLookupName(); 10574 if (SuggestedNamespaces.empty()) { 10575 SemaRef.Diag(Best->Function->getLocation(), 10576 diag::note_not_found_by_two_phase_lookup) 10577 << R.getLookupName() << 0; 10578 } else if (SuggestedNamespaces.size() == 1) { 10579 SemaRef.Diag(Best->Function->getLocation(), 10580 diag::note_not_found_by_two_phase_lookup) 10581 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10582 } else { 10583 // FIXME: It would be useful to list the associated namespaces here, 10584 // but the diagnostics infrastructure doesn't provide a way to produce 10585 // a localized representation of a list of items. 10586 SemaRef.Diag(Best->Function->getLocation(), 10587 diag::note_not_found_by_two_phase_lookup) 10588 << R.getLookupName() << 2; 10589 } 10590 10591 // Try to recover by calling this function. 10592 return true; 10593 } 10594 10595 R.clear(); 10596 } 10597 10598 return false; 10599 } 10600 10601 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10602 /// template, where the non-dependent operator was declared after the template 10603 /// was defined. 10604 /// 10605 /// Returns true if a viable candidate was found and a diagnostic was issued. 10606 static bool 10607 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10608 SourceLocation OpLoc, 10609 ArrayRef<Expr *> Args) { 10610 DeclarationName OpName = 10611 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10612 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10613 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10614 OverloadCandidateSet::CSK_Operator, 10615 /*ExplicitTemplateArgs=*/nullptr, Args); 10616 } 10617 10618 namespace { 10619 class BuildRecoveryCallExprRAII { 10620 Sema &SemaRef; 10621 public: 10622 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10623 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10624 SemaRef.IsBuildingRecoveryCallExpr = true; 10625 } 10626 10627 ~BuildRecoveryCallExprRAII() { 10628 SemaRef.IsBuildingRecoveryCallExpr = false; 10629 } 10630 }; 10631 10632 } 10633 10634 static std::unique_ptr<CorrectionCandidateCallback> 10635 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10636 bool HasTemplateArgs, bool AllowTypoCorrection) { 10637 if (!AllowTypoCorrection) 10638 return llvm::make_unique<NoTypoCorrectionCCC>(); 10639 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10640 HasTemplateArgs, ME); 10641 } 10642 10643 /// Attempts to recover from a call where no functions were found. 10644 /// 10645 /// Returns true if new candidates were found. 10646 static ExprResult 10647 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10648 UnresolvedLookupExpr *ULE, 10649 SourceLocation LParenLoc, 10650 MutableArrayRef<Expr *> Args, 10651 SourceLocation RParenLoc, 10652 bool EmptyLookup, bool AllowTypoCorrection) { 10653 // Do not try to recover if it is already building a recovery call. 10654 // This stops infinite loops for template instantiations like 10655 // 10656 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10657 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10658 // 10659 if (SemaRef.IsBuildingRecoveryCallExpr) 10660 return ExprError(); 10661 BuildRecoveryCallExprRAII RCE(SemaRef); 10662 10663 CXXScopeSpec SS; 10664 SS.Adopt(ULE->getQualifierLoc()); 10665 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10666 10667 TemplateArgumentListInfo TABuffer; 10668 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10669 if (ULE->hasExplicitTemplateArgs()) { 10670 ULE->copyTemplateArgumentsInto(TABuffer); 10671 ExplicitTemplateArgs = &TABuffer; 10672 } 10673 10674 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10675 Sema::LookupOrdinaryName); 10676 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10677 OverloadCandidateSet::CSK_Normal, 10678 ExplicitTemplateArgs, Args) && 10679 (!EmptyLookup || 10680 SemaRef.DiagnoseEmptyLookup( 10681 S, SS, R, 10682 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10683 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10684 ExplicitTemplateArgs, Args))) 10685 return ExprError(); 10686 10687 assert(!R.empty() && "lookup results empty despite recovery"); 10688 10689 // Build an implicit member call if appropriate. Just drop the 10690 // casts and such from the call, we don't really care. 10691 ExprResult NewFn = ExprError(); 10692 if ((*R.begin())->isCXXClassMember()) 10693 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10694 R, ExplicitTemplateArgs); 10695 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10696 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10697 ExplicitTemplateArgs); 10698 else 10699 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10700 10701 if (NewFn.isInvalid()) 10702 return ExprError(); 10703 10704 // This shouldn't cause an infinite loop because we're giving it 10705 // an expression with viable lookup results, which should never 10706 // end up here. 10707 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10708 MultiExprArg(Args.data(), Args.size()), 10709 RParenLoc); 10710 } 10711 10712 /// \brief Constructs and populates an OverloadedCandidateSet from 10713 /// the given function. 10714 /// \returns true when an the ExprResult output parameter has been set. 10715 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10716 UnresolvedLookupExpr *ULE, 10717 MultiExprArg Args, 10718 SourceLocation RParenLoc, 10719 OverloadCandidateSet *CandidateSet, 10720 ExprResult *Result) { 10721 #ifndef NDEBUG 10722 if (ULE->requiresADL()) { 10723 // To do ADL, we must have found an unqualified name. 10724 assert(!ULE->getQualifier() && "qualified name with ADL"); 10725 10726 // We don't perform ADL for implicit declarations of builtins. 10727 // Verify that this was correctly set up. 10728 FunctionDecl *F; 10729 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10730 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10731 F->getBuiltinID() && F->isImplicit()) 10732 llvm_unreachable("performing ADL for builtin"); 10733 10734 // We don't perform ADL in C. 10735 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10736 } 10737 #endif 10738 10739 UnbridgedCastsSet UnbridgedCasts; 10740 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10741 *Result = ExprError(); 10742 return true; 10743 } 10744 10745 // Add the functions denoted by the callee to the set of candidate 10746 // functions, including those from argument-dependent lookup. 10747 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10748 10749 // If we found nothing, try to recover. 10750 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10751 // out if it fails. 10752 if (CandidateSet->empty()) { 10753 // In Microsoft mode, if we are inside a template class member function then 10754 // create a type dependent CallExpr. The goal is to postpone name lookup 10755 // to instantiation time to be able to search into type dependent base 10756 // classes. 10757 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10758 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10759 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10760 Context.DependentTy, VK_RValue, 10761 RParenLoc); 10762 CE->setTypeDependent(true); 10763 *Result = CE; 10764 return true; 10765 } 10766 return false; 10767 } 10768 10769 UnbridgedCasts.restore(); 10770 return false; 10771 } 10772 10773 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10774 /// the completed call expression. If overload resolution fails, emits 10775 /// diagnostics and returns ExprError() 10776 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10777 UnresolvedLookupExpr *ULE, 10778 SourceLocation LParenLoc, 10779 MultiExprArg Args, 10780 SourceLocation RParenLoc, 10781 Expr *ExecConfig, 10782 OverloadCandidateSet *CandidateSet, 10783 OverloadCandidateSet::iterator *Best, 10784 OverloadingResult OverloadResult, 10785 bool AllowTypoCorrection) { 10786 if (CandidateSet->empty()) 10787 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10788 RParenLoc, /*EmptyLookup=*/true, 10789 AllowTypoCorrection); 10790 10791 switch (OverloadResult) { 10792 case OR_Success: { 10793 FunctionDecl *FDecl = (*Best)->Function; 10794 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10795 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10796 return ExprError(); 10797 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10798 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10799 ExecConfig); 10800 } 10801 10802 case OR_No_Viable_Function: { 10803 // Try to recover by looking for viable functions which the user might 10804 // have meant to call. 10805 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10806 Args, RParenLoc, 10807 /*EmptyLookup=*/false, 10808 AllowTypoCorrection); 10809 if (!Recovery.isInvalid()) 10810 return Recovery; 10811 10812 SemaRef.Diag(Fn->getLocStart(), 10813 diag::err_ovl_no_viable_function_in_call) 10814 << ULE->getName() << Fn->getSourceRange(); 10815 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10816 break; 10817 } 10818 10819 case OR_Ambiguous: 10820 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10821 << ULE->getName() << Fn->getSourceRange(); 10822 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10823 break; 10824 10825 case OR_Deleted: { 10826 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10827 << (*Best)->Function->isDeleted() 10828 << ULE->getName() 10829 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10830 << Fn->getSourceRange(); 10831 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10832 10833 // We emitted an error for the unvailable/deleted function call but keep 10834 // the call in the AST. 10835 FunctionDecl *FDecl = (*Best)->Function; 10836 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10837 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10838 ExecConfig); 10839 } 10840 } 10841 10842 // Overload resolution failed. 10843 return ExprError(); 10844 } 10845 10846 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10847 /// (which eventually refers to the declaration Func) and the call 10848 /// arguments Args/NumArgs, attempt to resolve the function call down 10849 /// to a specific function. If overload resolution succeeds, returns 10850 /// the call expression produced by overload resolution. 10851 /// Otherwise, emits diagnostics and returns ExprError. 10852 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10853 UnresolvedLookupExpr *ULE, 10854 SourceLocation LParenLoc, 10855 MultiExprArg Args, 10856 SourceLocation RParenLoc, 10857 Expr *ExecConfig, 10858 bool AllowTypoCorrection) { 10859 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10860 OverloadCandidateSet::CSK_Normal); 10861 ExprResult result; 10862 10863 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10864 &result)) 10865 return result; 10866 10867 OverloadCandidateSet::iterator Best; 10868 OverloadingResult OverloadResult = 10869 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10870 10871 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10872 RParenLoc, ExecConfig, &CandidateSet, 10873 &Best, OverloadResult, 10874 AllowTypoCorrection); 10875 } 10876 10877 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10878 return Functions.size() > 1 || 10879 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10880 } 10881 10882 /// \brief Create a unary operation that may resolve to an overloaded 10883 /// operator. 10884 /// 10885 /// \param OpLoc The location of the operator itself (e.g., '*'). 10886 /// 10887 /// \param OpcIn The UnaryOperator::Opcode that describes this 10888 /// operator. 10889 /// 10890 /// \param Fns The set of non-member functions that will be 10891 /// considered by overload resolution. The caller needs to build this 10892 /// set based on the context using, e.g., 10893 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10894 /// set should not contain any member functions; those will be added 10895 /// by CreateOverloadedUnaryOp(). 10896 /// 10897 /// \param Input The input argument. 10898 ExprResult 10899 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10900 const UnresolvedSetImpl &Fns, 10901 Expr *Input) { 10902 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10903 10904 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10905 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10906 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10907 // TODO: provide better source location info. 10908 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10909 10910 if (checkPlaceholderForOverload(*this, Input)) 10911 return ExprError(); 10912 10913 Expr *Args[2] = { Input, nullptr }; 10914 unsigned NumArgs = 1; 10915 10916 // For post-increment and post-decrement, add the implicit '0' as 10917 // the second argument, so that we know this is a post-increment or 10918 // post-decrement. 10919 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10920 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10921 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10922 SourceLocation()); 10923 NumArgs = 2; 10924 } 10925 10926 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10927 10928 if (Input->isTypeDependent()) { 10929 if (Fns.empty()) 10930 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 10931 VK_RValue, OK_Ordinary, OpLoc); 10932 10933 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 10934 UnresolvedLookupExpr *Fn 10935 = UnresolvedLookupExpr::Create(Context, NamingClass, 10936 NestedNameSpecifierLoc(), OpNameInfo, 10937 /*ADL*/ true, IsOverloaded(Fns), 10938 Fns.begin(), Fns.end()); 10939 return new (Context) 10940 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 10941 VK_RValue, OpLoc, false); 10942 } 10943 10944 // Build an empty overload set. 10945 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10946 10947 // Add the candidates from the given function set. 10948 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 10949 10950 // Add operator candidates that are member functions. 10951 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10952 10953 // Add candidates from ADL. 10954 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10955 /*ExplicitTemplateArgs*/nullptr, 10956 CandidateSet); 10957 10958 // Add builtin operator candidates. 10959 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10960 10961 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10962 10963 // Perform overload resolution. 10964 OverloadCandidateSet::iterator Best; 10965 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10966 case OR_Success: { 10967 // We found a built-in operator or an overloaded operator. 10968 FunctionDecl *FnDecl = Best->Function; 10969 10970 if (FnDecl) { 10971 // We matched an overloaded operator. Build a call to that 10972 // operator. 10973 10974 // Convert the arguments. 10975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10976 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 10977 10978 ExprResult InputRes = 10979 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 10980 Best->FoundDecl, Method); 10981 if (InputRes.isInvalid()) 10982 return ExprError(); 10983 Input = InputRes.get(); 10984 } else { 10985 // Convert the arguments. 10986 ExprResult InputInit 10987 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10988 Context, 10989 FnDecl->getParamDecl(0)), 10990 SourceLocation(), 10991 Input); 10992 if (InputInit.isInvalid()) 10993 return ExprError(); 10994 Input = InputInit.get(); 10995 } 10996 10997 // Build the actual expression node. 10998 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10999 HadMultipleCandidates, OpLoc); 11000 if (FnExpr.isInvalid()) 11001 return ExprError(); 11002 11003 // Determine the result type. 11004 QualType ResultTy = FnDecl->getReturnType(); 11005 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11006 ResultTy = ResultTy.getNonLValueExprType(Context); 11007 11008 Args[0] = Input; 11009 CallExpr *TheCall = 11010 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11011 ResultTy, VK, OpLoc, false); 11012 11013 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11014 return ExprError(); 11015 11016 return MaybeBindToTemporary(TheCall); 11017 } else { 11018 // We matched a built-in operator. Convert the arguments, then 11019 // break out so that we will build the appropriate built-in 11020 // operator node. 11021 ExprResult InputRes = 11022 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11023 Best->Conversions[0], AA_Passing); 11024 if (InputRes.isInvalid()) 11025 return ExprError(); 11026 Input = InputRes.get(); 11027 break; 11028 } 11029 } 11030 11031 case OR_No_Viable_Function: 11032 // This is an erroneous use of an operator which can be overloaded by 11033 // a non-member function. Check for non-member operators which were 11034 // defined too late to be candidates. 11035 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11036 // FIXME: Recover by calling the found function. 11037 return ExprError(); 11038 11039 // No viable function; fall through to handling this as a 11040 // built-in operator, which will produce an error message for us. 11041 break; 11042 11043 case OR_Ambiguous: 11044 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11045 << UnaryOperator::getOpcodeStr(Opc) 11046 << Input->getType() 11047 << Input->getSourceRange(); 11048 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11049 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11050 return ExprError(); 11051 11052 case OR_Deleted: 11053 Diag(OpLoc, diag::err_ovl_deleted_oper) 11054 << Best->Function->isDeleted() 11055 << UnaryOperator::getOpcodeStr(Opc) 11056 << getDeletedOrUnavailableSuffix(Best->Function) 11057 << Input->getSourceRange(); 11058 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11059 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11060 return ExprError(); 11061 } 11062 11063 // Either we found no viable overloaded operator or we matched a 11064 // built-in operator. In either case, fall through to trying to 11065 // build a built-in operation. 11066 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11067 } 11068 11069 /// \brief Create a binary operation that may resolve to an overloaded 11070 /// operator. 11071 /// 11072 /// \param OpLoc The location of the operator itself (e.g., '+'). 11073 /// 11074 /// \param OpcIn The BinaryOperator::Opcode that describes this 11075 /// operator. 11076 /// 11077 /// \param Fns The set of non-member functions that will be 11078 /// considered by overload resolution. The caller needs to build this 11079 /// set based on the context using, e.g., 11080 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11081 /// set should not contain any member functions; those will be added 11082 /// by CreateOverloadedBinOp(). 11083 /// 11084 /// \param LHS Left-hand argument. 11085 /// \param RHS Right-hand argument. 11086 ExprResult 11087 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11088 unsigned OpcIn, 11089 const UnresolvedSetImpl &Fns, 11090 Expr *LHS, Expr *RHS) { 11091 Expr *Args[2] = { LHS, RHS }; 11092 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11093 11094 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11095 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11097 11098 // If either side is type-dependent, create an appropriate dependent 11099 // expression. 11100 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11101 if (Fns.empty()) { 11102 // If there are no functions to store, just build a dependent 11103 // BinaryOperator or CompoundAssignment. 11104 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11105 return new (Context) BinaryOperator( 11106 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11107 OpLoc, FPFeatures.fp_contract); 11108 11109 return new (Context) CompoundAssignOperator( 11110 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11111 Context.DependentTy, Context.DependentTy, OpLoc, 11112 FPFeatures.fp_contract); 11113 } 11114 11115 // FIXME: save results of ADL from here? 11116 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11117 // TODO: provide better source location info in DNLoc component. 11118 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11119 UnresolvedLookupExpr *Fn 11120 = UnresolvedLookupExpr::Create(Context, NamingClass, 11121 NestedNameSpecifierLoc(), OpNameInfo, 11122 /*ADL*/ true, IsOverloaded(Fns), 11123 Fns.begin(), Fns.end()); 11124 return new (Context) 11125 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11126 VK_RValue, OpLoc, FPFeatures.fp_contract); 11127 } 11128 11129 // Always do placeholder-like conversions on the RHS. 11130 if (checkPlaceholderForOverload(*this, Args[1])) 11131 return ExprError(); 11132 11133 // Do placeholder-like conversion on the LHS; note that we should 11134 // not get here with a PseudoObject LHS. 11135 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11136 if (checkPlaceholderForOverload(*this, Args[0])) 11137 return ExprError(); 11138 11139 // If this is the assignment operator, we only perform overload resolution 11140 // if the left-hand side is a class or enumeration type. This is actually 11141 // a hack. The standard requires that we do overload resolution between the 11142 // various built-in candidates, but as DR507 points out, this can lead to 11143 // problems. So we do it this way, which pretty much follows what GCC does. 11144 // Note that we go the traditional code path for compound assignment forms. 11145 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11146 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11147 11148 // If this is the .* operator, which is not overloadable, just 11149 // create a built-in binary operator. 11150 if (Opc == BO_PtrMemD) 11151 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11152 11153 // Build an empty overload set. 11154 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11155 11156 // Add the candidates from the given function set. 11157 AddFunctionCandidates(Fns, Args, CandidateSet); 11158 11159 // Add operator candidates that are member functions. 11160 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11161 11162 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11163 // performed for an assignment operator (nor for operator[] nor operator->, 11164 // which don't get here). 11165 if (Opc != BO_Assign) 11166 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11167 /*ExplicitTemplateArgs*/ nullptr, 11168 CandidateSet); 11169 11170 // Add builtin operator candidates. 11171 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11172 11173 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11174 11175 // Perform overload resolution. 11176 OverloadCandidateSet::iterator Best; 11177 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11178 case OR_Success: { 11179 // We found a built-in operator or an overloaded operator. 11180 FunctionDecl *FnDecl = Best->Function; 11181 11182 if (FnDecl) { 11183 // We matched an overloaded operator. Build a call to that 11184 // operator. 11185 11186 // Convert the arguments. 11187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11188 // Best->Access is only meaningful for class members. 11189 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11190 11191 ExprResult Arg1 = 11192 PerformCopyInitialization( 11193 InitializedEntity::InitializeParameter(Context, 11194 FnDecl->getParamDecl(0)), 11195 SourceLocation(), Args[1]); 11196 if (Arg1.isInvalid()) 11197 return ExprError(); 11198 11199 ExprResult Arg0 = 11200 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11201 Best->FoundDecl, Method); 11202 if (Arg0.isInvalid()) 11203 return ExprError(); 11204 Args[0] = Arg0.getAs<Expr>(); 11205 Args[1] = RHS = Arg1.getAs<Expr>(); 11206 } else { 11207 // Convert the arguments. 11208 ExprResult Arg0 = PerformCopyInitialization( 11209 InitializedEntity::InitializeParameter(Context, 11210 FnDecl->getParamDecl(0)), 11211 SourceLocation(), Args[0]); 11212 if (Arg0.isInvalid()) 11213 return ExprError(); 11214 11215 ExprResult Arg1 = 11216 PerformCopyInitialization( 11217 InitializedEntity::InitializeParameter(Context, 11218 FnDecl->getParamDecl(1)), 11219 SourceLocation(), Args[1]); 11220 if (Arg1.isInvalid()) 11221 return ExprError(); 11222 Args[0] = LHS = Arg0.getAs<Expr>(); 11223 Args[1] = RHS = Arg1.getAs<Expr>(); 11224 } 11225 11226 // Build the actual expression node. 11227 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11228 Best->FoundDecl, 11229 HadMultipleCandidates, OpLoc); 11230 if (FnExpr.isInvalid()) 11231 return ExprError(); 11232 11233 // Determine the result type. 11234 QualType ResultTy = FnDecl->getReturnType(); 11235 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11236 ResultTy = ResultTy.getNonLValueExprType(Context); 11237 11238 CXXOperatorCallExpr *TheCall = 11239 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11240 Args, ResultTy, VK, OpLoc, 11241 FPFeatures.fp_contract); 11242 11243 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11244 FnDecl)) 11245 return ExprError(); 11246 11247 ArrayRef<const Expr *> ArgsArray(Args, 2); 11248 // Cut off the implicit 'this'. 11249 if (isa<CXXMethodDecl>(FnDecl)) 11250 ArgsArray = ArgsArray.slice(1); 11251 11252 // Check for a self move. 11253 if (Op == OO_Equal) 11254 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11255 11256 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 11257 TheCall->getSourceRange(), VariadicDoesNotApply); 11258 11259 return MaybeBindToTemporary(TheCall); 11260 } else { 11261 // We matched a built-in operator. Convert the arguments, then 11262 // break out so that we will build the appropriate built-in 11263 // operator node. 11264 ExprResult ArgsRes0 = 11265 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11266 Best->Conversions[0], AA_Passing); 11267 if (ArgsRes0.isInvalid()) 11268 return ExprError(); 11269 Args[0] = ArgsRes0.get(); 11270 11271 ExprResult ArgsRes1 = 11272 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11273 Best->Conversions[1], AA_Passing); 11274 if (ArgsRes1.isInvalid()) 11275 return ExprError(); 11276 Args[1] = ArgsRes1.get(); 11277 break; 11278 } 11279 } 11280 11281 case OR_No_Viable_Function: { 11282 // C++ [over.match.oper]p9: 11283 // If the operator is the operator , [...] and there are no 11284 // viable functions, then the operator is assumed to be the 11285 // built-in operator and interpreted according to clause 5. 11286 if (Opc == BO_Comma) 11287 break; 11288 11289 // For class as left operand for assignment or compound assigment 11290 // operator do not fall through to handling in built-in, but report that 11291 // no overloaded assignment operator found 11292 ExprResult Result = ExprError(); 11293 if (Args[0]->getType()->isRecordType() && 11294 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11295 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11296 << BinaryOperator::getOpcodeStr(Opc) 11297 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11298 if (Args[0]->getType()->isIncompleteType()) { 11299 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11300 << Args[0]->getType() 11301 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11302 } 11303 } else { 11304 // This is an erroneous use of an operator which can be overloaded by 11305 // a non-member function. Check for non-member operators which were 11306 // defined too late to be candidates. 11307 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11308 // FIXME: Recover by calling the found function. 11309 return ExprError(); 11310 11311 // No viable function; try to create a built-in operation, which will 11312 // produce an error. Then, show the non-viable candidates. 11313 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11314 } 11315 assert(Result.isInvalid() && 11316 "C++ binary operator overloading is missing candidates!"); 11317 if (Result.isInvalid()) 11318 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11319 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11320 return Result; 11321 } 11322 11323 case OR_Ambiguous: 11324 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11325 << BinaryOperator::getOpcodeStr(Opc) 11326 << Args[0]->getType() << Args[1]->getType() 11327 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11328 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11329 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11330 return ExprError(); 11331 11332 case OR_Deleted: 11333 if (isImplicitlyDeleted(Best->Function)) { 11334 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11335 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11336 << Context.getRecordType(Method->getParent()) 11337 << getSpecialMember(Method); 11338 11339 // The user probably meant to call this special member. Just 11340 // explain why it's deleted. 11341 NoteDeletedFunction(Method); 11342 return ExprError(); 11343 } else { 11344 Diag(OpLoc, diag::err_ovl_deleted_oper) 11345 << Best->Function->isDeleted() 11346 << BinaryOperator::getOpcodeStr(Opc) 11347 << getDeletedOrUnavailableSuffix(Best->Function) 11348 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11349 } 11350 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11351 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11352 return ExprError(); 11353 } 11354 11355 // We matched a built-in operator; build it. 11356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11357 } 11358 11359 ExprResult 11360 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11361 SourceLocation RLoc, 11362 Expr *Base, Expr *Idx) { 11363 Expr *Args[2] = { Base, Idx }; 11364 DeclarationName OpName = 11365 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11366 11367 // If either side is type-dependent, create an appropriate dependent 11368 // expression. 11369 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11370 11371 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11372 // CHECKME: no 'operator' keyword? 11373 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11374 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11375 UnresolvedLookupExpr *Fn 11376 = UnresolvedLookupExpr::Create(Context, NamingClass, 11377 NestedNameSpecifierLoc(), OpNameInfo, 11378 /*ADL*/ true, /*Overloaded*/ false, 11379 UnresolvedSetIterator(), 11380 UnresolvedSetIterator()); 11381 // Can't add any actual overloads yet 11382 11383 return new (Context) 11384 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11385 Context.DependentTy, VK_RValue, RLoc, false); 11386 } 11387 11388 // Handle placeholders on both operands. 11389 if (checkPlaceholderForOverload(*this, Args[0])) 11390 return ExprError(); 11391 if (checkPlaceholderForOverload(*this, Args[1])) 11392 return ExprError(); 11393 11394 // Build an empty overload set. 11395 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11396 11397 // Subscript can only be overloaded as a member function. 11398 11399 // Add operator candidates that are member functions. 11400 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11401 11402 // Add builtin operator candidates. 11403 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11404 11405 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11406 11407 // Perform overload resolution. 11408 OverloadCandidateSet::iterator Best; 11409 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11410 case OR_Success: { 11411 // We found a built-in operator or an overloaded operator. 11412 FunctionDecl *FnDecl = Best->Function; 11413 11414 if (FnDecl) { 11415 // We matched an overloaded operator. Build a call to that 11416 // operator. 11417 11418 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11419 11420 // Convert the arguments. 11421 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11422 ExprResult Arg0 = 11423 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11424 Best->FoundDecl, Method); 11425 if (Arg0.isInvalid()) 11426 return ExprError(); 11427 Args[0] = Arg0.get(); 11428 11429 // Convert the arguments. 11430 ExprResult InputInit 11431 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11432 Context, 11433 FnDecl->getParamDecl(0)), 11434 SourceLocation(), 11435 Args[1]); 11436 if (InputInit.isInvalid()) 11437 return ExprError(); 11438 11439 Args[1] = InputInit.getAs<Expr>(); 11440 11441 // Build the actual expression node. 11442 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11443 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11444 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11445 Best->FoundDecl, 11446 HadMultipleCandidates, 11447 OpLocInfo.getLoc(), 11448 OpLocInfo.getInfo()); 11449 if (FnExpr.isInvalid()) 11450 return ExprError(); 11451 11452 // Determine the result type 11453 QualType ResultTy = FnDecl->getReturnType(); 11454 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11455 ResultTy = ResultTy.getNonLValueExprType(Context); 11456 11457 CXXOperatorCallExpr *TheCall = 11458 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11459 FnExpr.get(), Args, 11460 ResultTy, VK, RLoc, 11461 false); 11462 11463 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11464 return ExprError(); 11465 11466 return MaybeBindToTemporary(TheCall); 11467 } else { 11468 // We matched a built-in operator. Convert the arguments, then 11469 // break out so that we will build the appropriate built-in 11470 // operator node. 11471 ExprResult ArgsRes0 = 11472 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11473 Best->Conversions[0], AA_Passing); 11474 if (ArgsRes0.isInvalid()) 11475 return ExprError(); 11476 Args[0] = ArgsRes0.get(); 11477 11478 ExprResult ArgsRes1 = 11479 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11480 Best->Conversions[1], AA_Passing); 11481 if (ArgsRes1.isInvalid()) 11482 return ExprError(); 11483 Args[1] = ArgsRes1.get(); 11484 11485 break; 11486 } 11487 } 11488 11489 case OR_No_Viable_Function: { 11490 if (CandidateSet.empty()) 11491 Diag(LLoc, diag::err_ovl_no_oper) 11492 << Args[0]->getType() << /*subscript*/ 0 11493 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11494 else 11495 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11496 << Args[0]->getType() 11497 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11499 "[]", LLoc); 11500 return ExprError(); 11501 } 11502 11503 case OR_Ambiguous: 11504 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11505 << "[]" 11506 << Args[0]->getType() << Args[1]->getType() 11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11508 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11509 "[]", LLoc); 11510 return ExprError(); 11511 11512 case OR_Deleted: 11513 Diag(LLoc, diag::err_ovl_deleted_oper) 11514 << Best->Function->isDeleted() << "[]" 11515 << getDeletedOrUnavailableSuffix(Best->Function) 11516 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11517 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11518 "[]", LLoc); 11519 return ExprError(); 11520 } 11521 11522 // We matched a built-in operator; build it. 11523 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11524 } 11525 11526 /// BuildCallToMemberFunction - Build a call to a member 11527 /// function. MemExpr is the expression that refers to the member 11528 /// function (and includes the object parameter), Args/NumArgs are the 11529 /// arguments to the function call (not including the object 11530 /// parameter). The caller needs to validate that the member 11531 /// expression refers to a non-static member function or an overloaded 11532 /// member function. 11533 ExprResult 11534 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11535 SourceLocation LParenLoc, 11536 MultiExprArg Args, 11537 SourceLocation RParenLoc) { 11538 assert(MemExprE->getType() == Context.BoundMemberTy || 11539 MemExprE->getType() == Context.OverloadTy); 11540 11541 // Dig out the member expression. This holds both the object 11542 // argument and the member function we're referring to. 11543 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11544 11545 // Determine whether this is a call to a pointer-to-member function. 11546 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11547 assert(op->getType() == Context.BoundMemberTy); 11548 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11549 11550 QualType fnType = 11551 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11552 11553 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11554 QualType resultType = proto->getCallResultType(Context); 11555 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11556 11557 // Check that the object type isn't more qualified than the 11558 // member function we're calling. 11559 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11560 11561 QualType objectType = op->getLHS()->getType(); 11562 if (op->getOpcode() == BO_PtrMemI) 11563 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11564 Qualifiers objectQuals = objectType.getQualifiers(); 11565 11566 Qualifiers difference = objectQuals - funcQuals; 11567 difference.removeObjCGCAttr(); 11568 difference.removeAddressSpace(); 11569 if (difference) { 11570 std::string qualsString = difference.getAsString(); 11571 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11572 << fnType.getUnqualifiedType() 11573 << qualsString 11574 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11575 } 11576 11577 if (resultType->isMemberPointerType()) 11578 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11579 RequireCompleteType(LParenLoc, resultType, 0); 11580 11581 CXXMemberCallExpr *call 11582 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11583 resultType, valueKind, RParenLoc); 11584 11585 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11586 call, nullptr)) 11587 return ExprError(); 11588 11589 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11590 return ExprError(); 11591 11592 if (CheckOtherCall(call, proto)) 11593 return ExprError(); 11594 11595 return MaybeBindToTemporary(call); 11596 } 11597 11598 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11599 return new (Context) 11600 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11601 11602 UnbridgedCastsSet UnbridgedCasts; 11603 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11604 return ExprError(); 11605 11606 MemberExpr *MemExpr; 11607 CXXMethodDecl *Method = nullptr; 11608 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11609 NestedNameSpecifier *Qualifier = nullptr; 11610 if (isa<MemberExpr>(NakedMemExpr)) { 11611 MemExpr = cast<MemberExpr>(NakedMemExpr); 11612 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11613 FoundDecl = MemExpr->getFoundDecl(); 11614 Qualifier = MemExpr->getQualifier(); 11615 UnbridgedCasts.restore(); 11616 } else { 11617 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11618 Qualifier = UnresExpr->getQualifier(); 11619 11620 QualType ObjectType = UnresExpr->getBaseType(); 11621 Expr::Classification ObjectClassification 11622 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11623 : UnresExpr->getBase()->Classify(Context); 11624 11625 // Add overload candidates 11626 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11627 OverloadCandidateSet::CSK_Normal); 11628 11629 // FIXME: avoid copy. 11630 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11631 if (UnresExpr->hasExplicitTemplateArgs()) { 11632 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11633 TemplateArgs = &TemplateArgsBuffer; 11634 } 11635 11636 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11637 E = UnresExpr->decls_end(); I != E; ++I) { 11638 11639 NamedDecl *Func = *I; 11640 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11641 if (isa<UsingShadowDecl>(Func)) 11642 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11643 11644 11645 // Microsoft supports direct constructor calls. 11646 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11647 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11648 Args, CandidateSet); 11649 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11650 // If explicit template arguments were provided, we can't call a 11651 // non-template member function. 11652 if (TemplateArgs) 11653 continue; 11654 11655 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11656 ObjectClassification, Args, CandidateSet, 11657 /*SuppressUserConversions=*/false); 11658 } else { 11659 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11660 I.getPair(), ActingDC, TemplateArgs, 11661 ObjectType, ObjectClassification, 11662 Args, CandidateSet, 11663 /*SuppressUsedConversions=*/false); 11664 } 11665 } 11666 11667 DeclarationName DeclName = UnresExpr->getMemberName(); 11668 11669 UnbridgedCasts.restore(); 11670 11671 OverloadCandidateSet::iterator Best; 11672 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11673 Best)) { 11674 case OR_Success: 11675 Method = cast<CXXMethodDecl>(Best->Function); 11676 FoundDecl = Best->FoundDecl; 11677 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11678 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11679 return ExprError(); 11680 // If FoundDecl is different from Method (such as if one is a template 11681 // and the other a specialization), make sure DiagnoseUseOfDecl is 11682 // called on both. 11683 // FIXME: This would be more comprehensively addressed by modifying 11684 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11685 // being used. 11686 if (Method != FoundDecl.getDecl() && 11687 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11688 return ExprError(); 11689 break; 11690 11691 case OR_No_Viable_Function: 11692 Diag(UnresExpr->getMemberLoc(), 11693 diag::err_ovl_no_viable_member_function_in_call) 11694 << DeclName << MemExprE->getSourceRange(); 11695 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11696 // FIXME: Leaking incoming expressions! 11697 return ExprError(); 11698 11699 case OR_Ambiguous: 11700 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11701 << DeclName << MemExprE->getSourceRange(); 11702 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11703 // FIXME: Leaking incoming expressions! 11704 return ExprError(); 11705 11706 case OR_Deleted: 11707 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11708 << Best->Function->isDeleted() 11709 << DeclName 11710 << getDeletedOrUnavailableSuffix(Best->Function) 11711 << MemExprE->getSourceRange(); 11712 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11713 // FIXME: Leaking incoming expressions! 11714 return ExprError(); 11715 } 11716 11717 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11718 11719 // If overload resolution picked a static member, build a 11720 // non-member call based on that function. 11721 if (Method->isStatic()) { 11722 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11723 RParenLoc); 11724 } 11725 11726 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11727 } 11728 11729 QualType ResultType = Method->getReturnType(); 11730 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11731 ResultType = ResultType.getNonLValueExprType(Context); 11732 11733 assert(Method && "Member call to something that isn't a method?"); 11734 CXXMemberCallExpr *TheCall = 11735 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11736 ResultType, VK, RParenLoc); 11737 11738 // (CUDA B.1): Check for invalid calls between targets. 11739 if (getLangOpts().CUDA) { 11740 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11741 if (CheckCUDATarget(Caller, Method)) { 11742 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11743 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11744 << IdentifyCUDATarget(Caller); 11745 return ExprError(); 11746 } 11747 } 11748 } 11749 11750 // Check for a valid return type. 11751 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11752 TheCall, Method)) 11753 return ExprError(); 11754 11755 // Convert the object argument (for a non-static member function call). 11756 // We only need to do this if there was actually an overload; otherwise 11757 // it was done at lookup. 11758 if (!Method->isStatic()) { 11759 ExprResult ObjectArg = 11760 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11761 FoundDecl, Method); 11762 if (ObjectArg.isInvalid()) 11763 return ExprError(); 11764 MemExpr->setBase(ObjectArg.get()); 11765 } 11766 11767 // Convert the rest of the arguments 11768 const FunctionProtoType *Proto = 11769 Method->getType()->getAs<FunctionProtoType>(); 11770 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11771 RParenLoc)) 11772 return ExprError(); 11773 11774 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11775 11776 if (CheckFunctionCall(Method, TheCall, Proto)) 11777 return ExprError(); 11778 11779 if ((isa<CXXConstructorDecl>(CurContext) || 11780 isa<CXXDestructorDecl>(CurContext)) && 11781 TheCall->getMethodDecl()->isPure()) { 11782 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11783 11784 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11785 Diag(MemExpr->getLocStart(), 11786 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11787 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11788 << MD->getParent()->getDeclName(); 11789 11790 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11791 } 11792 } 11793 return MaybeBindToTemporary(TheCall); 11794 } 11795 11796 /// BuildCallToObjectOfClassType - Build a call to an object of class 11797 /// type (C++ [over.call.object]), which can end up invoking an 11798 /// overloaded function call operator (@c operator()) or performing a 11799 /// user-defined conversion on the object argument. 11800 ExprResult 11801 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11802 SourceLocation LParenLoc, 11803 MultiExprArg Args, 11804 SourceLocation RParenLoc) { 11805 if (checkPlaceholderForOverload(*this, Obj)) 11806 return ExprError(); 11807 ExprResult Object = Obj; 11808 11809 UnbridgedCastsSet UnbridgedCasts; 11810 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11811 return ExprError(); 11812 11813 assert(Object.get()->getType()->isRecordType() && 11814 "Requires object type argument"); 11815 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11816 11817 // C++ [over.call.object]p1: 11818 // If the primary-expression E in the function call syntax 11819 // evaluates to a class object of type "cv T", then the set of 11820 // candidate functions includes at least the function call 11821 // operators of T. The function call operators of T are obtained by 11822 // ordinary lookup of the name operator() in the context of 11823 // (E).operator(). 11824 OverloadCandidateSet CandidateSet(LParenLoc, 11825 OverloadCandidateSet::CSK_Operator); 11826 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11827 11828 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11829 diag::err_incomplete_object_call, Object.get())) 11830 return true; 11831 11832 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11833 LookupQualifiedName(R, Record->getDecl()); 11834 R.suppressDiagnostics(); 11835 11836 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11837 Oper != OperEnd; ++Oper) { 11838 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11839 Object.get()->Classify(Context), 11840 Args, CandidateSet, 11841 /*SuppressUserConversions=*/ false); 11842 } 11843 11844 // C++ [over.call.object]p2: 11845 // In addition, for each (non-explicit in C++0x) conversion function 11846 // declared in T of the form 11847 // 11848 // operator conversion-type-id () cv-qualifier; 11849 // 11850 // where cv-qualifier is the same cv-qualification as, or a 11851 // greater cv-qualification than, cv, and where conversion-type-id 11852 // denotes the type "pointer to function of (P1,...,Pn) returning 11853 // R", or the type "reference to pointer to function of 11854 // (P1,...,Pn) returning R", or the type "reference to function 11855 // of (P1,...,Pn) returning R", a surrogate call function [...] 11856 // is also considered as a candidate function. Similarly, 11857 // surrogate call functions are added to the set of candidate 11858 // functions for each conversion function declared in an 11859 // accessible base class provided the function is not hidden 11860 // within T by another intervening declaration. 11861 const auto &Conversions = 11862 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11863 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 11864 NamedDecl *D = *I; 11865 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11866 if (isa<UsingShadowDecl>(D)) 11867 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11868 11869 // Skip over templated conversion functions; they aren't 11870 // surrogates. 11871 if (isa<FunctionTemplateDecl>(D)) 11872 continue; 11873 11874 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11875 if (!Conv->isExplicit()) { 11876 // Strip the reference type (if any) and then the pointer type (if 11877 // any) to get down to what might be a function type. 11878 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11879 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11880 ConvType = ConvPtrType->getPointeeType(); 11881 11882 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11883 { 11884 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11885 Object.get(), Args, CandidateSet); 11886 } 11887 } 11888 } 11889 11890 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11891 11892 // Perform overload resolution. 11893 OverloadCandidateSet::iterator Best; 11894 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11895 Best)) { 11896 case OR_Success: 11897 // Overload resolution succeeded; we'll build the appropriate call 11898 // below. 11899 break; 11900 11901 case OR_No_Viable_Function: 11902 if (CandidateSet.empty()) 11903 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11904 << Object.get()->getType() << /*call*/ 1 11905 << Object.get()->getSourceRange(); 11906 else 11907 Diag(Object.get()->getLocStart(), 11908 diag::err_ovl_no_viable_object_call) 11909 << Object.get()->getType() << Object.get()->getSourceRange(); 11910 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11911 break; 11912 11913 case OR_Ambiguous: 11914 Diag(Object.get()->getLocStart(), 11915 diag::err_ovl_ambiguous_object_call) 11916 << Object.get()->getType() << Object.get()->getSourceRange(); 11917 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11918 break; 11919 11920 case OR_Deleted: 11921 Diag(Object.get()->getLocStart(), 11922 diag::err_ovl_deleted_object_call) 11923 << Best->Function->isDeleted() 11924 << Object.get()->getType() 11925 << getDeletedOrUnavailableSuffix(Best->Function) 11926 << Object.get()->getSourceRange(); 11927 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11928 break; 11929 } 11930 11931 if (Best == CandidateSet.end()) 11932 return true; 11933 11934 UnbridgedCasts.restore(); 11935 11936 if (Best->Function == nullptr) { 11937 // Since there is no function declaration, this is one of the 11938 // surrogate candidates. Dig out the conversion function. 11939 CXXConversionDecl *Conv 11940 = cast<CXXConversionDecl>( 11941 Best->Conversions[0].UserDefined.ConversionFunction); 11942 11943 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 11944 Best->FoundDecl); 11945 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11946 return ExprError(); 11947 assert(Conv == Best->FoundDecl.getDecl() && 11948 "Found Decl & conversion-to-functionptr should be same, right?!"); 11949 // We selected one of the surrogate functions that converts the 11950 // object parameter to a function pointer. Perform the conversion 11951 // on the object argument, then let ActOnCallExpr finish the job. 11952 11953 // Create an implicit member expr to refer to the conversion operator. 11954 // and then call it. 11955 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11956 Conv, HadMultipleCandidates); 11957 if (Call.isInvalid()) 11958 return ExprError(); 11959 // Record usage of conversion in an implicit cast. 11960 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 11961 CK_UserDefinedConversion, Call.get(), 11962 nullptr, VK_RValue); 11963 11964 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11965 } 11966 11967 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 11968 11969 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11970 // that calls this method, using Object for the implicit object 11971 // parameter and passing along the remaining arguments. 11972 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11973 11974 // An error diagnostic has already been printed when parsing the declaration. 11975 if (Method->isInvalidDecl()) 11976 return ExprError(); 11977 11978 const FunctionProtoType *Proto = 11979 Method->getType()->getAs<FunctionProtoType>(); 11980 11981 unsigned NumParams = Proto->getNumParams(); 11982 11983 DeclarationNameInfo OpLocInfo( 11984 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11985 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11986 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11987 HadMultipleCandidates, 11988 OpLocInfo.getLoc(), 11989 OpLocInfo.getInfo()); 11990 if (NewFn.isInvalid()) 11991 return true; 11992 11993 // Build the full argument list for the method call (the implicit object 11994 // parameter is placed at the beginning of the list). 11995 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11996 MethodArgs[0] = Object.get(); 11997 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11998 11999 // Once we've built TheCall, all of the expressions are properly 12000 // owned. 12001 QualType ResultTy = Method->getReturnType(); 12002 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12003 ResultTy = ResultTy.getNonLValueExprType(Context); 12004 12005 CXXOperatorCallExpr *TheCall = new (Context) 12006 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12007 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12008 ResultTy, VK, RParenLoc, false); 12009 MethodArgs.reset(); 12010 12011 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12012 return true; 12013 12014 // We may have default arguments. If so, we need to allocate more 12015 // slots in the call for them. 12016 if (Args.size() < NumParams) 12017 TheCall->setNumArgs(Context, NumParams + 1); 12018 12019 bool IsError = false; 12020 12021 // Initialize the implicit object parameter. 12022 ExprResult ObjRes = 12023 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12024 Best->FoundDecl, Method); 12025 if (ObjRes.isInvalid()) 12026 IsError = true; 12027 else 12028 Object = ObjRes; 12029 TheCall->setArg(0, Object.get()); 12030 12031 // Check the argument types. 12032 for (unsigned i = 0; i != NumParams; i++) { 12033 Expr *Arg; 12034 if (i < Args.size()) { 12035 Arg = Args[i]; 12036 12037 // Pass the argument. 12038 12039 ExprResult InputInit 12040 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12041 Context, 12042 Method->getParamDecl(i)), 12043 SourceLocation(), Arg); 12044 12045 IsError |= InputInit.isInvalid(); 12046 Arg = InputInit.getAs<Expr>(); 12047 } else { 12048 ExprResult DefArg 12049 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12050 if (DefArg.isInvalid()) { 12051 IsError = true; 12052 break; 12053 } 12054 12055 Arg = DefArg.getAs<Expr>(); 12056 } 12057 12058 TheCall->setArg(i + 1, Arg); 12059 } 12060 12061 // If this is a variadic call, handle args passed through "...". 12062 if (Proto->isVariadic()) { 12063 // Promote the arguments (C99 6.5.2.2p7). 12064 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12065 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12066 nullptr); 12067 IsError |= Arg.isInvalid(); 12068 TheCall->setArg(i + 1, Arg.get()); 12069 } 12070 } 12071 12072 if (IsError) return true; 12073 12074 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12075 12076 if (CheckFunctionCall(Method, TheCall, Proto)) 12077 return true; 12078 12079 return MaybeBindToTemporary(TheCall); 12080 } 12081 12082 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12083 /// (if one exists), where @c Base is an expression of class type and 12084 /// @c Member is the name of the member we're trying to find. 12085 ExprResult 12086 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12087 bool *NoArrowOperatorFound) { 12088 assert(Base->getType()->isRecordType() && 12089 "left-hand side must have class type"); 12090 12091 if (checkPlaceholderForOverload(*this, Base)) 12092 return ExprError(); 12093 12094 SourceLocation Loc = Base->getExprLoc(); 12095 12096 // C++ [over.ref]p1: 12097 // 12098 // [...] An expression x->m is interpreted as (x.operator->())->m 12099 // for a class object x of type T if T::operator->() exists and if 12100 // the operator is selected as the best match function by the 12101 // overload resolution mechanism (13.3). 12102 DeclarationName OpName = 12103 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12104 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12105 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12106 12107 if (RequireCompleteType(Loc, Base->getType(), 12108 diag::err_typecheck_incomplete_tag, Base)) 12109 return ExprError(); 12110 12111 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12112 LookupQualifiedName(R, BaseRecord->getDecl()); 12113 R.suppressDiagnostics(); 12114 12115 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12116 Oper != OperEnd; ++Oper) { 12117 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12118 None, CandidateSet, /*SuppressUserConversions=*/false); 12119 } 12120 12121 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12122 12123 // Perform overload resolution. 12124 OverloadCandidateSet::iterator Best; 12125 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12126 case OR_Success: 12127 // Overload resolution succeeded; we'll build the call below. 12128 break; 12129 12130 case OR_No_Viable_Function: 12131 if (CandidateSet.empty()) { 12132 QualType BaseType = Base->getType(); 12133 if (NoArrowOperatorFound) { 12134 // Report this specific error to the caller instead of emitting a 12135 // diagnostic, as requested. 12136 *NoArrowOperatorFound = true; 12137 return ExprError(); 12138 } 12139 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12140 << BaseType << Base->getSourceRange(); 12141 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12142 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12143 << FixItHint::CreateReplacement(OpLoc, "."); 12144 } 12145 } else 12146 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12147 << "operator->" << Base->getSourceRange(); 12148 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12149 return ExprError(); 12150 12151 case OR_Ambiguous: 12152 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12153 << "->" << Base->getType() << Base->getSourceRange(); 12154 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12155 return ExprError(); 12156 12157 case OR_Deleted: 12158 Diag(OpLoc, diag::err_ovl_deleted_oper) 12159 << Best->Function->isDeleted() 12160 << "->" 12161 << getDeletedOrUnavailableSuffix(Best->Function) 12162 << Base->getSourceRange(); 12163 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12164 return ExprError(); 12165 } 12166 12167 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12168 12169 // Convert the object parameter. 12170 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12171 ExprResult BaseResult = 12172 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12173 Best->FoundDecl, Method); 12174 if (BaseResult.isInvalid()) 12175 return ExprError(); 12176 Base = BaseResult.get(); 12177 12178 // Build the operator call. 12179 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12180 HadMultipleCandidates, OpLoc); 12181 if (FnExpr.isInvalid()) 12182 return ExprError(); 12183 12184 QualType ResultTy = Method->getReturnType(); 12185 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12186 ResultTy = ResultTy.getNonLValueExprType(Context); 12187 CXXOperatorCallExpr *TheCall = 12188 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12189 Base, ResultTy, VK, OpLoc, false); 12190 12191 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12192 return ExprError(); 12193 12194 return MaybeBindToTemporary(TheCall); 12195 } 12196 12197 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12198 /// a literal operator described by the provided lookup results. 12199 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12200 DeclarationNameInfo &SuffixInfo, 12201 ArrayRef<Expr*> Args, 12202 SourceLocation LitEndLoc, 12203 TemplateArgumentListInfo *TemplateArgs) { 12204 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12205 12206 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12207 OverloadCandidateSet::CSK_Normal); 12208 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12209 /*SuppressUserConversions=*/true); 12210 12211 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12212 12213 // Perform overload resolution. This will usually be trivial, but might need 12214 // to perform substitutions for a literal operator template. 12215 OverloadCandidateSet::iterator Best; 12216 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12217 case OR_Success: 12218 case OR_Deleted: 12219 break; 12220 12221 case OR_No_Viable_Function: 12222 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12223 << R.getLookupName(); 12224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12225 return ExprError(); 12226 12227 case OR_Ambiguous: 12228 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12229 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12230 return ExprError(); 12231 } 12232 12233 FunctionDecl *FD = Best->Function; 12234 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12235 HadMultipleCandidates, 12236 SuffixInfo.getLoc(), 12237 SuffixInfo.getInfo()); 12238 if (Fn.isInvalid()) 12239 return true; 12240 12241 // Check the argument types. This should almost always be a no-op, except 12242 // that array-to-pointer decay is applied to string literals. 12243 Expr *ConvArgs[2]; 12244 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12245 ExprResult InputInit = PerformCopyInitialization( 12246 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12247 SourceLocation(), Args[ArgIdx]); 12248 if (InputInit.isInvalid()) 12249 return true; 12250 ConvArgs[ArgIdx] = InputInit.get(); 12251 } 12252 12253 QualType ResultTy = FD->getReturnType(); 12254 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12255 ResultTy = ResultTy.getNonLValueExprType(Context); 12256 12257 UserDefinedLiteral *UDL = 12258 new (Context) UserDefinedLiteral(Context, Fn.get(), 12259 llvm::makeArrayRef(ConvArgs, Args.size()), 12260 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12261 12262 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12263 return ExprError(); 12264 12265 if (CheckFunctionCall(FD, UDL, nullptr)) 12266 return ExprError(); 12267 12268 return MaybeBindToTemporary(UDL); 12269 } 12270 12271 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12272 /// given LookupResult is non-empty, it is assumed to describe a member which 12273 /// will be invoked. Otherwise, the function will be found via argument 12274 /// dependent lookup. 12275 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12276 /// otherwise CallExpr is set to ExprError() and some non-success value 12277 /// is returned. 12278 Sema::ForRangeStatus 12279 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12280 SourceLocation RangeLoc, VarDecl *Decl, 12281 BeginEndFunction BEF, 12282 const DeclarationNameInfo &NameInfo, 12283 LookupResult &MemberLookup, 12284 OverloadCandidateSet *CandidateSet, 12285 Expr *Range, ExprResult *CallExpr) { 12286 CandidateSet->clear(); 12287 if (!MemberLookup.empty()) { 12288 ExprResult MemberRef = 12289 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12290 /*IsPtr=*/false, CXXScopeSpec(), 12291 /*TemplateKWLoc=*/SourceLocation(), 12292 /*FirstQualifierInScope=*/nullptr, 12293 MemberLookup, 12294 /*TemplateArgs=*/nullptr); 12295 if (MemberRef.isInvalid()) { 12296 *CallExpr = ExprError(); 12297 Diag(Range->getLocStart(), diag::note_in_for_range) 12298 << RangeLoc << BEF << Range->getType(); 12299 return FRS_DiagnosticIssued; 12300 } 12301 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12302 if (CallExpr->isInvalid()) { 12303 *CallExpr = ExprError(); 12304 Diag(Range->getLocStart(), diag::note_in_for_range) 12305 << RangeLoc << BEF << Range->getType(); 12306 return FRS_DiagnosticIssued; 12307 } 12308 } else { 12309 UnresolvedSet<0> FoundNames; 12310 UnresolvedLookupExpr *Fn = 12311 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12312 NestedNameSpecifierLoc(), NameInfo, 12313 /*NeedsADL=*/true, /*Overloaded=*/false, 12314 FoundNames.begin(), FoundNames.end()); 12315 12316 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12317 CandidateSet, CallExpr); 12318 if (CandidateSet->empty() || CandidateSetError) { 12319 *CallExpr = ExprError(); 12320 return FRS_NoViableFunction; 12321 } 12322 OverloadCandidateSet::iterator Best; 12323 OverloadingResult OverloadResult = 12324 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12325 12326 if (OverloadResult == OR_No_Viable_Function) { 12327 *CallExpr = ExprError(); 12328 return FRS_NoViableFunction; 12329 } 12330 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12331 Loc, nullptr, CandidateSet, &Best, 12332 OverloadResult, 12333 /*AllowTypoCorrection=*/false); 12334 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12335 *CallExpr = ExprError(); 12336 Diag(Range->getLocStart(), diag::note_in_for_range) 12337 << RangeLoc << BEF << Range->getType(); 12338 return FRS_DiagnosticIssued; 12339 } 12340 } 12341 return FRS_Success; 12342 } 12343 12344 12345 /// FixOverloadedFunctionReference - E is an expression that refers to 12346 /// a C++ overloaded function (possibly with some parentheses and 12347 /// perhaps a '&' around it). We have resolved the overloaded function 12348 /// to the function declaration Fn, so patch up the expression E to 12349 /// refer (possibly indirectly) to Fn. Returns the new expr. 12350 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12351 FunctionDecl *Fn) { 12352 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12353 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12354 Found, Fn); 12355 if (SubExpr == PE->getSubExpr()) 12356 return PE; 12357 12358 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12359 } 12360 12361 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12362 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12363 Found, Fn); 12364 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12365 SubExpr->getType()) && 12366 "Implicit cast type cannot be determined from overload"); 12367 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12368 if (SubExpr == ICE->getSubExpr()) 12369 return ICE; 12370 12371 return ImplicitCastExpr::Create(Context, ICE->getType(), 12372 ICE->getCastKind(), 12373 SubExpr, nullptr, 12374 ICE->getValueKind()); 12375 } 12376 12377 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12378 assert(UnOp->getOpcode() == UO_AddrOf && 12379 "Can only take the address of an overloaded function"); 12380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12381 if (Method->isStatic()) { 12382 // Do nothing: static member functions aren't any different 12383 // from non-member functions. 12384 } else { 12385 // Fix the subexpression, which really has to be an 12386 // UnresolvedLookupExpr holding an overloaded member function 12387 // or template. 12388 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12389 Found, Fn); 12390 if (SubExpr == UnOp->getSubExpr()) 12391 return UnOp; 12392 12393 assert(isa<DeclRefExpr>(SubExpr) 12394 && "fixed to something other than a decl ref"); 12395 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12396 && "fixed to a member ref with no nested name qualifier"); 12397 12398 // We have taken the address of a pointer to member 12399 // function. Perform the computation here so that we get the 12400 // appropriate pointer to member type. 12401 QualType ClassType 12402 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12403 QualType MemPtrType 12404 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12405 12406 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12407 VK_RValue, OK_Ordinary, 12408 UnOp->getOperatorLoc()); 12409 } 12410 } 12411 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12412 Found, Fn); 12413 if (SubExpr == UnOp->getSubExpr()) 12414 return UnOp; 12415 12416 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12417 Context.getPointerType(SubExpr->getType()), 12418 VK_RValue, OK_Ordinary, 12419 UnOp->getOperatorLoc()); 12420 } 12421 12422 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12423 // FIXME: avoid copy. 12424 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12425 if (ULE->hasExplicitTemplateArgs()) { 12426 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12427 TemplateArgs = &TemplateArgsBuffer; 12428 } 12429 12430 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12431 ULE->getQualifierLoc(), 12432 ULE->getTemplateKeywordLoc(), 12433 Fn, 12434 /*enclosing*/ false, // FIXME? 12435 ULE->getNameLoc(), 12436 Fn->getType(), 12437 VK_LValue, 12438 Found.getDecl(), 12439 TemplateArgs); 12440 MarkDeclRefReferenced(DRE); 12441 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12442 return DRE; 12443 } 12444 12445 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12446 // FIXME: avoid copy. 12447 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12448 if (MemExpr->hasExplicitTemplateArgs()) { 12449 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12450 TemplateArgs = &TemplateArgsBuffer; 12451 } 12452 12453 Expr *Base; 12454 12455 // If we're filling in a static method where we used to have an 12456 // implicit member access, rewrite to a simple decl ref. 12457 if (MemExpr->isImplicitAccess()) { 12458 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12459 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12460 MemExpr->getQualifierLoc(), 12461 MemExpr->getTemplateKeywordLoc(), 12462 Fn, 12463 /*enclosing*/ false, 12464 MemExpr->getMemberLoc(), 12465 Fn->getType(), 12466 VK_LValue, 12467 Found.getDecl(), 12468 TemplateArgs); 12469 MarkDeclRefReferenced(DRE); 12470 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12471 return DRE; 12472 } else { 12473 SourceLocation Loc = MemExpr->getMemberLoc(); 12474 if (MemExpr->getQualifier()) 12475 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12476 CheckCXXThisCapture(Loc); 12477 Base = new (Context) CXXThisExpr(Loc, 12478 MemExpr->getBaseType(), 12479 /*isImplicit=*/true); 12480 } 12481 } else 12482 Base = MemExpr->getBase(); 12483 12484 ExprValueKind valueKind; 12485 QualType type; 12486 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12487 valueKind = VK_LValue; 12488 type = Fn->getType(); 12489 } else { 12490 valueKind = VK_RValue; 12491 type = Context.BoundMemberTy; 12492 } 12493 12494 MemberExpr *ME = MemberExpr::Create( 12495 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12496 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12497 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12498 OK_Ordinary); 12499 ME->setHadMultipleCandidates(true); 12500 MarkMemberReferenced(ME); 12501 return ME; 12502 } 12503 12504 llvm_unreachable("Invalid reference to overloaded function"); 12505 } 12506 12507 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12508 DeclAccessPair Found, 12509 FunctionDecl *Fn) { 12510 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12511 } 12512