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 // Conversion between Objective-C pointers. 2156 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2157 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2158 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2159 if (getLangOpts().CPlusPlus && LHS && RHS && 2160 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2161 FromObjCPtr->getPointeeType())) 2162 return false; 2163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2164 ToObjCPtr->getPointeeType(), 2165 ToType, Context); 2166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2167 return true; 2168 } 2169 2170 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2171 // Okay: this is some kind of implicit downcast of Objective-C 2172 // interfaces, which is permitted. However, we're going to 2173 // complain about it. 2174 IncompatibleObjC = true; 2175 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2176 ToObjCPtr->getPointeeType(), 2177 ToType, Context); 2178 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2179 return true; 2180 } 2181 } 2182 // Beyond this point, both types need to be C pointers or block pointers. 2183 QualType ToPointeeType; 2184 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2185 ToPointeeType = ToCPtr->getPointeeType(); 2186 else if (const BlockPointerType *ToBlockPtr = 2187 ToType->getAs<BlockPointerType>()) { 2188 // Objective C++: We're able to convert from a pointer to any object 2189 // to a block pointer type. 2190 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2191 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2192 return true; 2193 } 2194 ToPointeeType = ToBlockPtr->getPointeeType(); 2195 } 2196 else if (FromType->getAs<BlockPointerType>() && 2197 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2198 // Objective C++: We're able to convert from a block pointer type to a 2199 // pointer to any object. 2200 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2201 return true; 2202 } 2203 else 2204 return false; 2205 2206 QualType FromPointeeType; 2207 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2208 FromPointeeType = FromCPtr->getPointeeType(); 2209 else if (const BlockPointerType *FromBlockPtr = 2210 FromType->getAs<BlockPointerType>()) 2211 FromPointeeType = FromBlockPtr->getPointeeType(); 2212 else 2213 return false; 2214 2215 // If we have pointers to pointers, recursively check whether this 2216 // is an Objective-C conversion. 2217 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2219 IncompatibleObjC)) { 2220 // We always complain about this conversion. 2221 IncompatibleObjC = true; 2222 ConvertedType = Context.getPointerType(ConvertedType); 2223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2224 return true; 2225 } 2226 // Allow conversion of pointee being objective-c pointer to another one; 2227 // as in I* to id. 2228 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2229 ToPointeeType->getAs<ObjCObjectPointerType>() && 2230 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2231 IncompatibleObjC)) { 2232 2233 ConvertedType = Context.getPointerType(ConvertedType); 2234 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2235 return true; 2236 } 2237 2238 // If we have pointers to functions or blocks, check whether the only 2239 // differences in the argument and result types are in Objective-C 2240 // pointer conversions. If so, we permit the conversion (but 2241 // complain about it). 2242 const FunctionProtoType *FromFunctionType 2243 = FromPointeeType->getAs<FunctionProtoType>(); 2244 const FunctionProtoType *ToFunctionType 2245 = ToPointeeType->getAs<FunctionProtoType>(); 2246 if (FromFunctionType && ToFunctionType) { 2247 // If the function types are exactly the same, this isn't an 2248 // Objective-C pointer conversion. 2249 if (Context.getCanonicalType(FromPointeeType) 2250 == Context.getCanonicalType(ToPointeeType)) 2251 return false; 2252 2253 // Perform the quick checks that will tell us whether these 2254 // function types are obviously different. 2255 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2256 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2257 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2258 return false; 2259 2260 bool HasObjCConversion = false; 2261 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2262 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2263 // Okay, the types match exactly. Nothing to do. 2264 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2265 ToFunctionType->getReturnType(), 2266 ConvertedType, IncompatibleObjC)) { 2267 // Okay, we have an Objective-C pointer conversion. 2268 HasObjCConversion = true; 2269 } else { 2270 // Function types are too different. Abort. 2271 return false; 2272 } 2273 2274 // Check argument types. 2275 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2276 ArgIdx != NumArgs; ++ArgIdx) { 2277 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2278 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2279 if (Context.getCanonicalType(FromArgType) 2280 == Context.getCanonicalType(ToArgType)) { 2281 // Okay, the types match exactly. Nothing to do. 2282 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2283 ConvertedType, IncompatibleObjC)) { 2284 // Okay, we have an Objective-C pointer conversion. 2285 HasObjCConversion = true; 2286 } else { 2287 // Argument types are too different. Abort. 2288 return false; 2289 } 2290 } 2291 2292 if (HasObjCConversion) { 2293 // We had an Objective-C conversion. Allow this pointer 2294 // conversion, but complain about it. 2295 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2296 IncompatibleObjC = true; 2297 return true; 2298 } 2299 } 2300 2301 return false; 2302 } 2303 2304 /// \brief Determine whether this is an Objective-C writeback conversion, 2305 /// used for parameter passing when performing automatic reference counting. 2306 /// 2307 /// \param FromType The type we're converting form. 2308 /// 2309 /// \param ToType The type we're converting to. 2310 /// 2311 /// \param ConvertedType The type that will be produced after applying 2312 /// this conversion. 2313 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2314 QualType &ConvertedType) { 2315 if (!getLangOpts().ObjCAutoRefCount || 2316 Context.hasSameUnqualifiedType(FromType, ToType)) 2317 return false; 2318 2319 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2320 QualType ToPointee; 2321 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2322 ToPointee = ToPointer->getPointeeType(); 2323 else 2324 return false; 2325 2326 Qualifiers ToQuals = ToPointee.getQualifiers(); 2327 if (!ToPointee->isObjCLifetimeType() || 2328 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2329 !ToQuals.withoutObjCLifetime().empty()) 2330 return false; 2331 2332 // Argument must be a pointer to __strong to __weak. 2333 QualType FromPointee; 2334 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2335 FromPointee = FromPointer->getPointeeType(); 2336 else 2337 return false; 2338 2339 Qualifiers FromQuals = FromPointee.getQualifiers(); 2340 if (!FromPointee->isObjCLifetimeType() || 2341 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2342 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2343 return false; 2344 2345 // Make sure that we have compatible qualifiers. 2346 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2347 if (!ToQuals.compatiblyIncludes(FromQuals)) 2348 return false; 2349 2350 // Remove qualifiers from the pointee type we're converting from; they 2351 // aren't used in the compatibility check belong, and we'll be adding back 2352 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2353 FromPointee = FromPointee.getUnqualifiedType(); 2354 2355 // The unqualified form of the pointee types must be compatible. 2356 ToPointee = ToPointee.getUnqualifiedType(); 2357 bool IncompatibleObjC; 2358 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2359 FromPointee = ToPointee; 2360 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2361 IncompatibleObjC)) 2362 return false; 2363 2364 /// \brief Construct the type we're converting to, which is a pointer to 2365 /// __autoreleasing pointee. 2366 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2367 ConvertedType = Context.getPointerType(FromPointee); 2368 return true; 2369 } 2370 2371 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2372 QualType& ConvertedType) { 2373 QualType ToPointeeType; 2374 if (const BlockPointerType *ToBlockPtr = 2375 ToType->getAs<BlockPointerType>()) 2376 ToPointeeType = ToBlockPtr->getPointeeType(); 2377 else 2378 return false; 2379 2380 QualType FromPointeeType; 2381 if (const BlockPointerType *FromBlockPtr = 2382 FromType->getAs<BlockPointerType>()) 2383 FromPointeeType = FromBlockPtr->getPointeeType(); 2384 else 2385 return false; 2386 // We have pointer to blocks, check whether the only 2387 // differences in the argument and result types are in Objective-C 2388 // pointer conversions. If so, we permit the conversion. 2389 2390 const FunctionProtoType *FromFunctionType 2391 = FromPointeeType->getAs<FunctionProtoType>(); 2392 const FunctionProtoType *ToFunctionType 2393 = ToPointeeType->getAs<FunctionProtoType>(); 2394 2395 if (!FromFunctionType || !ToFunctionType) 2396 return false; 2397 2398 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2399 return true; 2400 2401 // Perform the quick checks that will tell us whether these 2402 // function types are obviously different. 2403 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2404 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2405 return false; 2406 2407 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2408 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2409 if (FromEInfo != ToEInfo) 2410 return false; 2411 2412 bool IncompatibleObjC = false; 2413 if (Context.hasSameType(FromFunctionType->getReturnType(), 2414 ToFunctionType->getReturnType())) { 2415 // Okay, the types match exactly. Nothing to do. 2416 } else { 2417 QualType RHS = FromFunctionType->getReturnType(); 2418 QualType LHS = ToFunctionType->getReturnType(); 2419 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2420 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2421 LHS = LHS.getUnqualifiedType(); 2422 2423 if (Context.hasSameType(RHS,LHS)) { 2424 // OK exact match. 2425 } else if (isObjCPointerConversion(RHS, LHS, 2426 ConvertedType, IncompatibleObjC)) { 2427 if (IncompatibleObjC) 2428 return false; 2429 // Okay, we have an Objective-C pointer conversion. 2430 } 2431 else 2432 return false; 2433 } 2434 2435 // Check argument types. 2436 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2437 ArgIdx != NumArgs; ++ArgIdx) { 2438 IncompatibleObjC = false; 2439 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2440 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2441 if (Context.hasSameType(FromArgType, ToArgType)) { 2442 // Okay, the types match exactly. Nothing to do. 2443 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2444 ConvertedType, IncompatibleObjC)) { 2445 if (IncompatibleObjC) 2446 return false; 2447 // Okay, we have an Objective-C pointer conversion. 2448 } else 2449 // Argument types are too different. Abort. 2450 return false; 2451 } 2452 if (LangOpts.ObjCAutoRefCount && 2453 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2454 ToFunctionType)) 2455 return false; 2456 2457 ConvertedType = ToType; 2458 return true; 2459 } 2460 2461 enum { 2462 ft_default, 2463 ft_different_class, 2464 ft_parameter_arity, 2465 ft_parameter_mismatch, 2466 ft_return_type, 2467 ft_qualifer_mismatch 2468 }; 2469 2470 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2471 /// function types. Catches different number of parameter, mismatch in 2472 /// parameter types, and different return types. 2473 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2474 QualType FromType, QualType ToType) { 2475 // If either type is not valid, include no extra info. 2476 if (FromType.isNull() || ToType.isNull()) { 2477 PDiag << ft_default; 2478 return; 2479 } 2480 2481 // Get the function type from the pointers. 2482 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2483 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2484 *ToMember = ToType->getAs<MemberPointerType>(); 2485 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2486 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2487 << QualType(FromMember->getClass(), 0); 2488 return; 2489 } 2490 FromType = FromMember->getPointeeType(); 2491 ToType = ToMember->getPointeeType(); 2492 } 2493 2494 if (FromType->isPointerType()) 2495 FromType = FromType->getPointeeType(); 2496 if (ToType->isPointerType()) 2497 ToType = ToType->getPointeeType(); 2498 2499 // Remove references. 2500 FromType = FromType.getNonReferenceType(); 2501 ToType = ToType.getNonReferenceType(); 2502 2503 // Don't print extra info for non-specialized template functions. 2504 if (FromType->isInstantiationDependentType() && 2505 !FromType->getAs<TemplateSpecializationType>()) { 2506 PDiag << ft_default; 2507 return; 2508 } 2509 2510 // No extra info for same types. 2511 if (Context.hasSameType(FromType, ToType)) { 2512 PDiag << ft_default; 2513 return; 2514 } 2515 2516 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2517 *ToFunction = ToType->getAs<FunctionProtoType>(); 2518 2519 // Both types need to be function types. 2520 if (!FromFunction || !ToFunction) { 2521 PDiag << ft_default; 2522 return; 2523 } 2524 2525 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2526 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2527 << FromFunction->getNumParams(); 2528 return; 2529 } 2530 2531 // Handle different parameter types. 2532 unsigned ArgPos; 2533 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2534 PDiag << ft_parameter_mismatch << ArgPos + 1 2535 << ToFunction->getParamType(ArgPos) 2536 << FromFunction->getParamType(ArgPos); 2537 return; 2538 } 2539 2540 // Handle different return type. 2541 if (!Context.hasSameType(FromFunction->getReturnType(), 2542 ToFunction->getReturnType())) { 2543 PDiag << ft_return_type << ToFunction->getReturnType() 2544 << FromFunction->getReturnType(); 2545 return; 2546 } 2547 2548 unsigned FromQuals = FromFunction->getTypeQuals(), 2549 ToQuals = ToFunction->getTypeQuals(); 2550 if (FromQuals != ToQuals) { 2551 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2552 return; 2553 } 2554 2555 // Unable to find a difference, so add no extra info. 2556 PDiag << ft_default; 2557 } 2558 2559 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2560 /// for equality of their argument types. Caller has already checked that 2561 /// they have same number of arguments. If the parameters are different, 2562 /// ArgPos will have the parameter index of the first different parameter. 2563 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2564 const FunctionProtoType *NewType, 2565 unsigned *ArgPos) { 2566 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2567 N = NewType->param_type_begin(), 2568 E = OldType->param_type_end(); 2569 O && (O != E); ++O, ++N) { 2570 if (!Context.hasSameType(O->getUnqualifiedType(), 2571 N->getUnqualifiedType())) { 2572 if (ArgPos) 2573 *ArgPos = O - OldType->param_type_begin(); 2574 return false; 2575 } 2576 } 2577 return true; 2578 } 2579 2580 /// CheckPointerConversion - Check the pointer conversion from the 2581 /// expression From to the type ToType. This routine checks for 2582 /// ambiguous or inaccessible derived-to-base pointer 2583 /// conversions for which IsPointerConversion has already returned 2584 /// true. It returns true and produces a diagnostic if there was an 2585 /// error, or returns false otherwise. 2586 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2587 CastKind &Kind, 2588 CXXCastPath& BasePath, 2589 bool IgnoreBaseAccess) { 2590 QualType FromType = From->getType(); 2591 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2592 2593 Kind = CK_BitCast; 2594 2595 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2596 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2597 Expr::NPCK_ZeroExpression) { 2598 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2599 DiagRuntimeBehavior(From->getExprLoc(), From, 2600 PDiag(diag::warn_impcast_bool_to_null_pointer) 2601 << ToType << From->getSourceRange()); 2602 else if (!isUnevaluatedContext()) 2603 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2604 << ToType << From->getSourceRange(); 2605 } 2606 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2607 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2608 QualType FromPointeeType = FromPtrType->getPointeeType(), 2609 ToPointeeType = ToPtrType->getPointeeType(); 2610 2611 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2612 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2613 // We must have a derived-to-base conversion. Check an 2614 // ambiguous or inaccessible conversion. 2615 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2616 From->getExprLoc(), 2617 From->getSourceRange(), &BasePath, 2618 IgnoreBaseAccess)) 2619 return true; 2620 2621 // The conversion was successful. 2622 Kind = CK_DerivedToBase; 2623 } 2624 } 2625 } else if (const ObjCObjectPointerType *ToPtrType = 2626 ToType->getAs<ObjCObjectPointerType>()) { 2627 if (const ObjCObjectPointerType *FromPtrType = 2628 FromType->getAs<ObjCObjectPointerType>()) { 2629 // Objective-C++ conversions are always okay. 2630 // FIXME: We should have a different class of conversions for the 2631 // Objective-C++ implicit conversions. 2632 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2633 return false; 2634 } else if (FromType->isBlockPointerType()) { 2635 Kind = CK_BlockPointerToObjCPointerCast; 2636 } else { 2637 Kind = CK_CPointerToObjCPointerCast; 2638 } 2639 } else if (ToType->isBlockPointerType()) { 2640 if (!FromType->isBlockPointerType()) 2641 Kind = CK_AnyPointerToBlockPointerCast; 2642 } 2643 2644 // We shouldn't fall into this case unless it's valid for other 2645 // reasons. 2646 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2647 Kind = CK_NullToPointer; 2648 2649 return false; 2650 } 2651 2652 /// IsMemberPointerConversion - Determines whether the conversion of the 2653 /// expression From, which has the (possibly adjusted) type FromType, can be 2654 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2655 /// If so, returns true and places the converted type (that might differ from 2656 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2657 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2658 QualType ToType, 2659 bool InOverloadResolution, 2660 QualType &ConvertedType) { 2661 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2662 if (!ToTypePtr) 2663 return false; 2664 2665 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2666 if (From->isNullPointerConstant(Context, 2667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2668 : Expr::NPC_ValueDependentIsNull)) { 2669 ConvertedType = ToType; 2670 return true; 2671 } 2672 2673 // Otherwise, both types have to be member pointers. 2674 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2675 if (!FromTypePtr) 2676 return false; 2677 2678 // A pointer to member of B can be converted to a pointer to member of D, 2679 // where D is derived from B (C++ 4.11p2). 2680 QualType FromClass(FromTypePtr->getClass(), 0); 2681 QualType ToClass(ToTypePtr->getClass(), 0); 2682 2683 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2684 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2685 IsDerivedFrom(ToClass, FromClass)) { 2686 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2687 ToClass.getTypePtr()); 2688 return true; 2689 } 2690 2691 return false; 2692 } 2693 2694 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2695 /// expression From to the type ToType. This routine checks for ambiguous or 2696 /// virtual or inaccessible base-to-derived member pointer conversions 2697 /// for which IsMemberPointerConversion has already returned true. It returns 2698 /// true and produces a diagnostic if there was an error, or returns false 2699 /// otherwise. 2700 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2701 CastKind &Kind, 2702 CXXCastPath &BasePath, 2703 bool IgnoreBaseAccess) { 2704 QualType FromType = From->getType(); 2705 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2706 if (!FromPtrType) { 2707 // This must be a null pointer to member pointer conversion 2708 assert(From->isNullPointerConstant(Context, 2709 Expr::NPC_ValueDependentIsNull) && 2710 "Expr must be null pointer constant!"); 2711 Kind = CK_NullToMemberPointer; 2712 return false; 2713 } 2714 2715 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2716 assert(ToPtrType && "No member pointer cast has a target type " 2717 "that is not a member pointer."); 2718 2719 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2720 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2721 2722 // FIXME: What about dependent types? 2723 assert(FromClass->isRecordType() && "Pointer into non-class."); 2724 assert(ToClass->isRecordType() && "Pointer into non-class."); 2725 2726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2727 /*DetectVirtual=*/true); 2728 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2729 assert(DerivationOkay && 2730 "Should not have been called if derivation isn't OK."); 2731 (void)DerivationOkay; 2732 2733 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2734 getUnqualifiedType())) { 2735 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2736 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2737 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2738 return true; 2739 } 2740 2741 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2742 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2743 << FromClass << ToClass << QualType(VBase, 0) 2744 << From->getSourceRange(); 2745 return true; 2746 } 2747 2748 if (!IgnoreBaseAccess) 2749 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2750 Paths.front(), 2751 diag::err_downcast_from_inaccessible_base); 2752 2753 // Must be a base to derived member conversion. 2754 BuildBasePathArray(Paths, BasePath); 2755 Kind = CK_BaseToDerivedMemberPointer; 2756 return false; 2757 } 2758 2759 /// Determine whether the lifetime conversion between the two given 2760 /// qualifiers sets is nontrivial. 2761 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2762 Qualifiers ToQuals) { 2763 // Converting anything to const __unsafe_unretained is trivial. 2764 if (ToQuals.hasConst() && 2765 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2766 return false; 2767 2768 return true; 2769 } 2770 2771 /// IsQualificationConversion - Determines whether the conversion from 2772 /// an rvalue of type FromType to ToType is a qualification conversion 2773 /// (C++ 4.4). 2774 /// 2775 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2776 /// when the qualification conversion involves a change in the Objective-C 2777 /// object lifetime. 2778 bool 2779 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2780 bool CStyle, bool &ObjCLifetimeConversion) { 2781 FromType = Context.getCanonicalType(FromType); 2782 ToType = Context.getCanonicalType(ToType); 2783 ObjCLifetimeConversion = false; 2784 2785 // If FromType and ToType are the same type, this is not a 2786 // qualification conversion. 2787 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2788 return false; 2789 2790 // (C++ 4.4p4): 2791 // A conversion can add cv-qualifiers at levels other than the first 2792 // in multi-level pointers, subject to the following rules: [...] 2793 bool PreviousToQualsIncludeConst = true; 2794 bool UnwrappedAnyPointer = false; 2795 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2796 // Within each iteration of the loop, we check the qualifiers to 2797 // determine if this still looks like a qualification 2798 // conversion. Then, if all is well, we unwrap one more level of 2799 // pointers or pointers-to-members and do it all again 2800 // until there are no more pointers or pointers-to-members left to 2801 // unwrap. 2802 UnwrappedAnyPointer = true; 2803 2804 Qualifiers FromQuals = FromType.getQualifiers(); 2805 Qualifiers ToQuals = ToType.getQualifiers(); 2806 2807 // Objective-C ARC: 2808 // Check Objective-C lifetime conversions. 2809 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2810 UnwrappedAnyPointer) { 2811 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2812 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2813 ObjCLifetimeConversion = true; 2814 FromQuals.removeObjCLifetime(); 2815 ToQuals.removeObjCLifetime(); 2816 } else { 2817 // Qualification conversions cannot cast between different 2818 // Objective-C lifetime qualifiers. 2819 return false; 2820 } 2821 } 2822 2823 // Allow addition/removal of GC attributes but not changing GC attributes. 2824 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2825 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2826 FromQuals.removeObjCGCAttr(); 2827 ToQuals.removeObjCGCAttr(); 2828 } 2829 2830 // -- for every j > 0, if const is in cv 1,j then const is in cv 2831 // 2,j, and similarly for volatile. 2832 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2833 return false; 2834 2835 // -- if the cv 1,j and cv 2,j are different, then const is in 2836 // every cv for 0 < k < j. 2837 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2838 && !PreviousToQualsIncludeConst) 2839 return false; 2840 2841 // Keep track of whether all prior cv-qualifiers in the "to" type 2842 // include const. 2843 PreviousToQualsIncludeConst 2844 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2845 } 2846 2847 // We are left with FromType and ToType being the pointee types 2848 // after unwrapping the original FromType and ToType the same number 2849 // of types. If we unwrapped any pointers, and if FromType and 2850 // ToType have the same unqualified type (since we checked 2851 // qualifiers above), then this is a qualification conversion. 2852 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2853 } 2854 2855 /// \brief - Determine whether this is a conversion from a scalar type to an 2856 /// atomic type. 2857 /// 2858 /// If successful, updates \c SCS's second and third steps in the conversion 2859 /// sequence to finish the conversion. 2860 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2861 bool InOverloadResolution, 2862 StandardConversionSequence &SCS, 2863 bool CStyle) { 2864 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2865 if (!ToAtomic) 2866 return false; 2867 2868 StandardConversionSequence InnerSCS; 2869 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2870 InOverloadResolution, InnerSCS, 2871 CStyle, /*AllowObjCWritebackConversion=*/false)) 2872 return false; 2873 2874 SCS.Second = InnerSCS.Second; 2875 SCS.setToType(1, InnerSCS.getToType(1)); 2876 SCS.Third = InnerSCS.Third; 2877 SCS.QualificationIncludesObjCLifetime 2878 = InnerSCS.QualificationIncludesObjCLifetime; 2879 SCS.setToType(2, InnerSCS.getToType(2)); 2880 return true; 2881 } 2882 2883 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2884 CXXConstructorDecl *Constructor, 2885 QualType Type) { 2886 const FunctionProtoType *CtorType = 2887 Constructor->getType()->getAs<FunctionProtoType>(); 2888 if (CtorType->getNumParams() > 0) { 2889 QualType FirstArg = CtorType->getParamType(0); 2890 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2891 return true; 2892 } 2893 return false; 2894 } 2895 2896 static OverloadingResult 2897 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2898 CXXRecordDecl *To, 2899 UserDefinedConversionSequence &User, 2900 OverloadCandidateSet &CandidateSet, 2901 bool AllowExplicit) { 2902 DeclContext::lookup_result R = S.LookupConstructors(To); 2903 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2904 Con != ConEnd; ++Con) { 2905 NamedDecl *D = *Con; 2906 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2907 2908 // Find the constructor (which may be a template). 2909 CXXConstructorDecl *Constructor = nullptr; 2910 FunctionTemplateDecl *ConstructorTmpl 2911 = dyn_cast<FunctionTemplateDecl>(D); 2912 if (ConstructorTmpl) 2913 Constructor 2914 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2915 else 2916 Constructor = cast<CXXConstructorDecl>(D); 2917 2918 bool Usable = !Constructor->isInvalidDecl() && 2919 S.isInitListConstructor(Constructor) && 2920 (AllowExplicit || !Constructor->isExplicit()); 2921 if (Usable) { 2922 // If the first argument is (a reference to) the target type, 2923 // suppress conversions. 2924 bool SuppressUserConversions = 2925 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2926 if (ConstructorTmpl) 2927 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2928 /*ExplicitArgs*/ nullptr, 2929 From, CandidateSet, 2930 SuppressUserConversions); 2931 else 2932 S.AddOverloadCandidate(Constructor, FoundDecl, 2933 From, CandidateSet, 2934 SuppressUserConversions); 2935 } 2936 } 2937 2938 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2939 2940 OverloadCandidateSet::iterator Best; 2941 switch (auto Result = 2942 CandidateSet.BestViableFunction(S, From->getLocStart(), 2943 Best, true)) { 2944 case OR_Deleted: 2945 case OR_Success: { 2946 // Record the standard conversion we used and the conversion function. 2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2948 QualType ThisType = Constructor->getThisType(S.Context); 2949 // Initializer lists don't have conversions as such. 2950 User.Before.setAsIdentityConversion(); 2951 User.HadMultipleCandidates = HadMultipleCandidates; 2952 User.ConversionFunction = Constructor; 2953 User.FoundConversionFunction = Best->FoundDecl; 2954 User.After.setAsIdentityConversion(); 2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2956 User.After.setAllToTypes(ToType); 2957 return Result; 2958 } 2959 2960 case OR_No_Viable_Function: 2961 return OR_No_Viable_Function; 2962 case OR_Ambiguous: 2963 return OR_Ambiguous; 2964 } 2965 2966 llvm_unreachable("Invalid OverloadResult!"); 2967 } 2968 2969 /// Determines whether there is a user-defined conversion sequence 2970 /// (C++ [over.ics.user]) that converts expression From to the type 2971 /// ToType. If such a conversion exists, User will contain the 2972 /// user-defined conversion sequence that performs such a conversion 2973 /// and this routine will return true. Otherwise, this routine returns 2974 /// false and User is unspecified. 2975 /// 2976 /// \param AllowExplicit true if the conversion should consider C++0x 2977 /// "explicit" conversion functions as well as non-explicit conversion 2978 /// functions (C++0x [class.conv.fct]p2). 2979 /// 2980 /// \param AllowObjCConversionOnExplicit true if the conversion should 2981 /// allow an extra Objective-C pointer conversion on uses of explicit 2982 /// constructors. Requires \c AllowExplicit to also be set. 2983 static OverloadingResult 2984 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2985 UserDefinedConversionSequence &User, 2986 OverloadCandidateSet &CandidateSet, 2987 bool AllowExplicit, 2988 bool AllowObjCConversionOnExplicit) { 2989 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 2990 2991 // Whether we will only visit constructors. 2992 bool ConstructorsOnly = false; 2993 2994 // If the type we are conversion to is a class type, enumerate its 2995 // constructors. 2996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2997 // C++ [over.match.ctor]p1: 2998 // When objects of class type are direct-initialized (8.5), or 2999 // copy-initialized from an expression of the same or a 3000 // derived class type (8.5), overload resolution selects the 3001 // constructor. [...] For copy-initialization, the candidate 3002 // functions are all the converting constructors (12.3.1) of 3003 // that class. The argument list is the expression-list within 3004 // the parentheses of the initializer. 3005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3006 (From->getType()->getAs<RecordType>() && 3007 S.IsDerivedFrom(From->getType(), ToType))) 3008 ConstructorsOnly = true; 3009 3010 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3011 // RequireCompleteType may have returned true due to some invalid decl 3012 // during template instantiation, but ToType may be complete enough now 3013 // to try to recover. 3014 if (ToType->isIncompleteType()) { 3015 // We're not going to find any constructors. 3016 } else if (CXXRecordDecl *ToRecordDecl 3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3018 3019 Expr **Args = &From; 3020 unsigned NumArgs = 1; 3021 bool ListInitializing = false; 3022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3023 // But first, see if there is an init-list-constructor that will work. 3024 OverloadingResult Result = IsInitializerListConstructorConversion( 3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3026 if (Result != OR_No_Viable_Function) 3027 return Result; 3028 // Never mind. 3029 CandidateSet.clear(); 3030 3031 // If we're list-initializing, we pass the individual elements as 3032 // arguments, not the entire list. 3033 Args = InitList->getInits(); 3034 NumArgs = InitList->getNumInits(); 3035 ListInitializing = true; 3036 } 3037 3038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3040 Con != ConEnd; ++Con) { 3041 NamedDecl *D = *Con; 3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3043 3044 // Find the constructor (which may be a template). 3045 CXXConstructorDecl *Constructor = nullptr; 3046 FunctionTemplateDecl *ConstructorTmpl 3047 = dyn_cast<FunctionTemplateDecl>(D); 3048 if (ConstructorTmpl) 3049 Constructor 3050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3051 else 3052 Constructor = cast<CXXConstructorDecl>(D); 3053 3054 bool Usable = !Constructor->isInvalidDecl(); 3055 if (ListInitializing) 3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3057 else 3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3059 if (Usable) { 3060 bool SuppressUserConversions = !ConstructorsOnly; 3061 if (SuppressUserConversions && ListInitializing) { 3062 SuppressUserConversions = false; 3063 if (NumArgs == 1) { 3064 // If the first argument is (a reference to) the target type, 3065 // suppress conversions. 3066 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3067 S.Context, Constructor, ToType); 3068 } 3069 } 3070 if (ConstructorTmpl) 3071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3072 /*ExplicitArgs*/ nullptr, 3073 llvm::makeArrayRef(Args, NumArgs), 3074 CandidateSet, SuppressUserConversions); 3075 else 3076 // Allow one user-defined conversion when user specifies a 3077 // From->ToType conversion via an static cast (c-style, etc). 3078 S.AddOverloadCandidate(Constructor, FoundDecl, 3079 llvm::makeArrayRef(Args, NumArgs), 3080 CandidateSet, SuppressUserConversions); 3081 } 3082 } 3083 } 3084 } 3085 3086 // Enumerate conversion functions, if we're allowed to. 3087 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3089 // No conversion functions from incomplete types. 3090 } else if (const RecordType *FromRecordType 3091 = From->getType()->getAs<RecordType>()) { 3092 if (CXXRecordDecl *FromRecordDecl 3093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3094 // Add all of the conversion functions as candidates. 3095 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3096 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3097 DeclAccessPair FoundDecl = I.getPair(); 3098 NamedDecl *D = FoundDecl.getDecl(); 3099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3100 if (isa<UsingShadowDecl>(D)) 3101 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3102 3103 CXXConversionDecl *Conv; 3104 FunctionTemplateDecl *ConvTemplate; 3105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3107 else 3108 Conv = cast<CXXConversionDecl>(D); 3109 3110 if (AllowExplicit || !Conv->isExplicit()) { 3111 if (ConvTemplate) 3112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3113 ActingContext, From, ToType, 3114 CandidateSet, 3115 AllowObjCConversionOnExplicit); 3116 else 3117 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3118 From, ToType, CandidateSet, 3119 AllowObjCConversionOnExplicit); 3120 } 3121 } 3122 } 3123 } 3124 3125 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3126 3127 OverloadCandidateSet::iterator Best; 3128 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3129 Best, true)) { 3130 case OR_Success: 3131 case OR_Deleted: 3132 // Record the standard conversion we used and the conversion function. 3133 if (CXXConstructorDecl *Constructor 3134 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3135 // C++ [over.ics.user]p1: 3136 // If the user-defined conversion is specified by a 3137 // constructor (12.3.1), the initial standard conversion 3138 // sequence converts the source type to the type required by 3139 // the argument of the constructor. 3140 // 3141 QualType ThisType = Constructor->getThisType(S.Context); 3142 if (isa<InitListExpr>(From)) { 3143 // Initializer lists don't have conversions as such. 3144 User.Before.setAsIdentityConversion(); 3145 } else { 3146 if (Best->Conversions[0].isEllipsis()) 3147 User.EllipsisConversion = true; 3148 else { 3149 User.Before = Best->Conversions[0].Standard; 3150 User.EllipsisConversion = false; 3151 } 3152 } 3153 User.HadMultipleCandidates = HadMultipleCandidates; 3154 User.ConversionFunction = Constructor; 3155 User.FoundConversionFunction = Best->FoundDecl; 3156 User.After.setAsIdentityConversion(); 3157 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3158 User.After.setAllToTypes(ToType); 3159 return Result; 3160 } 3161 if (CXXConversionDecl *Conversion 3162 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3163 // C++ [over.ics.user]p1: 3164 // 3165 // [...] If the user-defined conversion is specified by a 3166 // conversion function (12.3.2), the initial standard 3167 // conversion sequence converts the source type to the 3168 // implicit object parameter of the conversion function. 3169 User.Before = Best->Conversions[0].Standard; 3170 User.HadMultipleCandidates = HadMultipleCandidates; 3171 User.ConversionFunction = Conversion; 3172 User.FoundConversionFunction = Best->FoundDecl; 3173 User.EllipsisConversion = false; 3174 3175 // C++ [over.ics.user]p2: 3176 // The second standard conversion sequence converts the 3177 // result of the user-defined conversion to the target type 3178 // for the sequence. Since an implicit conversion sequence 3179 // is an initialization, the special rules for 3180 // initialization by user-defined conversion apply when 3181 // selecting the best user-defined conversion for a 3182 // user-defined conversion sequence (see 13.3.3 and 3183 // 13.3.3.1). 3184 User.After = Best->FinalConversion; 3185 return Result; 3186 } 3187 llvm_unreachable("Not a constructor or conversion function?"); 3188 3189 case OR_No_Viable_Function: 3190 return OR_No_Viable_Function; 3191 3192 case OR_Ambiguous: 3193 return OR_Ambiguous; 3194 } 3195 3196 llvm_unreachable("Invalid OverloadResult!"); 3197 } 3198 3199 bool 3200 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3201 ImplicitConversionSequence ICS; 3202 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3203 OverloadCandidateSet::CSK_Normal); 3204 OverloadingResult OvResult = 3205 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3206 CandidateSet, false, false); 3207 if (OvResult == OR_Ambiguous) 3208 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3209 << From->getType() << ToType << From->getSourceRange(); 3210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3211 if (!RequireCompleteType(From->getLocStart(), ToType, 3212 diag::err_typecheck_nonviable_condition_incomplete, 3213 From->getType(), From->getSourceRange())) 3214 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3215 << false << From->getType() << From->getSourceRange() << ToType; 3216 } else 3217 return false; 3218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3219 return true; 3220 } 3221 3222 /// \brief Compare the user-defined conversion functions or constructors 3223 /// of two user-defined conversion sequences to determine whether any ordering 3224 /// is possible. 3225 static ImplicitConversionSequence::CompareKind 3226 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3227 FunctionDecl *Function2) { 3228 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3229 return ImplicitConversionSequence::Indistinguishable; 3230 3231 // Objective-C++: 3232 // If both conversion functions are implicitly-declared conversions from 3233 // a lambda closure type to a function pointer and a block pointer, 3234 // respectively, always prefer the conversion to a function pointer, 3235 // because the function pointer is more lightweight and is more likely 3236 // to keep code working. 3237 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3238 if (!Conv1) 3239 return ImplicitConversionSequence::Indistinguishable; 3240 3241 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3242 if (!Conv2) 3243 return ImplicitConversionSequence::Indistinguishable; 3244 3245 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3246 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3247 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3248 if (Block1 != Block2) 3249 return Block1 ? ImplicitConversionSequence::Worse 3250 : ImplicitConversionSequence::Better; 3251 } 3252 3253 return ImplicitConversionSequence::Indistinguishable; 3254 } 3255 3256 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3257 const ImplicitConversionSequence &ICS) { 3258 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3259 (ICS.isUserDefined() && 3260 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3261 } 3262 3263 /// CompareImplicitConversionSequences - Compare two implicit 3264 /// conversion sequences to determine whether one is better than the 3265 /// other or if they are indistinguishable (C++ 13.3.3.2). 3266 static ImplicitConversionSequence::CompareKind 3267 CompareImplicitConversionSequences(Sema &S, 3268 const ImplicitConversionSequence& ICS1, 3269 const ImplicitConversionSequence& ICS2) 3270 { 3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3272 // conversion sequences (as defined in 13.3.3.1) 3273 // -- a standard conversion sequence (13.3.3.1.1) is a better 3274 // conversion sequence than a user-defined conversion sequence or 3275 // an ellipsis conversion sequence, and 3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3277 // conversion sequence than an ellipsis conversion sequence 3278 // (13.3.3.1.3). 3279 // 3280 // C++0x [over.best.ics]p10: 3281 // For the purpose of ranking implicit conversion sequences as 3282 // described in 13.3.3.2, the ambiguous conversion sequence is 3283 // treated as a user-defined sequence that is indistinguishable 3284 // from any other user-defined conversion sequence. 3285 3286 // String literal to 'char *' conversion has been deprecated in C++03. It has 3287 // been removed from C++11. We still accept this conversion, if it happens at 3288 // the best viable function. Otherwise, this conversion is considered worse 3289 // than ellipsis conversion. Consider this as an extension; this is not in the 3290 // standard. For example: 3291 // 3292 // int &f(...); // #1 3293 // void f(char*); // #2 3294 // void g() { int &r = f("foo"); } 3295 // 3296 // In C++03, we pick #2 as the best viable function. 3297 // In C++11, we pick #1 as the best viable function, because ellipsis 3298 // conversion is better than string-literal to char* conversion (since there 3299 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3300 // convert arguments, #2 would be the best viable function in C++11. 3301 // If the best viable function has this conversion, a warning will be issued 3302 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3303 3304 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3305 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3306 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3307 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3308 ? ImplicitConversionSequence::Worse 3309 : ImplicitConversionSequence::Better; 3310 3311 if (ICS1.getKindRank() < ICS2.getKindRank()) 3312 return ImplicitConversionSequence::Better; 3313 if (ICS2.getKindRank() < ICS1.getKindRank()) 3314 return ImplicitConversionSequence::Worse; 3315 3316 // The following checks require both conversion sequences to be of 3317 // the same kind. 3318 if (ICS1.getKind() != ICS2.getKind()) 3319 return ImplicitConversionSequence::Indistinguishable; 3320 3321 ImplicitConversionSequence::CompareKind Result = 3322 ImplicitConversionSequence::Indistinguishable; 3323 3324 // Two implicit conversion sequences of the same form are 3325 // indistinguishable conversion sequences unless one of the 3326 // following rules apply: (C++ 13.3.3.2p3): 3327 3328 // List-initialization sequence L1 is a better conversion sequence than 3329 // list-initialization sequence L2 if: 3330 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3331 // if not that, 3332 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3333 // and N1 is smaller than N2., 3334 // even if one of the other rules in this paragraph would otherwise apply. 3335 if (!ICS1.isBad()) { 3336 if (ICS1.isStdInitializerListElement() && 3337 !ICS2.isStdInitializerListElement()) 3338 return ImplicitConversionSequence::Better; 3339 if (!ICS1.isStdInitializerListElement() && 3340 ICS2.isStdInitializerListElement()) 3341 return ImplicitConversionSequence::Worse; 3342 } 3343 3344 if (ICS1.isStandard()) 3345 // Standard conversion sequence S1 is a better conversion sequence than 3346 // standard conversion sequence S2 if [...] 3347 Result = CompareStandardConversionSequences(S, 3348 ICS1.Standard, ICS2.Standard); 3349 else if (ICS1.isUserDefined()) { 3350 // User-defined conversion sequence U1 is a better conversion 3351 // sequence than another user-defined conversion sequence U2 if 3352 // they contain the same user-defined conversion function or 3353 // constructor and if the second standard conversion sequence of 3354 // U1 is better than the second standard conversion sequence of 3355 // U2 (C++ 13.3.3.2p3). 3356 if (ICS1.UserDefined.ConversionFunction == 3357 ICS2.UserDefined.ConversionFunction) 3358 Result = CompareStandardConversionSequences(S, 3359 ICS1.UserDefined.After, 3360 ICS2.UserDefined.After); 3361 else 3362 Result = compareConversionFunctions(S, 3363 ICS1.UserDefined.ConversionFunction, 3364 ICS2.UserDefined.ConversionFunction); 3365 } 3366 3367 return Result; 3368 } 3369 3370 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3371 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3372 Qualifiers Quals; 3373 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3374 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3375 } 3376 3377 return Context.hasSameUnqualifiedType(T1, T2); 3378 } 3379 3380 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3381 // determine if one is a proper subset of the other. 3382 static ImplicitConversionSequence::CompareKind 3383 compareStandardConversionSubsets(ASTContext &Context, 3384 const StandardConversionSequence& SCS1, 3385 const StandardConversionSequence& SCS2) { 3386 ImplicitConversionSequence::CompareKind Result 3387 = ImplicitConversionSequence::Indistinguishable; 3388 3389 // the identity conversion sequence is considered to be a subsequence of 3390 // any non-identity conversion sequence 3391 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3392 return ImplicitConversionSequence::Better; 3393 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3394 return ImplicitConversionSequence::Worse; 3395 3396 if (SCS1.Second != SCS2.Second) { 3397 if (SCS1.Second == ICK_Identity) 3398 Result = ImplicitConversionSequence::Better; 3399 else if (SCS2.Second == ICK_Identity) 3400 Result = ImplicitConversionSequence::Worse; 3401 else 3402 return ImplicitConversionSequence::Indistinguishable; 3403 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3404 return ImplicitConversionSequence::Indistinguishable; 3405 3406 if (SCS1.Third == SCS2.Third) { 3407 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3408 : ImplicitConversionSequence::Indistinguishable; 3409 } 3410 3411 if (SCS1.Third == ICK_Identity) 3412 return Result == ImplicitConversionSequence::Worse 3413 ? ImplicitConversionSequence::Indistinguishable 3414 : ImplicitConversionSequence::Better; 3415 3416 if (SCS2.Third == ICK_Identity) 3417 return Result == ImplicitConversionSequence::Better 3418 ? ImplicitConversionSequence::Indistinguishable 3419 : ImplicitConversionSequence::Worse; 3420 3421 return ImplicitConversionSequence::Indistinguishable; 3422 } 3423 3424 /// \brief Determine whether one of the given reference bindings is better 3425 /// than the other based on what kind of bindings they are. 3426 static bool 3427 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3428 const StandardConversionSequence &SCS2) { 3429 // C++0x [over.ics.rank]p3b4: 3430 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3431 // implicit object parameter of a non-static member function declared 3432 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3433 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3434 // lvalue reference to a function lvalue and S2 binds an rvalue 3435 // reference*. 3436 // 3437 // FIXME: Rvalue references. We're going rogue with the above edits, 3438 // because the semantics in the current C++0x working paper (N3225 at the 3439 // time of this writing) break the standard definition of std::forward 3440 // and std::reference_wrapper when dealing with references to functions. 3441 // Proposed wording changes submitted to CWG for consideration. 3442 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3443 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3444 return false; 3445 3446 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3447 SCS2.IsLvalueReference) || 3448 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3449 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3450 } 3451 3452 /// CompareStandardConversionSequences - Compare two standard 3453 /// conversion sequences to determine whether one is better than the 3454 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3455 static ImplicitConversionSequence::CompareKind 3456 CompareStandardConversionSequences(Sema &S, 3457 const StandardConversionSequence& SCS1, 3458 const StandardConversionSequence& SCS2) 3459 { 3460 // Standard conversion sequence S1 is a better conversion sequence 3461 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3462 3463 // -- S1 is a proper subsequence of S2 (comparing the conversion 3464 // sequences in the canonical form defined by 13.3.3.1.1, 3465 // excluding any Lvalue Transformation; the identity conversion 3466 // sequence is considered to be a subsequence of any 3467 // non-identity conversion sequence) or, if not that, 3468 if (ImplicitConversionSequence::CompareKind CK 3469 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3470 return CK; 3471 3472 // -- the rank of S1 is better than the rank of S2 (by the rules 3473 // defined below), or, if not that, 3474 ImplicitConversionRank Rank1 = SCS1.getRank(); 3475 ImplicitConversionRank Rank2 = SCS2.getRank(); 3476 if (Rank1 < Rank2) 3477 return ImplicitConversionSequence::Better; 3478 else if (Rank2 < Rank1) 3479 return ImplicitConversionSequence::Worse; 3480 3481 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3482 // are indistinguishable unless one of the following rules 3483 // applies: 3484 3485 // A conversion that is not a conversion of a pointer, or 3486 // pointer to member, to bool is better than another conversion 3487 // that is such a conversion. 3488 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3489 return SCS2.isPointerConversionToBool() 3490 ? ImplicitConversionSequence::Better 3491 : ImplicitConversionSequence::Worse; 3492 3493 // C++ [over.ics.rank]p4b2: 3494 // 3495 // If class B is derived directly or indirectly from class A, 3496 // conversion of B* to A* is better than conversion of B* to 3497 // void*, and conversion of A* to void* is better than conversion 3498 // of B* to void*. 3499 bool SCS1ConvertsToVoid 3500 = SCS1.isPointerConversionToVoidPointer(S.Context); 3501 bool SCS2ConvertsToVoid 3502 = SCS2.isPointerConversionToVoidPointer(S.Context); 3503 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3504 // Exactly one of the conversion sequences is a conversion to 3505 // a void pointer; it's the worse conversion. 3506 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3507 : ImplicitConversionSequence::Worse; 3508 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3509 // Neither conversion sequence converts to a void pointer; compare 3510 // their derived-to-base conversions. 3511 if (ImplicitConversionSequence::CompareKind DerivedCK 3512 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3513 return DerivedCK; 3514 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3515 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3516 // Both conversion sequences are conversions to void 3517 // pointers. Compare the source types to determine if there's an 3518 // inheritance relationship in their sources. 3519 QualType FromType1 = SCS1.getFromType(); 3520 QualType FromType2 = SCS2.getFromType(); 3521 3522 // Adjust the types we're converting from via the array-to-pointer 3523 // conversion, if we need to. 3524 if (SCS1.First == ICK_Array_To_Pointer) 3525 FromType1 = S.Context.getArrayDecayedType(FromType1); 3526 if (SCS2.First == ICK_Array_To_Pointer) 3527 FromType2 = S.Context.getArrayDecayedType(FromType2); 3528 3529 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3530 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3531 3532 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3533 return ImplicitConversionSequence::Better; 3534 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3535 return ImplicitConversionSequence::Worse; 3536 3537 // Objective-C++: If one interface is more specific than the 3538 // other, it is the better one. 3539 const ObjCObjectPointerType* FromObjCPtr1 3540 = FromType1->getAs<ObjCObjectPointerType>(); 3541 const ObjCObjectPointerType* FromObjCPtr2 3542 = FromType2->getAs<ObjCObjectPointerType>(); 3543 if (FromObjCPtr1 && FromObjCPtr2) { 3544 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3545 FromObjCPtr2); 3546 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3547 FromObjCPtr1); 3548 if (AssignLeft != AssignRight) { 3549 return AssignLeft? ImplicitConversionSequence::Better 3550 : ImplicitConversionSequence::Worse; 3551 } 3552 } 3553 } 3554 3555 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3556 // bullet 3). 3557 if (ImplicitConversionSequence::CompareKind QualCK 3558 = CompareQualificationConversions(S, SCS1, SCS2)) 3559 return QualCK; 3560 3561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3562 // Check for a better reference binding based on the kind of bindings. 3563 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3564 return ImplicitConversionSequence::Better; 3565 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3566 return ImplicitConversionSequence::Worse; 3567 3568 // C++ [over.ics.rank]p3b4: 3569 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3570 // which the references refer are the same type except for 3571 // top-level cv-qualifiers, and the type to which the reference 3572 // initialized by S2 refers is more cv-qualified than the type 3573 // to which the reference initialized by S1 refers. 3574 QualType T1 = SCS1.getToType(2); 3575 QualType T2 = SCS2.getToType(2); 3576 T1 = S.Context.getCanonicalType(T1); 3577 T2 = S.Context.getCanonicalType(T2); 3578 Qualifiers T1Quals, T2Quals; 3579 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3580 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3581 if (UnqualT1 == UnqualT2) { 3582 // Objective-C++ ARC: If the references refer to objects with different 3583 // lifetimes, prefer bindings that don't change lifetime. 3584 if (SCS1.ObjCLifetimeConversionBinding != 3585 SCS2.ObjCLifetimeConversionBinding) { 3586 return SCS1.ObjCLifetimeConversionBinding 3587 ? ImplicitConversionSequence::Worse 3588 : ImplicitConversionSequence::Better; 3589 } 3590 3591 // If the type is an array type, promote the element qualifiers to the 3592 // type for comparison. 3593 if (isa<ArrayType>(T1) && T1Quals) 3594 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3595 if (isa<ArrayType>(T2) && T2Quals) 3596 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3597 if (T2.isMoreQualifiedThan(T1)) 3598 return ImplicitConversionSequence::Better; 3599 else if (T1.isMoreQualifiedThan(T2)) 3600 return ImplicitConversionSequence::Worse; 3601 } 3602 } 3603 3604 // In Microsoft mode, prefer an integral conversion to a 3605 // floating-to-integral conversion if the integral conversion 3606 // is between types of the same size. 3607 // For example: 3608 // void f(float); 3609 // void f(int); 3610 // int main { 3611 // long a; 3612 // f(a); 3613 // } 3614 // Here, MSVC will call f(int) instead of generating a compile error 3615 // as clang will do in standard mode. 3616 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3617 SCS2.Second == ICK_Floating_Integral && 3618 S.Context.getTypeSize(SCS1.getFromType()) == 3619 S.Context.getTypeSize(SCS1.getToType(2))) 3620 return ImplicitConversionSequence::Better; 3621 3622 return ImplicitConversionSequence::Indistinguishable; 3623 } 3624 3625 /// CompareQualificationConversions - Compares two standard conversion 3626 /// sequences to determine whether they can be ranked based on their 3627 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3628 static ImplicitConversionSequence::CompareKind 3629 CompareQualificationConversions(Sema &S, 3630 const StandardConversionSequence& SCS1, 3631 const StandardConversionSequence& SCS2) { 3632 // C++ 13.3.3.2p3: 3633 // -- S1 and S2 differ only in their qualification conversion and 3634 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3635 // cv-qualification signature of type T1 is a proper subset of 3636 // the cv-qualification signature of type T2, and S1 is not the 3637 // deprecated string literal array-to-pointer conversion (4.2). 3638 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3639 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3640 return ImplicitConversionSequence::Indistinguishable; 3641 3642 // FIXME: the example in the standard doesn't use a qualification 3643 // conversion (!) 3644 QualType T1 = SCS1.getToType(2); 3645 QualType T2 = SCS2.getToType(2); 3646 T1 = S.Context.getCanonicalType(T1); 3647 T2 = S.Context.getCanonicalType(T2); 3648 Qualifiers T1Quals, T2Quals; 3649 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3650 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3651 3652 // If the types are the same, we won't learn anything by unwrapped 3653 // them. 3654 if (UnqualT1 == UnqualT2) 3655 return ImplicitConversionSequence::Indistinguishable; 3656 3657 // If the type is an array type, promote the element qualifiers to the type 3658 // for comparison. 3659 if (isa<ArrayType>(T1) && T1Quals) 3660 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3661 if (isa<ArrayType>(T2) && T2Quals) 3662 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3663 3664 ImplicitConversionSequence::CompareKind Result 3665 = ImplicitConversionSequence::Indistinguishable; 3666 3667 // Objective-C++ ARC: 3668 // Prefer qualification conversions not involving a change in lifetime 3669 // to qualification conversions that do not change lifetime. 3670 if (SCS1.QualificationIncludesObjCLifetime != 3671 SCS2.QualificationIncludesObjCLifetime) { 3672 Result = SCS1.QualificationIncludesObjCLifetime 3673 ? ImplicitConversionSequence::Worse 3674 : ImplicitConversionSequence::Better; 3675 } 3676 3677 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3678 // Within each iteration of the loop, we check the qualifiers to 3679 // determine if this still looks like a qualification 3680 // conversion. Then, if all is well, we unwrap one more level of 3681 // pointers or pointers-to-members and do it all again 3682 // until there are no more pointers or pointers-to-members left 3683 // to unwrap. This essentially mimics what 3684 // IsQualificationConversion does, but here we're checking for a 3685 // strict subset of qualifiers. 3686 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3687 // The qualifiers are the same, so this doesn't tell us anything 3688 // about how the sequences rank. 3689 ; 3690 else if (T2.isMoreQualifiedThan(T1)) { 3691 // T1 has fewer qualifiers, so it could be the better sequence. 3692 if (Result == ImplicitConversionSequence::Worse) 3693 // Neither has qualifiers that are a subset of the other's 3694 // qualifiers. 3695 return ImplicitConversionSequence::Indistinguishable; 3696 3697 Result = ImplicitConversionSequence::Better; 3698 } else if (T1.isMoreQualifiedThan(T2)) { 3699 // T2 has fewer qualifiers, so it could be the better sequence. 3700 if (Result == ImplicitConversionSequence::Better) 3701 // Neither has qualifiers that are a subset of the other's 3702 // qualifiers. 3703 return ImplicitConversionSequence::Indistinguishable; 3704 3705 Result = ImplicitConversionSequence::Worse; 3706 } else { 3707 // Qualifiers are disjoint. 3708 return ImplicitConversionSequence::Indistinguishable; 3709 } 3710 3711 // If the types after this point are equivalent, we're done. 3712 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3713 break; 3714 } 3715 3716 // Check that the winning standard conversion sequence isn't using 3717 // the deprecated string literal array to pointer conversion. 3718 switch (Result) { 3719 case ImplicitConversionSequence::Better: 3720 if (SCS1.DeprecatedStringLiteralToCharPtr) 3721 Result = ImplicitConversionSequence::Indistinguishable; 3722 break; 3723 3724 case ImplicitConversionSequence::Indistinguishable: 3725 break; 3726 3727 case ImplicitConversionSequence::Worse: 3728 if (SCS2.DeprecatedStringLiteralToCharPtr) 3729 Result = ImplicitConversionSequence::Indistinguishable; 3730 break; 3731 } 3732 3733 return Result; 3734 } 3735 3736 /// CompareDerivedToBaseConversions - Compares two standard conversion 3737 /// sequences to determine whether they can be ranked based on their 3738 /// various kinds of derived-to-base conversions (C++ 3739 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3740 /// conversions between Objective-C interface types. 3741 static ImplicitConversionSequence::CompareKind 3742 CompareDerivedToBaseConversions(Sema &S, 3743 const StandardConversionSequence& SCS1, 3744 const StandardConversionSequence& SCS2) { 3745 QualType FromType1 = SCS1.getFromType(); 3746 QualType ToType1 = SCS1.getToType(1); 3747 QualType FromType2 = SCS2.getFromType(); 3748 QualType ToType2 = SCS2.getToType(1); 3749 3750 // Adjust the types we're converting from via the array-to-pointer 3751 // conversion, if we need to. 3752 if (SCS1.First == ICK_Array_To_Pointer) 3753 FromType1 = S.Context.getArrayDecayedType(FromType1); 3754 if (SCS2.First == ICK_Array_To_Pointer) 3755 FromType2 = S.Context.getArrayDecayedType(FromType2); 3756 3757 // Canonicalize all of the types. 3758 FromType1 = S.Context.getCanonicalType(FromType1); 3759 ToType1 = S.Context.getCanonicalType(ToType1); 3760 FromType2 = S.Context.getCanonicalType(FromType2); 3761 ToType2 = S.Context.getCanonicalType(ToType2); 3762 3763 // C++ [over.ics.rank]p4b3: 3764 // 3765 // If class B is derived directly or indirectly from class A and 3766 // class C is derived directly or indirectly from B, 3767 // 3768 // Compare based on pointer conversions. 3769 if (SCS1.Second == ICK_Pointer_Conversion && 3770 SCS2.Second == ICK_Pointer_Conversion && 3771 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3772 FromType1->isPointerType() && FromType2->isPointerType() && 3773 ToType1->isPointerType() && ToType2->isPointerType()) { 3774 QualType FromPointee1 3775 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3776 QualType ToPointee1 3777 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3778 QualType FromPointee2 3779 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3780 QualType ToPointee2 3781 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3782 3783 // -- conversion of C* to B* is better than conversion of C* to A*, 3784 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3785 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3786 return ImplicitConversionSequence::Better; 3787 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3788 return ImplicitConversionSequence::Worse; 3789 } 3790 3791 // -- conversion of B* to A* is better than conversion of C* to A*, 3792 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3793 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3794 return ImplicitConversionSequence::Better; 3795 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3796 return ImplicitConversionSequence::Worse; 3797 } 3798 } else if (SCS1.Second == ICK_Pointer_Conversion && 3799 SCS2.Second == ICK_Pointer_Conversion) { 3800 const ObjCObjectPointerType *FromPtr1 3801 = FromType1->getAs<ObjCObjectPointerType>(); 3802 const ObjCObjectPointerType *FromPtr2 3803 = FromType2->getAs<ObjCObjectPointerType>(); 3804 const ObjCObjectPointerType *ToPtr1 3805 = ToType1->getAs<ObjCObjectPointerType>(); 3806 const ObjCObjectPointerType *ToPtr2 3807 = ToType2->getAs<ObjCObjectPointerType>(); 3808 3809 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3810 // Apply the same conversion ranking rules for Objective-C pointer types 3811 // that we do for C++ pointers to class types. However, we employ the 3812 // Objective-C pseudo-subtyping relationship used for assignment of 3813 // Objective-C pointer types. 3814 bool FromAssignLeft 3815 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3816 bool FromAssignRight 3817 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3818 bool ToAssignLeft 3819 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3820 bool ToAssignRight 3821 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3822 3823 // A conversion to an a non-id object pointer type or qualified 'id' 3824 // type is better than a conversion to 'id'. 3825 if (ToPtr1->isObjCIdType() && 3826 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3827 return ImplicitConversionSequence::Worse; 3828 if (ToPtr2->isObjCIdType() && 3829 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3830 return ImplicitConversionSequence::Better; 3831 3832 // A conversion to a non-id object pointer type is better than a 3833 // conversion to a qualified 'id' type 3834 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3835 return ImplicitConversionSequence::Worse; 3836 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3837 return ImplicitConversionSequence::Better; 3838 3839 // A conversion to an a non-Class object pointer type or qualified 'Class' 3840 // type is better than a conversion to 'Class'. 3841 if (ToPtr1->isObjCClassType() && 3842 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3843 return ImplicitConversionSequence::Worse; 3844 if (ToPtr2->isObjCClassType() && 3845 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3846 return ImplicitConversionSequence::Better; 3847 3848 // A conversion to a non-Class object pointer type is better than a 3849 // conversion to a qualified 'Class' type. 3850 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3851 return ImplicitConversionSequence::Worse; 3852 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3853 return ImplicitConversionSequence::Better; 3854 3855 // -- "conversion of C* to B* is better than conversion of C* to A*," 3856 if (S.Context.hasSameType(FromType1, FromType2) && 3857 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3858 (ToAssignLeft != ToAssignRight)) 3859 return ToAssignLeft? ImplicitConversionSequence::Worse 3860 : ImplicitConversionSequence::Better; 3861 3862 // -- "conversion of B* to A* is better than conversion of C* to A*," 3863 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3864 (FromAssignLeft != FromAssignRight)) 3865 return FromAssignLeft? ImplicitConversionSequence::Better 3866 : ImplicitConversionSequence::Worse; 3867 } 3868 } 3869 3870 // Ranking of member-pointer types. 3871 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3872 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3873 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3874 const MemberPointerType * FromMemPointer1 = 3875 FromType1->getAs<MemberPointerType>(); 3876 const MemberPointerType * ToMemPointer1 = 3877 ToType1->getAs<MemberPointerType>(); 3878 const MemberPointerType * FromMemPointer2 = 3879 FromType2->getAs<MemberPointerType>(); 3880 const MemberPointerType * ToMemPointer2 = 3881 ToType2->getAs<MemberPointerType>(); 3882 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3883 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3884 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3885 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3886 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3887 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3888 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3889 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3890 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3892 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3893 return ImplicitConversionSequence::Worse; 3894 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3895 return ImplicitConversionSequence::Better; 3896 } 3897 // conversion of B::* to C::* is better than conversion of A::* to C::* 3898 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3899 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3900 return ImplicitConversionSequence::Better; 3901 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3902 return ImplicitConversionSequence::Worse; 3903 } 3904 } 3905 3906 if (SCS1.Second == ICK_Derived_To_Base) { 3907 // -- conversion of C to B is better than conversion of C to A, 3908 // -- binding of an expression of type C to a reference of type 3909 // B& is better than binding an expression of type C to a 3910 // reference of type A&, 3911 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3912 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3913 if (S.IsDerivedFrom(ToType1, ToType2)) 3914 return ImplicitConversionSequence::Better; 3915 else if (S.IsDerivedFrom(ToType2, ToType1)) 3916 return ImplicitConversionSequence::Worse; 3917 } 3918 3919 // -- conversion of B to A is better than conversion of C to A. 3920 // -- binding of an expression of type B to a reference of type 3921 // A& is better than binding an expression of type C to a 3922 // reference of type A&, 3923 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3924 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3925 if (S.IsDerivedFrom(FromType2, FromType1)) 3926 return ImplicitConversionSequence::Better; 3927 else if (S.IsDerivedFrom(FromType1, FromType2)) 3928 return ImplicitConversionSequence::Worse; 3929 } 3930 } 3931 3932 return ImplicitConversionSequence::Indistinguishable; 3933 } 3934 3935 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3936 /// C++ class. 3937 static bool isTypeValid(QualType T) { 3938 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3939 return !Record->isInvalidDecl(); 3940 3941 return true; 3942 } 3943 3944 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3945 /// determine whether they are reference-related, 3946 /// reference-compatible, reference-compatible with added 3947 /// qualification, or incompatible, for use in C++ initialization by 3948 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3949 /// type, and the first type (T1) is the pointee type of the reference 3950 /// type being initialized. 3951 Sema::ReferenceCompareResult 3952 Sema::CompareReferenceRelationship(SourceLocation Loc, 3953 QualType OrigT1, QualType OrigT2, 3954 bool &DerivedToBase, 3955 bool &ObjCConversion, 3956 bool &ObjCLifetimeConversion) { 3957 assert(!OrigT1->isReferenceType() && 3958 "T1 must be the pointee type of the reference type"); 3959 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3960 3961 QualType T1 = Context.getCanonicalType(OrigT1); 3962 QualType T2 = Context.getCanonicalType(OrigT2); 3963 Qualifiers T1Quals, T2Quals; 3964 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3965 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3966 3967 // C++ [dcl.init.ref]p4: 3968 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3969 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3970 // T1 is a base class of T2. 3971 DerivedToBase = false; 3972 ObjCConversion = false; 3973 ObjCLifetimeConversion = false; 3974 if (UnqualT1 == UnqualT2) { 3975 // Nothing to do. 3976 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3977 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3978 IsDerivedFrom(UnqualT2, UnqualT1)) 3979 DerivedToBase = true; 3980 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3981 UnqualT2->isObjCObjectOrInterfaceType() && 3982 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3983 ObjCConversion = true; 3984 else 3985 return Ref_Incompatible; 3986 3987 // At this point, we know that T1 and T2 are reference-related (at 3988 // least). 3989 3990 // If the type is an array type, promote the element qualifiers to the type 3991 // for comparison. 3992 if (isa<ArrayType>(T1) && T1Quals) 3993 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3994 if (isa<ArrayType>(T2) && T2Quals) 3995 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3996 3997 // C++ [dcl.init.ref]p4: 3998 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3999 // reference-related to T2 and cv1 is the same cv-qualification 4000 // as, or greater cv-qualification than, cv2. For purposes of 4001 // overload resolution, cases for which cv1 is greater 4002 // cv-qualification than cv2 are identified as 4003 // reference-compatible with added qualification (see 13.3.3.2). 4004 // 4005 // Note that we also require equivalence of Objective-C GC and address-space 4006 // qualifiers when performing these computations, so that e.g., an int in 4007 // address space 1 is not reference-compatible with an int in address 4008 // space 2. 4009 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4010 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4011 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4012 ObjCLifetimeConversion = true; 4013 4014 T1Quals.removeObjCLifetime(); 4015 T2Quals.removeObjCLifetime(); 4016 } 4017 4018 if (T1Quals == T2Quals) 4019 return Ref_Compatible; 4020 else if (T1Quals.compatiblyIncludes(T2Quals)) 4021 return Ref_Compatible_With_Added_Qualification; 4022 else 4023 return Ref_Related; 4024 } 4025 4026 /// \brief Look for a user-defined conversion to an value reference-compatible 4027 /// with DeclType. Return true if something definite is found. 4028 static bool 4029 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4030 QualType DeclType, SourceLocation DeclLoc, 4031 Expr *Init, QualType T2, bool AllowRvalues, 4032 bool AllowExplicit) { 4033 assert(T2->isRecordType() && "Can only find conversions of record types."); 4034 CXXRecordDecl *T2RecordDecl 4035 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4036 4037 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4038 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4039 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4040 NamedDecl *D = *I; 4041 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4042 if (isa<UsingShadowDecl>(D)) 4043 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4044 4045 FunctionTemplateDecl *ConvTemplate 4046 = dyn_cast<FunctionTemplateDecl>(D); 4047 CXXConversionDecl *Conv; 4048 if (ConvTemplate) 4049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4050 else 4051 Conv = cast<CXXConversionDecl>(D); 4052 4053 // If this is an explicit conversion, and we're not allowed to consider 4054 // explicit conversions, skip it. 4055 if (!AllowExplicit && Conv->isExplicit()) 4056 continue; 4057 4058 if (AllowRvalues) { 4059 bool DerivedToBase = false; 4060 bool ObjCConversion = false; 4061 bool ObjCLifetimeConversion = false; 4062 4063 // If we are initializing an rvalue reference, don't permit conversion 4064 // functions that return lvalues. 4065 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4066 const ReferenceType *RefType 4067 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4068 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4069 continue; 4070 } 4071 4072 if (!ConvTemplate && 4073 S.CompareReferenceRelationship( 4074 DeclLoc, 4075 Conv->getConversionType().getNonReferenceType() 4076 .getUnqualifiedType(), 4077 DeclType.getNonReferenceType().getUnqualifiedType(), 4078 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4079 Sema::Ref_Incompatible) 4080 continue; 4081 } else { 4082 // If the conversion function doesn't return a reference type, 4083 // it can't be considered for this conversion. An rvalue reference 4084 // is only acceptable if its referencee is a function type. 4085 4086 const ReferenceType *RefType = 4087 Conv->getConversionType()->getAs<ReferenceType>(); 4088 if (!RefType || 4089 (!RefType->isLValueReferenceType() && 4090 !RefType->getPointeeType()->isFunctionType())) 4091 continue; 4092 } 4093 4094 if (ConvTemplate) 4095 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4096 Init, DeclType, CandidateSet, 4097 /*AllowObjCConversionOnExplicit=*/false); 4098 else 4099 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4100 DeclType, CandidateSet, 4101 /*AllowObjCConversionOnExplicit=*/false); 4102 } 4103 4104 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4105 4106 OverloadCandidateSet::iterator Best; 4107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4108 case OR_Success: 4109 // C++ [over.ics.ref]p1: 4110 // 4111 // [...] If the parameter binds directly to the result of 4112 // applying a conversion function to the argument 4113 // expression, the implicit conversion sequence is a 4114 // user-defined conversion sequence (13.3.3.1.2), with the 4115 // second standard conversion sequence either an identity 4116 // conversion or, if the conversion function returns an 4117 // entity of a type that is a derived class of the parameter 4118 // type, a derived-to-base Conversion. 4119 if (!Best->FinalConversion.DirectBinding) 4120 return false; 4121 4122 ICS.setUserDefined(); 4123 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4124 ICS.UserDefined.After = Best->FinalConversion; 4125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4126 ICS.UserDefined.ConversionFunction = Best->Function; 4127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4128 ICS.UserDefined.EllipsisConversion = false; 4129 assert(ICS.UserDefined.After.ReferenceBinding && 4130 ICS.UserDefined.After.DirectBinding && 4131 "Expected a direct reference binding!"); 4132 return true; 4133 4134 case OR_Ambiguous: 4135 ICS.setAmbiguous(); 4136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4137 Cand != CandidateSet.end(); ++Cand) 4138 if (Cand->Viable) 4139 ICS.Ambiguous.addConversion(Cand->Function); 4140 return true; 4141 4142 case OR_No_Viable_Function: 4143 case OR_Deleted: 4144 // There was no suitable conversion, or we found a deleted 4145 // conversion; continue with other checks. 4146 return false; 4147 } 4148 4149 llvm_unreachable("Invalid OverloadResult!"); 4150 } 4151 4152 /// \brief Compute an implicit conversion sequence for reference 4153 /// initialization. 4154 static ImplicitConversionSequence 4155 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4156 SourceLocation DeclLoc, 4157 bool SuppressUserConversions, 4158 bool AllowExplicit) { 4159 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4160 4161 // Most paths end in a failed conversion. 4162 ImplicitConversionSequence ICS; 4163 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4164 4165 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4166 QualType T2 = Init->getType(); 4167 4168 // If the initializer is the address of an overloaded function, try 4169 // to resolve the overloaded function. If all goes well, T2 is the 4170 // type of the resulting function. 4171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4172 DeclAccessPair Found; 4173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4174 false, Found)) 4175 T2 = Fn->getType(); 4176 } 4177 4178 // Compute some basic properties of the types and the initializer. 4179 bool isRValRef = DeclType->isRValueReferenceType(); 4180 bool DerivedToBase = false; 4181 bool ObjCConversion = false; 4182 bool ObjCLifetimeConversion = false; 4183 Expr::Classification InitCategory = Init->Classify(S.Context); 4184 Sema::ReferenceCompareResult RefRelationship 4185 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4186 ObjCConversion, ObjCLifetimeConversion); 4187 4188 4189 // C++0x [dcl.init.ref]p5: 4190 // A reference to type "cv1 T1" is initialized by an expression 4191 // of type "cv2 T2" as follows: 4192 4193 // -- If reference is an lvalue reference and the initializer expression 4194 if (!isRValRef) { 4195 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4196 // reference-compatible with "cv2 T2," or 4197 // 4198 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4199 if (InitCategory.isLValue() && 4200 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4201 // C++ [over.ics.ref]p1: 4202 // When a parameter of reference type binds directly (8.5.3) 4203 // to an argument expression, the implicit conversion sequence 4204 // is the identity conversion, unless the argument expression 4205 // has a type that is a derived class of the parameter type, 4206 // in which case the implicit conversion sequence is a 4207 // derived-to-base Conversion (13.3.3.1). 4208 ICS.setStandard(); 4209 ICS.Standard.First = ICK_Identity; 4210 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4211 : ObjCConversion? ICK_Compatible_Conversion 4212 : ICK_Identity; 4213 ICS.Standard.Third = ICK_Identity; 4214 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4215 ICS.Standard.setToType(0, T2); 4216 ICS.Standard.setToType(1, T1); 4217 ICS.Standard.setToType(2, T1); 4218 ICS.Standard.ReferenceBinding = true; 4219 ICS.Standard.DirectBinding = true; 4220 ICS.Standard.IsLvalueReference = !isRValRef; 4221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4222 ICS.Standard.BindsToRvalue = false; 4223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4224 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4225 ICS.Standard.CopyConstructor = nullptr; 4226 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4227 4228 // Nothing more to do: the inaccessibility/ambiguity check for 4229 // derived-to-base conversions is suppressed when we're 4230 // computing the implicit conversion sequence (C++ 4231 // [over.best.ics]p2). 4232 return ICS; 4233 } 4234 4235 // -- has a class type (i.e., T2 is a class type), where T1 is 4236 // not reference-related to T2, and can be implicitly 4237 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4238 // is reference-compatible with "cv3 T3" 92) (this 4239 // conversion is selected by enumerating the applicable 4240 // conversion functions (13.3.1.6) and choosing the best 4241 // one through overload resolution (13.3)), 4242 if (!SuppressUserConversions && T2->isRecordType() && 4243 !S.RequireCompleteType(DeclLoc, T2, 0) && 4244 RefRelationship == Sema::Ref_Incompatible) { 4245 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4246 Init, T2, /*AllowRvalues=*/false, 4247 AllowExplicit)) 4248 return ICS; 4249 } 4250 } 4251 4252 // -- Otherwise, the reference shall be an lvalue reference to a 4253 // non-volatile const type (i.e., cv1 shall be const), or the reference 4254 // shall be an rvalue reference. 4255 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4256 return ICS; 4257 4258 // -- If the initializer expression 4259 // 4260 // -- is an xvalue, class prvalue, array prvalue or function 4261 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4262 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4263 (InitCategory.isXValue() || 4264 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4265 (InitCategory.isLValue() && T2->isFunctionType()))) { 4266 ICS.setStandard(); 4267 ICS.Standard.First = ICK_Identity; 4268 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4269 : ObjCConversion? ICK_Compatible_Conversion 4270 : ICK_Identity; 4271 ICS.Standard.Third = ICK_Identity; 4272 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4273 ICS.Standard.setToType(0, T2); 4274 ICS.Standard.setToType(1, T1); 4275 ICS.Standard.setToType(2, T1); 4276 ICS.Standard.ReferenceBinding = true; 4277 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4278 // binding unless we're binding to a class prvalue. 4279 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4280 // allow the use of rvalue references in C++98/03 for the benefit of 4281 // standard library implementors; therefore, we need the xvalue check here. 4282 ICS.Standard.DirectBinding = 4283 S.getLangOpts().CPlusPlus11 || 4284 !(InitCategory.isPRValue() || T2->isRecordType()); 4285 ICS.Standard.IsLvalueReference = !isRValRef; 4286 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4287 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4288 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4289 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4290 ICS.Standard.CopyConstructor = nullptr; 4291 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4292 return ICS; 4293 } 4294 4295 // -- has a class type (i.e., T2 is a class type), where T1 is not 4296 // reference-related to T2, and can be implicitly converted to 4297 // an xvalue, class prvalue, or function lvalue of type 4298 // "cv3 T3", where "cv1 T1" is reference-compatible with 4299 // "cv3 T3", 4300 // 4301 // then the reference is bound to the value of the initializer 4302 // expression in the first case and to the result of the conversion 4303 // in the second case (or, in either case, to an appropriate base 4304 // class subobject). 4305 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4306 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4307 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4308 Init, T2, /*AllowRvalues=*/true, 4309 AllowExplicit)) { 4310 // In the second case, if the reference is an rvalue reference 4311 // and the second standard conversion sequence of the 4312 // user-defined conversion sequence includes an lvalue-to-rvalue 4313 // conversion, the program is ill-formed. 4314 if (ICS.isUserDefined() && isRValRef && 4315 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4316 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4317 4318 return ICS; 4319 } 4320 4321 // A temporary of function type cannot be created; don't even try. 4322 if (T1->isFunctionType()) 4323 return ICS; 4324 4325 // -- Otherwise, a temporary of type "cv1 T1" is created and 4326 // initialized from the initializer expression using the 4327 // rules for a non-reference copy initialization (8.5). The 4328 // reference is then bound to the temporary. If T1 is 4329 // reference-related to T2, cv1 must be the same 4330 // cv-qualification as, or greater cv-qualification than, 4331 // cv2; otherwise, the program is ill-formed. 4332 if (RefRelationship == Sema::Ref_Related) { 4333 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4334 // we would be reference-compatible or reference-compatible with 4335 // added qualification. But that wasn't the case, so the reference 4336 // initialization fails. 4337 // 4338 // Note that we only want to check address spaces and cvr-qualifiers here. 4339 // ObjC GC and lifetime qualifiers aren't important. 4340 Qualifiers T1Quals = T1.getQualifiers(); 4341 Qualifiers T2Quals = T2.getQualifiers(); 4342 T1Quals.removeObjCGCAttr(); 4343 T1Quals.removeObjCLifetime(); 4344 T2Quals.removeObjCGCAttr(); 4345 T2Quals.removeObjCLifetime(); 4346 if (!T1Quals.compatiblyIncludes(T2Quals)) 4347 return ICS; 4348 } 4349 4350 // If at least one of the types is a class type, the types are not 4351 // related, and we aren't allowed any user conversions, the 4352 // reference binding fails. This case is important for breaking 4353 // recursion, since TryImplicitConversion below will attempt to 4354 // create a temporary through the use of a copy constructor. 4355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4356 (T1->isRecordType() || T2->isRecordType())) 4357 return ICS; 4358 4359 // If T1 is reference-related to T2 and the reference is an rvalue 4360 // reference, the initializer expression shall not be an lvalue. 4361 if (RefRelationship >= Sema::Ref_Related && 4362 isRValRef && Init->Classify(S.Context).isLValue()) 4363 return ICS; 4364 4365 // C++ [over.ics.ref]p2: 4366 // When a parameter of reference type is not bound directly to 4367 // an argument expression, the conversion sequence is the one 4368 // required to convert the argument expression to the 4369 // underlying type of the reference according to 4370 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4371 // to copy-initializing a temporary of the underlying type with 4372 // the argument expression. Any difference in top-level 4373 // cv-qualification is subsumed by the initialization itself 4374 // and does not constitute a conversion. 4375 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4376 /*AllowExplicit=*/false, 4377 /*InOverloadResolution=*/false, 4378 /*CStyle=*/false, 4379 /*AllowObjCWritebackConversion=*/false, 4380 /*AllowObjCConversionOnExplicit=*/false); 4381 4382 // Of course, that's still a reference binding. 4383 if (ICS.isStandard()) { 4384 ICS.Standard.ReferenceBinding = true; 4385 ICS.Standard.IsLvalueReference = !isRValRef; 4386 ICS.Standard.BindsToFunctionLvalue = false; 4387 ICS.Standard.BindsToRvalue = true; 4388 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4389 ICS.Standard.ObjCLifetimeConversionBinding = false; 4390 } else if (ICS.isUserDefined()) { 4391 const ReferenceType *LValRefType = 4392 ICS.UserDefined.ConversionFunction->getReturnType() 4393 ->getAs<LValueReferenceType>(); 4394 4395 // C++ [over.ics.ref]p3: 4396 // Except for an implicit object parameter, for which see 13.3.1, a 4397 // standard conversion sequence cannot be formed if it requires [...] 4398 // binding an rvalue reference to an lvalue other than a function 4399 // lvalue. 4400 // Note that the function case is not possible here. 4401 if (DeclType->isRValueReferenceType() && LValRefType) { 4402 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4403 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4404 // reference to an rvalue! 4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4406 return ICS; 4407 } 4408 4409 ICS.UserDefined.Before.setAsIdentityConversion(); 4410 ICS.UserDefined.After.ReferenceBinding = true; 4411 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4412 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4413 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4414 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4415 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4416 } 4417 4418 return ICS; 4419 } 4420 4421 static ImplicitConversionSequence 4422 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4423 bool SuppressUserConversions, 4424 bool InOverloadResolution, 4425 bool AllowObjCWritebackConversion, 4426 bool AllowExplicit = false); 4427 4428 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4429 /// initializer list From. 4430 static ImplicitConversionSequence 4431 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4432 bool SuppressUserConversions, 4433 bool InOverloadResolution, 4434 bool AllowObjCWritebackConversion) { 4435 // C++11 [over.ics.list]p1: 4436 // When an argument is an initializer list, it is not an expression and 4437 // special rules apply for converting it to a parameter type. 4438 4439 ImplicitConversionSequence Result; 4440 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4441 4442 // We need a complete type for what follows. Incomplete types can never be 4443 // initialized from init lists. 4444 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4445 return Result; 4446 4447 // Per DR1467: 4448 // If the parameter type is a class X and the initializer list has a single 4449 // element of type cv U, where U is X or a class derived from X, the 4450 // implicit conversion sequence is the one required to convert the element 4451 // to the parameter type. 4452 // 4453 // Otherwise, if the parameter type is a character array [... ] 4454 // and the initializer list has a single element that is an 4455 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4456 // implicit conversion sequence is the identity conversion. 4457 if (From->getNumInits() == 1) { 4458 if (ToType->isRecordType()) { 4459 QualType InitType = From->getInit(0)->getType(); 4460 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4461 S.IsDerivedFrom(InitType, ToType)) 4462 return TryCopyInitialization(S, From->getInit(0), ToType, 4463 SuppressUserConversions, 4464 InOverloadResolution, 4465 AllowObjCWritebackConversion); 4466 } 4467 // FIXME: Check the other conditions here: array of character type, 4468 // initializer is a string literal. 4469 if (ToType->isArrayType()) { 4470 InitializedEntity Entity = 4471 InitializedEntity::InitializeParameter(S.Context, ToType, 4472 /*Consumed=*/false); 4473 if (S.CanPerformCopyInitialization(Entity, From)) { 4474 Result.setStandard(); 4475 Result.Standard.setAsIdentityConversion(); 4476 Result.Standard.setFromType(ToType); 4477 Result.Standard.setAllToTypes(ToType); 4478 return Result; 4479 } 4480 } 4481 } 4482 4483 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4484 // C++11 [over.ics.list]p2: 4485 // If the parameter type is std::initializer_list<X> or "array of X" and 4486 // all the elements can be implicitly converted to X, the implicit 4487 // conversion sequence is the worst conversion necessary to convert an 4488 // element of the list to X. 4489 // 4490 // C++14 [over.ics.list]p3: 4491 // Otherwise, if the parameter type is "array of N X", if the initializer 4492 // list has exactly N elements or if it has fewer than N elements and X is 4493 // default-constructible, and if all the elements of the initializer list 4494 // can be implicitly converted to X, the implicit conversion sequence is 4495 // the worst conversion necessary to convert an element of the list to X. 4496 // 4497 // FIXME: We're missing a lot of these checks. 4498 bool toStdInitializerList = false; 4499 QualType X; 4500 if (ToType->isArrayType()) 4501 X = S.Context.getAsArrayType(ToType)->getElementType(); 4502 else 4503 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4504 if (!X.isNull()) { 4505 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4506 Expr *Init = From->getInit(i); 4507 ImplicitConversionSequence ICS = 4508 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4509 InOverloadResolution, 4510 AllowObjCWritebackConversion); 4511 // If a single element isn't convertible, fail. 4512 if (ICS.isBad()) { 4513 Result = ICS; 4514 break; 4515 } 4516 // Otherwise, look for the worst conversion. 4517 if (Result.isBad() || 4518 CompareImplicitConversionSequences(S, ICS, Result) == 4519 ImplicitConversionSequence::Worse) 4520 Result = ICS; 4521 } 4522 4523 // For an empty list, we won't have computed any conversion sequence. 4524 // Introduce the identity conversion sequence. 4525 if (From->getNumInits() == 0) { 4526 Result.setStandard(); 4527 Result.Standard.setAsIdentityConversion(); 4528 Result.Standard.setFromType(ToType); 4529 Result.Standard.setAllToTypes(ToType); 4530 } 4531 4532 Result.setStdInitializerListElement(toStdInitializerList); 4533 return Result; 4534 } 4535 4536 // C++14 [over.ics.list]p4: 4537 // C++11 [over.ics.list]p3: 4538 // Otherwise, if the parameter is a non-aggregate class X and overload 4539 // resolution chooses a single best constructor [...] the implicit 4540 // conversion sequence is a user-defined conversion sequence. If multiple 4541 // constructors are viable but none is better than the others, the 4542 // implicit conversion sequence is a user-defined conversion sequence. 4543 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4544 // This function can deal with initializer lists. 4545 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4546 /*AllowExplicit=*/false, 4547 InOverloadResolution, /*CStyle=*/false, 4548 AllowObjCWritebackConversion, 4549 /*AllowObjCConversionOnExplicit=*/false); 4550 } 4551 4552 // C++14 [over.ics.list]p5: 4553 // C++11 [over.ics.list]p4: 4554 // Otherwise, if the parameter has an aggregate type which can be 4555 // initialized from the initializer list [...] the implicit conversion 4556 // sequence is a user-defined conversion sequence. 4557 if (ToType->isAggregateType()) { 4558 // Type is an aggregate, argument is an init list. At this point it comes 4559 // down to checking whether the initialization works. 4560 // FIXME: Find out whether this parameter is consumed or not. 4561 InitializedEntity Entity = 4562 InitializedEntity::InitializeParameter(S.Context, ToType, 4563 /*Consumed=*/false); 4564 if (S.CanPerformCopyInitialization(Entity, From)) { 4565 Result.setUserDefined(); 4566 Result.UserDefined.Before.setAsIdentityConversion(); 4567 // Initializer lists don't have a type. 4568 Result.UserDefined.Before.setFromType(QualType()); 4569 Result.UserDefined.Before.setAllToTypes(QualType()); 4570 4571 Result.UserDefined.After.setAsIdentityConversion(); 4572 Result.UserDefined.After.setFromType(ToType); 4573 Result.UserDefined.After.setAllToTypes(ToType); 4574 Result.UserDefined.ConversionFunction = nullptr; 4575 } 4576 return Result; 4577 } 4578 4579 // C++14 [over.ics.list]p6: 4580 // C++11 [over.ics.list]p5: 4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4582 if (ToType->isReferenceType()) { 4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4584 // mention initializer lists in any way. So we go by what list- 4585 // initialization would do and try to extrapolate from that. 4586 4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4588 4589 // If the initializer list has a single element that is reference-related 4590 // to the parameter type, we initialize the reference from that. 4591 if (From->getNumInits() == 1) { 4592 Expr *Init = From->getInit(0); 4593 4594 QualType T2 = Init->getType(); 4595 4596 // If the initializer is the address of an overloaded function, try 4597 // to resolve the overloaded function. If all goes well, T2 is the 4598 // type of the resulting function. 4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4600 DeclAccessPair Found; 4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4602 Init, ToType, false, Found)) 4603 T2 = Fn->getType(); 4604 } 4605 4606 // Compute some basic properties of the types and the initializer. 4607 bool dummy1 = false; 4608 bool dummy2 = false; 4609 bool dummy3 = false; 4610 Sema::ReferenceCompareResult RefRelationship 4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4612 dummy2, dummy3); 4613 4614 if (RefRelationship >= Sema::Ref_Related) { 4615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4616 SuppressUserConversions, 4617 /*AllowExplicit=*/false); 4618 } 4619 } 4620 4621 // Otherwise, we bind the reference to a temporary created from the 4622 // initializer list. 4623 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4624 InOverloadResolution, 4625 AllowObjCWritebackConversion); 4626 if (Result.isFailure()) 4627 return Result; 4628 assert(!Result.isEllipsis() && 4629 "Sub-initialization cannot result in ellipsis conversion."); 4630 4631 // Can we even bind to a temporary? 4632 if (ToType->isRValueReferenceType() || 4633 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4635 Result.UserDefined.After; 4636 SCS.ReferenceBinding = true; 4637 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4638 SCS.BindsToRvalue = true; 4639 SCS.BindsToFunctionLvalue = false; 4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4641 SCS.ObjCLifetimeConversionBinding = false; 4642 } else 4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4644 From, ToType); 4645 return Result; 4646 } 4647 4648 // C++14 [over.ics.list]p7: 4649 // C++11 [over.ics.list]p6: 4650 // Otherwise, if the parameter type is not a class: 4651 if (!ToType->isRecordType()) { 4652 // - if the initializer list has one element that is not itself an 4653 // initializer list, the implicit conversion sequence is the one 4654 // required to convert the element to the parameter type. 4655 unsigned NumInits = From->getNumInits(); 4656 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4657 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4658 SuppressUserConversions, 4659 InOverloadResolution, 4660 AllowObjCWritebackConversion); 4661 // - if the initializer list has no elements, the implicit conversion 4662 // sequence is the identity conversion. 4663 else if (NumInits == 0) { 4664 Result.setStandard(); 4665 Result.Standard.setAsIdentityConversion(); 4666 Result.Standard.setFromType(ToType); 4667 Result.Standard.setAllToTypes(ToType); 4668 } 4669 return Result; 4670 } 4671 4672 // C++14 [over.ics.list]p8: 4673 // C++11 [over.ics.list]p7: 4674 // In all cases other than those enumerated above, no conversion is possible 4675 return Result; 4676 } 4677 4678 /// TryCopyInitialization - Try to copy-initialize a value of type 4679 /// ToType from the expression From. Return the implicit conversion 4680 /// sequence required to pass this argument, which may be a bad 4681 /// conversion sequence (meaning that the argument cannot be passed to 4682 /// a parameter of this type). If @p SuppressUserConversions, then we 4683 /// do not permit any user-defined conversion sequences. 4684 static ImplicitConversionSequence 4685 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4686 bool SuppressUserConversions, 4687 bool InOverloadResolution, 4688 bool AllowObjCWritebackConversion, 4689 bool AllowExplicit) { 4690 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4691 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4692 InOverloadResolution,AllowObjCWritebackConversion); 4693 4694 if (ToType->isReferenceType()) 4695 return TryReferenceInit(S, From, ToType, 4696 /*FIXME:*/From->getLocStart(), 4697 SuppressUserConversions, 4698 AllowExplicit); 4699 4700 return TryImplicitConversion(S, From, ToType, 4701 SuppressUserConversions, 4702 /*AllowExplicit=*/false, 4703 InOverloadResolution, 4704 /*CStyle=*/false, 4705 AllowObjCWritebackConversion, 4706 /*AllowObjCConversionOnExplicit=*/false); 4707 } 4708 4709 static bool TryCopyInitialization(const CanQualType FromQTy, 4710 const CanQualType ToQTy, 4711 Sema &S, 4712 SourceLocation Loc, 4713 ExprValueKind FromVK) { 4714 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4715 ImplicitConversionSequence ICS = 4716 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4717 4718 return !ICS.isBad(); 4719 } 4720 4721 /// TryObjectArgumentInitialization - Try to initialize the object 4722 /// parameter of the given member function (@c Method) from the 4723 /// expression @p From. 4724 static ImplicitConversionSequence 4725 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4726 Expr::Classification FromClassification, 4727 CXXMethodDecl *Method, 4728 CXXRecordDecl *ActingContext) { 4729 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4730 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4731 // const volatile object. 4732 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4733 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4734 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4735 4736 // Set up the conversion sequence as a "bad" conversion, to allow us 4737 // to exit early. 4738 ImplicitConversionSequence ICS; 4739 4740 // We need to have an object of class type. 4741 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4742 FromType = PT->getPointeeType(); 4743 4744 // When we had a pointer, it's implicitly dereferenced, so we 4745 // better have an lvalue. 4746 assert(FromClassification.isLValue()); 4747 } 4748 4749 assert(FromType->isRecordType()); 4750 4751 // C++0x [over.match.funcs]p4: 4752 // For non-static member functions, the type of the implicit object 4753 // parameter is 4754 // 4755 // - "lvalue reference to cv X" for functions declared without a 4756 // ref-qualifier or with the & ref-qualifier 4757 // - "rvalue reference to cv X" for functions declared with the && 4758 // ref-qualifier 4759 // 4760 // where X is the class of which the function is a member and cv is the 4761 // cv-qualification on the member function declaration. 4762 // 4763 // However, when finding an implicit conversion sequence for the argument, we 4764 // are not allowed to create temporaries or perform user-defined conversions 4765 // (C++ [over.match.funcs]p5). We perform a simplified version of 4766 // reference binding here, that allows class rvalues to bind to 4767 // non-constant references. 4768 4769 // First check the qualifiers. 4770 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4771 if (ImplicitParamType.getCVRQualifiers() 4772 != FromTypeCanon.getLocalCVRQualifiers() && 4773 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4774 ICS.setBad(BadConversionSequence::bad_qualifiers, 4775 FromType, ImplicitParamType); 4776 return ICS; 4777 } 4778 4779 // Check that we have either the same type or a derived type. It 4780 // affects the conversion rank. 4781 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4782 ImplicitConversionKind SecondKind; 4783 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4784 SecondKind = ICK_Identity; 4785 } else if (S.IsDerivedFrom(FromType, ClassType)) 4786 SecondKind = ICK_Derived_To_Base; 4787 else { 4788 ICS.setBad(BadConversionSequence::unrelated_class, 4789 FromType, ImplicitParamType); 4790 return ICS; 4791 } 4792 4793 // Check the ref-qualifier. 4794 switch (Method->getRefQualifier()) { 4795 case RQ_None: 4796 // Do nothing; we don't care about lvalueness or rvalueness. 4797 break; 4798 4799 case RQ_LValue: 4800 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4801 // non-const lvalue reference cannot bind to an rvalue 4802 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4803 ImplicitParamType); 4804 return ICS; 4805 } 4806 break; 4807 4808 case RQ_RValue: 4809 if (!FromClassification.isRValue()) { 4810 // rvalue reference cannot bind to an lvalue 4811 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4812 ImplicitParamType); 4813 return ICS; 4814 } 4815 break; 4816 } 4817 4818 // Success. Mark this as a reference binding. 4819 ICS.setStandard(); 4820 ICS.Standard.setAsIdentityConversion(); 4821 ICS.Standard.Second = SecondKind; 4822 ICS.Standard.setFromType(FromType); 4823 ICS.Standard.setAllToTypes(ImplicitParamType); 4824 ICS.Standard.ReferenceBinding = true; 4825 ICS.Standard.DirectBinding = true; 4826 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4827 ICS.Standard.BindsToFunctionLvalue = false; 4828 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4830 = (Method->getRefQualifier() == RQ_None); 4831 return ICS; 4832 } 4833 4834 /// PerformObjectArgumentInitialization - Perform initialization of 4835 /// the implicit object parameter for the given Method with the given 4836 /// expression. 4837 ExprResult 4838 Sema::PerformObjectArgumentInitialization(Expr *From, 4839 NestedNameSpecifier *Qualifier, 4840 NamedDecl *FoundDecl, 4841 CXXMethodDecl *Method) { 4842 QualType FromRecordType, DestType; 4843 QualType ImplicitParamRecordType = 4844 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4845 4846 Expr::Classification FromClassification; 4847 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4848 FromRecordType = PT->getPointeeType(); 4849 DestType = Method->getThisType(Context); 4850 FromClassification = Expr::Classification::makeSimpleLValue(); 4851 } else { 4852 FromRecordType = From->getType(); 4853 DestType = ImplicitParamRecordType; 4854 FromClassification = From->Classify(Context); 4855 } 4856 4857 // Note that we always use the true parent context when performing 4858 // the actual argument initialization. 4859 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4860 *this, From->getType(), FromClassification, Method, Method->getParent()); 4861 if (ICS.isBad()) { 4862 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4863 Qualifiers FromQs = FromRecordType.getQualifiers(); 4864 Qualifiers ToQs = DestType.getQualifiers(); 4865 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4866 if (CVR) { 4867 Diag(From->getLocStart(), 4868 diag::err_member_function_call_bad_cvr) 4869 << Method->getDeclName() << FromRecordType << (CVR - 1) 4870 << From->getSourceRange(); 4871 Diag(Method->getLocation(), diag::note_previous_decl) 4872 << Method->getDeclName(); 4873 return ExprError(); 4874 } 4875 } 4876 4877 return Diag(From->getLocStart(), 4878 diag::err_implicit_object_parameter_init) 4879 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4880 } 4881 4882 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4883 ExprResult FromRes = 4884 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4885 if (FromRes.isInvalid()) 4886 return ExprError(); 4887 From = FromRes.get(); 4888 } 4889 4890 if (!Context.hasSameType(From->getType(), DestType)) 4891 From = ImpCastExprToType(From, DestType, CK_NoOp, 4892 From->getValueKind()).get(); 4893 return From; 4894 } 4895 4896 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4897 /// expression From to bool (C++0x [conv]p3). 4898 static ImplicitConversionSequence 4899 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4900 return TryImplicitConversion(S, From, S.Context.BoolTy, 4901 /*SuppressUserConversions=*/false, 4902 /*AllowExplicit=*/true, 4903 /*InOverloadResolution=*/false, 4904 /*CStyle=*/false, 4905 /*AllowObjCWritebackConversion=*/false, 4906 /*AllowObjCConversionOnExplicit=*/false); 4907 } 4908 4909 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4910 /// of the expression From to bool (C++0x [conv]p3). 4911 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4912 if (checkPlaceholderForOverload(*this, From)) 4913 return ExprError(); 4914 4915 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4916 if (!ICS.isBad()) 4917 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4918 4919 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4920 return Diag(From->getLocStart(), 4921 diag::err_typecheck_bool_condition) 4922 << From->getType() << From->getSourceRange(); 4923 return ExprError(); 4924 } 4925 4926 /// Check that the specified conversion is permitted in a converted constant 4927 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4928 /// is acceptable. 4929 static bool CheckConvertedConstantConversions(Sema &S, 4930 StandardConversionSequence &SCS) { 4931 // Since we know that the target type is an integral or unscoped enumeration 4932 // type, most conversion kinds are impossible. All possible First and Third 4933 // conversions are fine. 4934 switch (SCS.Second) { 4935 case ICK_Identity: 4936 case ICK_NoReturn_Adjustment: 4937 case ICK_Integral_Promotion: 4938 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4939 return true; 4940 4941 case ICK_Boolean_Conversion: 4942 // Conversion from an integral or unscoped enumeration type to bool is 4943 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4944 // conversion, so we allow it in a converted constant expression. 4945 // 4946 // FIXME: Per core issue 1407, we should not allow this, but that breaks 4947 // a lot of popular code. We should at least add a warning for this 4948 // (non-conforming) extension. 4949 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4950 SCS.getToType(2)->isBooleanType(); 4951 4952 case ICK_Pointer_Conversion: 4953 case ICK_Pointer_Member: 4954 // C++1z: null pointer conversions and null member pointer conversions are 4955 // only permitted if the source type is std::nullptr_t. 4956 return SCS.getFromType()->isNullPtrType(); 4957 4958 case ICK_Floating_Promotion: 4959 case ICK_Complex_Promotion: 4960 case ICK_Floating_Conversion: 4961 case ICK_Complex_Conversion: 4962 case ICK_Floating_Integral: 4963 case ICK_Compatible_Conversion: 4964 case ICK_Derived_To_Base: 4965 case ICK_Vector_Conversion: 4966 case ICK_Vector_Splat: 4967 case ICK_Complex_Real: 4968 case ICK_Block_Pointer_Conversion: 4969 case ICK_TransparentUnionConversion: 4970 case ICK_Writeback_Conversion: 4971 case ICK_Zero_Event_Conversion: 4972 return false; 4973 4974 case ICK_Lvalue_To_Rvalue: 4975 case ICK_Array_To_Pointer: 4976 case ICK_Function_To_Pointer: 4977 llvm_unreachable("found a first conversion kind in Second"); 4978 4979 case ICK_Qualification: 4980 llvm_unreachable("found a third conversion kind in Second"); 4981 4982 case ICK_Num_Conversion_Kinds: 4983 break; 4984 } 4985 4986 llvm_unreachable("unknown conversion kind"); 4987 } 4988 4989 /// CheckConvertedConstantExpression - Check that the expression From is a 4990 /// converted constant expression of type T, perform the conversion and produce 4991 /// the converted expression, per C++11 [expr.const]p3. 4992 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 4993 QualType T, APValue &Value, 4994 Sema::CCEKind CCE, 4995 bool RequireInt) { 4996 assert(S.getLangOpts().CPlusPlus11 && 4997 "converted constant expression outside C++11"); 4998 4999 if (checkPlaceholderForOverload(S, From)) 5000 return ExprError(); 5001 5002 // C++1z [expr.const]p3: 5003 // A converted constant expression of type T is an expression, 5004 // implicitly converted to type T, where the converted 5005 // expression is a constant expression and the implicit conversion 5006 // sequence contains only [... list of conversions ...]. 5007 ImplicitConversionSequence ICS = 5008 TryCopyInitialization(S, From, T, 5009 /*SuppressUserConversions=*/false, 5010 /*InOverloadResolution=*/false, 5011 /*AllowObjcWritebackConversion=*/false, 5012 /*AllowExplicit=*/false); 5013 StandardConversionSequence *SCS = nullptr; 5014 switch (ICS.getKind()) { 5015 case ImplicitConversionSequence::StandardConversion: 5016 SCS = &ICS.Standard; 5017 break; 5018 case ImplicitConversionSequence::UserDefinedConversion: 5019 // We are converting to a non-class type, so the Before sequence 5020 // must be trivial. 5021 SCS = &ICS.UserDefined.After; 5022 break; 5023 case ImplicitConversionSequence::AmbiguousConversion: 5024 case ImplicitConversionSequence::BadConversion: 5025 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5026 return S.Diag(From->getLocStart(), 5027 diag::err_typecheck_converted_constant_expression) 5028 << From->getType() << From->getSourceRange() << T; 5029 return ExprError(); 5030 5031 case ImplicitConversionSequence::EllipsisConversion: 5032 llvm_unreachable("ellipsis conversion in converted constant expression"); 5033 } 5034 5035 // Check that we would only use permitted conversions. 5036 if (!CheckConvertedConstantConversions(S, *SCS)) { 5037 return S.Diag(From->getLocStart(), 5038 diag::err_typecheck_converted_constant_expression_disallowed) 5039 << From->getType() << From->getSourceRange() << T; 5040 } 5041 // [...] and where the reference binding (if any) binds directly. 5042 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5043 return S.Diag(From->getLocStart(), 5044 diag::err_typecheck_converted_constant_expression_indirect) 5045 << From->getType() << From->getSourceRange() << T; 5046 } 5047 5048 ExprResult Result = 5049 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5050 if (Result.isInvalid()) 5051 return Result; 5052 5053 // Check for a narrowing implicit conversion. 5054 APValue PreNarrowingValue; 5055 QualType PreNarrowingType; 5056 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5057 PreNarrowingType)) { 5058 case NK_Variable_Narrowing: 5059 // Implicit conversion to a narrower type, and the value is not a constant 5060 // expression. We'll diagnose this in a moment. 5061 case NK_Not_Narrowing: 5062 break; 5063 5064 case NK_Constant_Narrowing: 5065 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5066 << CCE << /*Constant*/1 5067 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5068 break; 5069 5070 case NK_Type_Narrowing: 5071 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5072 << CCE << /*Constant*/0 << From->getType() << T; 5073 break; 5074 } 5075 5076 // Check the expression is a constant expression. 5077 SmallVector<PartialDiagnosticAt, 8> Notes; 5078 Expr::EvalResult Eval; 5079 Eval.Diag = &Notes; 5080 5081 if ((T->isReferenceType() 5082 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5083 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5084 (RequireInt && !Eval.Val.isInt())) { 5085 // The expression can't be folded, so we can't keep it at this position in 5086 // the AST. 5087 Result = ExprError(); 5088 } else { 5089 Value = Eval.Val; 5090 5091 if (Notes.empty()) { 5092 // It's a constant expression. 5093 return Result; 5094 } 5095 } 5096 5097 // It's not a constant expression. Produce an appropriate diagnostic. 5098 if (Notes.size() == 1 && 5099 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5100 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5101 else { 5102 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5103 << CCE << From->getSourceRange(); 5104 for (unsigned I = 0; I < Notes.size(); ++I) 5105 S.Diag(Notes[I].first, Notes[I].second); 5106 } 5107 return ExprError(); 5108 } 5109 5110 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5111 APValue &Value, CCEKind CCE) { 5112 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5113 } 5114 5115 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5116 llvm::APSInt &Value, 5117 CCEKind CCE) { 5118 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5119 5120 APValue V; 5121 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5122 if (!R.isInvalid()) 5123 Value = V.getInt(); 5124 return R; 5125 } 5126 5127 5128 /// dropPointerConversions - If the given standard conversion sequence 5129 /// involves any pointer conversions, remove them. This may change 5130 /// the result type of the conversion sequence. 5131 static void dropPointerConversion(StandardConversionSequence &SCS) { 5132 if (SCS.Second == ICK_Pointer_Conversion) { 5133 SCS.Second = ICK_Identity; 5134 SCS.Third = ICK_Identity; 5135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5136 } 5137 } 5138 5139 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5140 /// convert the expression From to an Objective-C pointer type. 5141 static ImplicitConversionSequence 5142 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5143 // Do an implicit conversion to 'id'. 5144 QualType Ty = S.Context.getObjCIdType(); 5145 ImplicitConversionSequence ICS 5146 = TryImplicitConversion(S, From, Ty, 5147 // FIXME: Are these flags correct? 5148 /*SuppressUserConversions=*/false, 5149 /*AllowExplicit=*/true, 5150 /*InOverloadResolution=*/false, 5151 /*CStyle=*/false, 5152 /*AllowObjCWritebackConversion=*/false, 5153 /*AllowObjCConversionOnExplicit=*/true); 5154 5155 // Strip off any final conversions to 'id'. 5156 switch (ICS.getKind()) { 5157 case ImplicitConversionSequence::BadConversion: 5158 case ImplicitConversionSequence::AmbiguousConversion: 5159 case ImplicitConversionSequence::EllipsisConversion: 5160 break; 5161 5162 case ImplicitConversionSequence::UserDefinedConversion: 5163 dropPointerConversion(ICS.UserDefined.After); 5164 break; 5165 5166 case ImplicitConversionSequence::StandardConversion: 5167 dropPointerConversion(ICS.Standard); 5168 break; 5169 } 5170 5171 return ICS; 5172 } 5173 5174 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5175 /// conversion of the expression From to an Objective-C pointer type. 5176 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5177 if (checkPlaceholderForOverload(*this, From)) 5178 return ExprError(); 5179 5180 QualType Ty = Context.getObjCIdType(); 5181 ImplicitConversionSequence ICS = 5182 TryContextuallyConvertToObjCPointer(*this, From); 5183 if (!ICS.isBad()) 5184 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5185 return ExprError(); 5186 } 5187 5188 /// Determine whether the provided type is an integral type, or an enumeration 5189 /// type of a permitted flavor. 5190 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5191 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5192 : T->isIntegralOrUnscopedEnumerationType(); 5193 } 5194 5195 static ExprResult 5196 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5197 Sema::ContextualImplicitConverter &Converter, 5198 QualType T, UnresolvedSetImpl &ViableConversions) { 5199 5200 if (Converter.Suppress) 5201 return ExprError(); 5202 5203 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5205 CXXConversionDecl *Conv = 5206 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5207 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5208 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5209 } 5210 return From; 5211 } 5212 5213 static bool 5214 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5215 Sema::ContextualImplicitConverter &Converter, 5216 QualType T, bool HadMultipleCandidates, 5217 UnresolvedSetImpl &ExplicitConversions) { 5218 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5219 DeclAccessPair Found = ExplicitConversions[0]; 5220 CXXConversionDecl *Conversion = 5221 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5222 5223 // The user probably meant to invoke the given explicit 5224 // conversion; use it. 5225 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5226 std::string TypeStr; 5227 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5228 5229 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5230 << FixItHint::CreateInsertion(From->getLocStart(), 5231 "static_cast<" + TypeStr + ">(") 5232 << FixItHint::CreateInsertion( 5233 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5234 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5235 5236 // If we aren't in a SFINAE context, build a call to the 5237 // explicit conversion function. 5238 if (SemaRef.isSFINAEContext()) 5239 return true; 5240 5241 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5242 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5243 HadMultipleCandidates); 5244 if (Result.isInvalid()) 5245 return true; 5246 // Record usage of conversion in an implicit cast. 5247 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5248 CK_UserDefinedConversion, Result.get(), 5249 nullptr, Result.get()->getValueKind()); 5250 } 5251 return false; 5252 } 5253 5254 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5255 Sema::ContextualImplicitConverter &Converter, 5256 QualType T, bool HadMultipleCandidates, 5257 DeclAccessPair &Found) { 5258 CXXConversionDecl *Conversion = 5259 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5260 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5261 5262 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5263 if (!Converter.SuppressConversion) { 5264 if (SemaRef.isSFINAEContext()) 5265 return true; 5266 5267 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5268 << From->getSourceRange(); 5269 } 5270 5271 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5272 HadMultipleCandidates); 5273 if (Result.isInvalid()) 5274 return true; 5275 // Record usage of conversion in an implicit cast. 5276 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5277 CK_UserDefinedConversion, Result.get(), 5278 nullptr, Result.get()->getValueKind()); 5279 return false; 5280 } 5281 5282 static ExprResult finishContextualImplicitConversion( 5283 Sema &SemaRef, SourceLocation Loc, Expr *From, 5284 Sema::ContextualImplicitConverter &Converter) { 5285 if (!Converter.match(From->getType()) && !Converter.Suppress) 5286 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5287 << From->getSourceRange(); 5288 5289 return SemaRef.DefaultLvalueConversion(From); 5290 } 5291 5292 static void 5293 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5294 UnresolvedSetImpl &ViableConversions, 5295 OverloadCandidateSet &CandidateSet) { 5296 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5297 DeclAccessPair FoundDecl = ViableConversions[I]; 5298 NamedDecl *D = FoundDecl.getDecl(); 5299 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5300 if (isa<UsingShadowDecl>(D)) 5301 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5302 5303 CXXConversionDecl *Conv; 5304 FunctionTemplateDecl *ConvTemplate; 5305 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5306 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5307 else 5308 Conv = cast<CXXConversionDecl>(D); 5309 5310 if (ConvTemplate) 5311 SemaRef.AddTemplateConversionCandidate( 5312 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5313 /*AllowObjCConversionOnExplicit=*/false); 5314 else 5315 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5316 ToType, CandidateSet, 5317 /*AllowObjCConversionOnExplicit=*/false); 5318 } 5319 } 5320 5321 /// \brief Attempt to convert the given expression to a type which is accepted 5322 /// by the given converter. 5323 /// 5324 /// This routine will attempt to convert an expression of class type to a 5325 /// type accepted by the specified converter. In C++11 and before, the class 5326 /// must have a single non-explicit conversion function converting to a matching 5327 /// type. In C++1y, there can be multiple such conversion functions, but only 5328 /// one target type. 5329 /// 5330 /// \param Loc The source location of the construct that requires the 5331 /// conversion. 5332 /// 5333 /// \param From The expression we're converting from. 5334 /// 5335 /// \param Converter Used to control and diagnose the conversion process. 5336 /// 5337 /// \returns The expression, converted to an integral or enumeration type if 5338 /// successful. 5339 ExprResult Sema::PerformContextualImplicitConversion( 5340 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5341 // We can't perform any more checking for type-dependent expressions. 5342 if (From->isTypeDependent()) 5343 return From; 5344 5345 // Process placeholders immediately. 5346 if (From->hasPlaceholderType()) { 5347 ExprResult result = CheckPlaceholderExpr(From); 5348 if (result.isInvalid()) 5349 return result; 5350 From = result.get(); 5351 } 5352 5353 // If the expression already has a matching type, we're golden. 5354 QualType T = From->getType(); 5355 if (Converter.match(T)) 5356 return DefaultLvalueConversion(From); 5357 5358 // FIXME: Check for missing '()' if T is a function type? 5359 5360 // We can only perform contextual implicit conversions on objects of class 5361 // type. 5362 const RecordType *RecordTy = T->getAs<RecordType>(); 5363 if (!RecordTy || !getLangOpts().CPlusPlus) { 5364 if (!Converter.Suppress) 5365 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5366 return From; 5367 } 5368 5369 // We must have a complete class type. 5370 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5371 ContextualImplicitConverter &Converter; 5372 Expr *From; 5373 5374 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5375 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5376 5377 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5378 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5379 } 5380 } IncompleteDiagnoser(Converter, From); 5381 5382 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5383 return From; 5384 5385 // Look for a conversion to an integral or enumeration type. 5386 UnresolvedSet<4> 5387 ViableConversions; // These are *potentially* viable in C++1y. 5388 UnresolvedSet<4> ExplicitConversions; 5389 const auto &Conversions = 5390 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5391 5392 bool HadMultipleCandidates = 5393 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5394 5395 // To check that there is only one target type, in C++1y: 5396 QualType ToType; 5397 bool HasUniqueTargetType = true; 5398 5399 // Collect explicit or viable (potentially in C++1y) conversions. 5400 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5401 NamedDecl *D = (*I)->getUnderlyingDecl(); 5402 CXXConversionDecl *Conversion; 5403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5404 if (ConvTemplate) { 5405 if (getLangOpts().CPlusPlus14) 5406 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5407 else 5408 continue; // C++11 does not consider conversion operator templates(?). 5409 } else 5410 Conversion = cast<CXXConversionDecl>(D); 5411 5412 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5413 "Conversion operator templates are considered potentially " 5414 "viable in C++1y"); 5415 5416 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5417 if (Converter.match(CurToType) || ConvTemplate) { 5418 5419 if (Conversion->isExplicit()) { 5420 // FIXME: For C++1y, do we need this restriction? 5421 // cf. diagnoseNoViableConversion() 5422 if (!ConvTemplate) 5423 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5424 } else { 5425 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5426 if (ToType.isNull()) 5427 ToType = CurToType.getUnqualifiedType(); 5428 else if (HasUniqueTargetType && 5429 (CurToType.getUnqualifiedType() != ToType)) 5430 HasUniqueTargetType = false; 5431 } 5432 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5433 } 5434 } 5435 } 5436 5437 if (getLangOpts().CPlusPlus14) { 5438 // C++1y [conv]p6: 5439 // ... An expression e of class type E appearing in such a context 5440 // is said to be contextually implicitly converted to a specified 5441 // type T and is well-formed if and only if e can be implicitly 5442 // converted to a type T that is determined as follows: E is searched 5443 // for conversion functions whose return type is cv T or reference to 5444 // cv T such that T is allowed by the context. There shall be 5445 // exactly one such T. 5446 5447 // If no unique T is found: 5448 if (ToType.isNull()) { 5449 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5450 HadMultipleCandidates, 5451 ExplicitConversions)) 5452 return ExprError(); 5453 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5454 } 5455 5456 // If more than one unique Ts are found: 5457 if (!HasUniqueTargetType) 5458 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5459 ViableConversions); 5460 5461 // If one unique T is found: 5462 // First, build a candidate set from the previously recorded 5463 // potentially viable conversions. 5464 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5465 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5466 CandidateSet); 5467 5468 // Then, perform overload resolution over the candidate set. 5469 OverloadCandidateSet::iterator Best; 5470 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5471 case OR_Success: { 5472 // Apply this conversion. 5473 DeclAccessPair Found = 5474 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5475 if (recordConversion(*this, Loc, From, Converter, T, 5476 HadMultipleCandidates, Found)) 5477 return ExprError(); 5478 break; 5479 } 5480 case OR_Ambiguous: 5481 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5482 ViableConversions); 5483 case OR_No_Viable_Function: 5484 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5485 HadMultipleCandidates, 5486 ExplicitConversions)) 5487 return ExprError(); 5488 // fall through 'OR_Deleted' case. 5489 case OR_Deleted: 5490 // We'll complain below about a non-integral condition type. 5491 break; 5492 } 5493 } else { 5494 switch (ViableConversions.size()) { 5495 case 0: { 5496 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5497 HadMultipleCandidates, 5498 ExplicitConversions)) 5499 return ExprError(); 5500 5501 // We'll complain below about a non-integral condition type. 5502 break; 5503 } 5504 case 1: { 5505 // Apply this conversion. 5506 DeclAccessPair Found = ViableConversions[0]; 5507 if (recordConversion(*this, Loc, From, Converter, T, 5508 HadMultipleCandidates, Found)) 5509 return ExprError(); 5510 break; 5511 } 5512 default: 5513 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5514 ViableConversions); 5515 } 5516 } 5517 5518 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5519 } 5520 5521 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5522 /// an acceptable non-member overloaded operator for a call whose 5523 /// arguments have types T1 (and, if non-empty, T2). This routine 5524 /// implements the check in C++ [over.match.oper]p3b2 concerning 5525 /// enumeration types. 5526 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5527 FunctionDecl *Fn, 5528 ArrayRef<Expr *> Args) { 5529 QualType T1 = Args[0]->getType(); 5530 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5531 5532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5533 return true; 5534 5535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5536 return true; 5537 5538 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5539 if (Proto->getNumParams() < 1) 5540 return false; 5541 5542 if (T1->isEnumeralType()) { 5543 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5544 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5545 return true; 5546 } 5547 5548 if (Proto->getNumParams() < 2) 5549 return false; 5550 5551 if (!T2.isNull() && T2->isEnumeralType()) { 5552 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5553 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5554 return true; 5555 } 5556 5557 return false; 5558 } 5559 5560 /// AddOverloadCandidate - Adds the given function to the set of 5561 /// candidate functions, using the given function call arguments. If 5562 /// @p SuppressUserConversions, then don't allow user-defined 5563 /// conversions via constructors or conversion operators. 5564 /// 5565 /// \param PartialOverloading true if we are performing "partial" overloading 5566 /// based on an incomplete set of function arguments. This feature is used by 5567 /// code completion. 5568 void 5569 Sema::AddOverloadCandidate(FunctionDecl *Function, 5570 DeclAccessPair FoundDecl, 5571 ArrayRef<Expr *> Args, 5572 OverloadCandidateSet &CandidateSet, 5573 bool SuppressUserConversions, 5574 bool PartialOverloading, 5575 bool AllowExplicit) { 5576 const FunctionProtoType *Proto 5577 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5578 assert(Proto && "Functions without a prototype cannot be overloaded"); 5579 assert(!Function->getDescribedFunctionTemplate() && 5580 "Use AddTemplateOverloadCandidate for function templates"); 5581 5582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5583 if (!isa<CXXConstructorDecl>(Method)) { 5584 // If we get here, it's because we're calling a member function 5585 // that is named without a member access expression (e.g., 5586 // "this->f") that was either written explicitly or created 5587 // implicitly. This can happen with a qualified call to a member 5588 // function, e.g., X::f(). We use an empty type for the implied 5589 // object argument (C++ [over.call.func]p3), and the acting context 5590 // is irrelevant. 5591 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5592 QualType(), Expr::Classification::makeSimpleLValue(), 5593 Args, CandidateSet, SuppressUserConversions, 5594 PartialOverloading); 5595 return; 5596 } 5597 // We treat a constructor like a non-member function, since its object 5598 // argument doesn't participate in overload resolution. 5599 } 5600 5601 if (!CandidateSet.isNewCandidate(Function)) 5602 return; 5603 5604 // C++ [over.match.oper]p3: 5605 // if no operand has a class type, only those non-member functions in the 5606 // lookup set that have a first parameter of type T1 or "reference to 5607 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5608 // is a right operand) a second parameter of type T2 or "reference to 5609 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5610 // candidate functions. 5611 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5612 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5613 return; 5614 5615 // C++11 [class.copy]p11: [DR1402] 5616 // A defaulted move constructor that is defined as deleted is ignored by 5617 // overload resolution. 5618 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5619 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5620 Constructor->isMoveConstructor()) 5621 return; 5622 5623 // Overload resolution is always an unevaluated context. 5624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5625 5626 // Add this candidate 5627 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5628 Candidate.FoundDecl = FoundDecl; 5629 Candidate.Function = Function; 5630 Candidate.Viable = true; 5631 Candidate.IsSurrogate = false; 5632 Candidate.IgnoreObjectArgument = false; 5633 Candidate.ExplicitCallArguments = Args.size(); 5634 5635 if (Constructor) { 5636 // C++ [class.copy]p3: 5637 // A member function template is never instantiated to perform the copy 5638 // of a class object to an object of its class type. 5639 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5640 if (Args.size() == 1 && 5641 Constructor->isSpecializationCopyingObject() && 5642 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5643 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5644 Candidate.Viable = false; 5645 Candidate.FailureKind = ovl_fail_illegal_constructor; 5646 return; 5647 } 5648 } 5649 5650 unsigned NumParams = Proto->getNumParams(); 5651 5652 // (C++ 13.3.2p2): A candidate function having fewer than m 5653 // parameters is viable only if it has an ellipsis in its parameter 5654 // list (8.3.5). 5655 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5656 !Proto->isVariadic()) { 5657 Candidate.Viable = false; 5658 Candidate.FailureKind = ovl_fail_too_many_arguments; 5659 return; 5660 } 5661 5662 // (C++ 13.3.2p2): A candidate function having more than m parameters 5663 // is viable only if the (m+1)st parameter has a default argument 5664 // (8.3.6). For the purposes of overload resolution, the 5665 // parameter list is truncated on the right, so that there are 5666 // exactly m parameters. 5667 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5668 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5669 // Not enough arguments. 5670 Candidate.Viable = false; 5671 Candidate.FailureKind = ovl_fail_too_few_arguments; 5672 return; 5673 } 5674 5675 // (CUDA B.1): Check for invalid calls between targets. 5676 if (getLangOpts().CUDA) 5677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5678 // Skip the check for callers that are implicit members, because in this 5679 // case we may not yet know what the member's target is; the target is 5680 // inferred for the member automatically, based on the bases and fields of 5681 // the class. 5682 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5683 Candidate.Viable = false; 5684 Candidate.FailureKind = ovl_fail_bad_target; 5685 return; 5686 } 5687 5688 // Determine the implicit conversion sequences for each of the 5689 // arguments. 5690 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5691 if (ArgIdx < NumParams) { 5692 // (C++ 13.3.2p3): for F to be a viable function, there shall 5693 // exist for each argument an implicit conversion sequence 5694 // (13.3.3.1) that converts that argument to the corresponding 5695 // parameter of F. 5696 QualType ParamType = Proto->getParamType(ArgIdx); 5697 Candidate.Conversions[ArgIdx] 5698 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5699 SuppressUserConversions, 5700 /*InOverloadResolution=*/true, 5701 /*AllowObjCWritebackConversion=*/ 5702 getLangOpts().ObjCAutoRefCount, 5703 AllowExplicit); 5704 if (Candidate.Conversions[ArgIdx].isBad()) { 5705 Candidate.Viable = false; 5706 Candidate.FailureKind = ovl_fail_bad_conversion; 5707 return; 5708 } 5709 } else { 5710 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5711 // argument for which there is no corresponding parameter is 5712 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5713 Candidate.Conversions[ArgIdx].setEllipsis(); 5714 } 5715 } 5716 5717 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5718 Candidate.Viable = false; 5719 Candidate.FailureKind = ovl_fail_enable_if; 5720 Candidate.DeductionFailure.Data = FailedAttr; 5721 return; 5722 } 5723 } 5724 5725 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5726 bool IsInstance) { 5727 SmallVector<ObjCMethodDecl*, 4> Methods; 5728 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5729 return nullptr; 5730 5731 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5732 bool Match = true; 5733 ObjCMethodDecl *Method = Methods[b]; 5734 unsigned NumNamedArgs = Sel.getNumArgs(); 5735 // Method might have more arguments than selector indicates. This is due 5736 // to addition of c-style arguments in method. 5737 if (Method->param_size() > NumNamedArgs) 5738 NumNamedArgs = Method->param_size(); 5739 if (Args.size() < NumNamedArgs) 5740 continue; 5741 5742 for (unsigned i = 0; i < NumNamedArgs; i++) { 5743 // We can't do any type-checking on a type-dependent argument. 5744 if (Args[i]->isTypeDependent()) { 5745 Match = false; 5746 break; 5747 } 5748 5749 ParmVarDecl *param = Method->parameters()[i]; 5750 Expr *argExpr = Args[i]; 5751 assert(argExpr && "SelectBestMethod(): missing expression"); 5752 5753 // Strip the unbridged-cast placeholder expression off unless it's 5754 // a consumed argument. 5755 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5756 !param->hasAttr<CFConsumedAttr>()) 5757 argExpr = stripARCUnbridgedCast(argExpr); 5758 5759 // If the parameter is __unknown_anytype, move on to the next method. 5760 if (param->getType() == Context.UnknownAnyTy) { 5761 Match = false; 5762 break; 5763 } 5764 5765 ImplicitConversionSequence ConversionState 5766 = TryCopyInitialization(*this, argExpr, param->getType(), 5767 /*SuppressUserConversions*/false, 5768 /*InOverloadResolution=*/true, 5769 /*AllowObjCWritebackConversion=*/ 5770 getLangOpts().ObjCAutoRefCount, 5771 /*AllowExplicit*/false); 5772 if (ConversionState.isBad()) { 5773 Match = false; 5774 break; 5775 } 5776 } 5777 // Promote additional arguments to variadic methods. 5778 if (Match && Method->isVariadic()) { 5779 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5780 if (Args[i]->isTypeDependent()) { 5781 Match = false; 5782 break; 5783 } 5784 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5785 nullptr); 5786 if (Arg.isInvalid()) { 5787 Match = false; 5788 break; 5789 } 5790 } 5791 } else { 5792 // Check for extra arguments to non-variadic methods. 5793 if (Args.size() != NumNamedArgs) 5794 Match = false; 5795 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5796 // Special case when selectors have no argument. In this case, select 5797 // one with the most general result type of 'id'. 5798 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5799 QualType ReturnT = Methods[b]->getReturnType(); 5800 if (ReturnT->isObjCIdType()) 5801 return Methods[b]; 5802 } 5803 } 5804 } 5805 5806 if (Match) 5807 return Method; 5808 } 5809 return nullptr; 5810 } 5811 5812 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5813 5814 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5815 bool MissingImplicitThis) { 5816 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5817 // we need to find the first failing one. 5818 if (!Function->hasAttrs()) 5819 return nullptr; 5820 AttrVec Attrs = Function->getAttrs(); 5821 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5822 IsNotEnableIfAttr); 5823 if (Attrs.begin() == E) 5824 return nullptr; 5825 std::reverse(Attrs.begin(), E); 5826 5827 SFINAETrap Trap(*this); 5828 5829 SmallVector<Expr *, 16> ConvertedArgs; 5830 bool InitializationFailed = false; 5831 bool ContainsValueDependentExpr = false; 5832 5833 // Convert the arguments. 5834 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5835 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5836 !cast<CXXMethodDecl>(Function)->isStatic() && 5837 !isa<CXXConstructorDecl>(Function)) { 5838 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5839 ExprResult R = 5840 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5841 Method, Method); 5842 if (R.isInvalid()) { 5843 InitializationFailed = true; 5844 break; 5845 } 5846 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5847 ConvertedArgs.push_back(R.get()); 5848 } else { 5849 ExprResult R = 5850 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5851 Context, 5852 Function->getParamDecl(i)), 5853 SourceLocation(), 5854 Args[i]); 5855 if (R.isInvalid()) { 5856 InitializationFailed = true; 5857 break; 5858 } 5859 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5860 ConvertedArgs.push_back(R.get()); 5861 } 5862 } 5863 5864 if (InitializationFailed || Trap.hasErrorOccurred()) 5865 return cast<EnableIfAttr>(Attrs[0]); 5866 5867 // Push default arguments if needed. 5868 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5869 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5870 ParmVarDecl *P = Function->getParamDecl(i); 5871 ExprResult R = PerformCopyInitialization( 5872 InitializedEntity::InitializeParameter(Context, 5873 Function->getParamDecl(i)), 5874 SourceLocation(), 5875 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5876 : P->getDefaultArg()); 5877 if (R.isInvalid()) { 5878 InitializationFailed = true; 5879 break; 5880 } 5881 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5882 ConvertedArgs.push_back(R.get()); 5883 } 5884 5885 if (InitializationFailed || Trap.hasErrorOccurred()) 5886 return cast<EnableIfAttr>(Attrs[0]); 5887 } 5888 5889 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5890 APValue Result; 5891 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5892 if (EIA->getCond()->isValueDependent()) { 5893 // Don't even try now, we'll examine it after instantiation. 5894 continue; 5895 } 5896 5897 if (!EIA->getCond()->EvaluateWithSubstitution( 5898 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5899 if (!ContainsValueDependentExpr) 5900 return EIA; 5901 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5902 return EIA; 5903 } 5904 } 5905 return nullptr; 5906 } 5907 5908 /// \brief Add all of the function declarations in the given function set to 5909 /// the overload candidate set. 5910 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5911 ArrayRef<Expr *> Args, 5912 OverloadCandidateSet& CandidateSet, 5913 TemplateArgumentListInfo *ExplicitTemplateArgs, 5914 bool SuppressUserConversions, 5915 bool PartialOverloading) { 5916 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5917 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5918 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5919 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5920 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5921 cast<CXXMethodDecl>(FD)->getParent(), 5922 Args[0]->getType(), Args[0]->Classify(Context), 5923 Args.slice(1), CandidateSet, 5924 SuppressUserConversions, PartialOverloading); 5925 else 5926 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5927 SuppressUserConversions, PartialOverloading); 5928 } else { 5929 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5930 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5931 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5932 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5933 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5934 ExplicitTemplateArgs, 5935 Args[0]->getType(), 5936 Args[0]->Classify(Context), Args.slice(1), 5937 CandidateSet, SuppressUserConversions, 5938 PartialOverloading); 5939 else 5940 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5941 ExplicitTemplateArgs, Args, 5942 CandidateSet, SuppressUserConversions, 5943 PartialOverloading); 5944 } 5945 } 5946 } 5947 5948 /// AddMethodCandidate - Adds a named decl (which is some kind of 5949 /// method) as a method candidate to the given overload set. 5950 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5951 QualType ObjectType, 5952 Expr::Classification ObjectClassification, 5953 ArrayRef<Expr *> Args, 5954 OverloadCandidateSet& CandidateSet, 5955 bool SuppressUserConversions) { 5956 NamedDecl *Decl = FoundDecl.getDecl(); 5957 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5958 5959 if (isa<UsingShadowDecl>(Decl)) 5960 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5961 5962 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5963 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5964 "Expected a member function template"); 5965 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5966 /*ExplicitArgs*/ nullptr, 5967 ObjectType, ObjectClassification, 5968 Args, CandidateSet, 5969 SuppressUserConversions); 5970 } else { 5971 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5972 ObjectType, ObjectClassification, 5973 Args, 5974 CandidateSet, SuppressUserConversions); 5975 } 5976 } 5977 5978 /// AddMethodCandidate - Adds the given C++ member function to the set 5979 /// of candidate functions, using the given function call arguments 5980 /// and the object argument (@c Object). For example, in a call 5981 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5982 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5983 /// allow user-defined conversions via constructors or conversion 5984 /// operators. 5985 void 5986 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5987 CXXRecordDecl *ActingContext, QualType ObjectType, 5988 Expr::Classification ObjectClassification, 5989 ArrayRef<Expr *> Args, 5990 OverloadCandidateSet &CandidateSet, 5991 bool SuppressUserConversions, 5992 bool PartialOverloading) { 5993 const FunctionProtoType *Proto 5994 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5995 assert(Proto && "Methods without a prototype cannot be overloaded"); 5996 assert(!isa<CXXConstructorDecl>(Method) && 5997 "Use AddOverloadCandidate for constructors"); 5998 5999 if (!CandidateSet.isNewCandidate(Method)) 6000 return; 6001 6002 // C++11 [class.copy]p23: [DR1402] 6003 // A defaulted move assignment operator that is defined as deleted is 6004 // ignored by overload resolution. 6005 if (Method->isDefaulted() && Method->isDeleted() && 6006 Method->isMoveAssignmentOperator()) 6007 return; 6008 6009 // Overload resolution is always an unevaluated context. 6010 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6011 6012 // Add this candidate 6013 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6014 Candidate.FoundDecl = FoundDecl; 6015 Candidate.Function = Method; 6016 Candidate.IsSurrogate = false; 6017 Candidate.IgnoreObjectArgument = false; 6018 Candidate.ExplicitCallArguments = Args.size(); 6019 6020 unsigned NumParams = Proto->getNumParams(); 6021 6022 // (C++ 13.3.2p2): A candidate function having fewer than m 6023 // parameters is viable only if it has an ellipsis in its parameter 6024 // list (8.3.5). 6025 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6026 !Proto->isVariadic()) { 6027 Candidate.Viable = false; 6028 Candidate.FailureKind = ovl_fail_too_many_arguments; 6029 return; 6030 } 6031 6032 // (C++ 13.3.2p2): A candidate function having more than m parameters 6033 // is viable only if the (m+1)st parameter has a default argument 6034 // (8.3.6). For the purposes of overload resolution, the 6035 // parameter list is truncated on the right, so that there are 6036 // exactly m parameters. 6037 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6038 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6039 // Not enough arguments. 6040 Candidate.Viable = false; 6041 Candidate.FailureKind = ovl_fail_too_few_arguments; 6042 return; 6043 } 6044 6045 Candidate.Viable = true; 6046 6047 if (Method->isStatic() || ObjectType.isNull()) 6048 // The implicit object argument is ignored. 6049 Candidate.IgnoreObjectArgument = true; 6050 else { 6051 // Determine the implicit conversion sequence for the object 6052 // parameter. 6053 Candidate.Conversions[0] 6054 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6055 Method, ActingContext); 6056 if (Candidate.Conversions[0].isBad()) { 6057 Candidate.Viable = false; 6058 Candidate.FailureKind = ovl_fail_bad_conversion; 6059 return; 6060 } 6061 } 6062 6063 // (CUDA B.1): Check for invalid calls between targets. 6064 if (getLangOpts().CUDA) 6065 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6066 if (CheckCUDATarget(Caller, Method)) { 6067 Candidate.Viable = false; 6068 Candidate.FailureKind = ovl_fail_bad_target; 6069 return; 6070 } 6071 6072 // Determine the implicit conversion sequences for each of the 6073 // arguments. 6074 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6075 if (ArgIdx < NumParams) { 6076 // (C++ 13.3.2p3): for F to be a viable function, there shall 6077 // exist for each argument an implicit conversion sequence 6078 // (13.3.3.1) that converts that argument to the corresponding 6079 // parameter of F. 6080 QualType ParamType = Proto->getParamType(ArgIdx); 6081 Candidate.Conversions[ArgIdx + 1] 6082 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6083 SuppressUserConversions, 6084 /*InOverloadResolution=*/true, 6085 /*AllowObjCWritebackConversion=*/ 6086 getLangOpts().ObjCAutoRefCount); 6087 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6088 Candidate.Viable = false; 6089 Candidate.FailureKind = ovl_fail_bad_conversion; 6090 return; 6091 } 6092 } else { 6093 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6094 // argument for which there is no corresponding parameter is 6095 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6096 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6097 } 6098 } 6099 6100 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6101 Candidate.Viable = false; 6102 Candidate.FailureKind = ovl_fail_enable_if; 6103 Candidate.DeductionFailure.Data = FailedAttr; 6104 return; 6105 } 6106 } 6107 6108 /// \brief Add a C++ member function template as a candidate to the candidate 6109 /// set, using template argument deduction to produce an appropriate member 6110 /// function template specialization. 6111 void 6112 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6113 DeclAccessPair FoundDecl, 6114 CXXRecordDecl *ActingContext, 6115 TemplateArgumentListInfo *ExplicitTemplateArgs, 6116 QualType ObjectType, 6117 Expr::Classification ObjectClassification, 6118 ArrayRef<Expr *> Args, 6119 OverloadCandidateSet& CandidateSet, 6120 bool SuppressUserConversions, 6121 bool PartialOverloading) { 6122 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6123 return; 6124 6125 // C++ [over.match.funcs]p7: 6126 // In each case where a candidate is a function template, candidate 6127 // function template specializations are generated using template argument 6128 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6129 // candidate functions in the usual way.113) A given name can refer to one 6130 // or more function templates and also to a set of overloaded non-template 6131 // functions. In such a case, the candidate functions generated from each 6132 // function template are combined with the set of non-template candidate 6133 // functions. 6134 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6135 FunctionDecl *Specialization = nullptr; 6136 if (TemplateDeductionResult Result 6137 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6138 Specialization, Info, PartialOverloading)) { 6139 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6140 Candidate.FoundDecl = FoundDecl; 6141 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6142 Candidate.Viable = false; 6143 Candidate.FailureKind = ovl_fail_bad_deduction; 6144 Candidate.IsSurrogate = false; 6145 Candidate.IgnoreObjectArgument = false; 6146 Candidate.ExplicitCallArguments = Args.size(); 6147 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6148 Info); 6149 return; 6150 } 6151 6152 // Add the function template specialization produced by template argument 6153 // deduction as a candidate. 6154 assert(Specialization && "Missing member function template specialization?"); 6155 assert(isa<CXXMethodDecl>(Specialization) && 6156 "Specialization is not a member function?"); 6157 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6158 ActingContext, ObjectType, ObjectClassification, Args, 6159 CandidateSet, SuppressUserConversions, PartialOverloading); 6160 } 6161 6162 /// \brief Add a C++ function template specialization as a candidate 6163 /// in the candidate set, using template argument deduction to produce 6164 /// an appropriate function template specialization. 6165 void 6166 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6167 DeclAccessPair FoundDecl, 6168 TemplateArgumentListInfo *ExplicitTemplateArgs, 6169 ArrayRef<Expr *> Args, 6170 OverloadCandidateSet& CandidateSet, 6171 bool SuppressUserConversions, 6172 bool PartialOverloading) { 6173 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6174 return; 6175 6176 // C++ [over.match.funcs]p7: 6177 // In each case where a candidate is a function template, candidate 6178 // function template specializations are generated using template argument 6179 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6180 // candidate functions in the usual way.113) A given name can refer to one 6181 // or more function templates and also to a set of overloaded non-template 6182 // functions. In such a case, the candidate functions generated from each 6183 // function template are combined with the set of non-template candidate 6184 // functions. 6185 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6186 FunctionDecl *Specialization = nullptr; 6187 if (TemplateDeductionResult Result 6188 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6189 Specialization, Info, PartialOverloading)) { 6190 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6191 Candidate.FoundDecl = FoundDecl; 6192 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6193 Candidate.Viable = false; 6194 Candidate.FailureKind = ovl_fail_bad_deduction; 6195 Candidate.IsSurrogate = false; 6196 Candidate.IgnoreObjectArgument = false; 6197 Candidate.ExplicitCallArguments = Args.size(); 6198 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6199 Info); 6200 return; 6201 } 6202 6203 // Add the function template specialization produced by template argument 6204 // deduction as a candidate. 6205 assert(Specialization && "Missing function template specialization?"); 6206 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6207 SuppressUserConversions, PartialOverloading); 6208 } 6209 6210 /// Determine whether this is an allowable conversion from the result 6211 /// of an explicit conversion operator to the expected type, per C++ 6212 /// [over.match.conv]p1 and [over.match.ref]p1. 6213 /// 6214 /// \param ConvType The return type of the conversion function. 6215 /// 6216 /// \param ToType The type we are converting to. 6217 /// 6218 /// \param AllowObjCPointerConversion Allow a conversion from one 6219 /// Objective-C pointer to another. 6220 /// 6221 /// \returns true if the conversion is allowable, false otherwise. 6222 static bool isAllowableExplicitConversion(Sema &S, 6223 QualType ConvType, QualType ToType, 6224 bool AllowObjCPointerConversion) { 6225 QualType ToNonRefType = ToType.getNonReferenceType(); 6226 6227 // Easy case: the types are the same. 6228 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6229 return true; 6230 6231 // Allow qualification conversions. 6232 bool ObjCLifetimeConversion; 6233 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6234 ObjCLifetimeConversion)) 6235 return true; 6236 6237 // If we're not allowed to consider Objective-C pointer conversions, 6238 // we're done. 6239 if (!AllowObjCPointerConversion) 6240 return false; 6241 6242 // Is this an Objective-C pointer conversion? 6243 bool IncompatibleObjC = false; 6244 QualType ConvertedType; 6245 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6246 IncompatibleObjC); 6247 } 6248 6249 /// AddConversionCandidate - Add a C++ conversion function as a 6250 /// candidate in the candidate set (C++ [over.match.conv], 6251 /// C++ [over.match.copy]). From is the expression we're converting from, 6252 /// and ToType is the type that we're eventually trying to convert to 6253 /// (which may or may not be the same type as the type that the 6254 /// conversion function produces). 6255 void 6256 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6257 DeclAccessPair FoundDecl, 6258 CXXRecordDecl *ActingContext, 6259 Expr *From, QualType ToType, 6260 OverloadCandidateSet& CandidateSet, 6261 bool AllowObjCConversionOnExplicit) { 6262 assert(!Conversion->getDescribedFunctionTemplate() && 6263 "Conversion function templates use AddTemplateConversionCandidate"); 6264 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6265 if (!CandidateSet.isNewCandidate(Conversion)) 6266 return; 6267 6268 // If the conversion function has an undeduced return type, trigger its 6269 // deduction now. 6270 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6271 if (DeduceReturnType(Conversion, From->getExprLoc())) 6272 return; 6273 ConvType = Conversion->getConversionType().getNonReferenceType(); 6274 } 6275 6276 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6277 // operator is only a candidate if its return type is the target type or 6278 // can be converted to the target type with a qualification conversion. 6279 if (Conversion->isExplicit() && 6280 !isAllowableExplicitConversion(*this, ConvType, ToType, 6281 AllowObjCConversionOnExplicit)) 6282 return; 6283 6284 // Overload resolution is always an unevaluated context. 6285 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6286 6287 // Add this candidate 6288 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6289 Candidate.FoundDecl = FoundDecl; 6290 Candidate.Function = Conversion; 6291 Candidate.IsSurrogate = false; 6292 Candidate.IgnoreObjectArgument = false; 6293 Candidate.FinalConversion.setAsIdentityConversion(); 6294 Candidate.FinalConversion.setFromType(ConvType); 6295 Candidate.FinalConversion.setAllToTypes(ToType); 6296 Candidate.Viable = true; 6297 Candidate.ExplicitCallArguments = 1; 6298 6299 // C++ [over.match.funcs]p4: 6300 // For conversion functions, the function is considered to be a member of 6301 // the class of the implicit implied object argument for the purpose of 6302 // defining the type of the implicit object parameter. 6303 // 6304 // Determine the implicit conversion sequence for the implicit 6305 // object parameter. 6306 QualType ImplicitParamType = From->getType(); 6307 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6308 ImplicitParamType = FromPtrType->getPointeeType(); 6309 CXXRecordDecl *ConversionContext 6310 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6311 6312 Candidate.Conversions[0] 6313 = TryObjectArgumentInitialization(*this, From->getType(), 6314 From->Classify(Context), 6315 Conversion, ConversionContext); 6316 6317 if (Candidate.Conversions[0].isBad()) { 6318 Candidate.Viable = false; 6319 Candidate.FailureKind = ovl_fail_bad_conversion; 6320 return; 6321 } 6322 6323 // We won't go through a user-defined type conversion function to convert a 6324 // derived to base as such conversions are given Conversion Rank. They only 6325 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6326 QualType FromCanon 6327 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6328 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6329 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6330 Candidate.Viable = false; 6331 Candidate.FailureKind = ovl_fail_trivial_conversion; 6332 return; 6333 } 6334 6335 // To determine what the conversion from the result of calling the 6336 // conversion function to the type we're eventually trying to 6337 // convert to (ToType), we need to synthesize a call to the 6338 // conversion function and attempt copy initialization from it. This 6339 // makes sure that we get the right semantics with respect to 6340 // lvalues/rvalues and the type. Fortunately, we can allocate this 6341 // call on the stack and we don't need its arguments to be 6342 // well-formed. 6343 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6344 VK_LValue, From->getLocStart()); 6345 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6346 Context.getPointerType(Conversion->getType()), 6347 CK_FunctionToPointerDecay, 6348 &ConversionRef, VK_RValue); 6349 6350 QualType ConversionType = Conversion->getConversionType(); 6351 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6352 Candidate.Viable = false; 6353 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6354 return; 6355 } 6356 6357 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6358 6359 // Note that it is safe to allocate CallExpr on the stack here because 6360 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6361 // allocator). 6362 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6363 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6364 From->getLocStart()); 6365 ImplicitConversionSequence ICS = 6366 TryCopyInitialization(*this, &Call, ToType, 6367 /*SuppressUserConversions=*/true, 6368 /*InOverloadResolution=*/false, 6369 /*AllowObjCWritebackConversion=*/false); 6370 6371 switch (ICS.getKind()) { 6372 case ImplicitConversionSequence::StandardConversion: 6373 Candidate.FinalConversion = ICS.Standard; 6374 6375 // C++ [over.ics.user]p3: 6376 // If the user-defined conversion is specified by a specialization of a 6377 // conversion function template, the second standard conversion sequence 6378 // shall have exact match rank. 6379 if (Conversion->getPrimaryTemplate() && 6380 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6381 Candidate.Viable = false; 6382 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6383 return; 6384 } 6385 6386 // C++0x [dcl.init.ref]p5: 6387 // In the second case, if the reference is an rvalue reference and 6388 // the second standard conversion sequence of the user-defined 6389 // conversion sequence includes an lvalue-to-rvalue conversion, the 6390 // program is ill-formed. 6391 if (ToType->isRValueReferenceType() && 6392 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6393 Candidate.Viable = false; 6394 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6395 return; 6396 } 6397 break; 6398 6399 case ImplicitConversionSequence::BadConversion: 6400 Candidate.Viable = false; 6401 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6402 return; 6403 6404 default: 6405 llvm_unreachable( 6406 "Can only end up with a standard conversion sequence or failure"); 6407 } 6408 6409 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6410 Candidate.Viable = false; 6411 Candidate.FailureKind = ovl_fail_enable_if; 6412 Candidate.DeductionFailure.Data = FailedAttr; 6413 return; 6414 } 6415 } 6416 6417 /// \brief Adds a conversion function template specialization 6418 /// candidate to the overload set, using template argument deduction 6419 /// to deduce the template arguments of the conversion function 6420 /// template from the type that we are converting to (C++ 6421 /// [temp.deduct.conv]). 6422 void 6423 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6424 DeclAccessPair FoundDecl, 6425 CXXRecordDecl *ActingDC, 6426 Expr *From, QualType ToType, 6427 OverloadCandidateSet &CandidateSet, 6428 bool AllowObjCConversionOnExplicit) { 6429 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6430 "Only conversion function templates permitted here"); 6431 6432 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6433 return; 6434 6435 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6436 CXXConversionDecl *Specialization = nullptr; 6437 if (TemplateDeductionResult Result 6438 = DeduceTemplateArguments(FunctionTemplate, ToType, 6439 Specialization, Info)) { 6440 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6441 Candidate.FoundDecl = FoundDecl; 6442 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6443 Candidate.Viable = false; 6444 Candidate.FailureKind = ovl_fail_bad_deduction; 6445 Candidate.IsSurrogate = false; 6446 Candidate.IgnoreObjectArgument = false; 6447 Candidate.ExplicitCallArguments = 1; 6448 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6449 Info); 6450 return; 6451 } 6452 6453 // Add the conversion function template specialization produced by 6454 // template argument deduction as a candidate. 6455 assert(Specialization && "Missing function template specialization?"); 6456 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6457 CandidateSet, AllowObjCConversionOnExplicit); 6458 } 6459 6460 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6461 /// converts the given @c Object to a function pointer via the 6462 /// conversion function @c Conversion, and then attempts to call it 6463 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6464 /// the type of function that we'll eventually be calling. 6465 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6466 DeclAccessPair FoundDecl, 6467 CXXRecordDecl *ActingContext, 6468 const FunctionProtoType *Proto, 6469 Expr *Object, 6470 ArrayRef<Expr *> Args, 6471 OverloadCandidateSet& CandidateSet) { 6472 if (!CandidateSet.isNewCandidate(Conversion)) 6473 return; 6474 6475 // Overload resolution is always an unevaluated context. 6476 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6477 6478 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6479 Candidate.FoundDecl = FoundDecl; 6480 Candidate.Function = nullptr; 6481 Candidate.Surrogate = Conversion; 6482 Candidate.Viable = true; 6483 Candidate.IsSurrogate = true; 6484 Candidate.IgnoreObjectArgument = false; 6485 Candidate.ExplicitCallArguments = Args.size(); 6486 6487 // Determine the implicit conversion sequence for the implicit 6488 // object parameter. 6489 ImplicitConversionSequence ObjectInit 6490 = TryObjectArgumentInitialization(*this, Object->getType(), 6491 Object->Classify(Context), 6492 Conversion, ActingContext); 6493 if (ObjectInit.isBad()) { 6494 Candidate.Viable = false; 6495 Candidate.FailureKind = ovl_fail_bad_conversion; 6496 Candidate.Conversions[0] = ObjectInit; 6497 return; 6498 } 6499 6500 // The first conversion is actually a user-defined conversion whose 6501 // first conversion is ObjectInit's standard conversion (which is 6502 // effectively a reference binding). Record it as such. 6503 Candidate.Conversions[0].setUserDefined(); 6504 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6505 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6506 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6507 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6508 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6509 Candidate.Conversions[0].UserDefined.After 6510 = Candidate.Conversions[0].UserDefined.Before; 6511 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6512 6513 // Find the 6514 unsigned NumParams = Proto->getNumParams(); 6515 6516 // (C++ 13.3.2p2): A candidate function having fewer than m 6517 // parameters is viable only if it has an ellipsis in its parameter 6518 // list (8.3.5). 6519 if (Args.size() > NumParams && !Proto->isVariadic()) { 6520 Candidate.Viable = false; 6521 Candidate.FailureKind = ovl_fail_too_many_arguments; 6522 return; 6523 } 6524 6525 // Function types don't have any default arguments, so just check if 6526 // we have enough arguments. 6527 if (Args.size() < NumParams) { 6528 // Not enough arguments. 6529 Candidate.Viable = false; 6530 Candidate.FailureKind = ovl_fail_too_few_arguments; 6531 return; 6532 } 6533 6534 // Determine the implicit conversion sequences for each of the 6535 // arguments. 6536 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6537 if (ArgIdx < NumParams) { 6538 // (C++ 13.3.2p3): for F to be a viable function, there shall 6539 // exist for each argument an implicit conversion sequence 6540 // (13.3.3.1) that converts that argument to the corresponding 6541 // parameter of F. 6542 QualType ParamType = Proto->getParamType(ArgIdx); 6543 Candidate.Conversions[ArgIdx + 1] 6544 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6545 /*SuppressUserConversions=*/false, 6546 /*InOverloadResolution=*/false, 6547 /*AllowObjCWritebackConversion=*/ 6548 getLangOpts().ObjCAutoRefCount); 6549 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6550 Candidate.Viable = false; 6551 Candidate.FailureKind = ovl_fail_bad_conversion; 6552 return; 6553 } 6554 } else { 6555 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6556 // argument for which there is no corresponding parameter is 6557 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6558 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6559 } 6560 } 6561 6562 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6563 Candidate.Viable = false; 6564 Candidate.FailureKind = ovl_fail_enable_if; 6565 Candidate.DeductionFailure.Data = FailedAttr; 6566 return; 6567 } 6568 } 6569 6570 /// \brief Add overload candidates for overloaded operators that are 6571 /// member functions. 6572 /// 6573 /// Add the overloaded operator candidates that are member functions 6574 /// for the operator Op that was used in an operator expression such 6575 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6576 /// CandidateSet will store the added overload candidates. (C++ 6577 /// [over.match.oper]). 6578 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6579 SourceLocation OpLoc, 6580 ArrayRef<Expr *> Args, 6581 OverloadCandidateSet& CandidateSet, 6582 SourceRange OpRange) { 6583 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6584 6585 // C++ [over.match.oper]p3: 6586 // For a unary operator @ with an operand of a type whose 6587 // cv-unqualified version is T1, and for a binary operator @ with 6588 // a left operand of a type whose cv-unqualified version is T1 and 6589 // a right operand of a type whose cv-unqualified version is T2, 6590 // three sets of candidate functions, designated member 6591 // candidates, non-member candidates and built-in candidates, are 6592 // constructed as follows: 6593 QualType T1 = Args[0]->getType(); 6594 6595 // -- If T1 is a complete class type or a class currently being 6596 // defined, the set of member candidates is the result of the 6597 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6598 // the set of member candidates is empty. 6599 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6600 // Complete the type if it can be completed. 6601 RequireCompleteType(OpLoc, T1, 0); 6602 // If the type is neither complete nor being defined, bail out now. 6603 if (!T1Rec->getDecl()->getDefinition()) 6604 return; 6605 6606 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6607 LookupQualifiedName(Operators, T1Rec->getDecl()); 6608 Operators.suppressDiagnostics(); 6609 6610 for (LookupResult::iterator Oper = Operators.begin(), 6611 OperEnd = Operators.end(); 6612 Oper != OperEnd; 6613 ++Oper) 6614 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6615 Args[0]->Classify(Context), 6616 Args.slice(1), 6617 CandidateSet, 6618 /* SuppressUserConversions = */ false); 6619 } 6620 } 6621 6622 /// AddBuiltinCandidate - Add a candidate for a built-in 6623 /// operator. ResultTy and ParamTys are the result and parameter types 6624 /// of the built-in candidate, respectively. Args and NumArgs are the 6625 /// arguments being passed to the candidate. IsAssignmentOperator 6626 /// should be true when this built-in candidate is an assignment 6627 /// operator. NumContextualBoolArguments is the number of arguments 6628 /// (at the beginning of the argument list) that will be contextually 6629 /// converted to bool. 6630 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6631 ArrayRef<Expr *> Args, 6632 OverloadCandidateSet& CandidateSet, 6633 bool IsAssignmentOperator, 6634 unsigned NumContextualBoolArguments) { 6635 // Overload resolution is always an unevaluated context. 6636 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6637 6638 // Add this candidate 6639 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6640 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6641 Candidate.Function = nullptr; 6642 Candidate.IsSurrogate = false; 6643 Candidate.IgnoreObjectArgument = false; 6644 Candidate.BuiltinTypes.ResultTy = ResultTy; 6645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6646 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6647 6648 // Determine the implicit conversion sequences for each of the 6649 // arguments. 6650 Candidate.Viable = true; 6651 Candidate.ExplicitCallArguments = Args.size(); 6652 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6653 // C++ [over.match.oper]p4: 6654 // For the built-in assignment operators, conversions of the 6655 // left operand are restricted as follows: 6656 // -- no temporaries are introduced to hold the left operand, and 6657 // -- no user-defined conversions are applied to the left 6658 // operand to achieve a type match with the left-most 6659 // parameter of a built-in candidate. 6660 // 6661 // We block these conversions by turning off user-defined 6662 // conversions, since that is the only way that initialization of 6663 // a reference to a non-class type can occur from something that 6664 // is not of the same type. 6665 if (ArgIdx < NumContextualBoolArguments) { 6666 assert(ParamTys[ArgIdx] == Context.BoolTy && 6667 "Contextual conversion to bool requires bool type"); 6668 Candidate.Conversions[ArgIdx] 6669 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6670 } else { 6671 Candidate.Conversions[ArgIdx] 6672 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6673 ArgIdx == 0 && IsAssignmentOperator, 6674 /*InOverloadResolution=*/false, 6675 /*AllowObjCWritebackConversion=*/ 6676 getLangOpts().ObjCAutoRefCount); 6677 } 6678 if (Candidate.Conversions[ArgIdx].isBad()) { 6679 Candidate.Viable = false; 6680 Candidate.FailureKind = ovl_fail_bad_conversion; 6681 break; 6682 } 6683 } 6684 } 6685 6686 namespace { 6687 6688 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6689 /// candidate operator functions for built-in operators (C++ 6690 /// [over.built]). The types are separated into pointer types and 6691 /// enumeration types. 6692 class BuiltinCandidateTypeSet { 6693 /// TypeSet - A set of types. 6694 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6695 6696 /// PointerTypes - The set of pointer types that will be used in the 6697 /// built-in candidates. 6698 TypeSet PointerTypes; 6699 6700 /// MemberPointerTypes - The set of member pointer types that will be 6701 /// used in the built-in candidates. 6702 TypeSet MemberPointerTypes; 6703 6704 /// EnumerationTypes - The set of enumeration types that will be 6705 /// used in the built-in candidates. 6706 TypeSet EnumerationTypes; 6707 6708 /// \brief The set of vector types that will be used in the built-in 6709 /// candidates. 6710 TypeSet VectorTypes; 6711 6712 /// \brief A flag indicating non-record types are viable candidates 6713 bool HasNonRecordTypes; 6714 6715 /// \brief A flag indicating whether either arithmetic or enumeration types 6716 /// were present in the candidate set. 6717 bool HasArithmeticOrEnumeralTypes; 6718 6719 /// \brief A flag indicating whether the nullptr type was present in the 6720 /// candidate set. 6721 bool HasNullPtrType; 6722 6723 /// Sema - The semantic analysis instance where we are building the 6724 /// candidate type set. 6725 Sema &SemaRef; 6726 6727 /// Context - The AST context in which we will build the type sets. 6728 ASTContext &Context; 6729 6730 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6731 const Qualifiers &VisibleQuals); 6732 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6733 6734 public: 6735 /// iterator - Iterates through the types that are part of the set. 6736 typedef TypeSet::iterator iterator; 6737 6738 BuiltinCandidateTypeSet(Sema &SemaRef) 6739 : HasNonRecordTypes(false), 6740 HasArithmeticOrEnumeralTypes(false), 6741 HasNullPtrType(false), 6742 SemaRef(SemaRef), 6743 Context(SemaRef.Context) { } 6744 6745 void AddTypesConvertedFrom(QualType Ty, 6746 SourceLocation Loc, 6747 bool AllowUserConversions, 6748 bool AllowExplicitConversions, 6749 const Qualifiers &VisibleTypeConversionsQuals); 6750 6751 /// pointer_begin - First pointer type found; 6752 iterator pointer_begin() { return PointerTypes.begin(); } 6753 6754 /// pointer_end - Past the last pointer type found; 6755 iterator pointer_end() { return PointerTypes.end(); } 6756 6757 /// member_pointer_begin - First member pointer type found; 6758 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6759 6760 /// member_pointer_end - Past the last member pointer type found; 6761 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6762 6763 /// enumeration_begin - First enumeration type found; 6764 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6765 6766 /// enumeration_end - Past the last enumeration type found; 6767 iterator enumeration_end() { return EnumerationTypes.end(); } 6768 6769 iterator vector_begin() { return VectorTypes.begin(); } 6770 iterator vector_end() { return VectorTypes.end(); } 6771 6772 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6773 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6774 bool hasNullPtrType() const { return HasNullPtrType; } 6775 }; 6776 6777 } // end anonymous namespace 6778 6779 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6780 /// the set of pointer types along with any more-qualified variants of 6781 /// that type. For example, if @p Ty is "int const *", this routine 6782 /// will add "int const *", "int const volatile *", "int const 6783 /// restrict *", and "int const volatile restrict *" to the set of 6784 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6785 /// false otherwise. 6786 /// 6787 /// FIXME: what to do about extended qualifiers? 6788 bool 6789 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6790 const Qualifiers &VisibleQuals) { 6791 6792 // Insert this type. 6793 if (!PointerTypes.insert(Ty).second) 6794 return false; 6795 6796 QualType PointeeTy; 6797 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6798 bool buildObjCPtr = false; 6799 if (!PointerTy) { 6800 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6801 PointeeTy = PTy->getPointeeType(); 6802 buildObjCPtr = true; 6803 } else { 6804 PointeeTy = PointerTy->getPointeeType(); 6805 } 6806 6807 // Don't add qualified variants of arrays. For one, they're not allowed 6808 // (the qualifier would sink to the element type), and for another, the 6809 // only overload situation where it matters is subscript or pointer +- int, 6810 // and those shouldn't have qualifier variants anyway. 6811 if (PointeeTy->isArrayType()) 6812 return true; 6813 6814 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6815 bool hasVolatile = VisibleQuals.hasVolatile(); 6816 bool hasRestrict = VisibleQuals.hasRestrict(); 6817 6818 // Iterate through all strict supersets of BaseCVR. 6819 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6820 if ((CVR | BaseCVR) != CVR) continue; 6821 // Skip over volatile if no volatile found anywhere in the types. 6822 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6823 6824 // Skip over restrict if no restrict found anywhere in the types, or if 6825 // the type cannot be restrict-qualified. 6826 if ((CVR & Qualifiers::Restrict) && 6827 (!hasRestrict || 6828 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6829 continue; 6830 6831 // Build qualified pointee type. 6832 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6833 6834 // Build qualified pointer type. 6835 QualType QPointerTy; 6836 if (!buildObjCPtr) 6837 QPointerTy = Context.getPointerType(QPointeeTy); 6838 else 6839 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6840 6841 // Insert qualified pointer type. 6842 PointerTypes.insert(QPointerTy); 6843 } 6844 6845 return true; 6846 } 6847 6848 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6849 /// to the set of pointer types along with any more-qualified variants of 6850 /// that type. For example, if @p Ty is "int const *", this routine 6851 /// will add "int const *", "int const volatile *", "int const 6852 /// restrict *", and "int const volatile restrict *" to the set of 6853 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6854 /// false otherwise. 6855 /// 6856 /// FIXME: what to do about extended qualifiers? 6857 bool 6858 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6859 QualType Ty) { 6860 // Insert this type. 6861 if (!MemberPointerTypes.insert(Ty).second) 6862 return false; 6863 6864 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6865 assert(PointerTy && "type was not a member pointer type!"); 6866 6867 QualType PointeeTy = PointerTy->getPointeeType(); 6868 // Don't add qualified variants of arrays. For one, they're not allowed 6869 // (the qualifier would sink to the element type), and for another, the 6870 // only overload situation where it matters is subscript or pointer +- int, 6871 // and those shouldn't have qualifier variants anyway. 6872 if (PointeeTy->isArrayType()) 6873 return true; 6874 const Type *ClassTy = PointerTy->getClass(); 6875 6876 // Iterate through all strict supersets of the pointee type's CVR 6877 // qualifiers. 6878 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6879 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6880 if ((CVR | BaseCVR) != CVR) continue; 6881 6882 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6883 MemberPointerTypes.insert( 6884 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6885 } 6886 6887 return true; 6888 } 6889 6890 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6891 /// Ty can be implicit converted to the given set of @p Types. We're 6892 /// primarily interested in pointer types and enumeration types. We also 6893 /// take member pointer types, for the conditional operator. 6894 /// AllowUserConversions is true if we should look at the conversion 6895 /// functions of a class type, and AllowExplicitConversions if we 6896 /// should also include the explicit conversion functions of a class 6897 /// type. 6898 void 6899 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6900 SourceLocation Loc, 6901 bool AllowUserConversions, 6902 bool AllowExplicitConversions, 6903 const Qualifiers &VisibleQuals) { 6904 // Only deal with canonical types. 6905 Ty = Context.getCanonicalType(Ty); 6906 6907 // Look through reference types; they aren't part of the type of an 6908 // expression for the purposes of conversions. 6909 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6910 Ty = RefTy->getPointeeType(); 6911 6912 // If we're dealing with an array type, decay to the pointer. 6913 if (Ty->isArrayType()) 6914 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6915 6916 // Otherwise, we don't care about qualifiers on the type. 6917 Ty = Ty.getLocalUnqualifiedType(); 6918 6919 // Flag if we ever add a non-record type. 6920 const RecordType *TyRec = Ty->getAs<RecordType>(); 6921 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6922 6923 // Flag if we encounter an arithmetic type. 6924 HasArithmeticOrEnumeralTypes = 6925 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6926 6927 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6928 PointerTypes.insert(Ty); 6929 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6930 // Insert our type, and its more-qualified variants, into the set 6931 // of types. 6932 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6933 return; 6934 } else if (Ty->isMemberPointerType()) { 6935 // Member pointers are far easier, since the pointee can't be converted. 6936 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6937 return; 6938 } else if (Ty->isEnumeralType()) { 6939 HasArithmeticOrEnumeralTypes = true; 6940 EnumerationTypes.insert(Ty); 6941 } else if (Ty->isVectorType()) { 6942 // We treat vector types as arithmetic types in many contexts as an 6943 // extension. 6944 HasArithmeticOrEnumeralTypes = true; 6945 VectorTypes.insert(Ty); 6946 } else if (Ty->isNullPtrType()) { 6947 HasNullPtrType = true; 6948 } else if (AllowUserConversions && TyRec) { 6949 // No conversion functions in incomplete types. 6950 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6951 return; 6952 6953 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6954 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 6955 if (isa<UsingShadowDecl>(D)) 6956 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6957 6958 // Skip conversion function templates; they don't tell us anything 6959 // about which builtin types we can convert to. 6960 if (isa<FunctionTemplateDecl>(D)) 6961 continue; 6962 6963 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6964 if (AllowExplicitConversions || !Conv->isExplicit()) { 6965 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6966 VisibleQuals); 6967 } 6968 } 6969 } 6970 } 6971 6972 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6973 /// the volatile- and non-volatile-qualified assignment operators for the 6974 /// given type to the candidate set. 6975 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6976 QualType T, 6977 ArrayRef<Expr *> Args, 6978 OverloadCandidateSet &CandidateSet) { 6979 QualType ParamTypes[2]; 6980 6981 // T& operator=(T&, T) 6982 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6983 ParamTypes[1] = T; 6984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6985 /*IsAssignmentOperator=*/true); 6986 6987 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6988 // volatile T& operator=(volatile T&, T) 6989 ParamTypes[0] 6990 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6991 ParamTypes[1] = T; 6992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6993 /*IsAssignmentOperator=*/true); 6994 } 6995 } 6996 6997 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6998 /// if any, found in visible type conversion functions found in ArgExpr's type. 6999 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7000 Qualifiers VRQuals; 7001 const RecordType *TyRec; 7002 if (const MemberPointerType *RHSMPType = 7003 ArgExpr->getType()->getAs<MemberPointerType>()) 7004 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7005 else 7006 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7007 if (!TyRec) { 7008 // Just to be safe, assume the worst case. 7009 VRQuals.addVolatile(); 7010 VRQuals.addRestrict(); 7011 return VRQuals; 7012 } 7013 7014 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7015 if (!ClassDecl->hasDefinition()) 7016 return VRQuals; 7017 7018 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7019 if (isa<UsingShadowDecl>(D)) 7020 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7021 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7022 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7023 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7024 CanTy = ResTypeRef->getPointeeType(); 7025 // Need to go down the pointer/mempointer chain and add qualifiers 7026 // as see them. 7027 bool done = false; 7028 while (!done) { 7029 if (CanTy.isRestrictQualified()) 7030 VRQuals.addRestrict(); 7031 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7032 CanTy = ResTypePtr->getPointeeType(); 7033 else if (const MemberPointerType *ResTypeMPtr = 7034 CanTy->getAs<MemberPointerType>()) 7035 CanTy = ResTypeMPtr->getPointeeType(); 7036 else 7037 done = true; 7038 if (CanTy.isVolatileQualified()) 7039 VRQuals.addVolatile(); 7040 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7041 return VRQuals; 7042 } 7043 } 7044 } 7045 return VRQuals; 7046 } 7047 7048 namespace { 7049 7050 /// \brief Helper class to manage the addition of builtin operator overload 7051 /// candidates. It provides shared state and utility methods used throughout 7052 /// the process, as well as a helper method to add each group of builtin 7053 /// operator overloads from the standard to a candidate set. 7054 class BuiltinOperatorOverloadBuilder { 7055 // Common instance state available to all overload candidate addition methods. 7056 Sema &S; 7057 ArrayRef<Expr *> Args; 7058 Qualifiers VisibleTypeConversionsQuals; 7059 bool HasArithmeticOrEnumeralCandidateType; 7060 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7061 OverloadCandidateSet &CandidateSet; 7062 7063 // Define some constants used to index and iterate over the arithemetic types 7064 // provided via the getArithmeticType() method below. 7065 // The "promoted arithmetic types" are the arithmetic 7066 // types are that preserved by promotion (C++ [over.built]p2). 7067 static const unsigned FirstIntegralType = 3; 7068 static const unsigned LastIntegralType = 20; 7069 static const unsigned FirstPromotedIntegralType = 3, 7070 LastPromotedIntegralType = 11; 7071 static const unsigned FirstPromotedArithmeticType = 0, 7072 LastPromotedArithmeticType = 11; 7073 static const unsigned NumArithmeticTypes = 20; 7074 7075 /// \brief Get the canonical type for a given arithmetic type index. 7076 CanQualType getArithmeticType(unsigned index) { 7077 assert(index < NumArithmeticTypes); 7078 static CanQualType ASTContext::* const 7079 ArithmeticTypes[NumArithmeticTypes] = { 7080 // Start of promoted types. 7081 &ASTContext::FloatTy, 7082 &ASTContext::DoubleTy, 7083 &ASTContext::LongDoubleTy, 7084 7085 // Start of integral types. 7086 &ASTContext::IntTy, 7087 &ASTContext::LongTy, 7088 &ASTContext::LongLongTy, 7089 &ASTContext::Int128Ty, 7090 &ASTContext::UnsignedIntTy, 7091 &ASTContext::UnsignedLongTy, 7092 &ASTContext::UnsignedLongLongTy, 7093 &ASTContext::UnsignedInt128Ty, 7094 // End of promoted types. 7095 7096 &ASTContext::BoolTy, 7097 &ASTContext::CharTy, 7098 &ASTContext::WCharTy, 7099 &ASTContext::Char16Ty, 7100 &ASTContext::Char32Ty, 7101 &ASTContext::SignedCharTy, 7102 &ASTContext::ShortTy, 7103 &ASTContext::UnsignedCharTy, 7104 &ASTContext::UnsignedShortTy, 7105 // End of integral types. 7106 // FIXME: What about complex? What about half? 7107 }; 7108 return S.Context.*ArithmeticTypes[index]; 7109 } 7110 7111 /// \brief Gets the canonical type resulting from the usual arithemetic 7112 /// converions for the given arithmetic types. 7113 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7114 // Accelerator table for performing the usual arithmetic conversions. 7115 // The rules are basically: 7116 // - if either is floating-point, use the wider floating-point 7117 // - if same signedness, use the higher rank 7118 // - if same size, use unsigned of the higher rank 7119 // - use the larger type 7120 // These rules, together with the axiom that higher ranks are 7121 // never smaller, are sufficient to precompute all of these results 7122 // *except* when dealing with signed types of higher rank. 7123 // (we could precompute SLL x UI for all known platforms, but it's 7124 // better not to make any assumptions). 7125 // We assume that int128 has a higher rank than long long on all platforms. 7126 enum PromotedType { 7127 Dep=-1, 7128 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7129 }; 7130 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7131 [LastPromotedArithmeticType] = { 7132 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7133 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7134 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7135 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7136 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7137 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7138 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7139 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7140 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7141 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7142 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7143 }; 7144 7145 assert(L < LastPromotedArithmeticType); 7146 assert(R < LastPromotedArithmeticType); 7147 int Idx = ConversionsTable[L][R]; 7148 7149 // Fast path: the table gives us a concrete answer. 7150 if (Idx != Dep) return getArithmeticType(Idx); 7151 7152 // Slow path: we need to compare widths. 7153 // An invariant is that the signed type has higher rank. 7154 CanQualType LT = getArithmeticType(L), 7155 RT = getArithmeticType(R); 7156 unsigned LW = S.Context.getIntWidth(LT), 7157 RW = S.Context.getIntWidth(RT); 7158 7159 // If they're different widths, use the signed type. 7160 if (LW > RW) return LT; 7161 else if (LW < RW) return RT; 7162 7163 // Otherwise, use the unsigned type of the signed type's rank. 7164 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7165 assert(L == SLL || R == SLL); 7166 return S.Context.UnsignedLongLongTy; 7167 } 7168 7169 /// \brief Helper method to factor out the common pattern of adding overloads 7170 /// for '++' and '--' builtin operators. 7171 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7172 bool HasVolatile, 7173 bool HasRestrict) { 7174 QualType ParamTypes[2] = { 7175 S.Context.getLValueReferenceType(CandidateTy), 7176 S.Context.IntTy 7177 }; 7178 7179 // Non-volatile version. 7180 if (Args.size() == 1) 7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7182 else 7183 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7184 7185 // Use a heuristic to reduce number of builtin candidates in the set: 7186 // add volatile version only if there are conversions to a volatile type. 7187 if (HasVolatile) { 7188 ParamTypes[0] = 7189 S.Context.getLValueReferenceType( 7190 S.Context.getVolatileType(CandidateTy)); 7191 if (Args.size() == 1) 7192 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7193 else 7194 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7195 } 7196 7197 // Add restrict version only if there are conversions to a restrict type 7198 // and our candidate type is a non-restrict-qualified pointer. 7199 if (HasRestrict && CandidateTy->isAnyPointerType() && 7200 !CandidateTy.isRestrictQualified()) { 7201 ParamTypes[0] 7202 = S.Context.getLValueReferenceType( 7203 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7204 if (Args.size() == 1) 7205 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7206 else 7207 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7208 7209 if (HasVolatile) { 7210 ParamTypes[0] 7211 = S.Context.getLValueReferenceType( 7212 S.Context.getCVRQualifiedType(CandidateTy, 7213 (Qualifiers::Volatile | 7214 Qualifiers::Restrict))); 7215 if (Args.size() == 1) 7216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7217 else 7218 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7219 } 7220 } 7221 7222 } 7223 7224 public: 7225 BuiltinOperatorOverloadBuilder( 7226 Sema &S, ArrayRef<Expr *> Args, 7227 Qualifiers VisibleTypeConversionsQuals, 7228 bool HasArithmeticOrEnumeralCandidateType, 7229 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7230 OverloadCandidateSet &CandidateSet) 7231 : S(S), Args(Args), 7232 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7233 HasArithmeticOrEnumeralCandidateType( 7234 HasArithmeticOrEnumeralCandidateType), 7235 CandidateTypes(CandidateTypes), 7236 CandidateSet(CandidateSet) { 7237 // Validate some of our static helper constants in debug builds. 7238 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7239 "Invalid first promoted integral type"); 7240 assert(getArithmeticType(LastPromotedIntegralType - 1) 7241 == S.Context.UnsignedInt128Ty && 7242 "Invalid last promoted integral type"); 7243 assert(getArithmeticType(FirstPromotedArithmeticType) 7244 == S.Context.FloatTy && 7245 "Invalid first promoted arithmetic type"); 7246 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7247 == S.Context.UnsignedInt128Ty && 7248 "Invalid last promoted arithmetic type"); 7249 } 7250 7251 // C++ [over.built]p3: 7252 // 7253 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7254 // is either volatile or empty, there exist candidate operator 7255 // functions of the form 7256 // 7257 // VQ T& operator++(VQ T&); 7258 // T operator++(VQ T&, int); 7259 // 7260 // C++ [over.built]p4: 7261 // 7262 // For every pair (T, VQ), where T is an arithmetic type other 7263 // than bool, and VQ is either volatile or empty, there exist 7264 // candidate operator functions of the form 7265 // 7266 // VQ T& operator--(VQ T&); 7267 // T operator--(VQ T&, int); 7268 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7269 if (!HasArithmeticOrEnumeralCandidateType) 7270 return; 7271 7272 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7273 Arith < NumArithmeticTypes; ++Arith) { 7274 addPlusPlusMinusMinusStyleOverloads( 7275 getArithmeticType(Arith), 7276 VisibleTypeConversionsQuals.hasVolatile(), 7277 VisibleTypeConversionsQuals.hasRestrict()); 7278 } 7279 } 7280 7281 // C++ [over.built]p5: 7282 // 7283 // For every pair (T, VQ), where T is a cv-qualified or 7284 // cv-unqualified object type, and VQ is either volatile or 7285 // empty, there exist candidate operator functions of the form 7286 // 7287 // T*VQ& operator++(T*VQ&); 7288 // T*VQ& operator--(T*VQ&); 7289 // T* operator++(T*VQ&, int); 7290 // T* operator--(T*VQ&, int); 7291 void addPlusPlusMinusMinusPointerOverloads() { 7292 for (BuiltinCandidateTypeSet::iterator 7293 Ptr = CandidateTypes[0].pointer_begin(), 7294 PtrEnd = CandidateTypes[0].pointer_end(); 7295 Ptr != PtrEnd; ++Ptr) { 7296 // Skip pointer types that aren't pointers to object types. 7297 if (!(*Ptr)->getPointeeType()->isObjectType()) 7298 continue; 7299 7300 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7301 (!(*Ptr).isVolatileQualified() && 7302 VisibleTypeConversionsQuals.hasVolatile()), 7303 (!(*Ptr).isRestrictQualified() && 7304 VisibleTypeConversionsQuals.hasRestrict())); 7305 } 7306 } 7307 7308 // C++ [over.built]p6: 7309 // For every cv-qualified or cv-unqualified object type T, there 7310 // exist candidate operator functions of the form 7311 // 7312 // T& operator*(T*); 7313 // 7314 // C++ [over.built]p7: 7315 // For every function type T that does not have cv-qualifiers or a 7316 // ref-qualifier, there exist candidate operator functions of the form 7317 // T& operator*(T*); 7318 void addUnaryStarPointerOverloads() { 7319 for (BuiltinCandidateTypeSet::iterator 7320 Ptr = CandidateTypes[0].pointer_begin(), 7321 PtrEnd = CandidateTypes[0].pointer_end(); 7322 Ptr != PtrEnd; ++Ptr) { 7323 QualType ParamTy = *Ptr; 7324 QualType PointeeTy = ParamTy->getPointeeType(); 7325 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7326 continue; 7327 7328 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7329 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7330 continue; 7331 7332 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7333 &ParamTy, Args, CandidateSet); 7334 } 7335 } 7336 7337 // C++ [over.built]p9: 7338 // For every promoted arithmetic type T, there exist candidate 7339 // operator functions of the form 7340 // 7341 // T operator+(T); 7342 // T operator-(T); 7343 void addUnaryPlusOrMinusArithmeticOverloads() { 7344 if (!HasArithmeticOrEnumeralCandidateType) 7345 return; 7346 7347 for (unsigned Arith = FirstPromotedArithmeticType; 7348 Arith < LastPromotedArithmeticType; ++Arith) { 7349 QualType ArithTy = getArithmeticType(Arith); 7350 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7351 } 7352 7353 // Extension: We also add these operators for vector types. 7354 for (BuiltinCandidateTypeSet::iterator 7355 Vec = CandidateTypes[0].vector_begin(), 7356 VecEnd = CandidateTypes[0].vector_end(); 7357 Vec != VecEnd; ++Vec) { 7358 QualType VecTy = *Vec; 7359 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7360 } 7361 } 7362 7363 // C++ [over.built]p8: 7364 // For every type T, there exist candidate operator functions of 7365 // the form 7366 // 7367 // T* operator+(T*); 7368 void addUnaryPlusPointerOverloads() { 7369 for (BuiltinCandidateTypeSet::iterator 7370 Ptr = CandidateTypes[0].pointer_begin(), 7371 PtrEnd = CandidateTypes[0].pointer_end(); 7372 Ptr != PtrEnd; ++Ptr) { 7373 QualType ParamTy = *Ptr; 7374 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7375 } 7376 } 7377 7378 // C++ [over.built]p10: 7379 // For every promoted integral type T, there exist candidate 7380 // operator functions of the form 7381 // 7382 // T operator~(T); 7383 void addUnaryTildePromotedIntegralOverloads() { 7384 if (!HasArithmeticOrEnumeralCandidateType) 7385 return; 7386 7387 for (unsigned Int = FirstPromotedIntegralType; 7388 Int < LastPromotedIntegralType; ++Int) { 7389 QualType IntTy = getArithmeticType(Int); 7390 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7391 } 7392 7393 // Extension: We also add this operator for vector types. 7394 for (BuiltinCandidateTypeSet::iterator 7395 Vec = CandidateTypes[0].vector_begin(), 7396 VecEnd = CandidateTypes[0].vector_end(); 7397 Vec != VecEnd; ++Vec) { 7398 QualType VecTy = *Vec; 7399 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7400 } 7401 } 7402 7403 // C++ [over.match.oper]p16: 7404 // For every pointer to member type T, there exist candidate operator 7405 // functions of the form 7406 // 7407 // bool operator==(T,T); 7408 // bool operator!=(T,T); 7409 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7410 /// Set of (canonical) types that we've already handled. 7411 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7412 7413 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7414 for (BuiltinCandidateTypeSet::iterator 7415 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7416 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7417 MemPtr != MemPtrEnd; 7418 ++MemPtr) { 7419 // Don't add the same builtin candidate twice. 7420 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7421 continue; 7422 7423 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7424 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7425 } 7426 } 7427 } 7428 7429 // C++ [over.built]p15: 7430 // 7431 // For every T, where T is an enumeration type, a pointer type, or 7432 // std::nullptr_t, there exist candidate operator functions of the form 7433 // 7434 // bool operator<(T, T); 7435 // bool operator>(T, T); 7436 // bool operator<=(T, T); 7437 // bool operator>=(T, T); 7438 // bool operator==(T, T); 7439 // bool operator!=(T, T); 7440 void addRelationalPointerOrEnumeralOverloads() { 7441 // C++ [over.match.oper]p3: 7442 // [...]the built-in candidates include all of the candidate operator 7443 // functions defined in 13.6 that, compared to the given operator, [...] 7444 // do not have the same parameter-type-list as any non-template non-member 7445 // candidate. 7446 // 7447 // Note that in practice, this only affects enumeration types because there 7448 // aren't any built-in candidates of record type, and a user-defined operator 7449 // must have an operand of record or enumeration type. Also, the only other 7450 // overloaded operator with enumeration arguments, operator=, 7451 // cannot be overloaded for enumeration types, so this is the only place 7452 // where we must suppress candidates like this. 7453 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7454 UserDefinedBinaryOperators; 7455 7456 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7457 if (CandidateTypes[ArgIdx].enumeration_begin() != 7458 CandidateTypes[ArgIdx].enumeration_end()) { 7459 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7460 CEnd = CandidateSet.end(); 7461 C != CEnd; ++C) { 7462 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7463 continue; 7464 7465 if (C->Function->isFunctionTemplateSpecialization()) 7466 continue; 7467 7468 QualType FirstParamType = 7469 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7470 QualType SecondParamType = 7471 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7472 7473 // Skip if either parameter isn't of enumeral type. 7474 if (!FirstParamType->isEnumeralType() || 7475 !SecondParamType->isEnumeralType()) 7476 continue; 7477 7478 // Add this operator to the set of known user-defined operators. 7479 UserDefinedBinaryOperators.insert( 7480 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7481 S.Context.getCanonicalType(SecondParamType))); 7482 } 7483 } 7484 } 7485 7486 /// Set of (canonical) types that we've already handled. 7487 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7488 7489 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7490 for (BuiltinCandidateTypeSet::iterator 7491 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7492 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7493 Ptr != PtrEnd; ++Ptr) { 7494 // Don't add the same builtin candidate twice. 7495 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7496 continue; 7497 7498 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7499 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7500 } 7501 for (BuiltinCandidateTypeSet::iterator 7502 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7503 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7504 Enum != EnumEnd; ++Enum) { 7505 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7506 7507 // Don't add the same builtin candidate twice, or if a user defined 7508 // candidate exists. 7509 if (!AddedTypes.insert(CanonType).second || 7510 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7511 CanonType))) 7512 continue; 7513 7514 QualType ParamTypes[2] = { *Enum, *Enum }; 7515 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7516 } 7517 7518 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7519 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7520 if (AddedTypes.insert(NullPtrTy).second && 7521 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7522 NullPtrTy))) { 7523 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7524 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7525 CandidateSet); 7526 } 7527 } 7528 } 7529 } 7530 7531 // C++ [over.built]p13: 7532 // 7533 // For every cv-qualified or cv-unqualified object type T 7534 // there exist candidate operator functions of the form 7535 // 7536 // T* operator+(T*, ptrdiff_t); 7537 // T& operator[](T*, ptrdiff_t); [BELOW] 7538 // T* operator-(T*, ptrdiff_t); 7539 // T* operator+(ptrdiff_t, T*); 7540 // T& operator[](ptrdiff_t, T*); [BELOW] 7541 // 7542 // C++ [over.built]p14: 7543 // 7544 // For every T, where T is a pointer to object type, there 7545 // exist candidate operator functions of the form 7546 // 7547 // ptrdiff_t operator-(T, T); 7548 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7549 /// Set of (canonical) types that we've already handled. 7550 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7551 7552 for (int Arg = 0; Arg < 2; ++Arg) { 7553 QualType AsymmetricParamTypes[2] = { 7554 S.Context.getPointerDiffType(), 7555 S.Context.getPointerDiffType(), 7556 }; 7557 for (BuiltinCandidateTypeSet::iterator 7558 Ptr = CandidateTypes[Arg].pointer_begin(), 7559 PtrEnd = CandidateTypes[Arg].pointer_end(); 7560 Ptr != PtrEnd; ++Ptr) { 7561 QualType PointeeTy = (*Ptr)->getPointeeType(); 7562 if (!PointeeTy->isObjectType()) 7563 continue; 7564 7565 AsymmetricParamTypes[Arg] = *Ptr; 7566 if (Arg == 0 || Op == OO_Plus) { 7567 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7568 // T* operator+(ptrdiff_t, T*); 7569 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7570 } 7571 if (Op == OO_Minus) { 7572 // ptrdiff_t operator-(T, T); 7573 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7574 continue; 7575 7576 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7577 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7578 Args, CandidateSet); 7579 } 7580 } 7581 } 7582 } 7583 7584 // C++ [over.built]p12: 7585 // 7586 // For every pair of promoted arithmetic types L and R, there 7587 // exist candidate operator functions of the form 7588 // 7589 // LR operator*(L, R); 7590 // LR operator/(L, R); 7591 // LR operator+(L, R); 7592 // LR operator-(L, R); 7593 // bool operator<(L, R); 7594 // bool operator>(L, R); 7595 // bool operator<=(L, R); 7596 // bool operator>=(L, R); 7597 // bool operator==(L, R); 7598 // bool operator!=(L, R); 7599 // 7600 // where LR is the result of the usual arithmetic conversions 7601 // between types L and R. 7602 // 7603 // C++ [over.built]p24: 7604 // 7605 // For every pair of promoted arithmetic types L and R, there exist 7606 // candidate operator functions of the form 7607 // 7608 // LR operator?(bool, L, R); 7609 // 7610 // where LR is the result of the usual arithmetic conversions 7611 // between types L and R. 7612 // Our candidates ignore the first parameter. 7613 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7614 if (!HasArithmeticOrEnumeralCandidateType) 7615 return; 7616 7617 for (unsigned Left = FirstPromotedArithmeticType; 7618 Left < LastPromotedArithmeticType; ++Left) { 7619 for (unsigned Right = FirstPromotedArithmeticType; 7620 Right < LastPromotedArithmeticType; ++Right) { 7621 QualType LandR[2] = { getArithmeticType(Left), 7622 getArithmeticType(Right) }; 7623 QualType Result = 7624 isComparison ? S.Context.BoolTy 7625 : getUsualArithmeticConversions(Left, Right); 7626 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7627 } 7628 } 7629 7630 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7631 // conditional operator for vector types. 7632 for (BuiltinCandidateTypeSet::iterator 7633 Vec1 = CandidateTypes[0].vector_begin(), 7634 Vec1End = CandidateTypes[0].vector_end(); 7635 Vec1 != Vec1End; ++Vec1) { 7636 for (BuiltinCandidateTypeSet::iterator 7637 Vec2 = CandidateTypes[1].vector_begin(), 7638 Vec2End = CandidateTypes[1].vector_end(); 7639 Vec2 != Vec2End; ++Vec2) { 7640 QualType LandR[2] = { *Vec1, *Vec2 }; 7641 QualType Result = S.Context.BoolTy; 7642 if (!isComparison) { 7643 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7644 Result = *Vec1; 7645 else 7646 Result = *Vec2; 7647 } 7648 7649 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7650 } 7651 } 7652 } 7653 7654 // C++ [over.built]p17: 7655 // 7656 // For every pair of promoted integral types L and R, there 7657 // exist candidate operator functions of the form 7658 // 7659 // LR operator%(L, R); 7660 // LR operator&(L, R); 7661 // LR operator^(L, R); 7662 // LR operator|(L, R); 7663 // L operator<<(L, R); 7664 // L operator>>(L, R); 7665 // 7666 // where LR is the result of the usual arithmetic conversions 7667 // between types L and R. 7668 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7669 if (!HasArithmeticOrEnumeralCandidateType) 7670 return; 7671 7672 for (unsigned Left = FirstPromotedIntegralType; 7673 Left < LastPromotedIntegralType; ++Left) { 7674 for (unsigned Right = FirstPromotedIntegralType; 7675 Right < LastPromotedIntegralType; ++Right) { 7676 QualType LandR[2] = { getArithmeticType(Left), 7677 getArithmeticType(Right) }; 7678 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7679 ? LandR[0] 7680 : getUsualArithmeticConversions(Left, Right); 7681 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7682 } 7683 } 7684 } 7685 7686 // C++ [over.built]p20: 7687 // 7688 // For every pair (T, VQ), where T is an enumeration or 7689 // pointer to member type and VQ is either volatile or 7690 // empty, there exist candidate operator functions of the form 7691 // 7692 // VQ T& operator=(VQ T&, T); 7693 void addAssignmentMemberPointerOrEnumeralOverloads() { 7694 /// Set of (canonical) types that we've already handled. 7695 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7696 7697 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7698 for (BuiltinCandidateTypeSet::iterator 7699 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7700 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7701 Enum != EnumEnd; ++Enum) { 7702 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7703 continue; 7704 7705 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7706 } 7707 7708 for (BuiltinCandidateTypeSet::iterator 7709 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7710 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7711 MemPtr != MemPtrEnd; ++MemPtr) { 7712 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7713 continue; 7714 7715 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7716 } 7717 } 7718 } 7719 7720 // C++ [over.built]p19: 7721 // 7722 // For every pair (T, VQ), where T is any type and VQ is either 7723 // volatile or empty, there exist candidate operator functions 7724 // of the form 7725 // 7726 // T*VQ& operator=(T*VQ&, T*); 7727 // 7728 // C++ [over.built]p21: 7729 // 7730 // For every pair (T, VQ), where T is a cv-qualified or 7731 // cv-unqualified object type and VQ is either volatile or 7732 // empty, there exist candidate operator functions of the form 7733 // 7734 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7735 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7736 void addAssignmentPointerOverloads(bool isEqualOp) { 7737 /// Set of (canonical) types that we've already handled. 7738 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7739 7740 for (BuiltinCandidateTypeSet::iterator 7741 Ptr = CandidateTypes[0].pointer_begin(), 7742 PtrEnd = CandidateTypes[0].pointer_end(); 7743 Ptr != PtrEnd; ++Ptr) { 7744 // If this is operator=, keep track of the builtin candidates we added. 7745 if (isEqualOp) 7746 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7747 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7748 continue; 7749 7750 // non-volatile version 7751 QualType ParamTypes[2] = { 7752 S.Context.getLValueReferenceType(*Ptr), 7753 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7754 }; 7755 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7756 /*IsAssigmentOperator=*/ isEqualOp); 7757 7758 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7759 VisibleTypeConversionsQuals.hasVolatile(); 7760 if (NeedVolatile) { 7761 // volatile version 7762 ParamTypes[0] = 7763 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7764 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7765 /*IsAssigmentOperator=*/isEqualOp); 7766 } 7767 7768 if (!(*Ptr).isRestrictQualified() && 7769 VisibleTypeConversionsQuals.hasRestrict()) { 7770 // restrict version 7771 ParamTypes[0] 7772 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7773 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7774 /*IsAssigmentOperator=*/isEqualOp); 7775 7776 if (NeedVolatile) { 7777 // volatile restrict version 7778 ParamTypes[0] 7779 = S.Context.getLValueReferenceType( 7780 S.Context.getCVRQualifiedType(*Ptr, 7781 (Qualifiers::Volatile | 7782 Qualifiers::Restrict))); 7783 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7784 /*IsAssigmentOperator=*/isEqualOp); 7785 } 7786 } 7787 } 7788 7789 if (isEqualOp) { 7790 for (BuiltinCandidateTypeSet::iterator 7791 Ptr = CandidateTypes[1].pointer_begin(), 7792 PtrEnd = CandidateTypes[1].pointer_end(); 7793 Ptr != PtrEnd; ++Ptr) { 7794 // Make sure we don't add the same candidate twice. 7795 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7796 continue; 7797 7798 QualType ParamTypes[2] = { 7799 S.Context.getLValueReferenceType(*Ptr), 7800 *Ptr, 7801 }; 7802 7803 // non-volatile version 7804 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7805 /*IsAssigmentOperator=*/true); 7806 7807 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7808 VisibleTypeConversionsQuals.hasVolatile(); 7809 if (NeedVolatile) { 7810 // volatile version 7811 ParamTypes[0] = 7812 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7813 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7814 /*IsAssigmentOperator=*/true); 7815 } 7816 7817 if (!(*Ptr).isRestrictQualified() && 7818 VisibleTypeConversionsQuals.hasRestrict()) { 7819 // restrict version 7820 ParamTypes[0] 7821 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7823 /*IsAssigmentOperator=*/true); 7824 7825 if (NeedVolatile) { 7826 // volatile restrict version 7827 ParamTypes[0] 7828 = S.Context.getLValueReferenceType( 7829 S.Context.getCVRQualifiedType(*Ptr, 7830 (Qualifiers::Volatile | 7831 Qualifiers::Restrict))); 7832 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7833 /*IsAssigmentOperator=*/true); 7834 } 7835 } 7836 } 7837 } 7838 } 7839 7840 // C++ [over.built]p18: 7841 // 7842 // For every triple (L, VQ, R), where L is an arithmetic type, 7843 // VQ is either volatile or empty, and R is a promoted 7844 // arithmetic type, there exist candidate operator functions of 7845 // the form 7846 // 7847 // VQ L& operator=(VQ L&, R); 7848 // VQ L& operator*=(VQ L&, R); 7849 // VQ L& operator/=(VQ L&, R); 7850 // VQ L& operator+=(VQ L&, R); 7851 // VQ L& operator-=(VQ L&, R); 7852 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7853 if (!HasArithmeticOrEnumeralCandidateType) 7854 return; 7855 7856 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7857 for (unsigned Right = FirstPromotedArithmeticType; 7858 Right < LastPromotedArithmeticType; ++Right) { 7859 QualType ParamTypes[2]; 7860 ParamTypes[1] = getArithmeticType(Right); 7861 7862 // Add this built-in operator as a candidate (VQ is empty). 7863 ParamTypes[0] = 7864 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7865 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7866 /*IsAssigmentOperator=*/isEqualOp); 7867 7868 // Add this built-in operator as a candidate (VQ is 'volatile'). 7869 if (VisibleTypeConversionsQuals.hasVolatile()) { 7870 ParamTypes[0] = 7871 S.Context.getVolatileType(getArithmeticType(Left)); 7872 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7873 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7874 /*IsAssigmentOperator=*/isEqualOp); 7875 } 7876 } 7877 } 7878 7879 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7880 for (BuiltinCandidateTypeSet::iterator 7881 Vec1 = CandidateTypes[0].vector_begin(), 7882 Vec1End = CandidateTypes[0].vector_end(); 7883 Vec1 != Vec1End; ++Vec1) { 7884 for (BuiltinCandidateTypeSet::iterator 7885 Vec2 = CandidateTypes[1].vector_begin(), 7886 Vec2End = CandidateTypes[1].vector_end(); 7887 Vec2 != Vec2End; ++Vec2) { 7888 QualType ParamTypes[2]; 7889 ParamTypes[1] = *Vec2; 7890 // Add this built-in operator as a candidate (VQ is empty). 7891 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7893 /*IsAssigmentOperator=*/isEqualOp); 7894 7895 // Add this built-in operator as a candidate (VQ is 'volatile'). 7896 if (VisibleTypeConversionsQuals.hasVolatile()) { 7897 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7898 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7900 /*IsAssigmentOperator=*/isEqualOp); 7901 } 7902 } 7903 } 7904 } 7905 7906 // C++ [over.built]p22: 7907 // 7908 // For every triple (L, VQ, R), where L is an integral type, VQ 7909 // is either volatile or empty, and R is a promoted integral 7910 // type, there exist candidate operator functions of the form 7911 // 7912 // VQ L& operator%=(VQ L&, R); 7913 // VQ L& operator<<=(VQ L&, R); 7914 // VQ L& operator>>=(VQ L&, R); 7915 // VQ L& operator&=(VQ L&, R); 7916 // VQ L& operator^=(VQ L&, R); 7917 // VQ L& operator|=(VQ L&, R); 7918 void addAssignmentIntegralOverloads() { 7919 if (!HasArithmeticOrEnumeralCandidateType) 7920 return; 7921 7922 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7923 for (unsigned Right = FirstPromotedIntegralType; 7924 Right < LastPromotedIntegralType; ++Right) { 7925 QualType ParamTypes[2]; 7926 ParamTypes[1] = getArithmeticType(Right); 7927 7928 // Add this built-in operator as a candidate (VQ is empty). 7929 ParamTypes[0] = 7930 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7931 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7932 if (VisibleTypeConversionsQuals.hasVolatile()) { 7933 // Add this built-in operator as a candidate (VQ is 'volatile'). 7934 ParamTypes[0] = getArithmeticType(Left); 7935 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7936 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7937 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7938 } 7939 } 7940 } 7941 } 7942 7943 // C++ [over.operator]p23: 7944 // 7945 // There also exist candidate operator functions of the form 7946 // 7947 // bool operator!(bool); 7948 // bool operator&&(bool, bool); 7949 // bool operator||(bool, bool); 7950 void addExclaimOverload() { 7951 QualType ParamTy = S.Context.BoolTy; 7952 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7953 /*IsAssignmentOperator=*/false, 7954 /*NumContextualBoolArguments=*/1); 7955 } 7956 void addAmpAmpOrPipePipeOverload() { 7957 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7958 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7959 /*IsAssignmentOperator=*/false, 7960 /*NumContextualBoolArguments=*/2); 7961 } 7962 7963 // C++ [over.built]p13: 7964 // 7965 // For every cv-qualified or cv-unqualified object type T there 7966 // exist candidate operator functions of the form 7967 // 7968 // T* operator+(T*, ptrdiff_t); [ABOVE] 7969 // T& operator[](T*, ptrdiff_t); 7970 // T* operator-(T*, ptrdiff_t); [ABOVE] 7971 // T* operator+(ptrdiff_t, T*); [ABOVE] 7972 // T& operator[](ptrdiff_t, T*); 7973 void addSubscriptOverloads() { 7974 for (BuiltinCandidateTypeSet::iterator 7975 Ptr = CandidateTypes[0].pointer_begin(), 7976 PtrEnd = CandidateTypes[0].pointer_end(); 7977 Ptr != PtrEnd; ++Ptr) { 7978 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7979 QualType PointeeType = (*Ptr)->getPointeeType(); 7980 if (!PointeeType->isObjectType()) 7981 continue; 7982 7983 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7984 7985 // T& operator[](T*, ptrdiff_t) 7986 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7987 } 7988 7989 for (BuiltinCandidateTypeSet::iterator 7990 Ptr = CandidateTypes[1].pointer_begin(), 7991 PtrEnd = CandidateTypes[1].pointer_end(); 7992 Ptr != PtrEnd; ++Ptr) { 7993 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7994 QualType PointeeType = (*Ptr)->getPointeeType(); 7995 if (!PointeeType->isObjectType()) 7996 continue; 7997 7998 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7999 8000 // T& operator[](ptrdiff_t, T*) 8001 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8002 } 8003 } 8004 8005 // C++ [over.built]p11: 8006 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8007 // C1 is the same type as C2 or is a derived class of C2, T is an object 8008 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8009 // there exist candidate operator functions of the form 8010 // 8011 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8012 // 8013 // where CV12 is the union of CV1 and CV2. 8014 void addArrowStarOverloads() { 8015 for (BuiltinCandidateTypeSet::iterator 8016 Ptr = CandidateTypes[0].pointer_begin(), 8017 PtrEnd = CandidateTypes[0].pointer_end(); 8018 Ptr != PtrEnd; ++Ptr) { 8019 QualType C1Ty = (*Ptr); 8020 QualType C1; 8021 QualifierCollector Q1; 8022 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8023 if (!isa<RecordType>(C1)) 8024 continue; 8025 // heuristic to reduce number of builtin candidates in the set. 8026 // Add volatile/restrict version only if there are conversions to a 8027 // volatile/restrict type. 8028 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8029 continue; 8030 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8031 continue; 8032 for (BuiltinCandidateTypeSet::iterator 8033 MemPtr = CandidateTypes[1].member_pointer_begin(), 8034 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8035 MemPtr != MemPtrEnd; ++MemPtr) { 8036 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8037 QualType C2 = QualType(mptr->getClass(), 0); 8038 C2 = C2.getUnqualifiedType(); 8039 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8040 break; 8041 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8042 // build CV12 T& 8043 QualType T = mptr->getPointeeType(); 8044 if (!VisibleTypeConversionsQuals.hasVolatile() && 8045 T.isVolatileQualified()) 8046 continue; 8047 if (!VisibleTypeConversionsQuals.hasRestrict() && 8048 T.isRestrictQualified()) 8049 continue; 8050 T = Q1.apply(S.Context, T); 8051 QualType ResultTy = S.Context.getLValueReferenceType(T); 8052 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8053 } 8054 } 8055 } 8056 8057 // Note that we don't consider the first argument, since it has been 8058 // contextually converted to bool long ago. The candidates below are 8059 // therefore added as binary. 8060 // 8061 // C++ [over.built]p25: 8062 // For every type T, where T is a pointer, pointer-to-member, or scoped 8063 // enumeration type, there exist candidate operator functions of the form 8064 // 8065 // T operator?(bool, T, T); 8066 // 8067 void addConditionalOperatorOverloads() { 8068 /// Set of (canonical) types that we've already handled. 8069 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8070 8071 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8072 for (BuiltinCandidateTypeSet::iterator 8073 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8074 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8075 Ptr != PtrEnd; ++Ptr) { 8076 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8077 continue; 8078 8079 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8080 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8081 } 8082 8083 for (BuiltinCandidateTypeSet::iterator 8084 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8085 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8086 MemPtr != MemPtrEnd; ++MemPtr) { 8087 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8088 continue; 8089 8090 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8091 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8092 } 8093 8094 if (S.getLangOpts().CPlusPlus11) { 8095 for (BuiltinCandidateTypeSet::iterator 8096 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8097 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8098 Enum != EnumEnd; ++Enum) { 8099 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8100 continue; 8101 8102 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8103 continue; 8104 8105 QualType ParamTypes[2] = { *Enum, *Enum }; 8106 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8107 } 8108 } 8109 } 8110 } 8111 }; 8112 8113 } // end anonymous namespace 8114 8115 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8116 /// operator overloads to the candidate set (C++ [over.built]), based 8117 /// on the operator @p Op and the arguments given. For example, if the 8118 /// operator is a binary '+', this routine might add "int 8119 /// operator+(int, int)" to cover integer addition. 8120 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8121 SourceLocation OpLoc, 8122 ArrayRef<Expr *> Args, 8123 OverloadCandidateSet &CandidateSet) { 8124 // Find all of the types that the arguments can convert to, but only 8125 // if the operator we're looking at has built-in operator candidates 8126 // that make use of these types. Also record whether we encounter non-record 8127 // candidate types or either arithmetic or enumeral candidate types. 8128 Qualifiers VisibleTypeConversionsQuals; 8129 VisibleTypeConversionsQuals.addConst(); 8130 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8131 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8132 8133 bool HasNonRecordCandidateType = false; 8134 bool HasArithmeticOrEnumeralCandidateType = false; 8135 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8136 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8137 CandidateTypes.emplace_back(*this); 8138 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8139 OpLoc, 8140 true, 8141 (Op == OO_Exclaim || 8142 Op == OO_AmpAmp || 8143 Op == OO_PipePipe), 8144 VisibleTypeConversionsQuals); 8145 HasNonRecordCandidateType = HasNonRecordCandidateType || 8146 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8147 HasArithmeticOrEnumeralCandidateType = 8148 HasArithmeticOrEnumeralCandidateType || 8149 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8150 } 8151 8152 // Exit early when no non-record types have been added to the candidate set 8153 // for any of the arguments to the operator. 8154 // 8155 // We can't exit early for !, ||, or &&, since there we have always have 8156 // 'bool' overloads. 8157 if (!HasNonRecordCandidateType && 8158 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8159 return; 8160 8161 // Setup an object to manage the common state for building overloads. 8162 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8163 VisibleTypeConversionsQuals, 8164 HasArithmeticOrEnumeralCandidateType, 8165 CandidateTypes, CandidateSet); 8166 8167 // Dispatch over the operation to add in only those overloads which apply. 8168 switch (Op) { 8169 case OO_None: 8170 case NUM_OVERLOADED_OPERATORS: 8171 llvm_unreachable("Expected an overloaded operator"); 8172 8173 case OO_New: 8174 case OO_Delete: 8175 case OO_Array_New: 8176 case OO_Array_Delete: 8177 case OO_Call: 8178 llvm_unreachable( 8179 "Special operators don't use AddBuiltinOperatorCandidates"); 8180 8181 case OO_Comma: 8182 case OO_Arrow: 8183 // C++ [over.match.oper]p3: 8184 // -- For the operator ',', the unary operator '&', or the 8185 // operator '->', the built-in candidates set is empty. 8186 break; 8187 8188 case OO_Plus: // '+' is either unary or binary 8189 if (Args.size() == 1) 8190 OpBuilder.addUnaryPlusPointerOverloads(); 8191 // Fall through. 8192 8193 case OO_Minus: // '-' is either unary or binary 8194 if (Args.size() == 1) { 8195 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8196 } else { 8197 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8198 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8199 } 8200 break; 8201 8202 case OO_Star: // '*' is either unary or binary 8203 if (Args.size() == 1) 8204 OpBuilder.addUnaryStarPointerOverloads(); 8205 else 8206 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8207 break; 8208 8209 case OO_Slash: 8210 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8211 break; 8212 8213 case OO_PlusPlus: 8214 case OO_MinusMinus: 8215 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8216 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8217 break; 8218 8219 case OO_EqualEqual: 8220 case OO_ExclaimEqual: 8221 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8222 // Fall through. 8223 8224 case OO_Less: 8225 case OO_Greater: 8226 case OO_LessEqual: 8227 case OO_GreaterEqual: 8228 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8229 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8230 break; 8231 8232 case OO_Percent: 8233 case OO_Caret: 8234 case OO_Pipe: 8235 case OO_LessLess: 8236 case OO_GreaterGreater: 8237 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8238 break; 8239 8240 case OO_Amp: // '&' is either unary or binary 8241 if (Args.size() == 1) 8242 // C++ [over.match.oper]p3: 8243 // -- For the operator ',', the unary operator '&', or the 8244 // operator '->', the built-in candidates set is empty. 8245 break; 8246 8247 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8248 break; 8249 8250 case OO_Tilde: 8251 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8252 break; 8253 8254 case OO_Equal: 8255 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8256 // Fall through. 8257 8258 case OO_PlusEqual: 8259 case OO_MinusEqual: 8260 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8261 // Fall through. 8262 8263 case OO_StarEqual: 8264 case OO_SlashEqual: 8265 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8266 break; 8267 8268 case OO_PercentEqual: 8269 case OO_LessLessEqual: 8270 case OO_GreaterGreaterEqual: 8271 case OO_AmpEqual: 8272 case OO_CaretEqual: 8273 case OO_PipeEqual: 8274 OpBuilder.addAssignmentIntegralOverloads(); 8275 break; 8276 8277 case OO_Exclaim: 8278 OpBuilder.addExclaimOverload(); 8279 break; 8280 8281 case OO_AmpAmp: 8282 case OO_PipePipe: 8283 OpBuilder.addAmpAmpOrPipePipeOverload(); 8284 break; 8285 8286 case OO_Subscript: 8287 OpBuilder.addSubscriptOverloads(); 8288 break; 8289 8290 case OO_ArrowStar: 8291 OpBuilder.addArrowStarOverloads(); 8292 break; 8293 8294 case OO_Conditional: 8295 OpBuilder.addConditionalOperatorOverloads(); 8296 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8297 break; 8298 } 8299 } 8300 8301 /// \brief Add function candidates found via argument-dependent lookup 8302 /// to the set of overloading candidates. 8303 /// 8304 /// This routine performs argument-dependent name lookup based on the 8305 /// given function name (which may also be an operator name) and adds 8306 /// all of the overload candidates found by ADL to the overload 8307 /// candidate set (C++ [basic.lookup.argdep]). 8308 void 8309 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8310 SourceLocation Loc, 8311 ArrayRef<Expr *> Args, 8312 TemplateArgumentListInfo *ExplicitTemplateArgs, 8313 OverloadCandidateSet& CandidateSet, 8314 bool PartialOverloading) { 8315 ADLResult Fns; 8316 8317 // FIXME: This approach for uniquing ADL results (and removing 8318 // redundant candidates from the set) relies on pointer-equality, 8319 // which means we need to key off the canonical decl. However, 8320 // always going back to the canonical decl might not get us the 8321 // right set of default arguments. What default arguments are 8322 // we supposed to consider on ADL candidates, anyway? 8323 8324 // FIXME: Pass in the explicit template arguments? 8325 ArgumentDependentLookup(Name, Loc, Args, Fns); 8326 8327 // Erase all of the candidates we already knew about. 8328 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8329 CandEnd = CandidateSet.end(); 8330 Cand != CandEnd; ++Cand) 8331 if (Cand->Function) { 8332 Fns.erase(Cand->Function); 8333 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8334 Fns.erase(FunTmpl); 8335 } 8336 8337 // For each of the ADL candidates we found, add it to the overload 8338 // set. 8339 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8340 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8342 if (ExplicitTemplateArgs) 8343 continue; 8344 8345 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8346 PartialOverloading); 8347 } else 8348 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8349 FoundDecl, ExplicitTemplateArgs, 8350 Args, CandidateSet, PartialOverloading); 8351 } 8352 } 8353 8354 /// isBetterOverloadCandidate - Determines whether the first overload 8355 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8356 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8357 const OverloadCandidate &Cand2, 8358 SourceLocation Loc, 8359 bool UserDefinedConversion) { 8360 // Define viable functions to be better candidates than non-viable 8361 // functions. 8362 if (!Cand2.Viable) 8363 return Cand1.Viable; 8364 else if (!Cand1.Viable) 8365 return false; 8366 8367 // C++ [over.match.best]p1: 8368 // 8369 // -- if F is a static member function, ICS1(F) is defined such 8370 // that ICS1(F) is neither better nor worse than ICS1(G) for 8371 // any function G, and, symmetrically, ICS1(G) is neither 8372 // better nor worse than ICS1(F). 8373 unsigned StartArg = 0; 8374 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8375 StartArg = 1; 8376 8377 // C++ [over.match.best]p1: 8378 // A viable function F1 is defined to be a better function than another 8379 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8380 // conversion sequence than ICSi(F2), and then... 8381 unsigned NumArgs = Cand1.NumConversions; 8382 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8383 bool HasBetterConversion = false; 8384 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8385 switch (CompareImplicitConversionSequences(S, 8386 Cand1.Conversions[ArgIdx], 8387 Cand2.Conversions[ArgIdx])) { 8388 case ImplicitConversionSequence::Better: 8389 // Cand1 has a better conversion sequence. 8390 HasBetterConversion = true; 8391 break; 8392 8393 case ImplicitConversionSequence::Worse: 8394 // Cand1 can't be better than Cand2. 8395 return false; 8396 8397 case ImplicitConversionSequence::Indistinguishable: 8398 // Do nothing. 8399 break; 8400 } 8401 } 8402 8403 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8404 // ICSj(F2), or, if not that, 8405 if (HasBetterConversion) 8406 return true; 8407 8408 // -- the context is an initialization by user-defined conversion 8409 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8410 // from the return type of F1 to the destination type (i.e., 8411 // the type of the entity being initialized) is a better 8412 // conversion sequence than the standard conversion sequence 8413 // from the return type of F2 to the destination type. 8414 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8415 isa<CXXConversionDecl>(Cand1.Function) && 8416 isa<CXXConversionDecl>(Cand2.Function)) { 8417 // First check whether we prefer one of the conversion functions over the 8418 // other. This only distinguishes the results in non-standard, extension 8419 // cases such as the conversion from a lambda closure type to a function 8420 // pointer or block. 8421 ImplicitConversionSequence::CompareKind Result = 8422 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8423 if (Result == ImplicitConversionSequence::Indistinguishable) 8424 Result = CompareStandardConversionSequences(S, 8425 Cand1.FinalConversion, 8426 Cand2.FinalConversion); 8427 8428 if (Result != ImplicitConversionSequence::Indistinguishable) 8429 return Result == ImplicitConversionSequence::Better; 8430 8431 // FIXME: Compare kind of reference binding if conversion functions 8432 // convert to a reference type used in direct reference binding, per 8433 // C++14 [over.match.best]p1 section 2 bullet 3. 8434 } 8435 8436 // -- F1 is a non-template function and F2 is a function template 8437 // specialization, or, if not that, 8438 bool Cand1IsSpecialization = Cand1.Function && 8439 Cand1.Function->getPrimaryTemplate(); 8440 bool Cand2IsSpecialization = Cand2.Function && 8441 Cand2.Function->getPrimaryTemplate(); 8442 if (Cand1IsSpecialization != Cand2IsSpecialization) 8443 return Cand2IsSpecialization; 8444 8445 // -- F1 and F2 are function template specializations, and the function 8446 // template for F1 is more specialized than the template for F2 8447 // according to the partial ordering rules described in 14.5.5.2, or, 8448 // if not that, 8449 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8450 if (FunctionTemplateDecl *BetterTemplate 8451 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8452 Cand2.Function->getPrimaryTemplate(), 8453 Loc, 8454 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8455 : TPOC_Call, 8456 Cand1.ExplicitCallArguments, 8457 Cand2.ExplicitCallArguments)) 8458 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8459 } 8460 8461 // Check for enable_if value-based overload resolution. 8462 if (Cand1.Function && Cand2.Function && 8463 (Cand1.Function->hasAttr<EnableIfAttr>() || 8464 Cand2.Function->hasAttr<EnableIfAttr>())) { 8465 // FIXME: The next several lines are just 8466 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8467 // instead of reverse order which is how they're stored in the AST. 8468 AttrVec Cand1Attrs; 8469 if (Cand1.Function->hasAttrs()) { 8470 Cand1Attrs = Cand1.Function->getAttrs(); 8471 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8472 IsNotEnableIfAttr), 8473 Cand1Attrs.end()); 8474 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end()); 8475 } 8476 8477 AttrVec Cand2Attrs; 8478 if (Cand2.Function->hasAttrs()) { 8479 Cand2Attrs = Cand2.Function->getAttrs(); 8480 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8481 IsNotEnableIfAttr), 8482 Cand2Attrs.end()); 8483 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end()); 8484 } 8485 8486 // Candidate 1 is better if it has strictly more attributes and 8487 // the common sequence is identical. 8488 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8489 return false; 8490 8491 auto Cand1I = Cand1Attrs.begin(); 8492 for (auto &Cand2A : Cand2Attrs) { 8493 auto &Cand1A = *Cand1I++; 8494 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8495 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID, 8496 S.getASTContext(), true); 8497 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID, 8498 S.getASTContext(), true); 8499 if (Cand1ID != Cand2ID) 8500 return false; 8501 } 8502 8503 return true; 8504 } 8505 8506 return false; 8507 } 8508 8509 /// \brief Computes the best viable function (C++ 13.3.3) 8510 /// within an overload candidate set. 8511 /// 8512 /// \param Loc The location of the function name (or operator symbol) for 8513 /// which overload resolution occurs. 8514 /// 8515 /// \param Best If overload resolution was successful or found a deleted 8516 /// function, \p Best points to the candidate function found. 8517 /// 8518 /// \returns The result of overload resolution. 8519 OverloadingResult 8520 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8521 iterator &Best, 8522 bool UserDefinedConversion) { 8523 // Find the best viable function. 8524 Best = end(); 8525 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8526 if (Cand->Viable) 8527 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8528 UserDefinedConversion)) 8529 Best = Cand; 8530 } 8531 8532 // If we didn't find any viable functions, abort. 8533 if (Best == end()) 8534 return OR_No_Viable_Function; 8535 8536 // Make sure that this function is better than every other viable 8537 // function. If not, we have an ambiguity. 8538 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8539 if (Cand->Viable && 8540 Cand != Best && 8541 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8542 UserDefinedConversion)) { 8543 Best = end(); 8544 return OR_Ambiguous; 8545 } 8546 } 8547 8548 // Best is the best viable function. 8549 if (Best->Function && 8550 (Best->Function->isDeleted() || 8551 S.isFunctionConsideredUnavailable(Best->Function))) 8552 return OR_Deleted; 8553 8554 return OR_Success; 8555 } 8556 8557 namespace { 8558 8559 enum OverloadCandidateKind { 8560 oc_function, 8561 oc_method, 8562 oc_constructor, 8563 oc_function_template, 8564 oc_method_template, 8565 oc_constructor_template, 8566 oc_implicit_default_constructor, 8567 oc_implicit_copy_constructor, 8568 oc_implicit_move_constructor, 8569 oc_implicit_copy_assignment, 8570 oc_implicit_move_assignment, 8571 oc_implicit_inherited_constructor 8572 }; 8573 8574 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8575 FunctionDecl *Fn, 8576 std::string &Description) { 8577 bool isTemplate = false; 8578 8579 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8580 isTemplate = true; 8581 Description = S.getTemplateArgumentBindingsText( 8582 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8583 } 8584 8585 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8586 if (!Ctor->isImplicit()) 8587 return isTemplate ? oc_constructor_template : oc_constructor; 8588 8589 if (Ctor->getInheritedConstructor()) 8590 return oc_implicit_inherited_constructor; 8591 8592 if (Ctor->isDefaultConstructor()) 8593 return oc_implicit_default_constructor; 8594 8595 if (Ctor->isMoveConstructor()) 8596 return oc_implicit_move_constructor; 8597 8598 assert(Ctor->isCopyConstructor() && 8599 "unexpected sort of implicit constructor"); 8600 return oc_implicit_copy_constructor; 8601 } 8602 8603 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8604 // This actually gets spelled 'candidate function' for now, but 8605 // it doesn't hurt to split it out. 8606 if (!Meth->isImplicit()) 8607 return isTemplate ? oc_method_template : oc_method; 8608 8609 if (Meth->isMoveAssignmentOperator()) 8610 return oc_implicit_move_assignment; 8611 8612 if (Meth->isCopyAssignmentOperator()) 8613 return oc_implicit_copy_assignment; 8614 8615 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8616 return oc_method; 8617 } 8618 8619 return isTemplate ? oc_function_template : oc_function; 8620 } 8621 8622 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8623 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8624 if (!Ctor) return; 8625 8626 Ctor = Ctor->getInheritedConstructor(); 8627 if (!Ctor) return; 8628 8629 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8630 } 8631 8632 } // end anonymous namespace 8633 8634 // Notes the location of an overload candidate. 8635 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8636 std::string FnDesc; 8637 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8638 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8639 << (unsigned) K << FnDesc; 8640 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8641 Diag(Fn->getLocation(), PD); 8642 MaybeEmitInheritedConstructorNote(*this, Fn); 8643 } 8644 8645 // Notes the location of all overload candidates designated through 8646 // OverloadedExpr 8647 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8648 assert(OverloadedExpr->getType() == Context.OverloadTy); 8649 8650 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8651 OverloadExpr *OvlExpr = Ovl.Expression; 8652 8653 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8654 IEnd = OvlExpr->decls_end(); 8655 I != IEnd; ++I) { 8656 if (FunctionTemplateDecl *FunTmpl = 8657 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8658 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8659 } else if (FunctionDecl *Fun 8660 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8661 NoteOverloadCandidate(Fun, DestType); 8662 } 8663 } 8664 } 8665 8666 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8667 /// "lead" diagnostic; it will be given two arguments, the source and 8668 /// target types of the conversion. 8669 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8670 Sema &S, 8671 SourceLocation CaretLoc, 8672 const PartialDiagnostic &PDiag) const { 8673 S.Diag(CaretLoc, PDiag) 8674 << Ambiguous.getFromType() << Ambiguous.getToType(); 8675 // FIXME: The note limiting machinery is borrowed from 8676 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8677 // refactoring here. 8678 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8679 unsigned CandsShown = 0; 8680 AmbiguousConversionSequence::const_iterator I, E; 8681 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8682 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8683 break; 8684 ++CandsShown; 8685 S.NoteOverloadCandidate(*I); 8686 } 8687 if (I != E) 8688 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8689 } 8690 8691 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8692 unsigned I) { 8693 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8694 assert(Conv.isBad()); 8695 assert(Cand->Function && "for now, candidate must be a function"); 8696 FunctionDecl *Fn = Cand->Function; 8697 8698 // There's a conversion slot for the object argument if this is a 8699 // non-constructor method. Note that 'I' corresponds the 8700 // conversion-slot index. 8701 bool isObjectArgument = false; 8702 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8703 if (I == 0) 8704 isObjectArgument = true; 8705 else 8706 I--; 8707 } 8708 8709 std::string FnDesc; 8710 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8711 8712 Expr *FromExpr = Conv.Bad.FromExpr; 8713 QualType FromTy = Conv.Bad.getFromType(); 8714 QualType ToTy = Conv.Bad.getToType(); 8715 8716 if (FromTy == S.Context.OverloadTy) { 8717 assert(FromExpr && "overload set argument came from implicit argument?"); 8718 Expr *E = FromExpr->IgnoreParens(); 8719 if (isa<UnaryOperator>(E)) 8720 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8721 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8722 8723 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8724 << (unsigned) FnKind << FnDesc 8725 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8726 << ToTy << Name << I+1; 8727 MaybeEmitInheritedConstructorNote(S, Fn); 8728 return; 8729 } 8730 8731 // Do some hand-waving analysis to see if the non-viability is due 8732 // to a qualifier mismatch. 8733 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8734 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8735 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8736 CToTy = RT->getPointeeType(); 8737 else { 8738 // TODO: detect and diagnose the full richness of const mismatches. 8739 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8740 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8741 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8742 } 8743 8744 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8745 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8746 Qualifiers FromQs = CFromTy.getQualifiers(); 8747 Qualifiers ToQs = CToTy.getQualifiers(); 8748 8749 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8750 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8751 << (unsigned) FnKind << FnDesc 8752 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8753 << FromTy 8754 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8755 << (unsigned) isObjectArgument << I+1; 8756 MaybeEmitInheritedConstructorNote(S, Fn); 8757 return; 8758 } 8759 8760 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8762 << (unsigned) FnKind << FnDesc 8763 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8764 << FromTy 8765 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8766 << (unsigned) isObjectArgument << I+1; 8767 MaybeEmitInheritedConstructorNote(S, Fn); 8768 return; 8769 } 8770 8771 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8773 << (unsigned) FnKind << FnDesc 8774 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8775 << FromTy 8776 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8777 << (unsigned) isObjectArgument << I+1; 8778 MaybeEmitInheritedConstructorNote(S, Fn); 8779 return; 8780 } 8781 8782 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8783 assert(CVR && "unexpected qualifiers mismatch"); 8784 8785 if (isObjectArgument) { 8786 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8787 << (unsigned) FnKind << FnDesc 8788 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8789 << FromTy << (CVR - 1); 8790 } else { 8791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8792 << (unsigned) FnKind << FnDesc 8793 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8794 << FromTy << (CVR - 1) << I+1; 8795 } 8796 MaybeEmitInheritedConstructorNote(S, Fn); 8797 return; 8798 } 8799 8800 // Special diagnostic for failure to convert an initializer list, since 8801 // telling the user that it has type void is not useful. 8802 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8803 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8804 << (unsigned) FnKind << FnDesc 8805 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8806 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8807 MaybeEmitInheritedConstructorNote(S, Fn); 8808 return; 8809 } 8810 8811 // Diagnose references or pointers to incomplete types differently, 8812 // since it's far from impossible that the incompleteness triggered 8813 // the failure. 8814 QualType TempFromTy = FromTy.getNonReferenceType(); 8815 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8816 TempFromTy = PTy->getPointeeType(); 8817 if (TempFromTy->isIncompleteType()) { 8818 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8819 << (unsigned) FnKind << FnDesc 8820 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8821 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8822 MaybeEmitInheritedConstructorNote(S, Fn); 8823 return; 8824 } 8825 8826 // Diagnose base -> derived pointer conversions. 8827 unsigned BaseToDerivedConversion = 0; 8828 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8829 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8830 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8831 FromPtrTy->getPointeeType()) && 8832 !FromPtrTy->getPointeeType()->isIncompleteType() && 8833 !ToPtrTy->getPointeeType()->isIncompleteType() && 8834 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8835 FromPtrTy->getPointeeType())) 8836 BaseToDerivedConversion = 1; 8837 } 8838 } else if (const ObjCObjectPointerType *FromPtrTy 8839 = FromTy->getAs<ObjCObjectPointerType>()) { 8840 if (const ObjCObjectPointerType *ToPtrTy 8841 = ToTy->getAs<ObjCObjectPointerType>()) 8842 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8843 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8844 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8845 FromPtrTy->getPointeeType()) && 8846 FromIface->isSuperClassOf(ToIface)) 8847 BaseToDerivedConversion = 2; 8848 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8849 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8850 !FromTy->isIncompleteType() && 8851 !ToRefTy->getPointeeType()->isIncompleteType() && 8852 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8853 BaseToDerivedConversion = 3; 8854 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8855 ToTy.getNonReferenceType().getCanonicalType() == 8856 FromTy.getNonReferenceType().getCanonicalType()) { 8857 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8858 << (unsigned) FnKind << FnDesc 8859 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8860 << (unsigned) isObjectArgument << I + 1; 8861 MaybeEmitInheritedConstructorNote(S, Fn); 8862 return; 8863 } 8864 } 8865 8866 if (BaseToDerivedConversion) { 8867 S.Diag(Fn->getLocation(), 8868 diag::note_ovl_candidate_bad_base_to_derived_conv) 8869 << (unsigned) FnKind << FnDesc 8870 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8871 << (BaseToDerivedConversion - 1) 8872 << FromTy << ToTy << I+1; 8873 MaybeEmitInheritedConstructorNote(S, Fn); 8874 return; 8875 } 8876 8877 if (isa<ObjCObjectPointerType>(CFromTy) && 8878 isa<PointerType>(CToTy)) { 8879 Qualifiers FromQs = CFromTy.getQualifiers(); 8880 Qualifiers ToQs = CToTy.getQualifiers(); 8881 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8882 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8883 << (unsigned) FnKind << FnDesc 8884 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8885 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8886 MaybeEmitInheritedConstructorNote(S, Fn); 8887 return; 8888 } 8889 } 8890 8891 // Emit the generic diagnostic and, optionally, add the hints to it. 8892 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8893 FDiag << (unsigned) FnKind << FnDesc 8894 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8895 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8896 << (unsigned) (Cand->Fix.Kind); 8897 8898 // If we can fix the conversion, suggest the FixIts. 8899 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8900 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8901 FDiag << *HI; 8902 S.Diag(Fn->getLocation(), FDiag); 8903 8904 MaybeEmitInheritedConstructorNote(S, Fn); 8905 } 8906 8907 /// Additional arity mismatch diagnosis specific to a function overload 8908 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8909 /// over a candidate in any candidate set. 8910 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8911 unsigned NumArgs) { 8912 FunctionDecl *Fn = Cand->Function; 8913 unsigned MinParams = Fn->getMinRequiredArguments(); 8914 8915 // With invalid overloaded operators, it's possible that we think we 8916 // have an arity mismatch when in fact it looks like we have the 8917 // right number of arguments, because only overloaded operators have 8918 // the weird behavior of overloading member and non-member functions. 8919 // Just don't report anything. 8920 if (Fn->isInvalidDecl() && 8921 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8922 return true; 8923 8924 if (NumArgs < MinParams) { 8925 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8926 (Cand->FailureKind == ovl_fail_bad_deduction && 8927 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8928 } else { 8929 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8930 (Cand->FailureKind == ovl_fail_bad_deduction && 8931 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8932 } 8933 8934 return false; 8935 } 8936 8937 /// General arity mismatch diagnosis over a candidate in a candidate set. 8938 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8939 assert(isa<FunctionDecl>(D) && 8940 "The templated declaration should at least be a function" 8941 " when diagnosing bad template argument deduction due to too many" 8942 " or too few arguments"); 8943 8944 FunctionDecl *Fn = cast<FunctionDecl>(D); 8945 8946 // TODO: treat calls to a missing default constructor as a special case 8947 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8948 unsigned MinParams = Fn->getMinRequiredArguments(); 8949 8950 // at least / at most / exactly 8951 unsigned mode, modeCount; 8952 if (NumFormalArgs < MinParams) { 8953 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8954 FnTy->isTemplateVariadic()) 8955 mode = 0; // "at least" 8956 else 8957 mode = 2; // "exactly" 8958 modeCount = MinParams; 8959 } else { 8960 if (MinParams != FnTy->getNumParams()) 8961 mode = 1; // "at most" 8962 else 8963 mode = 2; // "exactly" 8964 modeCount = FnTy->getNumParams(); 8965 } 8966 8967 std::string Description; 8968 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8969 8970 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8972 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8973 << mode << Fn->getParamDecl(0) << NumFormalArgs; 8974 else 8975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8976 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8977 << mode << modeCount << NumFormalArgs; 8978 MaybeEmitInheritedConstructorNote(S, Fn); 8979 } 8980 8981 /// Arity mismatch diagnosis specific to a function overload candidate. 8982 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8983 unsigned NumFormalArgs) { 8984 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8985 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8986 } 8987 8988 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 8989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8990 return FD->getDescribedFunctionTemplate(); 8991 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8992 return RD->getDescribedClassTemplate(); 8993 8994 llvm_unreachable("Unsupported: Getting the described template declaration" 8995 " for bad deduction diagnosis"); 8996 } 8997 8998 /// Diagnose a failed template-argument deduction. 8999 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9000 DeductionFailureInfo &DeductionFailure, 9001 unsigned NumArgs) { 9002 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9003 NamedDecl *ParamD; 9004 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9005 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9006 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9007 switch (DeductionFailure.Result) { 9008 case Sema::TDK_Success: 9009 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9010 9011 case Sema::TDK_Incomplete: { 9012 assert(ParamD && "no parameter found for incomplete deduction result"); 9013 S.Diag(Templated->getLocation(), 9014 diag::note_ovl_candidate_incomplete_deduction) 9015 << ParamD->getDeclName(); 9016 MaybeEmitInheritedConstructorNote(S, Templated); 9017 return; 9018 } 9019 9020 case Sema::TDK_Underqualified: { 9021 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9022 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9023 9024 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9025 9026 // Param will have been canonicalized, but it should just be a 9027 // qualified version of ParamD, so move the qualifiers to that. 9028 QualifierCollector Qs; 9029 Qs.strip(Param); 9030 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9031 assert(S.Context.hasSameType(Param, NonCanonParam)); 9032 9033 // Arg has also been canonicalized, but there's nothing we can do 9034 // about that. It also doesn't matter as much, because it won't 9035 // have any template parameters in it (because deduction isn't 9036 // done on dependent types). 9037 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9038 9039 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9040 << ParamD->getDeclName() << Arg << NonCanonParam; 9041 MaybeEmitInheritedConstructorNote(S, Templated); 9042 return; 9043 } 9044 9045 case Sema::TDK_Inconsistent: { 9046 assert(ParamD && "no parameter found for inconsistent deduction result"); 9047 int which = 0; 9048 if (isa<TemplateTypeParmDecl>(ParamD)) 9049 which = 0; 9050 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9051 which = 1; 9052 else { 9053 which = 2; 9054 } 9055 9056 S.Diag(Templated->getLocation(), 9057 diag::note_ovl_candidate_inconsistent_deduction) 9058 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9059 << *DeductionFailure.getSecondArg(); 9060 MaybeEmitInheritedConstructorNote(S, Templated); 9061 return; 9062 } 9063 9064 case Sema::TDK_InvalidExplicitArguments: 9065 assert(ParamD && "no parameter found for invalid explicit arguments"); 9066 if (ParamD->getDeclName()) 9067 S.Diag(Templated->getLocation(), 9068 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9069 << ParamD->getDeclName(); 9070 else { 9071 int index = 0; 9072 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9073 index = TTP->getIndex(); 9074 else if (NonTypeTemplateParmDecl *NTTP 9075 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9076 index = NTTP->getIndex(); 9077 else 9078 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9079 S.Diag(Templated->getLocation(), 9080 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9081 << (index + 1); 9082 } 9083 MaybeEmitInheritedConstructorNote(S, Templated); 9084 return; 9085 9086 case Sema::TDK_TooManyArguments: 9087 case Sema::TDK_TooFewArguments: 9088 DiagnoseArityMismatch(S, Templated, NumArgs); 9089 return; 9090 9091 case Sema::TDK_InstantiationDepth: 9092 S.Diag(Templated->getLocation(), 9093 diag::note_ovl_candidate_instantiation_depth); 9094 MaybeEmitInheritedConstructorNote(S, Templated); 9095 return; 9096 9097 case Sema::TDK_SubstitutionFailure: { 9098 // Format the template argument list into the argument string. 9099 SmallString<128> TemplateArgString; 9100 if (TemplateArgumentList *Args = 9101 DeductionFailure.getTemplateArgumentList()) { 9102 TemplateArgString = " "; 9103 TemplateArgString += S.getTemplateArgumentBindingsText( 9104 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9105 } 9106 9107 // If this candidate was disabled by enable_if, say so. 9108 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9109 if (PDiag && PDiag->second.getDiagID() == 9110 diag::err_typename_nested_not_found_enable_if) { 9111 // FIXME: Use the source range of the condition, and the fully-qualified 9112 // name of the enable_if template. These are both present in PDiag. 9113 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9114 << "'enable_if'" << TemplateArgString; 9115 return; 9116 } 9117 9118 // Format the SFINAE diagnostic into the argument string. 9119 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9120 // formatted message in another diagnostic. 9121 SmallString<128> SFINAEArgString; 9122 SourceRange R; 9123 if (PDiag) { 9124 SFINAEArgString = ": "; 9125 R = SourceRange(PDiag->first, PDiag->first); 9126 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9127 } 9128 9129 S.Diag(Templated->getLocation(), 9130 diag::note_ovl_candidate_substitution_failure) 9131 << TemplateArgString << SFINAEArgString << R; 9132 MaybeEmitInheritedConstructorNote(S, Templated); 9133 return; 9134 } 9135 9136 case Sema::TDK_FailedOverloadResolution: { 9137 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9138 S.Diag(Templated->getLocation(), 9139 diag::note_ovl_candidate_failed_overload_resolution) 9140 << R.Expression->getName(); 9141 return; 9142 } 9143 9144 case Sema::TDK_NonDeducedMismatch: { 9145 // FIXME: Provide a source location to indicate what we couldn't match. 9146 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9147 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9148 if (FirstTA.getKind() == TemplateArgument::Template && 9149 SecondTA.getKind() == TemplateArgument::Template) { 9150 TemplateName FirstTN = FirstTA.getAsTemplate(); 9151 TemplateName SecondTN = SecondTA.getAsTemplate(); 9152 if (FirstTN.getKind() == TemplateName::Template && 9153 SecondTN.getKind() == TemplateName::Template) { 9154 if (FirstTN.getAsTemplateDecl()->getName() == 9155 SecondTN.getAsTemplateDecl()->getName()) { 9156 // FIXME: This fixes a bad diagnostic where both templates are named 9157 // the same. This particular case is a bit difficult since: 9158 // 1) It is passed as a string to the diagnostic printer. 9159 // 2) The diagnostic printer only attempts to find a better 9160 // name for types, not decls. 9161 // Ideally, this should folded into the diagnostic printer. 9162 S.Diag(Templated->getLocation(), 9163 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9164 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9165 return; 9166 } 9167 } 9168 } 9169 // FIXME: For generic lambda parameters, check if the function is a lambda 9170 // call operator, and if so, emit a prettier and more informative 9171 // diagnostic that mentions 'auto' and lambda in addition to 9172 // (or instead of?) the canonical template type parameters. 9173 S.Diag(Templated->getLocation(), 9174 diag::note_ovl_candidate_non_deduced_mismatch) 9175 << FirstTA << SecondTA; 9176 return; 9177 } 9178 // TODO: diagnose these individually, then kill off 9179 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9180 case Sema::TDK_MiscellaneousDeductionFailure: 9181 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9182 MaybeEmitInheritedConstructorNote(S, Templated); 9183 return; 9184 } 9185 } 9186 9187 /// Diagnose a failed template-argument deduction, for function calls. 9188 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9189 unsigned NumArgs) { 9190 unsigned TDK = Cand->DeductionFailure.Result; 9191 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9192 if (CheckArityMismatch(S, Cand, NumArgs)) 9193 return; 9194 } 9195 DiagnoseBadDeduction(S, Cand->Function, // pattern 9196 Cand->DeductionFailure, NumArgs); 9197 } 9198 9199 /// CUDA: diagnose an invalid call across targets. 9200 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9201 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9202 FunctionDecl *Callee = Cand->Function; 9203 9204 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9205 CalleeTarget = S.IdentifyCUDATarget(Callee); 9206 9207 std::string FnDesc; 9208 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9209 9210 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9211 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9212 9213 // This could be an implicit constructor for which we could not infer the 9214 // target due to a collsion. Diagnose that case. 9215 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9216 if (Meth != nullptr && Meth->isImplicit()) { 9217 CXXRecordDecl *ParentClass = Meth->getParent(); 9218 Sema::CXXSpecialMember CSM; 9219 9220 switch (FnKind) { 9221 default: 9222 return; 9223 case oc_implicit_default_constructor: 9224 CSM = Sema::CXXDefaultConstructor; 9225 break; 9226 case oc_implicit_copy_constructor: 9227 CSM = Sema::CXXCopyConstructor; 9228 break; 9229 case oc_implicit_move_constructor: 9230 CSM = Sema::CXXMoveConstructor; 9231 break; 9232 case oc_implicit_copy_assignment: 9233 CSM = Sema::CXXCopyAssignment; 9234 break; 9235 case oc_implicit_move_assignment: 9236 CSM = Sema::CXXMoveAssignment; 9237 break; 9238 }; 9239 9240 bool ConstRHS = false; 9241 if (Meth->getNumParams()) { 9242 if (const ReferenceType *RT = 9243 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9244 ConstRHS = RT->getPointeeType().isConstQualified(); 9245 } 9246 } 9247 9248 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9249 /* ConstRHS */ ConstRHS, 9250 /* Diagnose */ true); 9251 } 9252 } 9253 9254 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9255 FunctionDecl *Callee = Cand->Function; 9256 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9257 9258 S.Diag(Callee->getLocation(), 9259 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9260 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9261 } 9262 9263 /// Generates a 'note' diagnostic for an overload candidate. We've 9264 /// already generated a primary error at the call site. 9265 /// 9266 /// It really does need to be a single diagnostic with its caret 9267 /// pointed at the candidate declaration. Yes, this creates some 9268 /// major challenges of technical writing. Yes, this makes pointing 9269 /// out problems with specific arguments quite awkward. It's still 9270 /// better than generating twenty screens of text for every failed 9271 /// overload. 9272 /// 9273 /// It would be great to be able to express per-candidate problems 9274 /// more richly for those diagnostic clients that cared, but we'd 9275 /// still have to be just as careful with the default diagnostics. 9276 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9277 unsigned NumArgs) { 9278 FunctionDecl *Fn = Cand->Function; 9279 9280 // Note deleted candidates, but only if they're viable. 9281 if (Cand->Viable && (Fn->isDeleted() || 9282 S.isFunctionConsideredUnavailable(Fn))) { 9283 std::string FnDesc; 9284 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9285 9286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9287 << FnKind << FnDesc 9288 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9289 MaybeEmitInheritedConstructorNote(S, Fn); 9290 return; 9291 } 9292 9293 // We don't really have anything else to say about viable candidates. 9294 if (Cand->Viable) { 9295 S.NoteOverloadCandidate(Fn); 9296 return; 9297 } 9298 9299 switch (Cand->FailureKind) { 9300 case ovl_fail_too_many_arguments: 9301 case ovl_fail_too_few_arguments: 9302 return DiagnoseArityMismatch(S, Cand, NumArgs); 9303 9304 case ovl_fail_bad_deduction: 9305 return DiagnoseBadDeduction(S, Cand, NumArgs); 9306 9307 case ovl_fail_illegal_constructor: { 9308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9309 << (Fn->getPrimaryTemplate() ? 1 : 0); 9310 MaybeEmitInheritedConstructorNote(S, Fn); 9311 return; 9312 } 9313 9314 case ovl_fail_trivial_conversion: 9315 case ovl_fail_bad_final_conversion: 9316 case ovl_fail_final_conversion_not_exact: 9317 return S.NoteOverloadCandidate(Fn); 9318 9319 case ovl_fail_bad_conversion: { 9320 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9321 for (unsigned N = Cand->NumConversions; I != N; ++I) 9322 if (Cand->Conversions[I].isBad()) 9323 return DiagnoseBadConversion(S, Cand, I); 9324 9325 // FIXME: this currently happens when we're called from SemaInit 9326 // when user-conversion overload fails. Figure out how to handle 9327 // those conditions and diagnose them well. 9328 return S.NoteOverloadCandidate(Fn); 9329 } 9330 9331 case ovl_fail_bad_target: 9332 return DiagnoseBadTarget(S, Cand); 9333 9334 case ovl_fail_enable_if: 9335 return DiagnoseFailedEnableIfAttr(S, Cand); 9336 } 9337 } 9338 9339 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9340 // Desugar the type of the surrogate down to a function type, 9341 // retaining as many typedefs as possible while still showing 9342 // the function type (and, therefore, its parameter types). 9343 QualType FnType = Cand->Surrogate->getConversionType(); 9344 bool isLValueReference = false; 9345 bool isRValueReference = false; 9346 bool isPointer = false; 9347 if (const LValueReferenceType *FnTypeRef = 9348 FnType->getAs<LValueReferenceType>()) { 9349 FnType = FnTypeRef->getPointeeType(); 9350 isLValueReference = true; 9351 } else if (const RValueReferenceType *FnTypeRef = 9352 FnType->getAs<RValueReferenceType>()) { 9353 FnType = FnTypeRef->getPointeeType(); 9354 isRValueReference = true; 9355 } 9356 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9357 FnType = FnTypePtr->getPointeeType(); 9358 isPointer = true; 9359 } 9360 // Desugar down to a function type. 9361 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9362 // Reconstruct the pointer/reference as appropriate. 9363 if (isPointer) FnType = S.Context.getPointerType(FnType); 9364 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9365 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9366 9367 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9368 << FnType; 9369 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9370 } 9371 9372 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9373 SourceLocation OpLoc, 9374 OverloadCandidate *Cand) { 9375 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9376 std::string TypeStr("operator"); 9377 TypeStr += Opc; 9378 TypeStr += "("; 9379 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9380 if (Cand->NumConversions == 1) { 9381 TypeStr += ")"; 9382 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9383 } else { 9384 TypeStr += ", "; 9385 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9386 TypeStr += ")"; 9387 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9388 } 9389 } 9390 9391 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9392 OverloadCandidate *Cand) { 9393 unsigned NoOperands = Cand->NumConversions; 9394 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9395 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9396 if (ICS.isBad()) break; // all meaningless after first invalid 9397 if (!ICS.isAmbiguous()) continue; 9398 9399 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9400 S.PDiag(diag::note_ambiguous_type_conversion)); 9401 } 9402 } 9403 9404 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9405 if (Cand->Function) 9406 return Cand->Function->getLocation(); 9407 if (Cand->IsSurrogate) 9408 return Cand->Surrogate->getLocation(); 9409 return SourceLocation(); 9410 } 9411 9412 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9413 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9414 case Sema::TDK_Success: 9415 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9416 9417 case Sema::TDK_Invalid: 9418 case Sema::TDK_Incomplete: 9419 return 1; 9420 9421 case Sema::TDK_Underqualified: 9422 case Sema::TDK_Inconsistent: 9423 return 2; 9424 9425 case Sema::TDK_SubstitutionFailure: 9426 case Sema::TDK_NonDeducedMismatch: 9427 case Sema::TDK_MiscellaneousDeductionFailure: 9428 return 3; 9429 9430 case Sema::TDK_InstantiationDepth: 9431 case Sema::TDK_FailedOverloadResolution: 9432 return 4; 9433 9434 case Sema::TDK_InvalidExplicitArguments: 9435 return 5; 9436 9437 case Sema::TDK_TooManyArguments: 9438 case Sema::TDK_TooFewArguments: 9439 return 6; 9440 } 9441 llvm_unreachable("Unhandled deduction result"); 9442 } 9443 9444 namespace { 9445 struct CompareOverloadCandidatesForDisplay { 9446 Sema &S; 9447 size_t NumArgs; 9448 9449 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9450 : S(S), NumArgs(nArgs) {} 9451 9452 bool operator()(const OverloadCandidate *L, 9453 const OverloadCandidate *R) { 9454 // Fast-path this check. 9455 if (L == R) return false; 9456 9457 // Order first by viability. 9458 if (L->Viable) { 9459 if (!R->Viable) return true; 9460 9461 // TODO: introduce a tri-valued comparison for overload 9462 // candidates. Would be more worthwhile if we had a sort 9463 // that could exploit it. 9464 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9465 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9466 } else if (R->Viable) 9467 return false; 9468 9469 assert(L->Viable == R->Viable); 9470 9471 // Criteria by which we can sort non-viable candidates: 9472 if (!L->Viable) { 9473 // 1. Arity mismatches come after other candidates. 9474 if (L->FailureKind == ovl_fail_too_many_arguments || 9475 L->FailureKind == ovl_fail_too_few_arguments) { 9476 if (R->FailureKind == ovl_fail_too_many_arguments || 9477 R->FailureKind == ovl_fail_too_few_arguments) { 9478 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9479 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9480 if (LDist == RDist) { 9481 if (L->FailureKind == R->FailureKind) 9482 // Sort non-surrogates before surrogates. 9483 return !L->IsSurrogate && R->IsSurrogate; 9484 // Sort candidates requiring fewer parameters than there were 9485 // arguments given after candidates requiring more parameters 9486 // than there were arguments given. 9487 return L->FailureKind == ovl_fail_too_many_arguments; 9488 } 9489 return LDist < RDist; 9490 } 9491 return false; 9492 } 9493 if (R->FailureKind == ovl_fail_too_many_arguments || 9494 R->FailureKind == ovl_fail_too_few_arguments) 9495 return true; 9496 9497 // 2. Bad conversions come first and are ordered by the number 9498 // of bad conversions and quality of good conversions. 9499 if (L->FailureKind == ovl_fail_bad_conversion) { 9500 if (R->FailureKind != ovl_fail_bad_conversion) 9501 return true; 9502 9503 // The conversion that can be fixed with a smaller number of changes, 9504 // comes first. 9505 unsigned numLFixes = L->Fix.NumConversionsFixed; 9506 unsigned numRFixes = R->Fix.NumConversionsFixed; 9507 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9508 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9509 if (numLFixes != numRFixes) { 9510 return numLFixes < numRFixes; 9511 } 9512 9513 // If there's any ordering between the defined conversions... 9514 // FIXME: this might not be transitive. 9515 assert(L->NumConversions == R->NumConversions); 9516 9517 int leftBetter = 0; 9518 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9519 for (unsigned E = L->NumConversions; I != E; ++I) { 9520 switch (CompareImplicitConversionSequences(S, 9521 L->Conversions[I], 9522 R->Conversions[I])) { 9523 case ImplicitConversionSequence::Better: 9524 leftBetter++; 9525 break; 9526 9527 case ImplicitConversionSequence::Worse: 9528 leftBetter--; 9529 break; 9530 9531 case ImplicitConversionSequence::Indistinguishable: 9532 break; 9533 } 9534 } 9535 if (leftBetter > 0) return true; 9536 if (leftBetter < 0) return false; 9537 9538 } else if (R->FailureKind == ovl_fail_bad_conversion) 9539 return false; 9540 9541 if (L->FailureKind == ovl_fail_bad_deduction) { 9542 if (R->FailureKind != ovl_fail_bad_deduction) 9543 return true; 9544 9545 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9546 return RankDeductionFailure(L->DeductionFailure) 9547 < RankDeductionFailure(R->DeductionFailure); 9548 } else if (R->FailureKind == ovl_fail_bad_deduction) 9549 return false; 9550 9551 // TODO: others? 9552 } 9553 9554 // Sort everything else by location. 9555 SourceLocation LLoc = GetLocationForCandidate(L); 9556 SourceLocation RLoc = GetLocationForCandidate(R); 9557 9558 // Put candidates without locations (e.g. builtins) at the end. 9559 if (LLoc.isInvalid()) return false; 9560 if (RLoc.isInvalid()) return true; 9561 9562 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9563 } 9564 }; 9565 } 9566 9567 /// CompleteNonViableCandidate - Normally, overload resolution only 9568 /// computes up to the first. Produces the FixIt set if possible. 9569 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9570 ArrayRef<Expr *> Args) { 9571 assert(!Cand->Viable); 9572 9573 // Don't do anything on failures other than bad conversion. 9574 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9575 9576 // We only want the FixIts if all the arguments can be corrected. 9577 bool Unfixable = false; 9578 // Use a implicit copy initialization to check conversion fixes. 9579 Cand->Fix.setConversionChecker(TryCopyInitialization); 9580 9581 // Skip forward to the first bad conversion. 9582 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9583 unsigned ConvCount = Cand->NumConversions; 9584 while (true) { 9585 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9586 ConvIdx++; 9587 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9588 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9589 break; 9590 } 9591 } 9592 9593 if (ConvIdx == ConvCount) 9594 return; 9595 9596 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9597 "remaining conversion is initialized?"); 9598 9599 // FIXME: this should probably be preserved from the overload 9600 // operation somehow. 9601 bool SuppressUserConversions = false; 9602 9603 const FunctionProtoType* Proto; 9604 unsigned ArgIdx = ConvIdx; 9605 9606 if (Cand->IsSurrogate) { 9607 QualType ConvType 9608 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9609 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9610 ConvType = ConvPtrType->getPointeeType(); 9611 Proto = ConvType->getAs<FunctionProtoType>(); 9612 ArgIdx--; 9613 } else if (Cand->Function) { 9614 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9615 if (isa<CXXMethodDecl>(Cand->Function) && 9616 !isa<CXXConstructorDecl>(Cand->Function)) 9617 ArgIdx--; 9618 } else { 9619 // Builtin binary operator with a bad first conversion. 9620 assert(ConvCount <= 3); 9621 for (; ConvIdx != ConvCount; ++ConvIdx) 9622 Cand->Conversions[ConvIdx] 9623 = TryCopyInitialization(S, Args[ConvIdx], 9624 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9625 SuppressUserConversions, 9626 /*InOverloadResolution*/ true, 9627 /*AllowObjCWritebackConversion=*/ 9628 S.getLangOpts().ObjCAutoRefCount); 9629 return; 9630 } 9631 9632 // Fill in the rest of the conversions. 9633 unsigned NumParams = Proto->getNumParams(); 9634 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9635 if (ArgIdx < NumParams) { 9636 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9637 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9638 /*InOverloadResolution=*/true, 9639 /*AllowObjCWritebackConversion=*/ 9640 S.getLangOpts().ObjCAutoRefCount); 9641 // Store the FixIt in the candidate if it exists. 9642 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9643 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9644 } 9645 else 9646 Cand->Conversions[ConvIdx].setEllipsis(); 9647 } 9648 } 9649 9650 /// PrintOverloadCandidates - When overload resolution fails, prints 9651 /// diagnostic messages containing the candidates in the candidate 9652 /// set. 9653 void OverloadCandidateSet::NoteCandidates(Sema &S, 9654 OverloadCandidateDisplayKind OCD, 9655 ArrayRef<Expr *> Args, 9656 StringRef Opc, 9657 SourceLocation OpLoc) { 9658 // Sort the candidates by viability and position. Sorting directly would 9659 // be prohibitive, so we make a set of pointers and sort those. 9660 SmallVector<OverloadCandidate*, 32> Cands; 9661 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9662 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9663 if (Cand->Viable) 9664 Cands.push_back(Cand); 9665 else if (OCD == OCD_AllCandidates) { 9666 CompleteNonViableCandidate(S, Cand, Args); 9667 if (Cand->Function || Cand->IsSurrogate) 9668 Cands.push_back(Cand); 9669 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9670 // want to list every possible builtin candidate. 9671 } 9672 } 9673 9674 std::sort(Cands.begin(), Cands.end(), 9675 CompareOverloadCandidatesForDisplay(S, Args.size())); 9676 9677 bool ReportedAmbiguousConversions = false; 9678 9679 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9680 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9681 unsigned CandsShown = 0; 9682 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9683 OverloadCandidate *Cand = *I; 9684 9685 // Set an arbitrary limit on the number of candidate functions we'll spam 9686 // the user with. FIXME: This limit should depend on details of the 9687 // candidate list. 9688 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9689 break; 9690 } 9691 ++CandsShown; 9692 9693 if (Cand->Function) 9694 NoteFunctionCandidate(S, Cand, Args.size()); 9695 else if (Cand->IsSurrogate) 9696 NoteSurrogateCandidate(S, Cand); 9697 else { 9698 assert(Cand->Viable && 9699 "Non-viable built-in candidates are not added to Cands."); 9700 // Generally we only see ambiguities including viable builtin 9701 // operators if overload resolution got screwed up by an 9702 // ambiguous user-defined conversion. 9703 // 9704 // FIXME: It's quite possible for different conversions to see 9705 // different ambiguities, though. 9706 if (!ReportedAmbiguousConversions) { 9707 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9708 ReportedAmbiguousConversions = true; 9709 } 9710 9711 // If this is a viable builtin, print it. 9712 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9713 } 9714 } 9715 9716 if (I != E) 9717 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9718 } 9719 9720 static SourceLocation 9721 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9722 return Cand->Specialization ? Cand->Specialization->getLocation() 9723 : SourceLocation(); 9724 } 9725 9726 namespace { 9727 struct CompareTemplateSpecCandidatesForDisplay { 9728 Sema &S; 9729 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9730 9731 bool operator()(const TemplateSpecCandidate *L, 9732 const TemplateSpecCandidate *R) { 9733 // Fast-path this check. 9734 if (L == R) 9735 return false; 9736 9737 // Assuming that both candidates are not matches... 9738 9739 // Sort by the ranking of deduction failures. 9740 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9741 return RankDeductionFailure(L->DeductionFailure) < 9742 RankDeductionFailure(R->DeductionFailure); 9743 9744 // Sort everything else by location. 9745 SourceLocation LLoc = GetLocationForCandidate(L); 9746 SourceLocation RLoc = GetLocationForCandidate(R); 9747 9748 // Put candidates without locations (e.g. builtins) at the end. 9749 if (LLoc.isInvalid()) 9750 return false; 9751 if (RLoc.isInvalid()) 9752 return true; 9753 9754 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9755 } 9756 }; 9757 } 9758 9759 /// Diagnose a template argument deduction failure. 9760 /// We are treating these failures as overload failures due to bad 9761 /// deductions. 9762 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9763 DiagnoseBadDeduction(S, Specialization, // pattern 9764 DeductionFailure, /*NumArgs=*/0); 9765 } 9766 9767 void TemplateSpecCandidateSet::destroyCandidates() { 9768 for (iterator i = begin(), e = end(); i != e; ++i) { 9769 i->DeductionFailure.Destroy(); 9770 } 9771 } 9772 9773 void TemplateSpecCandidateSet::clear() { 9774 destroyCandidates(); 9775 Candidates.clear(); 9776 } 9777 9778 /// NoteCandidates - When no template specialization match is found, prints 9779 /// diagnostic messages containing the non-matching specializations that form 9780 /// the candidate set. 9781 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9782 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9783 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9784 // Sort the candidates by position (assuming no candidate is a match). 9785 // Sorting directly would be prohibitive, so we make a set of pointers 9786 // and sort those. 9787 SmallVector<TemplateSpecCandidate *, 32> Cands; 9788 Cands.reserve(size()); 9789 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9790 if (Cand->Specialization) 9791 Cands.push_back(Cand); 9792 // Otherwise, this is a non-matching builtin candidate. We do not, 9793 // in general, want to list every possible builtin candidate. 9794 } 9795 9796 std::sort(Cands.begin(), Cands.end(), 9797 CompareTemplateSpecCandidatesForDisplay(S)); 9798 9799 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9800 // for generalization purposes (?). 9801 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9802 9803 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9804 unsigned CandsShown = 0; 9805 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9806 TemplateSpecCandidate *Cand = *I; 9807 9808 // Set an arbitrary limit on the number of candidates we'll spam 9809 // the user with. FIXME: This limit should depend on details of the 9810 // candidate list. 9811 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9812 break; 9813 ++CandsShown; 9814 9815 assert(Cand->Specialization && 9816 "Non-matching built-in candidates are not added to Cands."); 9817 Cand->NoteDeductionFailure(S); 9818 } 9819 9820 if (I != E) 9821 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9822 } 9823 9824 // [PossiblyAFunctionType] --> [Return] 9825 // NonFunctionType --> NonFunctionType 9826 // R (A) --> R(A) 9827 // R (*)(A) --> R (A) 9828 // R (&)(A) --> R (A) 9829 // R (S::*)(A) --> R (A) 9830 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9831 QualType Ret = PossiblyAFunctionType; 9832 if (const PointerType *ToTypePtr = 9833 PossiblyAFunctionType->getAs<PointerType>()) 9834 Ret = ToTypePtr->getPointeeType(); 9835 else if (const ReferenceType *ToTypeRef = 9836 PossiblyAFunctionType->getAs<ReferenceType>()) 9837 Ret = ToTypeRef->getPointeeType(); 9838 else if (const MemberPointerType *MemTypePtr = 9839 PossiblyAFunctionType->getAs<MemberPointerType>()) 9840 Ret = MemTypePtr->getPointeeType(); 9841 Ret = 9842 Context.getCanonicalType(Ret).getUnqualifiedType(); 9843 return Ret; 9844 } 9845 9846 namespace { 9847 // A helper class to help with address of function resolution 9848 // - allows us to avoid passing around all those ugly parameters 9849 class AddressOfFunctionResolver { 9850 Sema& S; 9851 Expr* SourceExpr; 9852 const QualType& TargetType; 9853 QualType TargetFunctionType; // Extracted function type from target type 9854 9855 bool Complain; 9856 //DeclAccessPair& ResultFunctionAccessPair; 9857 ASTContext& Context; 9858 9859 bool TargetTypeIsNonStaticMemberFunction; 9860 bool FoundNonTemplateFunction; 9861 bool StaticMemberFunctionFromBoundPointer; 9862 9863 OverloadExpr::FindResult OvlExprInfo; 9864 OverloadExpr *OvlExpr; 9865 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9866 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9867 TemplateSpecCandidateSet FailedCandidates; 9868 9869 public: 9870 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9871 const QualType &TargetType, bool Complain) 9872 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9873 Complain(Complain), Context(S.getASTContext()), 9874 TargetTypeIsNonStaticMemberFunction( 9875 !!TargetType->getAs<MemberPointerType>()), 9876 FoundNonTemplateFunction(false), 9877 StaticMemberFunctionFromBoundPointer(false), 9878 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9879 OvlExpr(OvlExprInfo.Expression), 9880 FailedCandidates(OvlExpr->getNameLoc()) { 9881 ExtractUnqualifiedFunctionTypeFromTargetType(); 9882 9883 if (TargetFunctionType->isFunctionType()) { 9884 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9885 if (!UME->isImplicitAccess() && 9886 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9887 StaticMemberFunctionFromBoundPointer = true; 9888 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9889 DeclAccessPair dap; 9890 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9891 OvlExpr, false, &dap)) { 9892 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9893 if (!Method->isStatic()) { 9894 // If the target type is a non-function type and the function found 9895 // is a non-static member function, pretend as if that was the 9896 // target, it's the only possible type to end up with. 9897 TargetTypeIsNonStaticMemberFunction = true; 9898 9899 // And skip adding the function if its not in the proper form. 9900 // We'll diagnose this due to an empty set of functions. 9901 if (!OvlExprInfo.HasFormOfMemberPointer) 9902 return; 9903 } 9904 9905 Matches.push_back(std::make_pair(dap, Fn)); 9906 } 9907 return; 9908 } 9909 9910 if (OvlExpr->hasExplicitTemplateArgs()) 9911 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9912 9913 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9914 // C++ [over.over]p4: 9915 // If more than one function is selected, [...] 9916 if (Matches.size() > 1) { 9917 if (FoundNonTemplateFunction) 9918 EliminateAllTemplateMatches(); 9919 else 9920 EliminateAllExceptMostSpecializedTemplate(); 9921 } 9922 } 9923 } 9924 9925 private: 9926 bool isTargetTypeAFunction() const { 9927 return TargetFunctionType->isFunctionType(); 9928 } 9929 9930 // [ToType] [Return] 9931 9932 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9933 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9934 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9935 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9936 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9937 } 9938 9939 // return true if any matching specializations were found 9940 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9941 const DeclAccessPair& CurAccessFunPair) { 9942 if (CXXMethodDecl *Method 9943 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9944 // Skip non-static function templates when converting to pointer, and 9945 // static when converting to member pointer. 9946 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9947 return false; 9948 } 9949 else if (TargetTypeIsNonStaticMemberFunction) 9950 return false; 9951 9952 // C++ [over.over]p2: 9953 // If the name is a function template, template argument deduction is 9954 // done (14.8.2.2), and if the argument deduction succeeds, the 9955 // resulting template argument list is used to generate a single 9956 // function template specialization, which is added to the set of 9957 // overloaded functions considered. 9958 FunctionDecl *Specialization = nullptr; 9959 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9960 if (Sema::TemplateDeductionResult Result 9961 = S.DeduceTemplateArguments(FunctionTemplate, 9962 &OvlExplicitTemplateArgs, 9963 TargetFunctionType, Specialization, 9964 Info, /*InOverloadResolution=*/true)) { 9965 // Make a note of the failed deduction for diagnostics. 9966 FailedCandidates.addCandidate() 9967 .set(FunctionTemplate->getTemplatedDecl(), 9968 MakeDeductionFailureInfo(Context, Result, Info)); 9969 return false; 9970 } 9971 9972 // Template argument deduction ensures that we have an exact match or 9973 // compatible pointer-to-function arguments that would be adjusted by ICS. 9974 // This function template specicalization works. 9975 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9976 assert(S.isSameOrCompatibleFunctionType( 9977 Context.getCanonicalType(Specialization->getType()), 9978 Context.getCanonicalType(TargetFunctionType))); 9979 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9980 return true; 9981 } 9982 9983 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9984 const DeclAccessPair& CurAccessFunPair) { 9985 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9986 // Skip non-static functions when converting to pointer, and static 9987 // when converting to member pointer. 9988 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9989 return false; 9990 } 9991 else if (TargetTypeIsNonStaticMemberFunction) 9992 return false; 9993 9994 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9995 if (S.getLangOpts().CUDA) 9996 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9997 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 9998 return false; 9999 10000 // If any candidate has a placeholder return type, trigger its deduction 10001 // now. 10002 if (S.getLangOpts().CPlusPlus14 && 10003 FunDecl->getReturnType()->isUndeducedType() && 10004 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 10005 return false; 10006 10007 QualType ResultTy; 10008 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10009 FunDecl->getType()) || 10010 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10011 ResultTy)) { 10012 Matches.push_back(std::make_pair(CurAccessFunPair, 10013 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10014 FoundNonTemplateFunction = true; 10015 return true; 10016 } 10017 } 10018 10019 return false; 10020 } 10021 10022 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10023 bool Ret = false; 10024 10025 // If the overload expression doesn't have the form of a pointer to 10026 // member, don't try to convert it to a pointer-to-member type. 10027 if (IsInvalidFormOfPointerToMemberFunction()) 10028 return false; 10029 10030 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10031 E = OvlExpr->decls_end(); 10032 I != E; ++I) { 10033 // Look through any using declarations to find the underlying function. 10034 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10035 10036 // C++ [over.over]p3: 10037 // Non-member functions and static member functions match 10038 // targets of type "pointer-to-function" or "reference-to-function." 10039 // Nonstatic member functions match targets of 10040 // type "pointer-to-member-function." 10041 // Note that according to DR 247, the containing class does not matter. 10042 if (FunctionTemplateDecl *FunctionTemplate 10043 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10044 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10045 Ret = true; 10046 } 10047 // If we have explicit template arguments supplied, skip non-templates. 10048 else if (!OvlExpr->hasExplicitTemplateArgs() && 10049 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10050 Ret = true; 10051 } 10052 assert(Ret || Matches.empty()); 10053 return Ret; 10054 } 10055 10056 void EliminateAllExceptMostSpecializedTemplate() { 10057 // [...] and any given function template specialization F1 is 10058 // eliminated if the set contains a second function template 10059 // specialization whose function template is more specialized 10060 // than the function template of F1 according to the partial 10061 // ordering rules of 14.5.5.2. 10062 10063 // The algorithm specified above is quadratic. We instead use a 10064 // two-pass algorithm (similar to the one used to identify the 10065 // best viable function in an overload set) that identifies the 10066 // best function template (if it exists). 10067 10068 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10069 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10070 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10071 10072 // TODO: It looks like FailedCandidates does not serve much purpose 10073 // here, since the no_viable diagnostic has index 0. 10074 UnresolvedSetIterator Result = S.getMostSpecialized( 10075 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10076 SourceExpr->getLocStart(), S.PDiag(), 10077 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10078 .second->getDeclName(), 10079 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10080 Complain, TargetFunctionType); 10081 10082 if (Result != MatchesCopy.end()) { 10083 // Make it the first and only element 10084 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10085 Matches[0].second = cast<FunctionDecl>(*Result); 10086 Matches.resize(1); 10087 } 10088 } 10089 10090 void EliminateAllTemplateMatches() { 10091 // [...] any function template specializations in the set are 10092 // eliminated if the set also contains a non-template function, [...] 10093 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10094 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10095 ++I; 10096 else { 10097 Matches[I] = Matches[--N]; 10098 Matches.set_size(N); 10099 } 10100 } 10101 } 10102 10103 public: 10104 void ComplainNoMatchesFound() const { 10105 assert(Matches.empty()); 10106 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10107 << OvlExpr->getName() << TargetFunctionType 10108 << OvlExpr->getSourceRange(); 10109 if (FailedCandidates.empty()) 10110 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10111 else { 10112 // We have some deduction failure messages. Use them to diagnose 10113 // the function templates, and diagnose the non-template candidates 10114 // normally. 10115 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10116 IEnd = OvlExpr->decls_end(); 10117 I != IEnd; ++I) 10118 if (FunctionDecl *Fun = 10119 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10120 S.NoteOverloadCandidate(Fun, TargetFunctionType); 10121 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10122 } 10123 } 10124 10125 bool IsInvalidFormOfPointerToMemberFunction() const { 10126 return TargetTypeIsNonStaticMemberFunction && 10127 !OvlExprInfo.HasFormOfMemberPointer; 10128 } 10129 10130 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10131 // TODO: Should we condition this on whether any functions might 10132 // have matched, or is it more appropriate to do that in callers? 10133 // TODO: a fixit wouldn't hurt. 10134 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10135 << TargetType << OvlExpr->getSourceRange(); 10136 } 10137 10138 bool IsStaticMemberFunctionFromBoundPointer() const { 10139 return StaticMemberFunctionFromBoundPointer; 10140 } 10141 10142 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10143 S.Diag(OvlExpr->getLocStart(), 10144 diag::err_invalid_form_pointer_member_function) 10145 << OvlExpr->getSourceRange(); 10146 } 10147 10148 void ComplainOfInvalidConversion() const { 10149 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10150 << OvlExpr->getName() << TargetType; 10151 } 10152 10153 void ComplainMultipleMatchesFound() const { 10154 assert(Matches.size() > 1); 10155 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10156 << OvlExpr->getName() 10157 << OvlExpr->getSourceRange(); 10158 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10159 } 10160 10161 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10162 10163 int getNumMatches() const { return Matches.size(); } 10164 10165 FunctionDecl* getMatchingFunctionDecl() const { 10166 if (Matches.size() != 1) return nullptr; 10167 return Matches[0].second; 10168 } 10169 10170 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10171 if (Matches.size() != 1) return nullptr; 10172 return &Matches[0].first; 10173 } 10174 }; 10175 } 10176 10177 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10178 /// an overloaded function (C++ [over.over]), where @p From is an 10179 /// expression with overloaded function type and @p ToType is the type 10180 /// we're trying to resolve to. For example: 10181 /// 10182 /// @code 10183 /// int f(double); 10184 /// int f(int); 10185 /// 10186 /// int (*pfd)(double) = f; // selects f(double) 10187 /// @endcode 10188 /// 10189 /// This routine returns the resulting FunctionDecl if it could be 10190 /// resolved, and NULL otherwise. When @p Complain is true, this 10191 /// routine will emit diagnostics if there is an error. 10192 FunctionDecl * 10193 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10194 QualType TargetType, 10195 bool Complain, 10196 DeclAccessPair &FoundResult, 10197 bool *pHadMultipleCandidates) { 10198 assert(AddressOfExpr->getType() == Context.OverloadTy); 10199 10200 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10201 Complain); 10202 int NumMatches = Resolver.getNumMatches(); 10203 FunctionDecl *Fn = nullptr; 10204 if (NumMatches == 0 && Complain) { 10205 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10206 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10207 else 10208 Resolver.ComplainNoMatchesFound(); 10209 } 10210 else if (NumMatches > 1 && Complain) 10211 Resolver.ComplainMultipleMatchesFound(); 10212 else if (NumMatches == 1) { 10213 Fn = Resolver.getMatchingFunctionDecl(); 10214 assert(Fn); 10215 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10216 if (Complain) { 10217 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10218 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10219 else 10220 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10221 } 10222 } 10223 10224 if (pHadMultipleCandidates) 10225 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10226 return Fn; 10227 } 10228 10229 /// \brief Given an expression that refers to an overloaded function, try to 10230 /// resolve that overloaded function expression down to a single function. 10231 /// 10232 /// This routine can only resolve template-ids that refer to a single function 10233 /// template, where that template-id refers to a single template whose template 10234 /// arguments are either provided by the template-id or have defaults, 10235 /// as described in C++0x [temp.arg.explicit]p3. 10236 /// 10237 /// If no template-ids are found, no diagnostics are emitted and NULL is 10238 /// returned. 10239 FunctionDecl * 10240 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10241 bool Complain, 10242 DeclAccessPair *FoundResult) { 10243 // C++ [over.over]p1: 10244 // [...] [Note: any redundant set of parentheses surrounding the 10245 // overloaded function name is ignored (5.1). ] 10246 // C++ [over.over]p1: 10247 // [...] The overloaded function name can be preceded by the & 10248 // operator. 10249 10250 // If we didn't actually find any template-ids, we're done. 10251 if (!ovl->hasExplicitTemplateArgs()) 10252 return nullptr; 10253 10254 TemplateArgumentListInfo ExplicitTemplateArgs; 10255 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10256 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10257 10258 // Look through all of the overloaded functions, searching for one 10259 // whose type matches exactly. 10260 FunctionDecl *Matched = nullptr; 10261 for (UnresolvedSetIterator I = ovl->decls_begin(), 10262 E = ovl->decls_end(); I != E; ++I) { 10263 // C++0x [temp.arg.explicit]p3: 10264 // [...] In contexts where deduction is done and fails, or in contexts 10265 // where deduction is not done, if a template argument list is 10266 // specified and it, along with any default template arguments, 10267 // identifies a single function template specialization, then the 10268 // template-id is an lvalue for the function template specialization. 10269 FunctionTemplateDecl *FunctionTemplate 10270 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10271 10272 // C++ [over.over]p2: 10273 // If the name is a function template, template argument deduction is 10274 // done (14.8.2.2), and if the argument deduction succeeds, the 10275 // resulting template argument list is used to generate a single 10276 // function template specialization, which is added to the set of 10277 // overloaded functions considered. 10278 FunctionDecl *Specialization = nullptr; 10279 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10280 if (TemplateDeductionResult Result 10281 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10282 Specialization, Info, 10283 /*InOverloadResolution=*/true)) { 10284 // Make a note of the failed deduction for diagnostics. 10285 // TODO: Actually use the failed-deduction info? 10286 FailedCandidates.addCandidate() 10287 .set(FunctionTemplate->getTemplatedDecl(), 10288 MakeDeductionFailureInfo(Context, Result, Info)); 10289 continue; 10290 } 10291 10292 assert(Specialization && "no specialization and no error?"); 10293 10294 // Multiple matches; we can't resolve to a single declaration. 10295 if (Matched) { 10296 if (Complain) { 10297 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10298 << ovl->getName(); 10299 NoteAllOverloadCandidates(ovl); 10300 } 10301 return nullptr; 10302 } 10303 10304 Matched = Specialization; 10305 if (FoundResult) *FoundResult = I.getPair(); 10306 } 10307 10308 if (Matched && getLangOpts().CPlusPlus14 && 10309 Matched->getReturnType()->isUndeducedType() && 10310 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10311 return nullptr; 10312 10313 return Matched; 10314 } 10315 10316 10317 10318 10319 // Resolve and fix an overloaded expression that can be resolved 10320 // because it identifies a single function template specialization. 10321 // 10322 // Last three arguments should only be supplied if Complain = true 10323 // 10324 // Return true if it was logically possible to so resolve the 10325 // expression, regardless of whether or not it succeeded. Always 10326 // returns true if 'complain' is set. 10327 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10328 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10329 bool complain, const SourceRange& OpRangeForComplaining, 10330 QualType DestTypeForComplaining, 10331 unsigned DiagIDForComplaining) { 10332 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10333 10334 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10335 10336 DeclAccessPair found; 10337 ExprResult SingleFunctionExpression; 10338 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10339 ovl.Expression, /*complain*/ false, &found)) { 10340 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10341 SrcExpr = ExprError(); 10342 return true; 10343 } 10344 10345 // It is only correct to resolve to an instance method if we're 10346 // resolving a form that's permitted to be a pointer to member. 10347 // Otherwise we'll end up making a bound member expression, which 10348 // is illegal in all the contexts we resolve like this. 10349 if (!ovl.HasFormOfMemberPointer && 10350 isa<CXXMethodDecl>(fn) && 10351 cast<CXXMethodDecl>(fn)->isInstance()) { 10352 if (!complain) return false; 10353 10354 Diag(ovl.Expression->getExprLoc(), 10355 diag::err_bound_member_function) 10356 << 0 << ovl.Expression->getSourceRange(); 10357 10358 // TODO: I believe we only end up here if there's a mix of 10359 // static and non-static candidates (otherwise the expression 10360 // would have 'bound member' type, not 'overload' type). 10361 // Ideally we would note which candidate was chosen and why 10362 // the static candidates were rejected. 10363 SrcExpr = ExprError(); 10364 return true; 10365 } 10366 10367 // Fix the expression to refer to 'fn'. 10368 SingleFunctionExpression = 10369 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10370 10371 // If desired, do function-to-pointer decay. 10372 if (doFunctionPointerConverion) { 10373 SingleFunctionExpression = 10374 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10375 if (SingleFunctionExpression.isInvalid()) { 10376 SrcExpr = ExprError(); 10377 return true; 10378 } 10379 } 10380 } 10381 10382 if (!SingleFunctionExpression.isUsable()) { 10383 if (complain) { 10384 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10385 << ovl.Expression->getName() 10386 << DestTypeForComplaining 10387 << OpRangeForComplaining 10388 << ovl.Expression->getQualifierLoc().getSourceRange(); 10389 NoteAllOverloadCandidates(SrcExpr.get()); 10390 10391 SrcExpr = ExprError(); 10392 return true; 10393 } 10394 10395 return false; 10396 } 10397 10398 SrcExpr = SingleFunctionExpression; 10399 return true; 10400 } 10401 10402 /// \brief Add a single candidate to the overload set. 10403 static void AddOverloadedCallCandidate(Sema &S, 10404 DeclAccessPair FoundDecl, 10405 TemplateArgumentListInfo *ExplicitTemplateArgs, 10406 ArrayRef<Expr *> Args, 10407 OverloadCandidateSet &CandidateSet, 10408 bool PartialOverloading, 10409 bool KnownValid) { 10410 NamedDecl *Callee = FoundDecl.getDecl(); 10411 if (isa<UsingShadowDecl>(Callee)) 10412 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10413 10414 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10415 if (ExplicitTemplateArgs) { 10416 assert(!KnownValid && "Explicit template arguments?"); 10417 return; 10418 } 10419 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10420 /*SuppressUsedConversions=*/false, 10421 PartialOverloading); 10422 return; 10423 } 10424 10425 if (FunctionTemplateDecl *FuncTemplate 10426 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10427 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10428 ExplicitTemplateArgs, Args, CandidateSet, 10429 /*SuppressUsedConversions=*/false, 10430 PartialOverloading); 10431 return; 10432 } 10433 10434 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10435 } 10436 10437 /// \brief Add the overload candidates named by callee and/or found by argument 10438 /// dependent lookup to the given overload set. 10439 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10440 ArrayRef<Expr *> Args, 10441 OverloadCandidateSet &CandidateSet, 10442 bool PartialOverloading) { 10443 10444 #ifndef NDEBUG 10445 // Verify that ArgumentDependentLookup is consistent with the rules 10446 // in C++0x [basic.lookup.argdep]p3: 10447 // 10448 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10449 // and let Y be the lookup set produced by argument dependent 10450 // lookup (defined as follows). If X contains 10451 // 10452 // -- a declaration of a class member, or 10453 // 10454 // -- a block-scope function declaration that is not a 10455 // using-declaration, or 10456 // 10457 // -- a declaration that is neither a function or a function 10458 // template 10459 // 10460 // then Y is empty. 10461 10462 if (ULE->requiresADL()) { 10463 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10464 E = ULE->decls_end(); I != E; ++I) { 10465 assert(!(*I)->getDeclContext()->isRecord()); 10466 assert(isa<UsingShadowDecl>(*I) || 10467 !(*I)->getDeclContext()->isFunctionOrMethod()); 10468 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10469 } 10470 } 10471 #endif 10472 10473 // It would be nice to avoid this copy. 10474 TemplateArgumentListInfo TABuffer; 10475 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10476 if (ULE->hasExplicitTemplateArgs()) { 10477 ULE->copyTemplateArgumentsInto(TABuffer); 10478 ExplicitTemplateArgs = &TABuffer; 10479 } 10480 10481 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10482 E = ULE->decls_end(); I != E; ++I) 10483 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10484 CandidateSet, PartialOverloading, 10485 /*KnownValid*/ true); 10486 10487 if (ULE->requiresADL()) 10488 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10489 Args, ExplicitTemplateArgs, 10490 CandidateSet, PartialOverloading); 10491 } 10492 10493 /// Determine whether a declaration with the specified name could be moved into 10494 /// a different namespace. 10495 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10496 switch (Name.getCXXOverloadedOperator()) { 10497 case OO_New: case OO_Array_New: 10498 case OO_Delete: case OO_Array_Delete: 10499 return false; 10500 10501 default: 10502 return true; 10503 } 10504 } 10505 10506 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10507 /// template, where the non-dependent name was declared after the template 10508 /// was defined. This is common in code written for a compilers which do not 10509 /// correctly implement two-stage name lookup. 10510 /// 10511 /// Returns true if a viable candidate was found and a diagnostic was issued. 10512 static bool 10513 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10514 const CXXScopeSpec &SS, LookupResult &R, 10515 OverloadCandidateSet::CandidateSetKind CSK, 10516 TemplateArgumentListInfo *ExplicitTemplateArgs, 10517 ArrayRef<Expr *> Args, 10518 bool *DoDiagnoseEmptyLookup = nullptr) { 10519 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10520 return false; 10521 10522 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10523 if (DC->isTransparentContext()) 10524 continue; 10525 10526 SemaRef.LookupQualifiedName(R, DC); 10527 10528 if (!R.empty()) { 10529 R.suppressDiagnostics(); 10530 10531 if (isa<CXXRecordDecl>(DC)) { 10532 // Don't diagnose names we find in classes; we get much better 10533 // diagnostics for these from DiagnoseEmptyLookup. 10534 R.clear(); 10535 if (DoDiagnoseEmptyLookup) 10536 *DoDiagnoseEmptyLookup = true; 10537 return false; 10538 } 10539 10540 OverloadCandidateSet Candidates(FnLoc, CSK); 10541 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10542 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10543 ExplicitTemplateArgs, Args, 10544 Candidates, false, /*KnownValid*/ false); 10545 10546 OverloadCandidateSet::iterator Best; 10547 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10548 // No viable functions. Don't bother the user with notes for functions 10549 // which don't work and shouldn't be found anyway. 10550 R.clear(); 10551 return false; 10552 } 10553 10554 // Find the namespaces where ADL would have looked, and suggest 10555 // declaring the function there instead. 10556 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10557 Sema::AssociatedClassSet AssociatedClasses; 10558 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10559 AssociatedNamespaces, 10560 AssociatedClasses); 10561 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10562 if (canBeDeclaredInNamespace(R.getLookupName())) { 10563 DeclContext *Std = SemaRef.getStdNamespace(); 10564 for (Sema::AssociatedNamespaceSet::iterator 10565 it = AssociatedNamespaces.begin(), 10566 end = AssociatedNamespaces.end(); it != end; ++it) { 10567 // Never suggest declaring a function within namespace 'std'. 10568 if (Std && Std->Encloses(*it)) 10569 continue; 10570 10571 // Never suggest declaring a function within a namespace with a 10572 // reserved name, like __gnu_cxx. 10573 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10574 if (NS && 10575 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10576 continue; 10577 10578 SuggestedNamespaces.insert(*it); 10579 } 10580 } 10581 10582 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10583 << R.getLookupName(); 10584 if (SuggestedNamespaces.empty()) { 10585 SemaRef.Diag(Best->Function->getLocation(), 10586 diag::note_not_found_by_two_phase_lookup) 10587 << R.getLookupName() << 0; 10588 } else if (SuggestedNamespaces.size() == 1) { 10589 SemaRef.Diag(Best->Function->getLocation(), 10590 diag::note_not_found_by_two_phase_lookup) 10591 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10592 } else { 10593 // FIXME: It would be useful to list the associated namespaces here, 10594 // but the diagnostics infrastructure doesn't provide a way to produce 10595 // a localized representation of a list of items. 10596 SemaRef.Diag(Best->Function->getLocation(), 10597 diag::note_not_found_by_two_phase_lookup) 10598 << R.getLookupName() << 2; 10599 } 10600 10601 // Try to recover by calling this function. 10602 return true; 10603 } 10604 10605 R.clear(); 10606 } 10607 10608 return false; 10609 } 10610 10611 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10612 /// template, where the non-dependent operator was declared after the template 10613 /// was defined. 10614 /// 10615 /// Returns true if a viable candidate was found and a diagnostic was issued. 10616 static bool 10617 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10618 SourceLocation OpLoc, 10619 ArrayRef<Expr *> Args) { 10620 DeclarationName OpName = 10621 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10622 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10623 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10624 OverloadCandidateSet::CSK_Operator, 10625 /*ExplicitTemplateArgs=*/nullptr, Args); 10626 } 10627 10628 namespace { 10629 class BuildRecoveryCallExprRAII { 10630 Sema &SemaRef; 10631 public: 10632 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10633 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10634 SemaRef.IsBuildingRecoveryCallExpr = true; 10635 } 10636 10637 ~BuildRecoveryCallExprRAII() { 10638 SemaRef.IsBuildingRecoveryCallExpr = false; 10639 } 10640 }; 10641 10642 } 10643 10644 static std::unique_ptr<CorrectionCandidateCallback> 10645 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10646 bool HasTemplateArgs, bool AllowTypoCorrection) { 10647 if (!AllowTypoCorrection) 10648 return llvm::make_unique<NoTypoCorrectionCCC>(); 10649 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10650 HasTemplateArgs, ME); 10651 } 10652 10653 /// Attempts to recover from a call where no functions were found. 10654 /// 10655 /// Returns true if new candidates were found. 10656 static ExprResult 10657 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10658 UnresolvedLookupExpr *ULE, 10659 SourceLocation LParenLoc, 10660 MutableArrayRef<Expr *> Args, 10661 SourceLocation RParenLoc, 10662 bool EmptyLookup, bool AllowTypoCorrection) { 10663 // Do not try to recover if it is already building a recovery call. 10664 // This stops infinite loops for template instantiations like 10665 // 10666 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10667 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10668 // 10669 if (SemaRef.IsBuildingRecoveryCallExpr) 10670 return ExprError(); 10671 BuildRecoveryCallExprRAII RCE(SemaRef); 10672 10673 CXXScopeSpec SS; 10674 SS.Adopt(ULE->getQualifierLoc()); 10675 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10676 10677 TemplateArgumentListInfo TABuffer; 10678 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10679 if (ULE->hasExplicitTemplateArgs()) { 10680 ULE->copyTemplateArgumentsInto(TABuffer); 10681 ExplicitTemplateArgs = &TABuffer; 10682 } 10683 10684 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10685 Sema::LookupOrdinaryName); 10686 bool DoDiagnoseEmptyLookup = EmptyLookup; 10687 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10688 OverloadCandidateSet::CSK_Normal, 10689 ExplicitTemplateArgs, Args, 10690 &DoDiagnoseEmptyLookup) && 10691 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 10692 S, SS, R, 10693 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10694 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10695 ExplicitTemplateArgs, Args))) 10696 return ExprError(); 10697 10698 assert(!R.empty() && "lookup results empty despite recovery"); 10699 10700 // Build an implicit member call if appropriate. Just drop the 10701 // casts and such from the call, we don't really care. 10702 ExprResult NewFn = ExprError(); 10703 if ((*R.begin())->isCXXClassMember()) 10704 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10705 R, ExplicitTemplateArgs); 10706 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10707 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10708 ExplicitTemplateArgs); 10709 else 10710 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10711 10712 if (NewFn.isInvalid()) 10713 return ExprError(); 10714 10715 // This shouldn't cause an infinite loop because we're giving it 10716 // an expression with viable lookup results, which should never 10717 // end up here. 10718 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10719 MultiExprArg(Args.data(), Args.size()), 10720 RParenLoc); 10721 } 10722 10723 /// \brief Constructs and populates an OverloadedCandidateSet from 10724 /// the given function. 10725 /// \returns true when an the ExprResult output parameter has been set. 10726 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10727 UnresolvedLookupExpr *ULE, 10728 MultiExprArg Args, 10729 SourceLocation RParenLoc, 10730 OverloadCandidateSet *CandidateSet, 10731 ExprResult *Result) { 10732 #ifndef NDEBUG 10733 if (ULE->requiresADL()) { 10734 // To do ADL, we must have found an unqualified name. 10735 assert(!ULE->getQualifier() && "qualified name with ADL"); 10736 10737 // We don't perform ADL for implicit declarations of builtins. 10738 // Verify that this was correctly set up. 10739 FunctionDecl *F; 10740 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10741 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10742 F->getBuiltinID() && F->isImplicit()) 10743 llvm_unreachable("performing ADL for builtin"); 10744 10745 // We don't perform ADL in C. 10746 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10747 } 10748 #endif 10749 10750 UnbridgedCastsSet UnbridgedCasts; 10751 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10752 *Result = ExprError(); 10753 return true; 10754 } 10755 10756 // Add the functions denoted by the callee to the set of candidate 10757 // functions, including those from argument-dependent lookup. 10758 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10759 10760 if (getLangOpts().MSVCCompat && 10761 CurContext->isDependentContext() && !isSFINAEContext() && 10762 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10763 10764 OverloadCandidateSet::iterator Best; 10765 if (CandidateSet->empty() || 10766 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 10767 OR_No_Viable_Function) { 10768 // In Microsoft mode, if we are inside a template class member function then 10769 // create a type dependent CallExpr. The goal is to postpone name lookup 10770 // to instantiation time to be able to search into type dependent base 10771 // classes. 10772 CallExpr *CE = new (Context) CallExpr( 10773 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 10774 CE->setTypeDependent(true); 10775 *Result = CE; 10776 return true; 10777 } 10778 } 10779 10780 if (CandidateSet->empty()) 10781 return false; 10782 10783 UnbridgedCasts.restore(); 10784 return false; 10785 } 10786 10787 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10788 /// the completed call expression. If overload resolution fails, emits 10789 /// diagnostics and returns ExprError() 10790 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10791 UnresolvedLookupExpr *ULE, 10792 SourceLocation LParenLoc, 10793 MultiExprArg Args, 10794 SourceLocation RParenLoc, 10795 Expr *ExecConfig, 10796 OverloadCandidateSet *CandidateSet, 10797 OverloadCandidateSet::iterator *Best, 10798 OverloadingResult OverloadResult, 10799 bool AllowTypoCorrection) { 10800 if (CandidateSet->empty()) 10801 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10802 RParenLoc, /*EmptyLookup=*/true, 10803 AllowTypoCorrection); 10804 10805 switch (OverloadResult) { 10806 case OR_Success: { 10807 FunctionDecl *FDecl = (*Best)->Function; 10808 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10809 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10810 return ExprError(); 10811 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10812 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10813 ExecConfig); 10814 } 10815 10816 case OR_No_Viable_Function: { 10817 // Try to recover by looking for viable functions which the user might 10818 // have meant to call. 10819 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10820 Args, RParenLoc, 10821 /*EmptyLookup=*/false, 10822 AllowTypoCorrection); 10823 if (!Recovery.isInvalid()) 10824 return Recovery; 10825 10826 SemaRef.Diag(Fn->getLocStart(), 10827 diag::err_ovl_no_viable_function_in_call) 10828 << ULE->getName() << Fn->getSourceRange(); 10829 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10830 break; 10831 } 10832 10833 case OR_Ambiguous: 10834 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10835 << ULE->getName() << Fn->getSourceRange(); 10836 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10837 break; 10838 10839 case OR_Deleted: { 10840 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10841 << (*Best)->Function->isDeleted() 10842 << ULE->getName() 10843 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10844 << Fn->getSourceRange(); 10845 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10846 10847 // We emitted an error for the unvailable/deleted function call but keep 10848 // the call in the AST. 10849 FunctionDecl *FDecl = (*Best)->Function; 10850 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10851 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10852 ExecConfig); 10853 } 10854 } 10855 10856 // Overload resolution failed. 10857 return ExprError(); 10858 } 10859 10860 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10861 /// (which eventually refers to the declaration Func) and the call 10862 /// arguments Args/NumArgs, attempt to resolve the function call down 10863 /// to a specific function. If overload resolution succeeds, returns 10864 /// the call expression produced by overload resolution. 10865 /// Otherwise, emits diagnostics and returns ExprError. 10866 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10867 UnresolvedLookupExpr *ULE, 10868 SourceLocation LParenLoc, 10869 MultiExprArg Args, 10870 SourceLocation RParenLoc, 10871 Expr *ExecConfig, 10872 bool AllowTypoCorrection) { 10873 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10874 OverloadCandidateSet::CSK_Normal); 10875 ExprResult result; 10876 10877 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10878 &result)) 10879 return result; 10880 10881 OverloadCandidateSet::iterator Best; 10882 OverloadingResult OverloadResult = 10883 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10884 10885 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10886 RParenLoc, ExecConfig, &CandidateSet, 10887 &Best, OverloadResult, 10888 AllowTypoCorrection); 10889 } 10890 10891 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10892 return Functions.size() > 1 || 10893 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10894 } 10895 10896 /// \brief Create a unary operation that may resolve to an overloaded 10897 /// operator. 10898 /// 10899 /// \param OpLoc The location of the operator itself (e.g., '*'). 10900 /// 10901 /// \param OpcIn The UnaryOperator::Opcode that describes this 10902 /// operator. 10903 /// 10904 /// \param Fns The set of non-member functions that will be 10905 /// considered by overload resolution. The caller needs to build this 10906 /// set based on the context using, e.g., 10907 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10908 /// set should not contain any member functions; those will be added 10909 /// by CreateOverloadedUnaryOp(). 10910 /// 10911 /// \param Input The input argument. 10912 ExprResult 10913 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10914 const UnresolvedSetImpl &Fns, 10915 Expr *Input) { 10916 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10917 10918 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10919 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10920 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10921 // TODO: provide better source location info. 10922 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10923 10924 if (checkPlaceholderForOverload(*this, Input)) 10925 return ExprError(); 10926 10927 Expr *Args[2] = { Input, nullptr }; 10928 unsigned NumArgs = 1; 10929 10930 // For post-increment and post-decrement, add the implicit '0' as 10931 // the second argument, so that we know this is a post-increment or 10932 // post-decrement. 10933 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10934 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10935 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10936 SourceLocation()); 10937 NumArgs = 2; 10938 } 10939 10940 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10941 10942 if (Input->isTypeDependent()) { 10943 if (Fns.empty()) 10944 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 10945 VK_RValue, OK_Ordinary, OpLoc); 10946 10947 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 10948 UnresolvedLookupExpr *Fn 10949 = UnresolvedLookupExpr::Create(Context, NamingClass, 10950 NestedNameSpecifierLoc(), OpNameInfo, 10951 /*ADL*/ true, IsOverloaded(Fns), 10952 Fns.begin(), Fns.end()); 10953 return new (Context) 10954 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 10955 VK_RValue, OpLoc, false); 10956 } 10957 10958 // Build an empty overload set. 10959 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10960 10961 // Add the candidates from the given function set. 10962 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 10963 10964 // Add operator candidates that are member functions. 10965 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10966 10967 // Add candidates from ADL. 10968 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10969 /*ExplicitTemplateArgs*/nullptr, 10970 CandidateSet); 10971 10972 // Add builtin operator candidates. 10973 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10974 10975 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10976 10977 // Perform overload resolution. 10978 OverloadCandidateSet::iterator Best; 10979 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10980 case OR_Success: { 10981 // We found a built-in operator or an overloaded operator. 10982 FunctionDecl *FnDecl = Best->Function; 10983 10984 if (FnDecl) { 10985 // We matched an overloaded operator. Build a call to that 10986 // operator. 10987 10988 // Convert the arguments. 10989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10990 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 10991 10992 ExprResult InputRes = 10993 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 10994 Best->FoundDecl, Method); 10995 if (InputRes.isInvalid()) 10996 return ExprError(); 10997 Input = InputRes.get(); 10998 } else { 10999 // Convert the arguments. 11000 ExprResult InputInit 11001 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11002 Context, 11003 FnDecl->getParamDecl(0)), 11004 SourceLocation(), 11005 Input); 11006 if (InputInit.isInvalid()) 11007 return ExprError(); 11008 Input = InputInit.get(); 11009 } 11010 11011 // Build the actual expression node. 11012 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11013 HadMultipleCandidates, OpLoc); 11014 if (FnExpr.isInvalid()) 11015 return ExprError(); 11016 11017 // Determine the result type. 11018 QualType ResultTy = FnDecl->getReturnType(); 11019 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11020 ResultTy = ResultTy.getNonLValueExprType(Context); 11021 11022 Args[0] = Input; 11023 CallExpr *TheCall = 11024 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11025 ResultTy, VK, OpLoc, false); 11026 11027 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11028 return ExprError(); 11029 11030 return MaybeBindToTemporary(TheCall); 11031 } else { 11032 // We matched a built-in operator. Convert the arguments, then 11033 // break out so that we will build the appropriate built-in 11034 // operator node. 11035 ExprResult InputRes = 11036 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11037 Best->Conversions[0], AA_Passing); 11038 if (InputRes.isInvalid()) 11039 return ExprError(); 11040 Input = InputRes.get(); 11041 break; 11042 } 11043 } 11044 11045 case OR_No_Viable_Function: 11046 // This is an erroneous use of an operator which can be overloaded by 11047 // a non-member function. Check for non-member operators which were 11048 // defined too late to be candidates. 11049 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11050 // FIXME: Recover by calling the found function. 11051 return ExprError(); 11052 11053 // No viable function; fall through to handling this as a 11054 // built-in operator, which will produce an error message for us. 11055 break; 11056 11057 case OR_Ambiguous: 11058 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11059 << UnaryOperator::getOpcodeStr(Opc) 11060 << Input->getType() 11061 << Input->getSourceRange(); 11062 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11063 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11064 return ExprError(); 11065 11066 case OR_Deleted: 11067 Diag(OpLoc, diag::err_ovl_deleted_oper) 11068 << Best->Function->isDeleted() 11069 << UnaryOperator::getOpcodeStr(Opc) 11070 << getDeletedOrUnavailableSuffix(Best->Function) 11071 << Input->getSourceRange(); 11072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11073 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11074 return ExprError(); 11075 } 11076 11077 // Either we found no viable overloaded operator or we matched a 11078 // built-in operator. In either case, fall through to trying to 11079 // build a built-in operation. 11080 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11081 } 11082 11083 /// \brief Create a binary operation that may resolve to an overloaded 11084 /// operator. 11085 /// 11086 /// \param OpLoc The location of the operator itself (e.g., '+'). 11087 /// 11088 /// \param OpcIn The BinaryOperator::Opcode that describes this 11089 /// operator. 11090 /// 11091 /// \param Fns The set of non-member functions that will be 11092 /// considered by overload resolution. The caller needs to build this 11093 /// set based on the context using, e.g., 11094 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11095 /// set should not contain any member functions; those will be added 11096 /// by CreateOverloadedBinOp(). 11097 /// 11098 /// \param LHS Left-hand argument. 11099 /// \param RHS Right-hand argument. 11100 ExprResult 11101 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11102 unsigned OpcIn, 11103 const UnresolvedSetImpl &Fns, 11104 Expr *LHS, Expr *RHS) { 11105 Expr *Args[2] = { LHS, RHS }; 11106 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11107 11108 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11109 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11110 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11111 11112 // If either side is type-dependent, create an appropriate dependent 11113 // expression. 11114 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11115 if (Fns.empty()) { 11116 // If there are no functions to store, just build a dependent 11117 // BinaryOperator or CompoundAssignment. 11118 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11119 return new (Context) BinaryOperator( 11120 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11121 OpLoc, FPFeatures.fp_contract); 11122 11123 return new (Context) CompoundAssignOperator( 11124 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11125 Context.DependentTy, Context.DependentTy, OpLoc, 11126 FPFeatures.fp_contract); 11127 } 11128 11129 // FIXME: save results of ADL from here? 11130 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11131 // TODO: provide better source location info in DNLoc component. 11132 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11133 UnresolvedLookupExpr *Fn 11134 = UnresolvedLookupExpr::Create(Context, NamingClass, 11135 NestedNameSpecifierLoc(), OpNameInfo, 11136 /*ADL*/ true, IsOverloaded(Fns), 11137 Fns.begin(), Fns.end()); 11138 return new (Context) 11139 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11140 VK_RValue, OpLoc, FPFeatures.fp_contract); 11141 } 11142 11143 // Always do placeholder-like conversions on the RHS. 11144 if (checkPlaceholderForOverload(*this, Args[1])) 11145 return ExprError(); 11146 11147 // Do placeholder-like conversion on the LHS; note that we should 11148 // not get here with a PseudoObject LHS. 11149 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11150 if (checkPlaceholderForOverload(*this, Args[0])) 11151 return ExprError(); 11152 11153 // If this is the assignment operator, we only perform overload resolution 11154 // if the left-hand side is a class or enumeration type. This is actually 11155 // a hack. The standard requires that we do overload resolution between the 11156 // various built-in candidates, but as DR507 points out, this can lead to 11157 // problems. So we do it this way, which pretty much follows what GCC does. 11158 // Note that we go the traditional code path for compound assignment forms. 11159 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11160 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11161 11162 // If this is the .* operator, which is not overloadable, just 11163 // create a built-in binary operator. 11164 if (Opc == BO_PtrMemD) 11165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11166 11167 // Build an empty overload set. 11168 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11169 11170 // Add the candidates from the given function set. 11171 AddFunctionCandidates(Fns, Args, CandidateSet); 11172 11173 // Add operator candidates that are member functions. 11174 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11175 11176 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11177 // performed for an assignment operator (nor for operator[] nor operator->, 11178 // which don't get here). 11179 if (Opc != BO_Assign) 11180 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11181 /*ExplicitTemplateArgs*/ nullptr, 11182 CandidateSet); 11183 11184 // Add builtin operator candidates. 11185 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11186 11187 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11188 11189 // Perform overload resolution. 11190 OverloadCandidateSet::iterator Best; 11191 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11192 case OR_Success: { 11193 // We found a built-in operator or an overloaded operator. 11194 FunctionDecl *FnDecl = Best->Function; 11195 11196 if (FnDecl) { 11197 // We matched an overloaded operator. Build a call to that 11198 // operator. 11199 11200 // Convert the arguments. 11201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11202 // Best->Access is only meaningful for class members. 11203 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11204 11205 ExprResult Arg1 = 11206 PerformCopyInitialization( 11207 InitializedEntity::InitializeParameter(Context, 11208 FnDecl->getParamDecl(0)), 11209 SourceLocation(), Args[1]); 11210 if (Arg1.isInvalid()) 11211 return ExprError(); 11212 11213 ExprResult Arg0 = 11214 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11215 Best->FoundDecl, Method); 11216 if (Arg0.isInvalid()) 11217 return ExprError(); 11218 Args[0] = Arg0.getAs<Expr>(); 11219 Args[1] = RHS = Arg1.getAs<Expr>(); 11220 } else { 11221 // Convert the arguments. 11222 ExprResult Arg0 = PerformCopyInitialization( 11223 InitializedEntity::InitializeParameter(Context, 11224 FnDecl->getParamDecl(0)), 11225 SourceLocation(), Args[0]); 11226 if (Arg0.isInvalid()) 11227 return ExprError(); 11228 11229 ExprResult Arg1 = 11230 PerformCopyInitialization( 11231 InitializedEntity::InitializeParameter(Context, 11232 FnDecl->getParamDecl(1)), 11233 SourceLocation(), Args[1]); 11234 if (Arg1.isInvalid()) 11235 return ExprError(); 11236 Args[0] = LHS = Arg0.getAs<Expr>(); 11237 Args[1] = RHS = Arg1.getAs<Expr>(); 11238 } 11239 11240 // Build the actual expression node. 11241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11242 Best->FoundDecl, 11243 HadMultipleCandidates, OpLoc); 11244 if (FnExpr.isInvalid()) 11245 return ExprError(); 11246 11247 // Determine the result type. 11248 QualType ResultTy = FnDecl->getReturnType(); 11249 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11250 ResultTy = ResultTy.getNonLValueExprType(Context); 11251 11252 CXXOperatorCallExpr *TheCall = 11253 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11254 Args, ResultTy, VK, OpLoc, 11255 FPFeatures.fp_contract); 11256 11257 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11258 FnDecl)) 11259 return ExprError(); 11260 11261 ArrayRef<const Expr *> ArgsArray(Args, 2); 11262 // Cut off the implicit 'this'. 11263 if (isa<CXXMethodDecl>(FnDecl)) 11264 ArgsArray = ArgsArray.slice(1); 11265 11266 // Check for a self move. 11267 if (Op == OO_Equal) 11268 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11269 11270 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11271 TheCall->getSourceRange(), VariadicDoesNotApply); 11272 11273 return MaybeBindToTemporary(TheCall); 11274 } else { 11275 // We matched a built-in operator. Convert the arguments, then 11276 // break out so that we will build the appropriate built-in 11277 // operator node. 11278 ExprResult ArgsRes0 = 11279 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11280 Best->Conversions[0], AA_Passing); 11281 if (ArgsRes0.isInvalid()) 11282 return ExprError(); 11283 Args[0] = ArgsRes0.get(); 11284 11285 ExprResult ArgsRes1 = 11286 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11287 Best->Conversions[1], AA_Passing); 11288 if (ArgsRes1.isInvalid()) 11289 return ExprError(); 11290 Args[1] = ArgsRes1.get(); 11291 break; 11292 } 11293 } 11294 11295 case OR_No_Viable_Function: { 11296 // C++ [over.match.oper]p9: 11297 // If the operator is the operator , [...] and there are no 11298 // viable functions, then the operator is assumed to be the 11299 // built-in operator and interpreted according to clause 5. 11300 if (Opc == BO_Comma) 11301 break; 11302 11303 // For class as left operand for assignment or compound assigment 11304 // operator do not fall through to handling in built-in, but report that 11305 // no overloaded assignment operator found 11306 ExprResult Result = ExprError(); 11307 if (Args[0]->getType()->isRecordType() && 11308 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11309 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11310 << BinaryOperator::getOpcodeStr(Opc) 11311 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11312 if (Args[0]->getType()->isIncompleteType()) { 11313 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11314 << Args[0]->getType() 11315 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11316 } 11317 } else { 11318 // This is an erroneous use of an operator which can be overloaded by 11319 // a non-member function. Check for non-member operators which were 11320 // defined too late to be candidates. 11321 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11322 // FIXME: Recover by calling the found function. 11323 return ExprError(); 11324 11325 // No viable function; try to create a built-in operation, which will 11326 // produce an error. Then, show the non-viable candidates. 11327 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11328 } 11329 assert(Result.isInvalid() && 11330 "C++ binary operator overloading is missing candidates!"); 11331 if (Result.isInvalid()) 11332 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11333 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11334 return Result; 11335 } 11336 11337 case OR_Ambiguous: 11338 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11339 << BinaryOperator::getOpcodeStr(Opc) 11340 << Args[0]->getType() << Args[1]->getType() 11341 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11342 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11343 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11344 return ExprError(); 11345 11346 case OR_Deleted: 11347 if (isImplicitlyDeleted(Best->Function)) { 11348 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11349 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11350 << Context.getRecordType(Method->getParent()) 11351 << getSpecialMember(Method); 11352 11353 // The user probably meant to call this special member. Just 11354 // explain why it's deleted. 11355 NoteDeletedFunction(Method); 11356 return ExprError(); 11357 } else { 11358 Diag(OpLoc, diag::err_ovl_deleted_oper) 11359 << Best->Function->isDeleted() 11360 << BinaryOperator::getOpcodeStr(Opc) 11361 << getDeletedOrUnavailableSuffix(Best->Function) 11362 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11363 } 11364 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11365 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11366 return ExprError(); 11367 } 11368 11369 // We matched a built-in operator; build it. 11370 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11371 } 11372 11373 ExprResult 11374 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11375 SourceLocation RLoc, 11376 Expr *Base, Expr *Idx) { 11377 Expr *Args[2] = { Base, Idx }; 11378 DeclarationName OpName = 11379 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11380 11381 // If either side is type-dependent, create an appropriate dependent 11382 // expression. 11383 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11384 11385 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11386 // CHECKME: no 'operator' keyword? 11387 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11388 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11389 UnresolvedLookupExpr *Fn 11390 = UnresolvedLookupExpr::Create(Context, NamingClass, 11391 NestedNameSpecifierLoc(), OpNameInfo, 11392 /*ADL*/ true, /*Overloaded*/ false, 11393 UnresolvedSetIterator(), 11394 UnresolvedSetIterator()); 11395 // Can't add any actual overloads yet 11396 11397 return new (Context) 11398 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11399 Context.DependentTy, VK_RValue, RLoc, false); 11400 } 11401 11402 // Handle placeholders on both operands. 11403 if (checkPlaceholderForOverload(*this, Args[0])) 11404 return ExprError(); 11405 if (checkPlaceholderForOverload(*this, Args[1])) 11406 return ExprError(); 11407 11408 // Build an empty overload set. 11409 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11410 11411 // Subscript can only be overloaded as a member function. 11412 11413 // Add operator candidates that are member functions. 11414 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11415 11416 // Add builtin operator candidates. 11417 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11418 11419 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11420 11421 // Perform overload resolution. 11422 OverloadCandidateSet::iterator Best; 11423 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11424 case OR_Success: { 11425 // We found a built-in operator or an overloaded operator. 11426 FunctionDecl *FnDecl = Best->Function; 11427 11428 if (FnDecl) { 11429 // We matched an overloaded operator. Build a call to that 11430 // operator. 11431 11432 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11433 11434 // Convert the arguments. 11435 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11436 ExprResult Arg0 = 11437 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11438 Best->FoundDecl, Method); 11439 if (Arg0.isInvalid()) 11440 return ExprError(); 11441 Args[0] = Arg0.get(); 11442 11443 // Convert the arguments. 11444 ExprResult InputInit 11445 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11446 Context, 11447 FnDecl->getParamDecl(0)), 11448 SourceLocation(), 11449 Args[1]); 11450 if (InputInit.isInvalid()) 11451 return ExprError(); 11452 11453 Args[1] = InputInit.getAs<Expr>(); 11454 11455 // Build the actual expression node. 11456 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11457 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11458 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11459 Best->FoundDecl, 11460 HadMultipleCandidates, 11461 OpLocInfo.getLoc(), 11462 OpLocInfo.getInfo()); 11463 if (FnExpr.isInvalid()) 11464 return ExprError(); 11465 11466 // Determine the result type 11467 QualType ResultTy = FnDecl->getReturnType(); 11468 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11469 ResultTy = ResultTy.getNonLValueExprType(Context); 11470 11471 CXXOperatorCallExpr *TheCall = 11472 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11473 FnExpr.get(), Args, 11474 ResultTy, VK, RLoc, 11475 false); 11476 11477 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11478 return ExprError(); 11479 11480 return MaybeBindToTemporary(TheCall); 11481 } else { 11482 // We matched a built-in operator. Convert the arguments, then 11483 // break out so that we will build the appropriate built-in 11484 // operator node. 11485 ExprResult ArgsRes0 = 11486 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11487 Best->Conversions[0], AA_Passing); 11488 if (ArgsRes0.isInvalid()) 11489 return ExprError(); 11490 Args[0] = ArgsRes0.get(); 11491 11492 ExprResult ArgsRes1 = 11493 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11494 Best->Conversions[1], AA_Passing); 11495 if (ArgsRes1.isInvalid()) 11496 return ExprError(); 11497 Args[1] = ArgsRes1.get(); 11498 11499 break; 11500 } 11501 } 11502 11503 case OR_No_Viable_Function: { 11504 if (CandidateSet.empty()) 11505 Diag(LLoc, diag::err_ovl_no_oper) 11506 << Args[0]->getType() << /*subscript*/ 0 11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11508 else 11509 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11510 << Args[0]->getType() 11511 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11512 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11513 "[]", LLoc); 11514 return ExprError(); 11515 } 11516 11517 case OR_Ambiguous: 11518 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11519 << "[]" 11520 << Args[0]->getType() << Args[1]->getType() 11521 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11522 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11523 "[]", LLoc); 11524 return ExprError(); 11525 11526 case OR_Deleted: 11527 Diag(LLoc, diag::err_ovl_deleted_oper) 11528 << Best->Function->isDeleted() << "[]" 11529 << getDeletedOrUnavailableSuffix(Best->Function) 11530 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11531 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11532 "[]", LLoc); 11533 return ExprError(); 11534 } 11535 11536 // We matched a built-in operator; build it. 11537 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11538 } 11539 11540 /// BuildCallToMemberFunction - Build a call to a member 11541 /// function. MemExpr is the expression that refers to the member 11542 /// function (and includes the object parameter), Args/NumArgs are the 11543 /// arguments to the function call (not including the object 11544 /// parameter). The caller needs to validate that the member 11545 /// expression refers to a non-static member function or an overloaded 11546 /// member function. 11547 ExprResult 11548 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11549 SourceLocation LParenLoc, 11550 MultiExprArg Args, 11551 SourceLocation RParenLoc) { 11552 assert(MemExprE->getType() == Context.BoundMemberTy || 11553 MemExprE->getType() == Context.OverloadTy); 11554 11555 // Dig out the member expression. This holds both the object 11556 // argument and the member function we're referring to. 11557 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11558 11559 // Determine whether this is a call to a pointer-to-member function. 11560 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11561 assert(op->getType() == Context.BoundMemberTy); 11562 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11563 11564 QualType fnType = 11565 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11566 11567 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11568 QualType resultType = proto->getCallResultType(Context); 11569 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11570 11571 // Check that the object type isn't more qualified than the 11572 // member function we're calling. 11573 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11574 11575 QualType objectType = op->getLHS()->getType(); 11576 if (op->getOpcode() == BO_PtrMemI) 11577 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11578 Qualifiers objectQuals = objectType.getQualifiers(); 11579 11580 Qualifiers difference = objectQuals - funcQuals; 11581 difference.removeObjCGCAttr(); 11582 difference.removeAddressSpace(); 11583 if (difference) { 11584 std::string qualsString = difference.getAsString(); 11585 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11586 << fnType.getUnqualifiedType() 11587 << qualsString 11588 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11589 } 11590 11591 if (resultType->isMemberPointerType()) 11592 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11593 RequireCompleteType(LParenLoc, resultType, 0); 11594 11595 CXXMemberCallExpr *call 11596 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11597 resultType, valueKind, RParenLoc); 11598 11599 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11600 call, nullptr)) 11601 return ExprError(); 11602 11603 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11604 return ExprError(); 11605 11606 if (CheckOtherCall(call, proto)) 11607 return ExprError(); 11608 11609 return MaybeBindToTemporary(call); 11610 } 11611 11612 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11613 return new (Context) 11614 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11615 11616 UnbridgedCastsSet UnbridgedCasts; 11617 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11618 return ExprError(); 11619 11620 MemberExpr *MemExpr; 11621 CXXMethodDecl *Method = nullptr; 11622 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11623 NestedNameSpecifier *Qualifier = nullptr; 11624 if (isa<MemberExpr>(NakedMemExpr)) { 11625 MemExpr = cast<MemberExpr>(NakedMemExpr); 11626 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11627 FoundDecl = MemExpr->getFoundDecl(); 11628 Qualifier = MemExpr->getQualifier(); 11629 UnbridgedCasts.restore(); 11630 11631 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 11632 Diag(MemExprE->getLocStart(), 11633 diag::err_ovl_no_viable_member_function_in_call) 11634 << Method << Method->getSourceRange(); 11635 Diag(Method->getLocation(), 11636 diag::note_ovl_candidate_disabled_by_enable_if_attr) 11637 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11638 return ExprError(); 11639 } 11640 } else { 11641 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11642 Qualifier = UnresExpr->getQualifier(); 11643 11644 QualType ObjectType = UnresExpr->getBaseType(); 11645 Expr::Classification ObjectClassification 11646 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11647 : UnresExpr->getBase()->Classify(Context); 11648 11649 // Add overload candidates 11650 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11651 OverloadCandidateSet::CSK_Normal); 11652 11653 // FIXME: avoid copy. 11654 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11655 if (UnresExpr->hasExplicitTemplateArgs()) { 11656 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11657 TemplateArgs = &TemplateArgsBuffer; 11658 } 11659 11660 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11661 E = UnresExpr->decls_end(); I != E; ++I) { 11662 11663 NamedDecl *Func = *I; 11664 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11665 if (isa<UsingShadowDecl>(Func)) 11666 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11667 11668 11669 // Microsoft supports direct constructor calls. 11670 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11671 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11672 Args, CandidateSet); 11673 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11674 // If explicit template arguments were provided, we can't call a 11675 // non-template member function. 11676 if (TemplateArgs) 11677 continue; 11678 11679 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11680 ObjectClassification, Args, CandidateSet, 11681 /*SuppressUserConversions=*/false); 11682 } else { 11683 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11684 I.getPair(), ActingDC, TemplateArgs, 11685 ObjectType, ObjectClassification, 11686 Args, CandidateSet, 11687 /*SuppressUsedConversions=*/false); 11688 } 11689 } 11690 11691 DeclarationName DeclName = UnresExpr->getMemberName(); 11692 11693 UnbridgedCasts.restore(); 11694 11695 OverloadCandidateSet::iterator Best; 11696 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11697 Best)) { 11698 case OR_Success: 11699 Method = cast<CXXMethodDecl>(Best->Function); 11700 FoundDecl = Best->FoundDecl; 11701 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11702 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11703 return ExprError(); 11704 // If FoundDecl is different from Method (such as if one is a template 11705 // and the other a specialization), make sure DiagnoseUseOfDecl is 11706 // called on both. 11707 // FIXME: This would be more comprehensively addressed by modifying 11708 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11709 // being used. 11710 if (Method != FoundDecl.getDecl() && 11711 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11712 return ExprError(); 11713 break; 11714 11715 case OR_No_Viable_Function: 11716 Diag(UnresExpr->getMemberLoc(), 11717 diag::err_ovl_no_viable_member_function_in_call) 11718 << DeclName << MemExprE->getSourceRange(); 11719 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11720 // FIXME: Leaking incoming expressions! 11721 return ExprError(); 11722 11723 case OR_Ambiguous: 11724 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11725 << DeclName << MemExprE->getSourceRange(); 11726 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11727 // FIXME: Leaking incoming expressions! 11728 return ExprError(); 11729 11730 case OR_Deleted: 11731 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11732 << Best->Function->isDeleted() 11733 << DeclName 11734 << getDeletedOrUnavailableSuffix(Best->Function) 11735 << MemExprE->getSourceRange(); 11736 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11737 // FIXME: Leaking incoming expressions! 11738 return ExprError(); 11739 } 11740 11741 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11742 11743 // If overload resolution picked a static member, build a 11744 // non-member call based on that function. 11745 if (Method->isStatic()) { 11746 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11747 RParenLoc); 11748 } 11749 11750 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11751 } 11752 11753 QualType ResultType = Method->getReturnType(); 11754 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11755 ResultType = ResultType.getNonLValueExprType(Context); 11756 11757 assert(Method && "Member call to something that isn't a method?"); 11758 CXXMemberCallExpr *TheCall = 11759 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11760 ResultType, VK, RParenLoc); 11761 11762 // (CUDA B.1): Check for invalid calls between targets. 11763 if (getLangOpts().CUDA) { 11764 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11765 if (CheckCUDATarget(Caller, Method)) { 11766 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11767 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11768 << IdentifyCUDATarget(Caller); 11769 return ExprError(); 11770 } 11771 } 11772 } 11773 11774 // Check for a valid return type. 11775 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11776 TheCall, Method)) 11777 return ExprError(); 11778 11779 // Convert the object argument (for a non-static member function call). 11780 // We only need to do this if there was actually an overload; otherwise 11781 // it was done at lookup. 11782 if (!Method->isStatic()) { 11783 ExprResult ObjectArg = 11784 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11785 FoundDecl, Method); 11786 if (ObjectArg.isInvalid()) 11787 return ExprError(); 11788 MemExpr->setBase(ObjectArg.get()); 11789 } 11790 11791 // Convert the rest of the arguments 11792 const FunctionProtoType *Proto = 11793 Method->getType()->getAs<FunctionProtoType>(); 11794 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11795 RParenLoc)) 11796 return ExprError(); 11797 11798 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11799 11800 if (CheckFunctionCall(Method, TheCall, Proto)) 11801 return ExprError(); 11802 11803 if ((isa<CXXConstructorDecl>(CurContext) || 11804 isa<CXXDestructorDecl>(CurContext)) && 11805 TheCall->getMethodDecl()->isPure()) { 11806 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11807 11808 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 11809 MemExpr->performsVirtualDispatch(getLangOpts())) { 11810 Diag(MemExpr->getLocStart(), 11811 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11812 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11813 << MD->getParent()->getDeclName(); 11814 11815 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11816 if (getLangOpts().AppleKext) 11817 Diag(MemExpr->getLocStart(), 11818 diag::note_pure_qualified_call_kext) 11819 << MD->getParent()->getDeclName() 11820 << MD->getDeclName(); 11821 } 11822 } 11823 return MaybeBindToTemporary(TheCall); 11824 } 11825 11826 /// BuildCallToObjectOfClassType - Build a call to an object of class 11827 /// type (C++ [over.call.object]), which can end up invoking an 11828 /// overloaded function call operator (@c operator()) or performing a 11829 /// user-defined conversion on the object argument. 11830 ExprResult 11831 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11832 SourceLocation LParenLoc, 11833 MultiExprArg Args, 11834 SourceLocation RParenLoc) { 11835 if (checkPlaceholderForOverload(*this, Obj)) 11836 return ExprError(); 11837 ExprResult Object = Obj; 11838 11839 UnbridgedCastsSet UnbridgedCasts; 11840 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11841 return ExprError(); 11842 11843 assert(Object.get()->getType()->isRecordType() && 11844 "Requires object type argument"); 11845 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11846 11847 // C++ [over.call.object]p1: 11848 // If the primary-expression E in the function call syntax 11849 // evaluates to a class object of type "cv T", then the set of 11850 // candidate functions includes at least the function call 11851 // operators of T. The function call operators of T are obtained by 11852 // ordinary lookup of the name operator() in the context of 11853 // (E).operator(). 11854 OverloadCandidateSet CandidateSet(LParenLoc, 11855 OverloadCandidateSet::CSK_Operator); 11856 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11857 11858 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11859 diag::err_incomplete_object_call, Object.get())) 11860 return true; 11861 11862 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11863 LookupQualifiedName(R, Record->getDecl()); 11864 R.suppressDiagnostics(); 11865 11866 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11867 Oper != OperEnd; ++Oper) { 11868 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11869 Object.get()->Classify(Context), 11870 Args, CandidateSet, 11871 /*SuppressUserConversions=*/ false); 11872 } 11873 11874 // C++ [over.call.object]p2: 11875 // In addition, for each (non-explicit in C++0x) conversion function 11876 // declared in T of the form 11877 // 11878 // operator conversion-type-id () cv-qualifier; 11879 // 11880 // where cv-qualifier is the same cv-qualification as, or a 11881 // greater cv-qualification than, cv, and where conversion-type-id 11882 // denotes the type "pointer to function of (P1,...,Pn) returning 11883 // R", or the type "reference to pointer to function of 11884 // (P1,...,Pn) returning R", or the type "reference to function 11885 // of (P1,...,Pn) returning R", a surrogate call function [...] 11886 // is also considered as a candidate function. Similarly, 11887 // surrogate call functions are added to the set of candidate 11888 // functions for each conversion function declared in an 11889 // accessible base class provided the function is not hidden 11890 // within T by another intervening declaration. 11891 const auto &Conversions = 11892 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11893 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 11894 NamedDecl *D = *I; 11895 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11896 if (isa<UsingShadowDecl>(D)) 11897 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11898 11899 // Skip over templated conversion functions; they aren't 11900 // surrogates. 11901 if (isa<FunctionTemplateDecl>(D)) 11902 continue; 11903 11904 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11905 if (!Conv->isExplicit()) { 11906 // Strip the reference type (if any) and then the pointer type (if 11907 // any) to get down to what might be a function type. 11908 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11909 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11910 ConvType = ConvPtrType->getPointeeType(); 11911 11912 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11913 { 11914 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11915 Object.get(), Args, CandidateSet); 11916 } 11917 } 11918 } 11919 11920 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11921 11922 // Perform overload resolution. 11923 OverloadCandidateSet::iterator Best; 11924 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11925 Best)) { 11926 case OR_Success: 11927 // Overload resolution succeeded; we'll build the appropriate call 11928 // below. 11929 break; 11930 11931 case OR_No_Viable_Function: 11932 if (CandidateSet.empty()) 11933 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11934 << Object.get()->getType() << /*call*/ 1 11935 << Object.get()->getSourceRange(); 11936 else 11937 Diag(Object.get()->getLocStart(), 11938 diag::err_ovl_no_viable_object_call) 11939 << Object.get()->getType() << Object.get()->getSourceRange(); 11940 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11941 break; 11942 11943 case OR_Ambiguous: 11944 Diag(Object.get()->getLocStart(), 11945 diag::err_ovl_ambiguous_object_call) 11946 << Object.get()->getType() << Object.get()->getSourceRange(); 11947 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11948 break; 11949 11950 case OR_Deleted: 11951 Diag(Object.get()->getLocStart(), 11952 diag::err_ovl_deleted_object_call) 11953 << Best->Function->isDeleted() 11954 << Object.get()->getType() 11955 << getDeletedOrUnavailableSuffix(Best->Function) 11956 << Object.get()->getSourceRange(); 11957 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11958 break; 11959 } 11960 11961 if (Best == CandidateSet.end()) 11962 return true; 11963 11964 UnbridgedCasts.restore(); 11965 11966 if (Best->Function == nullptr) { 11967 // Since there is no function declaration, this is one of the 11968 // surrogate candidates. Dig out the conversion function. 11969 CXXConversionDecl *Conv 11970 = cast<CXXConversionDecl>( 11971 Best->Conversions[0].UserDefined.ConversionFunction); 11972 11973 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 11974 Best->FoundDecl); 11975 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11976 return ExprError(); 11977 assert(Conv == Best->FoundDecl.getDecl() && 11978 "Found Decl & conversion-to-functionptr should be same, right?!"); 11979 // We selected one of the surrogate functions that converts the 11980 // object parameter to a function pointer. Perform the conversion 11981 // on the object argument, then let ActOnCallExpr finish the job. 11982 11983 // Create an implicit member expr to refer to the conversion operator. 11984 // and then call it. 11985 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11986 Conv, HadMultipleCandidates); 11987 if (Call.isInvalid()) 11988 return ExprError(); 11989 // Record usage of conversion in an implicit cast. 11990 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 11991 CK_UserDefinedConversion, Call.get(), 11992 nullptr, VK_RValue); 11993 11994 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11995 } 11996 11997 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 11998 11999 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12000 // that calls this method, using Object for the implicit object 12001 // parameter and passing along the remaining arguments. 12002 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12003 12004 // An error diagnostic has already been printed when parsing the declaration. 12005 if (Method->isInvalidDecl()) 12006 return ExprError(); 12007 12008 const FunctionProtoType *Proto = 12009 Method->getType()->getAs<FunctionProtoType>(); 12010 12011 unsigned NumParams = Proto->getNumParams(); 12012 12013 DeclarationNameInfo OpLocInfo( 12014 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12015 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12016 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12017 HadMultipleCandidates, 12018 OpLocInfo.getLoc(), 12019 OpLocInfo.getInfo()); 12020 if (NewFn.isInvalid()) 12021 return true; 12022 12023 // Build the full argument list for the method call (the implicit object 12024 // parameter is placed at the beginning of the list). 12025 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12026 MethodArgs[0] = Object.get(); 12027 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12028 12029 // Once we've built TheCall, all of the expressions are properly 12030 // owned. 12031 QualType ResultTy = Method->getReturnType(); 12032 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12033 ResultTy = ResultTy.getNonLValueExprType(Context); 12034 12035 CXXOperatorCallExpr *TheCall = new (Context) 12036 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12037 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12038 ResultTy, VK, RParenLoc, false); 12039 MethodArgs.reset(); 12040 12041 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12042 return true; 12043 12044 // We may have default arguments. If so, we need to allocate more 12045 // slots in the call for them. 12046 if (Args.size() < NumParams) 12047 TheCall->setNumArgs(Context, NumParams + 1); 12048 12049 bool IsError = false; 12050 12051 // Initialize the implicit object parameter. 12052 ExprResult ObjRes = 12053 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12054 Best->FoundDecl, Method); 12055 if (ObjRes.isInvalid()) 12056 IsError = true; 12057 else 12058 Object = ObjRes; 12059 TheCall->setArg(0, Object.get()); 12060 12061 // Check the argument types. 12062 for (unsigned i = 0; i != NumParams; i++) { 12063 Expr *Arg; 12064 if (i < Args.size()) { 12065 Arg = Args[i]; 12066 12067 // Pass the argument. 12068 12069 ExprResult InputInit 12070 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12071 Context, 12072 Method->getParamDecl(i)), 12073 SourceLocation(), Arg); 12074 12075 IsError |= InputInit.isInvalid(); 12076 Arg = InputInit.getAs<Expr>(); 12077 } else { 12078 ExprResult DefArg 12079 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12080 if (DefArg.isInvalid()) { 12081 IsError = true; 12082 break; 12083 } 12084 12085 Arg = DefArg.getAs<Expr>(); 12086 } 12087 12088 TheCall->setArg(i + 1, Arg); 12089 } 12090 12091 // If this is a variadic call, handle args passed through "...". 12092 if (Proto->isVariadic()) { 12093 // Promote the arguments (C99 6.5.2.2p7). 12094 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12095 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12096 nullptr); 12097 IsError |= Arg.isInvalid(); 12098 TheCall->setArg(i + 1, Arg.get()); 12099 } 12100 } 12101 12102 if (IsError) return true; 12103 12104 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12105 12106 if (CheckFunctionCall(Method, TheCall, Proto)) 12107 return true; 12108 12109 return MaybeBindToTemporary(TheCall); 12110 } 12111 12112 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12113 /// (if one exists), where @c Base is an expression of class type and 12114 /// @c Member is the name of the member we're trying to find. 12115 ExprResult 12116 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12117 bool *NoArrowOperatorFound) { 12118 assert(Base->getType()->isRecordType() && 12119 "left-hand side must have class type"); 12120 12121 if (checkPlaceholderForOverload(*this, Base)) 12122 return ExprError(); 12123 12124 SourceLocation Loc = Base->getExprLoc(); 12125 12126 // C++ [over.ref]p1: 12127 // 12128 // [...] An expression x->m is interpreted as (x.operator->())->m 12129 // for a class object x of type T if T::operator->() exists and if 12130 // the operator is selected as the best match function by the 12131 // overload resolution mechanism (13.3). 12132 DeclarationName OpName = 12133 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12134 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12135 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12136 12137 if (RequireCompleteType(Loc, Base->getType(), 12138 diag::err_typecheck_incomplete_tag, Base)) 12139 return ExprError(); 12140 12141 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12142 LookupQualifiedName(R, BaseRecord->getDecl()); 12143 R.suppressDiagnostics(); 12144 12145 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12146 Oper != OperEnd; ++Oper) { 12147 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12148 None, CandidateSet, /*SuppressUserConversions=*/false); 12149 } 12150 12151 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12152 12153 // Perform overload resolution. 12154 OverloadCandidateSet::iterator Best; 12155 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12156 case OR_Success: 12157 // Overload resolution succeeded; we'll build the call below. 12158 break; 12159 12160 case OR_No_Viable_Function: 12161 if (CandidateSet.empty()) { 12162 QualType BaseType = Base->getType(); 12163 if (NoArrowOperatorFound) { 12164 // Report this specific error to the caller instead of emitting a 12165 // diagnostic, as requested. 12166 *NoArrowOperatorFound = true; 12167 return ExprError(); 12168 } 12169 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12170 << BaseType << Base->getSourceRange(); 12171 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12172 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12173 << FixItHint::CreateReplacement(OpLoc, "."); 12174 } 12175 } else 12176 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12177 << "operator->" << Base->getSourceRange(); 12178 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12179 return ExprError(); 12180 12181 case OR_Ambiguous: 12182 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12183 << "->" << Base->getType() << Base->getSourceRange(); 12184 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12185 return ExprError(); 12186 12187 case OR_Deleted: 12188 Diag(OpLoc, diag::err_ovl_deleted_oper) 12189 << Best->Function->isDeleted() 12190 << "->" 12191 << getDeletedOrUnavailableSuffix(Best->Function) 12192 << Base->getSourceRange(); 12193 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12194 return ExprError(); 12195 } 12196 12197 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12198 12199 // Convert the object parameter. 12200 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12201 ExprResult BaseResult = 12202 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12203 Best->FoundDecl, Method); 12204 if (BaseResult.isInvalid()) 12205 return ExprError(); 12206 Base = BaseResult.get(); 12207 12208 // Build the operator call. 12209 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12210 HadMultipleCandidates, OpLoc); 12211 if (FnExpr.isInvalid()) 12212 return ExprError(); 12213 12214 QualType ResultTy = Method->getReturnType(); 12215 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12216 ResultTy = ResultTy.getNonLValueExprType(Context); 12217 CXXOperatorCallExpr *TheCall = 12218 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12219 Base, ResultTy, VK, OpLoc, false); 12220 12221 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12222 return ExprError(); 12223 12224 return MaybeBindToTemporary(TheCall); 12225 } 12226 12227 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12228 /// a literal operator described by the provided lookup results. 12229 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12230 DeclarationNameInfo &SuffixInfo, 12231 ArrayRef<Expr*> Args, 12232 SourceLocation LitEndLoc, 12233 TemplateArgumentListInfo *TemplateArgs) { 12234 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12235 12236 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12237 OverloadCandidateSet::CSK_Normal); 12238 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12239 /*SuppressUserConversions=*/true); 12240 12241 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12242 12243 // Perform overload resolution. This will usually be trivial, but might need 12244 // to perform substitutions for a literal operator template. 12245 OverloadCandidateSet::iterator Best; 12246 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12247 case OR_Success: 12248 case OR_Deleted: 12249 break; 12250 12251 case OR_No_Viable_Function: 12252 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12253 << R.getLookupName(); 12254 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12255 return ExprError(); 12256 12257 case OR_Ambiguous: 12258 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12259 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12260 return ExprError(); 12261 } 12262 12263 FunctionDecl *FD = Best->Function; 12264 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12265 HadMultipleCandidates, 12266 SuffixInfo.getLoc(), 12267 SuffixInfo.getInfo()); 12268 if (Fn.isInvalid()) 12269 return true; 12270 12271 // Check the argument types. This should almost always be a no-op, except 12272 // that array-to-pointer decay is applied to string literals. 12273 Expr *ConvArgs[2]; 12274 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12275 ExprResult InputInit = PerformCopyInitialization( 12276 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12277 SourceLocation(), Args[ArgIdx]); 12278 if (InputInit.isInvalid()) 12279 return true; 12280 ConvArgs[ArgIdx] = InputInit.get(); 12281 } 12282 12283 QualType ResultTy = FD->getReturnType(); 12284 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12285 ResultTy = ResultTy.getNonLValueExprType(Context); 12286 12287 UserDefinedLiteral *UDL = 12288 new (Context) UserDefinedLiteral(Context, Fn.get(), 12289 llvm::makeArrayRef(ConvArgs, Args.size()), 12290 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12291 12292 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12293 return ExprError(); 12294 12295 if (CheckFunctionCall(FD, UDL, nullptr)) 12296 return ExprError(); 12297 12298 return MaybeBindToTemporary(UDL); 12299 } 12300 12301 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12302 /// given LookupResult is non-empty, it is assumed to describe a member which 12303 /// will be invoked. Otherwise, the function will be found via argument 12304 /// dependent lookup. 12305 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12306 /// otherwise CallExpr is set to ExprError() and some non-success value 12307 /// is returned. 12308 Sema::ForRangeStatus 12309 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12310 SourceLocation RangeLoc, VarDecl *Decl, 12311 BeginEndFunction BEF, 12312 const DeclarationNameInfo &NameInfo, 12313 LookupResult &MemberLookup, 12314 OverloadCandidateSet *CandidateSet, 12315 Expr *Range, ExprResult *CallExpr) { 12316 CandidateSet->clear(); 12317 if (!MemberLookup.empty()) { 12318 ExprResult MemberRef = 12319 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12320 /*IsPtr=*/false, CXXScopeSpec(), 12321 /*TemplateKWLoc=*/SourceLocation(), 12322 /*FirstQualifierInScope=*/nullptr, 12323 MemberLookup, 12324 /*TemplateArgs=*/nullptr); 12325 if (MemberRef.isInvalid()) { 12326 *CallExpr = ExprError(); 12327 Diag(Range->getLocStart(), diag::note_in_for_range) 12328 << RangeLoc << BEF << Range->getType(); 12329 return FRS_DiagnosticIssued; 12330 } 12331 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12332 if (CallExpr->isInvalid()) { 12333 *CallExpr = ExprError(); 12334 Diag(Range->getLocStart(), diag::note_in_for_range) 12335 << RangeLoc << BEF << Range->getType(); 12336 return FRS_DiagnosticIssued; 12337 } 12338 } else { 12339 UnresolvedSet<0> FoundNames; 12340 UnresolvedLookupExpr *Fn = 12341 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12342 NestedNameSpecifierLoc(), NameInfo, 12343 /*NeedsADL=*/true, /*Overloaded=*/false, 12344 FoundNames.begin(), FoundNames.end()); 12345 12346 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12347 CandidateSet, CallExpr); 12348 if (CandidateSet->empty() || CandidateSetError) { 12349 *CallExpr = ExprError(); 12350 return FRS_NoViableFunction; 12351 } 12352 OverloadCandidateSet::iterator Best; 12353 OverloadingResult OverloadResult = 12354 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12355 12356 if (OverloadResult == OR_No_Viable_Function) { 12357 *CallExpr = ExprError(); 12358 return FRS_NoViableFunction; 12359 } 12360 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12361 Loc, nullptr, CandidateSet, &Best, 12362 OverloadResult, 12363 /*AllowTypoCorrection=*/false); 12364 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12365 *CallExpr = ExprError(); 12366 Diag(Range->getLocStart(), diag::note_in_for_range) 12367 << RangeLoc << BEF << Range->getType(); 12368 return FRS_DiagnosticIssued; 12369 } 12370 } 12371 return FRS_Success; 12372 } 12373 12374 12375 /// FixOverloadedFunctionReference - E is an expression that refers to 12376 /// a C++ overloaded function (possibly with some parentheses and 12377 /// perhaps a '&' around it). We have resolved the overloaded function 12378 /// to the function declaration Fn, so patch up the expression E to 12379 /// refer (possibly indirectly) to Fn. Returns the new expr. 12380 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12381 FunctionDecl *Fn) { 12382 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12383 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12384 Found, Fn); 12385 if (SubExpr == PE->getSubExpr()) 12386 return PE; 12387 12388 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12389 } 12390 12391 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12392 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12393 Found, Fn); 12394 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12395 SubExpr->getType()) && 12396 "Implicit cast type cannot be determined from overload"); 12397 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12398 if (SubExpr == ICE->getSubExpr()) 12399 return ICE; 12400 12401 return ImplicitCastExpr::Create(Context, ICE->getType(), 12402 ICE->getCastKind(), 12403 SubExpr, nullptr, 12404 ICE->getValueKind()); 12405 } 12406 12407 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12408 assert(UnOp->getOpcode() == UO_AddrOf && 12409 "Can only take the address of an overloaded function"); 12410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12411 if (Method->isStatic()) { 12412 // Do nothing: static member functions aren't any different 12413 // from non-member functions. 12414 } else { 12415 // Fix the subexpression, which really has to be an 12416 // UnresolvedLookupExpr holding an overloaded member function 12417 // or template. 12418 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12419 Found, Fn); 12420 if (SubExpr == UnOp->getSubExpr()) 12421 return UnOp; 12422 12423 assert(isa<DeclRefExpr>(SubExpr) 12424 && "fixed to something other than a decl ref"); 12425 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12426 && "fixed to a member ref with no nested name qualifier"); 12427 12428 // We have taken the address of a pointer to member 12429 // function. Perform the computation here so that we get the 12430 // appropriate pointer to member type. 12431 QualType ClassType 12432 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12433 QualType MemPtrType 12434 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12435 12436 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12437 VK_RValue, OK_Ordinary, 12438 UnOp->getOperatorLoc()); 12439 } 12440 } 12441 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12442 Found, Fn); 12443 if (SubExpr == UnOp->getSubExpr()) 12444 return UnOp; 12445 12446 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12447 Context.getPointerType(SubExpr->getType()), 12448 VK_RValue, OK_Ordinary, 12449 UnOp->getOperatorLoc()); 12450 } 12451 12452 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12453 // FIXME: avoid copy. 12454 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12455 if (ULE->hasExplicitTemplateArgs()) { 12456 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12457 TemplateArgs = &TemplateArgsBuffer; 12458 } 12459 12460 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12461 ULE->getQualifierLoc(), 12462 ULE->getTemplateKeywordLoc(), 12463 Fn, 12464 /*enclosing*/ false, // FIXME? 12465 ULE->getNameLoc(), 12466 Fn->getType(), 12467 VK_LValue, 12468 Found.getDecl(), 12469 TemplateArgs); 12470 MarkDeclRefReferenced(DRE); 12471 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12472 return DRE; 12473 } 12474 12475 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12476 // FIXME: avoid copy. 12477 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12478 if (MemExpr->hasExplicitTemplateArgs()) { 12479 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12480 TemplateArgs = &TemplateArgsBuffer; 12481 } 12482 12483 Expr *Base; 12484 12485 // If we're filling in a static method where we used to have an 12486 // implicit member access, rewrite to a simple decl ref. 12487 if (MemExpr->isImplicitAccess()) { 12488 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12489 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12490 MemExpr->getQualifierLoc(), 12491 MemExpr->getTemplateKeywordLoc(), 12492 Fn, 12493 /*enclosing*/ false, 12494 MemExpr->getMemberLoc(), 12495 Fn->getType(), 12496 VK_LValue, 12497 Found.getDecl(), 12498 TemplateArgs); 12499 MarkDeclRefReferenced(DRE); 12500 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12501 return DRE; 12502 } else { 12503 SourceLocation Loc = MemExpr->getMemberLoc(); 12504 if (MemExpr->getQualifier()) 12505 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12506 CheckCXXThisCapture(Loc); 12507 Base = new (Context) CXXThisExpr(Loc, 12508 MemExpr->getBaseType(), 12509 /*isImplicit=*/true); 12510 } 12511 } else 12512 Base = MemExpr->getBase(); 12513 12514 ExprValueKind valueKind; 12515 QualType type; 12516 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12517 valueKind = VK_LValue; 12518 type = Fn->getType(); 12519 } else { 12520 valueKind = VK_RValue; 12521 type = Context.BoundMemberTy; 12522 } 12523 12524 MemberExpr *ME = MemberExpr::Create( 12525 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12526 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12527 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12528 OK_Ordinary); 12529 ME->setHadMultipleCandidates(true); 12530 MarkMemberReferenced(ME); 12531 return ME; 12532 } 12533 12534 llvm_unreachable("Invalid reference to overloaded function"); 12535 } 12536 12537 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12538 DeclAccessPair Found, 12539 FunctionDecl *Fn) { 12540 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12541 } 12542