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/Optional.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallString.h" 36 #include <algorithm> 37 #include <cstdlib> 38 39 using namespace clang; 40 using namespace sema; 41 42 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 43 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 44 return P->hasAttr<PassObjectSizeAttr>(); 45 }); 46 } 47 48 /// A convenience routine for creating a decayed reference to a function. 49 static ExprResult 50 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 51 const Expr *Base, bool HadMultipleCandidates, 52 SourceLocation Loc = SourceLocation(), 53 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 54 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 55 return ExprError(); 56 // If FoundDecl is different from Fn (such as if one is a template 57 // and the other a specialization), make sure DiagnoseUseOfDecl is 58 // called on both. 59 // FIXME: This would be more comprehensively addressed by modifying 60 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 61 // being used. 62 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 63 return ExprError(); 64 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 65 S.ResolveExceptionSpec(Loc, FPT); 66 DeclRefExpr *DRE = new (S.Context) 67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 73 CK_FunctionToPointerDecay); 74 } 75 76 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 77 bool InOverloadResolution, 78 StandardConversionSequence &SCS, 79 bool CStyle, 80 bool AllowObjCWritebackConversion); 81 82 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 83 QualType &ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle); 87 static OverloadingResult 88 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 89 UserDefinedConversionSequence& User, 90 OverloadCandidateSet& Conversions, 91 bool AllowExplicit, 92 bool AllowObjCConversionOnExplicit); 93 94 95 static ImplicitConversionSequence::CompareKind 96 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 97 const StandardConversionSequence& SCS1, 98 const StandardConversionSequence& SCS2); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareQualificationConversions(Sema &S, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 /// GetConversionRank - Retrieve the implicit conversion rank 111 /// corresponding to the given implicit conversion kind. 112 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 113 static const ImplicitConversionRank 114 Rank[(int)ICK_Num_Conversion_Kinds] = { 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Exact_Match, 121 ICR_Promotion, 122 ICR_Promotion, 123 ICR_Promotion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_OCL_Scalar_Widening, 135 ICR_Complex_Real_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Writeback_Conversion, 139 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 140 // it was omitted by the patch that added 141 // ICK_Zero_Event_Conversion 142 ICR_C_Conversion, 143 ICR_C_Conversion_Extension 144 }; 145 return Rank[(int)Kind]; 146 } 147 148 /// GetImplicitConversionName - Return the name of this kind of 149 /// implicit conversion. 150 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 151 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 152 "No conversion", 153 "Lvalue-to-rvalue", 154 "Array-to-pointer", 155 "Function-to-pointer", 156 "Function pointer conversion", 157 "Qualification", 158 "Integral promotion", 159 "Floating point promotion", 160 "Complex promotion", 161 "Integral conversion", 162 "Floating conversion", 163 "Complex conversion", 164 "Floating-integral conversion", 165 "Pointer conversion", 166 "Pointer-to-member conversion", 167 "Boolean conversion", 168 "Compatible-types conversion", 169 "Derived-to-base conversion", 170 "Vector conversion", 171 "Vector splat", 172 "Complex-real conversion", 173 "Block Pointer conversion", 174 "Transparent Union Conversion", 175 "Writeback conversion", 176 "OpenCL Zero Event Conversion", 177 "C specific type conversion", 178 "Incompatible pointer conversion" 179 }; 180 return Name[Kind]; 181 } 182 183 /// StandardConversionSequence - Set the standard conversion 184 /// sequence to the identity conversion. 185 void StandardConversionSequence::setAsIdentityConversion() { 186 First = ICK_Identity; 187 Second = ICK_Identity; 188 Third = ICK_Identity; 189 DeprecatedStringLiteralToCharPtr = false; 190 QualificationIncludesObjCLifetime = false; 191 ReferenceBinding = false; 192 DirectBinding = false; 193 IsLvalueReference = true; 194 BindsToFunctionLvalue = false; 195 BindsToRvalue = false; 196 BindsImplicitObjectArgumentWithoutRefQualifier = false; 197 ObjCLifetimeConversionBinding = false; 198 CopyConstructor = nullptr; 199 } 200 201 /// getRank - Retrieve the rank of this standard conversion sequence 202 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 203 /// implicit conversions. 204 ImplicitConversionRank StandardConversionSequence::getRank() const { 205 ImplicitConversionRank Rank = ICR_Exact_Match; 206 if (GetConversionRank(First) > Rank) 207 Rank = GetConversionRank(First); 208 if (GetConversionRank(Second) > Rank) 209 Rank = GetConversionRank(Second); 210 if (GetConversionRank(Third) > Rank) 211 Rank = GetConversionRank(Third); 212 return Rank; 213 } 214 215 /// isPointerConversionToBool - Determines whether this conversion is 216 /// a conversion of a pointer or pointer-to-member to bool. This is 217 /// used as part of the ranking of standard conversion sequences 218 /// (C++ 13.3.3.2p4). 219 bool StandardConversionSequence::isPointerConversionToBool() const { 220 // Note that FromType has not necessarily been transformed by the 221 // array-to-pointer or function-to-pointer implicit conversions, so 222 // check for their presence as well as checking whether FromType is 223 // a pointer. 224 if (getToType(1)->isBooleanType() && 225 (getFromType()->isPointerType() || 226 getFromType()->isMemberPointerType() || 227 getFromType()->isObjCObjectPointerType() || 228 getFromType()->isBlockPointerType() || 229 getFromType()->isNullPtrType() || 230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 231 return true; 232 233 return false; 234 } 235 236 /// isPointerConversionToVoidPointer - Determines whether this 237 /// conversion is a conversion of a pointer to a void pointer. This is 238 /// used as part of the ranking of standard conversion sequences (C++ 239 /// 13.3.3.2p4). 240 bool 241 StandardConversionSequence:: 242 isPointerConversionToVoidPointer(ASTContext& Context) const { 243 QualType FromType = getFromType(); 244 QualType ToType = getToType(1); 245 246 // Note that FromType has not necessarily been transformed by the 247 // array-to-pointer implicit conversion, so check for its presence 248 // and redo the conversion to get a pointer. 249 if (First == ICK_Array_To_Pointer) 250 FromType = Context.getArrayDecayedType(FromType); 251 252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 254 return ToPtrType->getPointeeType()->isVoidType(); 255 256 return false; 257 } 258 259 /// Skip any implicit casts which could be either part of a narrowing conversion 260 /// or after one in an implicit conversion. 261 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 263 switch (ICE->getCastKind()) { 264 case CK_NoOp: 265 case CK_IntegralCast: 266 case CK_IntegralToBoolean: 267 case CK_IntegralToFloating: 268 case CK_BooleanToSignedIntegral: 269 case CK_FloatingToIntegral: 270 case CK_FloatingToBoolean: 271 case CK_FloatingCast: 272 Converted = ICE->getSubExpr(); 273 continue; 274 275 default: 276 return Converted; 277 } 278 } 279 280 return Converted; 281 } 282 283 /// Check if this standard conversion sequence represents a narrowing 284 /// conversion, according to C++11 [dcl.init.list]p7. 285 /// 286 /// \param Ctx The AST context. 287 /// \param Converted The result of applying this standard conversion sequence. 288 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 289 /// value of the expression prior to the narrowing conversion. 290 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 291 /// type of the expression prior to the narrowing conversion. 292 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 293 /// from floating point types to integral types should be ignored. 294 NarrowingKind StandardConversionSequence::getNarrowingKind( 295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 298 299 // C++11 [dcl.init.list]p7: 300 // A narrowing conversion is an implicit conversion ... 301 QualType FromType = getToType(0); 302 QualType ToType = getToType(1); 303 304 // A conversion to an enumeration type is narrowing if the conversion to 305 // the underlying type is narrowing. This only arises for expressions of 306 // the form 'Enum{init}'. 307 if (auto *ET = ToType->getAs<EnumType>()) 308 ToType = ET->getDecl()->getIntegerType(); 309 310 switch (Second) { 311 // 'bool' is an integral type; dispatch to the right place to handle it. 312 case ICK_Boolean_Conversion: 313 if (FromType->isRealFloatingType()) 314 goto FloatingIntegralConversion; 315 if (FromType->isIntegralOrUnscopedEnumerationType()) 316 goto IntegralConversion; 317 // Boolean conversions can be from pointers and pointers to members 318 // [conv.bool], and those aren't considered narrowing conversions. 319 return NK_Not_Narrowing; 320 321 // -- from a floating-point type to an integer type, or 322 // 323 // -- from an integer type or unscoped enumeration type to a floating-point 324 // type, except where the source is a constant expression and the actual 325 // value after conversion will fit into the target type and will produce 326 // the original value when converted back to the original type, or 327 case ICK_Floating_Integral: 328 FloatingIntegralConversion: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 332 ToType->isRealFloatingType()) { 333 if (IgnoreFloatToIntegralConversion) 334 return NK_Not_Narrowing; 335 llvm::APSInt IntConstantValue; 336 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 337 assert(Initializer && "Unknown conversion expression"); 338 339 // If it's value-dependent, we can't tell whether it's narrowing. 340 if (Initializer->isValueDependent()) 341 return NK_Dependent_Narrowing; 342 343 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 344 // Convert the integer to the floating type. 345 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 346 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 347 llvm::APFloat::rmNearestTiesToEven); 348 // And back. 349 llvm::APSInt ConvertedValue = IntConstantValue; 350 bool ignored; 351 Result.convertToInteger(ConvertedValue, 352 llvm::APFloat::rmTowardZero, &ignored); 353 // If the resulting value is different, this was a narrowing conversion. 354 if (IntConstantValue != ConvertedValue) { 355 ConstantValue = APValue(IntConstantValue); 356 ConstantType = Initializer->getType(); 357 return NK_Constant_Narrowing; 358 } 359 } else { 360 // Variables are always narrowings. 361 return NK_Variable_Narrowing; 362 } 363 } 364 return NK_Not_Narrowing; 365 366 // -- from long double to double or float, or from double to float, except 367 // where the source is a constant expression and the actual value after 368 // conversion is within the range of values that can be represented (even 369 // if it cannot be represented exactly), or 370 case ICK_Floating_Conversion: 371 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 372 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 373 // FromType is larger than ToType. 374 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 375 376 // If it's value-dependent, we can't tell whether it's narrowing. 377 if (Initializer->isValueDependent()) 378 return NK_Dependent_Narrowing; 379 380 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 381 // Constant! 382 assert(ConstantValue.isFloat()); 383 llvm::APFloat FloatVal = ConstantValue.getFloat(); 384 // Convert the source value into the target type. 385 bool ignored; 386 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 387 Ctx.getFloatTypeSemantics(ToType), 388 llvm::APFloat::rmNearestTiesToEven, &ignored); 389 // If there was no overflow, the source value is within the range of 390 // values that can be represented. 391 if (ConvertStatus & llvm::APFloat::opOverflow) { 392 ConstantType = Initializer->getType(); 393 return NK_Constant_Narrowing; 394 } 395 } else { 396 return NK_Variable_Narrowing; 397 } 398 } 399 return NK_Not_Narrowing; 400 401 // -- from an integer type or unscoped enumeration type to an integer type 402 // that cannot represent all the values of the original type, except where 403 // the source is a constant expression and the actual value after 404 // conversion will fit into the target type and will produce the original 405 // value when converted back to the original type. 406 case ICK_Integral_Conversion: 407 IntegralConversion: { 408 assert(FromType->isIntegralOrUnscopedEnumerationType()); 409 assert(ToType->isIntegralOrUnscopedEnumerationType()); 410 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 411 const unsigned FromWidth = Ctx.getIntWidth(FromType); 412 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 413 const unsigned ToWidth = Ctx.getIntWidth(ToType); 414 415 if (FromWidth > ToWidth || 416 (FromWidth == ToWidth && FromSigned != ToSigned) || 417 (FromSigned && !ToSigned)) { 418 // Not all values of FromType can be represented in ToType. 419 llvm::APSInt InitializerValue; 420 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 421 422 // If it's value-dependent, we can't tell whether it's narrowing. 423 if (Initializer->isValueDependent()) 424 return NK_Dependent_Narrowing; 425 426 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 427 // Such conversions on variables are always narrowing. 428 return NK_Variable_Narrowing; 429 } 430 bool Narrowing = false; 431 if (FromWidth < ToWidth) { 432 // Negative -> unsigned is narrowing. Otherwise, more bits is never 433 // narrowing. 434 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 435 Narrowing = true; 436 } else { 437 // Add a bit to the InitializerValue so we don't have to worry about 438 // signed vs. unsigned comparisons. 439 InitializerValue = InitializerValue.extend( 440 InitializerValue.getBitWidth() + 1); 441 // Convert the initializer to and from the target width and signed-ness. 442 llvm::APSInt ConvertedValue = InitializerValue; 443 ConvertedValue = ConvertedValue.trunc(ToWidth); 444 ConvertedValue.setIsSigned(ToSigned); 445 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 446 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 447 // If the result is different, this was a narrowing conversion. 448 if (ConvertedValue != InitializerValue) 449 Narrowing = true; 450 } 451 if (Narrowing) { 452 ConstantType = Initializer->getType(); 453 ConstantValue = APValue(InitializerValue); 454 return NK_Constant_Narrowing; 455 } 456 } 457 return NK_Not_Narrowing; 458 } 459 460 default: 461 // Other kinds of conversions are not narrowings. 462 return NK_Not_Narrowing; 463 } 464 } 465 466 /// dump - Print this standard conversion sequence to standard 467 /// error. Useful for debugging overloading issues. 468 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 469 raw_ostream &OS = llvm::errs(); 470 bool PrintedSomething = false; 471 if (First != ICK_Identity) { 472 OS << GetImplicitConversionName(First); 473 PrintedSomething = true; 474 } 475 476 if (Second != ICK_Identity) { 477 if (PrintedSomething) { 478 OS << " -> "; 479 } 480 OS << GetImplicitConversionName(Second); 481 482 if (CopyConstructor) { 483 OS << " (by copy constructor)"; 484 } else if (DirectBinding) { 485 OS << " (direct reference binding)"; 486 } else if (ReferenceBinding) { 487 OS << " (reference binding)"; 488 } 489 PrintedSomething = true; 490 } 491 492 if (Third != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Third); 497 PrintedSomething = true; 498 } 499 500 if (!PrintedSomething) { 501 OS << "No conversions required"; 502 } 503 } 504 505 /// dump - Print this user-defined conversion sequence to standard 506 /// error. Useful for debugging overloading issues. 507 void UserDefinedConversionSequence::dump() const { 508 raw_ostream &OS = llvm::errs(); 509 if (Before.First || Before.Second || Before.Third) { 510 Before.dump(); 511 OS << " -> "; 512 } 513 if (ConversionFunction) 514 OS << '\'' << *ConversionFunction << '\''; 515 else 516 OS << "aggregate initialization"; 517 if (After.First || After.Second || After.Third) { 518 OS << " -> "; 519 After.dump(); 520 } 521 } 522 523 /// dump - Print this implicit conversion sequence to standard 524 /// error. Useful for debugging overloading issues. 525 void ImplicitConversionSequence::dump() const { 526 raw_ostream &OS = llvm::errs(); 527 if (isStdInitializerListElement()) 528 OS << "Worst std::initializer_list element conversion: "; 529 switch (ConversionKind) { 530 case StandardConversion: 531 OS << "Standard conversion: "; 532 Standard.dump(); 533 break; 534 case UserDefinedConversion: 535 OS << "User-defined conversion: "; 536 UserDefined.dump(); 537 break; 538 case EllipsisConversion: 539 OS << "Ellipsis conversion"; 540 break; 541 case AmbiguousConversion: 542 OS << "Ambiguous conversion"; 543 break; 544 case BadConversion: 545 OS << "Bad conversion"; 546 break; 547 } 548 549 OS << "\n"; 550 } 551 552 void AmbiguousConversionSequence::construct() { 553 new (&conversions()) ConversionSet(); 554 } 555 556 void AmbiguousConversionSequence::destruct() { 557 conversions().~ConversionSet(); 558 } 559 560 void 561 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 562 FromTypePtr = O.FromTypePtr; 563 ToTypePtr = O.ToTypePtr; 564 new (&conversions()) ConversionSet(O.conversions()); 565 } 566 567 namespace { 568 // Structure used by DeductionFailureInfo to store 569 // template argument information. 570 struct DFIArguments { 571 TemplateArgument FirstArg; 572 TemplateArgument SecondArg; 573 }; 574 // Structure used by DeductionFailureInfo to store 575 // template parameter and template argument information. 576 struct DFIParamWithArguments : DFIArguments { 577 TemplateParameter Param; 578 }; 579 // Structure used by DeductionFailureInfo to store template argument 580 // information and the index of the problematic call argument. 581 struct DFIDeducedMismatchArgs : DFIArguments { 582 TemplateArgumentList *TemplateArgs; 583 unsigned CallArgIndex; 584 }; 585 } 586 587 /// Convert from Sema's representation of template deduction information 588 /// to the form used in overload-candidate information. 589 DeductionFailureInfo 590 clang::MakeDeductionFailureInfo(ASTContext &Context, 591 Sema::TemplateDeductionResult TDK, 592 TemplateDeductionInfo &Info) { 593 DeductionFailureInfo Result; 594 Result.Result = static_cast<unsigned>(TDK); 595 Result.HasDiagnostic = false; 596 switch (TDK) { 597 case Sema::TDK_Invalid: 598 case Sema::TDK_InstantiationDepth: 599 case Sema::TDK_TooManyArguments: 600 case Sema::TDK_TooFewArguments: 601 case Sema::TDK_MiscellaneousDeductionFailure: 602 case Sema::TDK_CUDATargetMismatch: 603 Result.Data = nullptr; 604 break; 605 606 case Sema::TDK_Incomplete: 607 case Sema::TDK_InvalidExplicitArguments: 608 Result.Data = Info.Param.getOpaqueValue(); 609 break; 610 611 case Sema::TDK_DeducedMismatch: 612 case Sema::TDK_DeducedMismatchNested: { 613 // FIXME: Should allocate from normal heap so that we can free this later. 614 auto *Saved = new (Context) DFIDeducedMismatchArgs; 615 Saved->FirstArg = Info.FirstArg; 616 Saved->SecondArg = Info.SecondArg; 617 Saved->TemplateArgs = Info.take(); 618 Saved->CallArgIndex = Info.CallArgIndex; 619 Result.Data = Saved; 620 break; 621 } 622 623 case Sema::TDK_NonDeducedMismatch: { 624 // FIXME: Should allocate from normal heap so that we can free this later. 625 DFIArguments *Saved = new (Context) DFIArguments; 626 Saved->FirstArg = Info.FirstArg; 627 Saved->SecondArg = Info.SecondArg; 628 Result.Data = Saved; 629 break; 630 } 631 632 case Sema::TDK_IncompletePack: 633 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 634 case Sema::TDK_Inconsistent: 635 case Sema::TDK_Underqualified: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 638 Saved->Param = Info.Param; 639 Saved->FirstArg = Info.FirstArg; 640 Saved->SecondArg = Info.SecondArg; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_SubstitutionFailure: 646 Result.Data = Info.take(); 647 if (Info.hasSFINAEDiagnostic()) { 648 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 649 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 650 Info.takeSFINAEDiagnostic(*Diag); 651 Result.HasDiagnostic = true; 652 } 653 break; 654 655 case Sema::TDK_Success: 656 case Sema::TDK_NonDependentConversionFailure: 657 llvm_unreachable("not a deduction failure"); 658 } 659 660 return Result; 661 } 662 663 void DeductionFailureInfo::Destroy() { 664 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 665 case Sema::TDK_Success: 666 case Sema::TDK_Invalid: 667 case Sema::TDK_InstantiationDepth: 668 case Sema::TDK_Incomplete: 669 case Sema::TDK_TooManyArguments: 670 case Sema::TDK_TooFewArguments: 671 case Sema::TDK_InvalidExplicitArguments: 672 case Sema::TDK_CUDATargetMismatch: 673 case Sema::TDK_NonDependentConversionFailure: 674 break; 675 676 case Sema::TDK_IncompletePack: 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 case Sema::TDK_DeducedMismatch: 680 case Sema::TDK_DeducedMismatchNested: 681 case Sema::TDK_NonDeducedMismatch: 682 // FIXME: Destroy the data? 683 Data = nullptr; 684 break; 685 686 case Sema::TDK_SubstitutionFailure: 687 // FIXME: Destroy the template argument list? 688 Data = nullptr; 689 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 690 Diag->~PartialDiagnosticAt(); 691 HasDiagnostic = false; 692 } 693 break; 694 695 // Unhandled 696 case Sema::TDK_MiscellaneousDeductionFailure: 697 break; 698 } 699 } 700 701 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 702 if (HasDiagnostic) 703 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 704 return nullptr; 705 } 706 707 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 708 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 709 case Sema::TDK_Success: 710 case Sema::TDK_Invalid: 711 case Sema::TDK_InstantiationDepth: 712 case Sema::TDK_TooManyArguments: 713 case Sema::TDK_TooFewArguments: 714 case Sema::TDK_SubstitutionFailure: 715 case Sema::TDK_DeducedMismatch: 716 case Sema::TDK_DeducedMismatchNested: 717 case Sema::TDK_NonDeducedMismatch: 718 case Sema::TDK_CUDATargetMismatch: 719 case Sema::TDK_NonDependentConversionFailure: 720 return TemplateParameter(); 721 722 case Sema::TDK_Incomplete: 723 case Sema::TDK_InvalidExplicitArguments: 724 return TemplateParameter::getFromOpaqueValue(Data); 725 726 case Sema::TDK_IncompletePack: 727 case Sema::TDK_Inconsistent: 728 case Sema::TDK_Underqualified: 729 return static_cast<DFIParamWithArguments*>(Data)->Param; 730 731 // Unhandled 732 case Sema::TDK_MiscellaneousDeductionFailure: 733 break; 734 } 735 736 return TemplateParameter(); 737 } 738 739 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 741 case Sema::TDK_Success: 742 case Sema::TDK_Invalid: 743 case Sema::TDK_InstantiationDepth: 744 case Sema::TDK_TooManyArguments: 745 case Sema::TDK_TooFewArguments: 746 case Sema::TDK_Incomplete: 747 case Sema::TDK_IncompletePack: 748 case Sema::TDK_InvalidExplicitArguments: 749 case Sema::TDK_Inconsistent: 750 case Sema::TDK_Underqualified: 751 case Sema::TDK_NonDeducedMismatch: 752 case Sema::TDK_CUDATargetMismatch: 753 case Sema::TDK_NonDependentConversionFailure: 754 return nullptr; 755 756 case Sema::TDK_DeducedMismatch: 757 case Sema::TDK_DeducedMismatchNested: 758 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 759 760 case Sema::TDK_SubstitutionFailure: 761 return static_cast<TemplateArgumentList*>(Data); 762 763 // Unhandled 764 case Sema::TDK_MiscellaneousDeductionFailure: 765 break; 766 } 767 768 return nullptr; 769 } 770 771 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 772 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 773 case Sema::TDK_Success: 774 case Sema::TDK_Invalid: 775 case Sema::TDK_InstantiationDepth: 776 case Sema::TDK_Incomplete: 777 case Sema::TDK_TooManyArguments: 778 case Sema::TDK_TooFewArguments: 779 case Sema::TDK_InvalidExplicitArguments: 780 case Sema::TDK_SubstitutionFailure: 781 case Sema::TDK_CUDATargetMismatch: 782 case Sema::TDK_NonDependentConversionFailure: 783 return nullptr; 784 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_Inconsistent: 787 case Sema::TDK_Underqualified: 788 case Sema::TDK_DeducedMismatch: 789 case Sema::TDK_DeducedMismatchNested: 790 case Sema::TDK_NonDeducedMismatch: 791 return &static_cast<DFIArguments*>(Data)->FirstArg; 792 793 // Unhandled 794 case Sema::TDK_MiscellaneousDeductionFailure: 795 break; 796 } 797 798 return nullptr; 799 } 800 801 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 802 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 803 case Sema::TDK_Success: 804 case Sema::TDK_Invalid: 805 case Sema::TDK_InstantiationDepth: 806 case Sema::TDK_Incomplete: 807 case Sema::TDK_IncompletePack: 808 case Sema::TDK_TooManyArguments: 809 case Sema::TDK_TooFewArguments: 810 case Sema::TDK_InvalidExplicitArguments: 811 case Sema::TDK_SubstitutionFailure: 812 case Sema::TDK_CUDATargetMismatch: 813 case Sema::TDK_NonDependentConversionFailure: 814 return nullptr; 815 816 case Sema::TDK_Inconsistent: 817 case Sema::TDK_Underqualified: 818 case Sema::TDK_DeducedMismatch: 819 case Sema::TDK_DeducedMismatchNested: 820 case Sema::TDK_NonDeducedMismatch: 821 return &static_cast<DFIArguments*>(Data)->SecondArg; 822 823 // Unhandled 824 case Sema::TDK_MiscellaneousDeductionFailure: 825 break; 826 } 827 828 return nullptr; 829 } 830 831 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 832 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 836 837 default: 838 return llvm::None; 839 } 840 } 841 842 void OverloadCandidateSet::destroyCandidates() { 843 for (iterator i = begin(), e = end(); i != e; ++i) { 844 for (auto &C : i->Conversions) 845 C.~ImplicitConversionSequence(); 846 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 847 i->DeductionFailure.Destroy(); 848 } 849 } 850 851 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 852 destroyCandidates(); 853 SlabAllocator.Reset(); 854 NumInlineBytesUsed = 0; 855 Candidates.clear(); 856 Functions.clear(); 857 Kind = CSK; 858 } 859 860 namespace { 861 class UnbridgedCastsSet { 862 struct Entry { 863 Expr **Addr; 864 Expr *Saved; 865 }; 866 SmallVector<Entry, 2> Entries; 867 868 public: 869 void save(Sema &S, Expr *&E) { 870 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 871 Entry entry = { &E, E }; 872 Entries.push_back(entry); 873 E = S.stripARCUnbridgedCast(E); 874 } 875 876 void restore() { 877 for (SmallVectorImpl<Entry>::iterator 878 i = Entries.begin(), e = Entries.end(); i != e; ++i) 879 *i->Addr = i->Saved; 880 } 881 }; 882 } 883 884 /// checkPlaceholderForOverload - Do any interesting placeholder-like 885 /// preprocessing on the given expression. 886 /// 887 /// \param unbridgedCasts a collection to which to add unbridged casts; 888 /// without this, they will be immediately diagnosed as errors 889 /// 890 /// Return true on unrecoverable error. 891 static bool 892 checkPlaceholderForOverload(Sema &S, Expr *&E, 893 UnbridgedCastsSet *unbridgedCasts = nullptr) { 894 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 895 // We can't handle overloaded expressions here because overload 896 // resolution might reasonably tweak them. 897 if (placeholder->getKind() == BuiltinType::Overload) return false; 898 899 // If the context potentially accepts unbridged ARC casts, strip 900 // the unbridged cast and add it to the collection for later restoration. 901 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 902 unbridgedCasts) { 903 unbridgedCasts->save(S, E); 904 return false; 905 } 906 907 // Go ahead and check everything else. 908 ExprResult result = S.CheckPlaceholderExpr(E); 909 if (result.isInvalid()) 910 return true; 911 912 E = result.get(); 913 return false; 914 } 915 916 // Nothing to do. 917 return false; 918 } 919 920 /// checkArgPlaceholdersForOverload - Check a set of call operands for 921 /// placeholders. 922 static bool checkArgPlaceholdersForOverload(Sema &S, 923 MultiExprArg Args, 924 UnbridgedCastsSet &unbridged) { 925 for (unsigned i = 0, e = Args.size(); i != e; ++i) 926 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 927 return true; 928 929 return false; 930 } 931 932 /// Determine whether the given New declaration is an overload of the 933 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 934 /// New and Old cannot be overloaded, e.g., if New has the same signature as 935 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 936 /// functions (or function templates) at all. When it does return Ovl_Match or 937 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 938 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 939 /// declaration. 940 /// 941 /// Example: Given the following input: 942 /// 943 /// void f(int, float); // #1 944 /// void f(int, int); // #2 945 /// int f(int, int); // #3 946 /// 947 /// When we process #1, there is no previous declaration of "f", so IsOverload 948 /// will not be used. 949 /// 950 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 951 /// the parameter types, we see that #1 and #2 are overloaded (since they have 952 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 953 /// unchanged. 954 /// 955 /// When we process #3, Old is an overload set containing #1 and #2. We compare 956 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 957 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 958 /// functions are not part of the signature), IsOverload returns Ovl_Match and 959 /// MatchedDecl will be set to point to the FunctionDecl for #2. 960 /// 961 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 962 /// by a using declaration. The rules for whether to hide shadow declarations 963 /// ignore some properties which otherwise figure into a function template's 964 /// signature. 965 Sema::OverloadKind 966 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 967 NamedDecl *&Match, bool NewIsUsingDecl) { 968 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 969 I != E; ++I) { 970 NamedDecl *OldD = *I; 971 972 bool OldIsUsingDecl = false; 973 if (isa<UsingShadowDecl>(OldD)) { 974 OldIsUsingDecl = true; 975 976 // We can always introduce two using declarations into the same 977 // context, even if they have identical signatures. 978 if (NewIsUsingDecl) continue; 979 980 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 981 } 982 983 // A using-declaration does not conflict with another declaration 984 // if one of them is hidden. 985 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 986 continue; 987 988 // If either declaration was introduced by a using declaration, 989 // we'll need to use slightly different rules for matching. 990 // Essentially, these rules are the normal rules, except that 991 // function templates hide function templates with different 992 // return types or template parameter lists. 993 bool UseMemberUsingDeclRules = 994 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 995 !New->getFriendObjectKind(); 996 997 if (FunctionDecl *OldF = OldD->getAsFunction()) { 998 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 999 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1000 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1001 continue; 1002 } 1003 1004 if (!isa<FunctionTemplateDecl>(OldD) && 1005 !shouldLinkPossiblyHiddenDecl(*I, New)) 1006 continue; 1007 1008 Match = *I; 1009 return Ovl_Match; 1010 } 1011 1012 // Builtins that have custom typechecking or have a reference should 1013 // not be overloadable or redeclarable. 1014 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1015 Match = *I; 1016 return Ovl_NonFunction; 1017 } 1018 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1019 // We can overload with these, which can show up when doing 1020 // redeclaration checks for UsingDecls. 1021 assert(Old.getLookupKind() == LookupUsingDeclName); 1022 } else if (isa<TagDecl>(OldD)) { 1023 // We can always overload with tags by hiding them. 1024 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1025 // Optimistically assume that an unresolved using decl will 1026 // overload; if it doesn't, we'll have to diagnose during 1027 // template instantiation. 1028 // 1029 // Exception: if the scope is dependent and this is not a class 1030 // member, the using declaration can only introduce an enumerator. 1031 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1032 Match = *I; 1033 return Ovl_NonFunction; 1034 } 1035 } else { 1036 // (C++ 13p1): 1037 // Only function declarations can be overloaded; object and type 1038 // declarations cannot be overloaded. 1039 Match = *I; 1040 return Ovl_NonFunction; 1041 } 1042 } 1043 1044 // C++ [temp.friend]p1: 1045 // For a friend function declaration that is not a template declaration: 1046 // -- if the name of the friend is a qualified or unqualified template-id, 1047 // [...], otherwise 1048 // -- if the name of the friend is a qualified-id and a matching 1049 // non-template function is found in the specified class or namespace, 1050 // the friend declaration refers to that function, otherwise, 1051 // -- if the name of the friend is a qualified-id and a matching function 1052 // template is found in the specified class or namespace, the friend 1053 // declaration refers to the deduced specialization of that function 1054 // template, otherwise 1055 // -- the name shall be an unqualified-id [...] 1056 // If we get here for a qualified friend declaration, we've just reached the 1057 // third bullet. If the type of the friend is dependent, skip this lookup 1058 // until instantiation. 1059 if (New->getFriendObjectKind() && New->getQualifier() && 1060 !New->getType()->isDependentType()) { 1061 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1062 TemplateSpecResult.addAllDecls(Old); 1063 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1064 /*QualifiedFriend*/true)) { 1065 New->setInvalidDecl(); 1066 return Ovl_Overload; 1067 } 1068 1069 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1070 return Ovl_Match; 1071 } 1072 1073 return Ovl_Overload; 1074 } 1075 1076 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1077 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1078 // C++ [basic.start.main]p2: This function shall not be overloaded. 1079 if (New->isMain()) 1080 return false; 1081 1082 // MSVCRT user defined entry points cannot be overloaded. 1083 if (New->isMSVCRTEntryPoint()) 1084 return false; 1085 1086 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1087 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1088 1089 // C++ [temp.fct]p2: 1090 // A function template can be overloaded with other function templates 1091 // and with normal (non-template) functions. 1092 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1093 return true; 1094 1095 // Is the function New an overload of the function Old? 1096 QualType OldQType = Context.getCanonicalType(Old->getType()); 1097 QualType NewQType = Context.getCanonicalType(New->getType()); 1098 1099 // Compare the signatures (C++ 1.3.10) of the two functions to 1100 // determine whether they are overloads. If we find any mismatch 1101 // in the signature, they are overloads. 1102 1103 // If either of these functions is a K&R-style function (no 1104 // prototype), then we consider them to have matching signatures. 1105 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1106 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1107 return false; 1108 1109 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1110 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1111 1112 // The signature of a function includes the types of its 1113 // parameters (C++ 1.3.10), which includes the presence or absence 1114 // of the ellipsis; see C++ DR 357). 1115 if (OldQType != NewQType && 1116 (OldType->getNumParams() != NewType->getNumParams() || 1117 OldType->isVariadic() != NewType->isVariadic() || 1118 !FunctionParamTypesAreEqual(OldType, NewType))) 1119 return true; 1120 1121 // C++ [temp.over.link]p4: 1122 // The signature of a function template consists of its function 1123 // signature, its return type and its template parameter list. The names 1124 // of the template parameters are significant only for establishing the 1125 // relationship between the template parameters and the rest of the 1126 // signature. 1127 // 1128 // We check the return type and template parameter lists for function 1129 // templates first; the remaining checks follow. 1130 // 1131 // However, we don't consider either of these when deciding whether 1132 // a member introduced by a shadow declaration is hidden. 1133 if (!UseMemberUsingDeclRules && NewTemplate && 1134 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1135 OldTemplate->getTemplateParameters(), 1136 false, TPL_TemplateMatch) || 1137 !Context.hasSameType(Old->getDeclaredReturnType(), 1138 New->getDeclaredReturnType()))) 1139 return true; 1140 1141 // If the function is a class member, its signature includes the 1142 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1143 // 1144 // As part of this, also check whether one of the member functions 1145 // is static, in which case they are not overloads (C++ 1146 // 13.1p2). While not part of the definition of the signature, 1147 // this check is important to determine whether these functions 1148 // can be overloaded. 1149 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1150 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1151 if (OldMethod && NewMethod && 1152 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1153 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1154 if (!UseMemberUsingDeclRules && 1155 (OldMethod->getRefQualifier() == RQ_None || 1156 NewMethod->getRefQualifier() == RQ_None)) { 1157 // C++0x [over.load]p2: 1158 // - Member function declarations with the same name and the same 1159 // parameter-type-list as well as member function template 1160 // declarations with the same name, the same parameter-type-list, and 1161 // the same template parameter lists cannot be overloaded if any of 1162 // them, but not all, have a ref-qualifier (8.3.5). 1163 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1164 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1165 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1166 } 1167 return true; 1168 } 1169 1170 // We may not have applied the implicit const for a constexpr member 1171 // function yet (because we haven't yet resolved whether this is a static 1172 // or non-static member function). Add it now, on the assumption that this 1173 // is a redeclaration of OldMethod. 1174 // FIXME: OpenCL: Need to consider address spaces 1175 unsigned OldQuals = OldMethod->getTypeQualifiers().getCVRUQualifiers(); 1176 unsigned NewQuals = NewMethod->getTypeQualifiers().getCVRUQualifiers(); 1177 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1178 !isa<CXXConstructorDecl>(NewMethod)) 1179 NewQuals |= Qualifiers::Const; 1180 1181 // We do not allow overloading based off of '__restrict'. 1182 OldQuals &= ~Qualifiers::Restrict; 1183 NewQuals &= ~Qualifiers::Restrict; 1184 if (OldQuals != NewQuals) 1185 return true; 1186 } 1187 1188 // Though pass_object_size is placed on parameters and takes an argument, we 1189 // consider it to be a function-level modifier for the sake of function 1190 // identity. Either the function has one or more parameters with 1191 // pass_object_size or it doesn't. 1192 if (functionHasPassObjectSizeParams(New) != 1193 functionHasPassObjectSizeParams(Old)) 1194 return true; 1195 1196 // enable_if attributes are an order-sensitive part of the signature. 1197 for (specific_attr_iterator<EnableIfAttr> 1198 NewI = New->specific_attr_begin<EnableIfAttr>(), 1199 NewE = New->specific_attr_end<EnableIfAttr>(), 1200 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1201 OldE = Old->specific_attr_end<EnableIfAttr>(); 1202 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1203 if (NewI == NewE || OldI == OldE) 1204 return true; 1205 llvm::FoldingSetNodeID NewID, OldID; 1206 NewI->getCond()->Profile(NewID, Context, true); 1207 OldI->getCond()->Profile(OldID, Context, true); 1208 if (NewID != OldID) 1209 return true; 1210 } 1211 1212 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1213 // Don't allow overloading of destructors. (In theory we could, but it 1214 // would be a giant change to clang.) 1215 if (isa<CXXDestructorDecl>(New)) 1216 return false; 1217 1218 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1219 OldTarget = IdentifyCUDATarget(Old); 1220 if (NewTarget == CFT_InvalidTarget) 1221 return false; 1222 1223 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1224 1225 // Allow overloading of functions with same signature and different CUDA 1226 // target attributes. 1227 return NewTarget != OldTarget; 1228 } 1229 1230 // The signatures match; this is not an overload. 1231 return false; 1232 } 1233 1234 /// Checks availability of the function depending on the current 1235 /// function context. Inside an unavailable function, unavailability is ignored. 1236 /// 1237 /// \returns true if \arg FD is unavailable and current context is inside 1238 /// an available function, false otherwise. 1239 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1240 if (!FD->isUnavailable()) 1241 return false; 1242 1243 // Walk up the context of the caller. 1244 Decl *C = cast<Decl>(CurContext); 1245 do { 1246 if (C->isUnavailable()) 1247 return false; 1248 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1249 return true; 1250 } 1251 1252 /// Tries a user-defined conversion from From to ToType. 1253 /// 1254 /// Produces an implicit conversion sequence for when a standard conversion 1255 /// is not an option. See TryImplicitConversion for more information. 1256 static ImplicitConversionSequence 1257 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1258 bool SuppressUserConversions, 1259 bool AllowExplicit, 1260 bool InOverloadResolution, 1261 bool CStyle, 1262 bool AllowObjCWritebackConversion, 1263 bool AllowObjCConversionOnExplicit) { 1264 ImplicitConversionSequence ICS; 1265 1266 if (SuppressUserConversions) { 1267 // We're not in the case above, so there is no conversion that 1268 // we can perform. 1269 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1270 return ICS; 1271 } 1272 1273 // Attempt user-defined conversion. 1274 OverloadCandidateSet Conversions(From->getExprLoc(), 1275 OverloadCandidateSet::CSK_Normal); 1276 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1277 Conversions, AllowExplicit, 1278 AllowObjCConversionOnExplicit)) { 1279 case OR_Success: 1280 case OR_Deleted: 1281 ICS.setUserDefined(); 1282 // C++ [over.ics.user]p4: 1283 // A conversion of an expression of class type to the same class 1284 // type is given Exact Match rank, and a conversion of an 1285 // expression of class type to a base class of that type is 1286 // given Conversion rank, in spite of the fact that a copy 1287 // constructor (i.e., a user-defined conversion function) is 1288 // called for those cases. 1289 if (CXXConstructorDecl *Constructor 1290 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1291 QualType FromCanon 1292 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1293 QualType ToCanon 1294 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1295 if (Constructor->isCopyConstructor() && 1296 (FromCanon == ToCanon || 1297 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1298 // Turn this into a "standard" conversion sequence, so that it 1299 // gets ranked with standard conversion sequences. 1300 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1301 ICS.setStandard(); 1302 ICS.Standard.setAsIdentityConversion(); 1303 ICS.Standard.setFromType(From->getType()); 1304 ICS.Standard.setAllToTypes(ToType); 1305 ICS.Standard.CopyConstructor = Constructor; 1306 ICS.Standard.FoundCopyConstructor = Found; 1307 if (ToCanon != FromCanon) 1308 ICS.Standard.Second = ICK_Derived_To_Base; 1309 } 1310 } 1311 break; 1312 1313 case OR_Ambiguous: 1314 ICS.setAmbiguous(); 1315 ICS.Ambiguous.setFromType(From->getType()); 1316 ICS.Ambiguous.setToType(ToType); 1317 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1318 Cand != Conversions.end(); ++Cand) 1319 if (Cand->Viable) 1320 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1321 break; 1322 1323 // Fall through. 1324 case OR_No_Viable_Function: 1325 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1326 break; 1327 } 1328 1329 return ICS; 1330 } 1331 1332 /// TryImplicitConversion - Attempt to perform an implicit conversion 1333 /// from the given expression (Expr) to the given type (ToType). This 1334 /// function returns an implicit conversion sequence that can be used 1335 /// to perform the initialization. Given 1336 /// 1337 /// void f(float f); 1338 /// void g(int i) { f(i); } 1339 /// 1340 /// this routine would produce an implicit conversion sequence to 1341 /// describe the initialization of f from i, which will be a standard 1342 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1343 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1344 // 1345 /// Note that this routine only determines how the conversion can be 1346 /// performed; it does not actually perform the conversion. As such, 1347 /// it will not produce any diagnostics if no conversion is available, 1348 /// but will instead return an implicit conversion sequence of kind 1349 /// "BadConversion". 1350 /// 1351 /// If @p SuppressUserConversions, then user-defined conversions are 1352 /// not permitted. 1353 /// If @p AllowExplicit, then explicit user-defined conversions are 1354 /// permitted. 1355 /// 1356 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1357 /// writeback conversion, which allows __autoreleasing id* parameters to 1358 /// be initialized with __strong id* or __weak id* arguments. 1359 static ImplicitConversionSequence 1360 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1361 bool SuppressUserConversions, 1362 bool AllowExplicit, 1363 bool InOverloadResolution, 1364 bool CStyle, 1365 bool AllowObjCWritebackConversion, 1366 bool AllowObjCConversionOnExplicit) { 1367 ImplicitConversionSequence ICS; 1368 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1369 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1370 ICS.setStandard(); 1371 return ICS; 1372 } 1373 1374 if (!S.getLangOpts().CPlusPlus) { 1375 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1376 return ICS; 1377 } 1378 1379 // C++ [over.ics.user]p4: 1380 // A conversion of an expression of class type to the same class 1381 // type is given Exact Match rank, and a conversion of an 1382 // expression of class type to a base class of that type is 1383 // given Conversion rank, in spite of the fact that a copy/move 1384 // constructor (i.e., a user-defined conversion function) is 1385 // called for those cases. 1386 QualType FromType = From->getType(); 1387 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1388 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1389 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1390 ICS.setStandard(); 1391 ICS.Standard.setAsIdentityConversion(); 1392 ICS.Standard.setFromType(FromType); 1393 ICS.Standard.setAllToTypes(ToType); 1394 1395 // We don't actually check at this point whether there is a valid 1396 // copy/move constructor, since overloading just assumes that it 1397 // exists. When we actually perform initialization, we'll find the 1398 // appropriate constructor to copy the returned object, if needed. 1399 ICS.Standard.CopyConstructor = nullptr; 1400 1401 // Determine whether this is considered a derived-to-base conversion. 1402 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1403 ICS.Standard.Second = ICK_Derived_To_Base; 1404 1405 return ICS; 1406 } 1407 1408 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1409 AllowExplicit, InOverloadResolution, CStyle, 1410 AllowObjCWritebackConversion, 1411 AllowObjCConversionOnExplicit); 1412 } 1413 1414 ImplicitConversionSequence 1415 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1416 bool SuppressUserConversions, 1417 bool AllowExplicit, 1418 bool InOverloadResolution, 1419 bool CStyle, 1420 bool AllowObjCWritebackConversion) { 1421 return ::TryImplicitConversion(*this, From, ToType, 1422 SuppressUserConversions, AllowExplicit, 1423 InOverloadResolution, CStyle, 1424 AllowObjCWritebackConversion, 1425 /*AllowObjCConversionOnExplicit=*/false); 1426 } 1427 1428 /// PerformImplicitConversion - Perform an implicit conversion of the 1429 /// expression From to the type ToType. Returns the 1430 /// converted expression. Flavor is the kind of conversion we're 1431 /// performing, used in the error message. If @p AllowExplicit, 1432 /// explicit user-defined conversions are permitted. 1433 ExprResult 1434 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1435 AssignmentAction Action, bool AllowExplicit) { 1436 ImplicitConversionSequence ICS; 1437 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1438 } 1439 1440 ExprResult 1441 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1442 AssignmentAction Action, bool AllowExplicit, 1443 ImplicitConversionSequence& ICS) { 1444 if (checkPlaceholderForOverload(*this, From)) 1445 return ExprError(); 1446 1447 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1448 bool AllowObjCWritebackConversion 1449 = getLangOpts().ObjCAutoRefCount && 1450 (Action == AA_Passing || Action == AA_Sending); 1451 if (getLangOpts().ObjC) 1452 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1453 From->getType(), From); 1454 ICS = ::TryImplicitConversion(*this, From, ToType, 1455 /*SuppressUserConversions=*/false, 1456 AllowExplicit, 1457 /*InOverloadResolution=*/false, 1458 /*CStyle=*/false, 1459 AllowObjCWritebackConversion, 1460 /*AllowObjCConversionOnExplicit=*/false); 1461 return PerformImplicitConversion(From, ToType, ICS, Action); 1462 } 1463 1464 /// Determine whether the conversion from FromType to ToType is a valid 1465 /// conversion that strips "noexcept" or "noreturn" off the nested function 1466 /// type. 1467 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1468 QualType &ResultTy) { 1469 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1470 return false; 1471 1472 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1473 // or F(t noexcept) -> F(t) 1474 // where F adds one of the following at most once: 1475 // - a pointer 1476 // - a member pointer 1477 // - a block pointer 1478 // Changes here need matching changes in FindCompositePointerType. 1479 CanQualType CanTo = Context.getCanonicalType(ToType); 1480 CanQualType CanFrom = Context.getCanonicalType(FromType); 1481 Type::TypeClass TyClass = CanTo->getTypeClass(); 1482 if (TyClass != CanFrom->getTypeClass()) return false; 1483 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1484 if (TyClass == Type::Pointer) { 1485 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1486 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1487 } else if (TyClass == Type::BlockPointer) { 1488 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1489 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1490 } else if (TyClass == Type::MemberPointer) { 1491 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1492 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1493 // A function pointer conversion cannot change the class of the function. 1494 if (ToMPT->getClass() != FromMPT->getClass()) 1495 return false; 1496 CanTo = ToMPT->getPointeeType(); 1497 CanFrom = FromMPT->getPointeeType(); 1498 } else { 1499 return false; 1500 } 1501 1502 TyClass = CanTo->getTypeClass(); 1503 if (TyClass != CanFrom->getTypeClass()) return false; 1504 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1505 return false; 1506 } 1507 1508 const auto *FromFn = cast<FunctionType>(CanFrom); 1509 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1510 1511 const auto *ToFn = cast<FunctionType>(CanTo); 1512 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1513 1514 bool Changed = false; 1515 1516 // Drop 'noreturn' if not present in target type. 1517 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1518 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1519 Changed = true; 1520 } 1521 1522 // Drop 'noexcept' if not present in target type. 1523 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1524 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1525 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1526 FromFn = cast<FunctionType>( 1527 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1528 EST_None) 1529 .getTypePtr()); 1530 Changed = true; 1531 } 1532 1533 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1534 // only if the ExtParameterInfo lists of the two function prototypes can be 1535 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1536 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1537 bool CanUseToFPT, CanUseFromFPT; 1538 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1539 CanUseFromFPT, NewParamInfos) && 1540 CanUseToFPT && !CanUseFromFPT) { 1541 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1542 ExtInfo.ExtParameterInfos = 1543 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1544 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1545 FromFPT->getParamTypes(), ExtInfo); 1546 FromFn = QT->getAs<FunctionType>(); 1547 Changed = true; 1548 } 1549 } 1550 1551 if (!Changed) 1552 return false; 1553 1554 assert(QualType(FromFn, 0).isCanonical()); 1555 if (QualType(FromFn, 0) != CanTo) return false; 1556 1557 ResultTy = ToType; 1558 return true; 1559 } 1560 1561 /// Determine whether the conversion from FromType to ToType is a valid 1562 /// vector conversion. 1563 /// 1564 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1565 /// conversion. 1566 static bool IsVectorConversion(Sema &S, QualType FromType, 1567 QualType ToType, ImplicitConversionKind &ICK) { 1568 // We need at least one of these types to be a vector type to have a vector 1569 // conversion. 1570 if (!ToType->isVectorType() && !FromType->isVectorType()) 1571 return false; 1572 1573 // Identical types require no conversions. 1574 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1575 return false; 1576 1577 // There are no conversions between extended vector types, only identity. 1578 if (ToType->isExtVectorType()) { 1579 // There are no conversions between extended vector types other than the 1580 // identity conversion. 1581 if (FromType->isExtVectorType()) 1582 return false; 1583 1584 // Vector splat from any arithmetic type to a vector. 1585 if (FromType->isArithmeticType()) { 1586 ICK = ICK_Vector_Splat; 1587 return true; 1588 } 1589 } 1590 1591 // We can perform the conversion between vector types in the following cases: 1592 // 1)vector types are equivalent AltiVec and GCC vector types 1593 // 2)lax vector conversions are permitted and the vector types are of the 1594 // same size 1595 if (ToType->isVectorType() && FromType->isVectorType()) { 1596 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1597 S.isLaxVectorConversion(FromType, ToType)) { 1598 ICK = ICK_Vector_Conversion; 1599 return true; 1600 } 1601 } 1602 1603 return false; 1604 } 1605 1606 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1607 bool InOverloadResolution, 1608 StandardConversionSequence &SCS, 1609 bool CStyle); 1610 1611 /// IsStandardConversion - Determines whether there is a standard 1612 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1613 /// expression From to the type ToType. Standard conversion sequences 1614 /// only consider non-class types; for conversions that involve class 1615 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1616 /// contain the standard conversion sequence required to perform this 1617 /// conversion and this routine will return true. Otherwise, this 1618 /// routine will return false and the value of SCS is unspecified. 1619 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1620 bool InOverloadResolution, 1621 StandardConversionSequence &SCS, 1622 bool CStyle, 1623 bool AllowObjCWritebackConversion) { 1624 QualType FromType = From->getType(); 1625 1626 // Standard conversions (C++ [conv]) 1627 SCS.setAsIdentityConversion(); 1628 SCS.IncompatibleObjC = false; 1629 SCS.setFromType(FromType); 1630 SCS.CopyConstructor = nullptr; 1631 1632 // There are no standard conversions for class types in C++, so 1633 // abort early. When overloading in C, however, we do permit them. 1634 if (S.getLangOpts().CPlusPlus && 1635 (FromType->isRecordType() || ToType->isRecordType())) 1636 return false; 1637 1638 // The first conversion can be an lvalue-to-rvalue conversion, 1639 // array-to-pointer conversion, or function-to-pointer conversion 1640 // (C++ 4p1). 1641 1642 if (FromType == S.Context.OverloadTy) { 1643 DeclAccessPair AccessPair; 1644 if (FunctionDecl *Fn 1645 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1646 AccessPair)) { 1647 // We were able to resolve the address of the overloaded function, 1648 // so we can convert to the type of that function. 1649 FromType = Fn->getType(); 1650 SCS.setFromType(FromType); 1651 1652 // we can sometimes resolve &foo<int> regardless of ToType, so check 1653 // if the type matches (identity) or we are converting to bool 1654 if (!S.Context.hasSameUnqualifiedType( 1655 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1656 QualType resultTy; 1657 // if the function type matches except for [[noreturn]], it's ok 1658 if (!S.IsFunctionConversion(FromType, 1659 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1660 // otherwise, only a boolean conversion is standard 1661 if (!ToType->isBooleanType()) 1662 return false; 1663 } 1664 1665 // Check if the "from" expression is taking the address of an overloaded 1666 // function and recompute the FromType accordingly. Take advantage of the 1667 // fact that non-static member functions *must* have such an address-of 1668 // expression. 1669 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1670 if (Method && !Method->isStatic()) { 1671 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1672 "Non-unary operator on non-static member address"); 1673 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1674 == UO_AddrOf && 1675 "Non-address-of operator on non-static member address"); 1676 const Type *ClassType 1677 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1678 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1679 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1680 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1681 UO_AddrOf && 1682 "Non-address-of operator for overloaded function expression"); 1683 FromType = S.Context.getPointerType(FromType); 1684 } 1685 1686 // Check that we've computed the proper type after overload resolution. 1687 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1688 // be calling it from within an NDEBUG block. 1689 assert(S.Context.hasSameType( 1690 FromType, 1691 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1692 } else { 1693 return false; 1694 } 1695 } 1696 // Lvalue-to-rvalue conversion (C++11 4.1): 1697 // A glvalue (3.10) of a non-function, non-array type T can 1698 // be converted to a prvalue. 1699 bool argIsLValue = From->isGLValue(); 1700 if (argIsLValue && 1701 !FromType->isFunctionType() && !FromType->isArrayType() && 1702 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1703 SCS.First = ICK_Lvalue_To_Rvalue; 1704 1705 // C11 6.3.2.1p2: 1706 // ... if the lvalue has atomic type, the value has the non-atomic version 1707 // of the type of the lvalue ... 1708 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1709 FromType = Atomic->getValueType(); 1710 1711 // If T is a non-class type, the type of the rvalue is the 1712 // cv-unqualified version of T. Otherwise, the type of the rvalue 1713 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1714 // just strip the qualifiers because they don't matter. 1715 FromType = FromType.getUnqualifiedType(); 1716 } else if (FromType->isArrayType()) { 1717 // Array-to-pointer conversion (C++ 4.2) 1718 SCS.First = ICK_Array_To_Pointer; 1719 1720 // An lvalue or rvalue of type "array of N T" or "array of unknown 1721 // bound of T" can be converted to an rvalue of type "pointer to 1722 // T" (C++ 4.2p1). 1723 FromType = S.Context.getArrayDecayedType(FromType); 1724 1725 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1726 // This conversion is deprecated in C++03 (D.4) 1727 SCS.DeprecatedStringLiteralToCharPtr = true; 1728 1729 // For the purpose of ranking in overload resolution 1730 // (13.3.3.1.1), this conversion is considered an 1731 // array-to-pointer conversion followed by a qualification 1732 // conversion (4.4). (C++ 4.2p2) 1733 SCS.Second = ICK_Identity; 1734 SCS.Third = ICK_Qualification; 1735 SCS.QualificationIncludesObjCLifetime = false; 1736 SCS.setAllToTypes(FromType); 1737 return true; 1738 } 1739 } else if (FromType->isFunctionType() && argIsLValue) { 1740 // Function-to-pointer conversion (C++ 4.3). 1741 SCS.First = ICK_Function_To_Pointer; 1742 1743 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1744 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1745 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1746 return false; 1747 1748 // An lvalue of function type T can be converted to an rvalue of 1749 // type "pointer to T." The result is a pointer to the 1750 // function. (C++ 4.3p1). 1751 FromType = S.Context.getPointerType(FromType); 1752 } else { 1753 // We don't require any conversions for the first step. 1754 SCS.First = ICK_Identity; 1755 } 1756 SCS.setToType(0, FromType); 1757 1758 // The second conversion can be an integral promotion, floating 1759 // point promotion, integral conversion, floating point conversion, 1760 // floating-integral conversion, pointer conversion, 1761 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1762 // For overloading in C, this can also be a "compatible-type" 1763 // conversion. 1764 bool IncompatibleObjC = false; 1765 ImplicitConversionKind SecondICK = ICK_Identity; 1766 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1767 // The unqualified versions of the types are the same: there's no 1768 // conversion to do. 1769 SCS.Second = ICK_Identity; 1770 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1771 // Integral promotion (C++ 4.5). 1772 SCS.Second = ICK_Integral_Promotion; 1773 FromType = ToType.getUnqualifiedType(); 1774 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1775 // Floating point promotion (C++ 4.6). 1776 SCS.Second = ICK_Floating_Promotion; 1777 FromType = ToType.getUnqualifiedType(); 1778 } else if (S.IsComplexPromotion(FromType, ToType)) { 1779 // Complex promotion (Clang extension) 1780 SCS.Second = ICK_Complex_Promotion; 1781 FromType = ToType.getUnqualifiedType(); 1782 } else if (ToType->isBooleanType() && 1783 (FromType->isArithmeticType() || 1784 FromType->isAnyPointerType() || 1785 FromType->isBlockPointerType() || 1786 FromType->isMemberPointerType() || 1787 FromType->isNullPtrType())) { 1788 // Boolean conversions (C++ 4.12). 1789 SCS.Second = ICK_Boolean_Conversion; 1790 FromType = S.Context.BoolTy; 1791 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1792 ToType->isIntegralType(S.Context)) { 1793 // Integral conversions (C++ 4.7). 1794 SCS.Second = ICK_Integral_Conversion; 1795 FromType = ToType.getUnqualifiedType(); 1796 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1797 // Complex conversions (C99 6.3.1.6) 1798 SCS.Second = ICK_Complex_Conversion; 1799 FromType = ToType.getUnqualifiedType(); 1800 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1801 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1802 // Complex-real conversions (C99 6.3.1.7) 1803 SCS.Second = ICK_Complex_Real; 1804 FromType = ToType.getUnqualifiedType(); 1805 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1806 // FIXME: disable conversions between long double and __float128 if 1807 // their representation is different until there is back end support 1808 // We of course allow this conversion if long double is really double. 1809 if (&S.Context.getFloatTypeSemantics(FromType) != 1810 &S.Context.getFloatTypeSemantics(ToType)) { 1811 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1812 ToType == S.Context.LongDoubleTy) || 1813 (FromType == S.Context.LongDoubleTy && 1814 ToType == S.Context.Float128Ty)); 1815 if (Float128AndLongDouble && 1816 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1817 &llvm::APFloat::PPCDoubleDouble())) 1818 return false; 1819 } 1820 // Floating point conversions (C++ 4.8). 1821 SCS.Second = ICK_Floating_Conversion; 1822 FromType = ToType.getUnqualifiedType(); 1823 } else if ((FromType->isRealFloatingType() && 1824 ToType->isIntegralType(S.Context)) || 1825 (FromType->isIntegralOrUnscopedEnumerationType() && 1826 ToType->isRealFloatingType())) { 1827 // Floating-integral conversions (C++ 4.9). 1828 SCS.Second = ICK_Floating_Integral; 1829 FromType = ToType.getUnqualifiedType(); 1830 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1831 SCS.Second = ICK_Block_Pointer_Conversion; 1832 } else if (AllowObjCWritebackConversion && 1833 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1834 SCS.Second = ICK_Writeback_Conversion; 1835 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1836 FromType, IncompatibleObjC)) { 1837 // Pointer conversions (C++ 4.10). 1838 SCS.Second = ICK_Pointer_Conversion; 1839 SCS.IncompatibleObjC = IncompatibleObjC; 1840 FromType = FromType.getUnqualifiedType(); 1841 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1842 InOverloadResolution, FromType)) { 1843 // Pointer to member conversions (4.11). 1844 SCS.Second = ICK_Pointer_Member; 1845 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1846 SCS.Second = SecondICK; 1847 FromType = ToType.getUnqualifiedType(); 1848 } else if (!S.getLangOpts().CPlusPlus && 1849 S.Context.typesAreCompatible(ToType, FromType)) { 1850 // Compatible conversions (Clang extension for C function overloading) 1851 SCS.Second = ICK_Compatible_Conversion; 1852 FromType = ToType.getUnqualifiedType(); 1853 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1854 InOverloadResolution, 1855 SCS, CStyle)) { 1856 SCS.Second = ICK_TransparentUnionConversion; 1857 FromType = ToType; 1858 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1859 CStyle)) { 1860 // tryAtomicConversion has updated the standard conversion sequence 1861 // appropriately. 1862 return true; 1863 } else if (ToType->isEventT() && 1864 From->isIntegerConstantExpr(S.getASTContext()) && 1865 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1866 SCS.Second = ICK_Zero_Event_Conversion; 1867 FromType = ToType; 1868 } else if (ToType->isQueueT() && 1869 From->isIntegerConstantExpr(S.getASTContext()) && 1870 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1871 SCS.Second = ICK_Zero_Queue_Conversion; 1872 FromType = ToType; 1873 } else { 1874 // No second conversion required. 1875 SCS.Second = ICK_Identity; 1876 } 1877 SCS.setToType(1, FromType); 1878 1879 // The third conversion can be a function pointer conversion or a 1880 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1881 bool ObjCLifetimeConversion; 1882 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1883 // Function pointer conversions (removing 'noexcept') including removal of 1884 // 'noreturn' (Clang extension). 1885 SCS.Third = ICK_Function_Conversion; 1886 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1887 ObjCLifetimeConversion)) { 1888 SCS.Third = ICK_Qualification; 1889 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1890 FromType = ToType; 1891 } else { 1892 // No conversion required 1893 SCS.Third = ICK_Identity; 1894 } 1895 1896 // C++ [over.best.ics]p6: 1897 // [...] Any difference in top-level cv-qualification is 1898 // subsumed by the initialization itself and does not constitute 1899 // a conversion. [...] 1900 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1901 QualType CanonTo = S.Context.getCanonicalType(ToType); 1902 if (CanonFrom.getLocalUnqualifiedType() 1903 == CanonTo.getLocalUnqualifiedType() && 1904 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1905 FromType = ToType; 1906 CanonFrom = CanonTo; 1907 } 1908 1909 SCS.setToType(2, FromType); 1910 1911 if (CanonFrom == CanonTo) 1912 return true; 1913 1914 // If we have not converted the argument type to the parameter type, 1915 // this is a bad conversion sequence, unless we're resolving an overload in C. 1916 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1917 return false; 1918 1919 ExprResult ER = ExprResult{From}; 1920 Sema::AssignConvertType Conv = 1921 S.CheckSingleAssignmentConstraints(ToType, ER, 1922 /*Diagnose=*/false, 1923 /*DiagnoseCFAudited=*/false, 1924 /*ConvertRHS=*/false); 1925 ImplicitConversionKind SecondConv; 1926 switch (Conv) { 1927 case Sema::Compatible: 1928 SecondConv = ICK_C_Only_Conversion; 1929 break; 1930 // For our purposes, discarding qualifiers is just as bad as using an 1931 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1932 // qualifiers, as well. 1933 case Sema::CompatiblePointerDiscardsQualifiers: 1934 case Sema::IncompatiblePointer: 1935 case Sema::IncompatiblePointerSign: 1936 SecondConv = ICK_Incompatible_Pointer_Conversion; 1937 break; 1938 default: 1939 return false; 1940 } 1941 1942 // First can only be an lvalue conversion, so we pretend that this was the 1943 // second conversion. First should already be valid from earlier in the 1944 // function. 1945 SCS.Second = SecondConv; 1946 SCS.setToType(1, ToType); 1947 1948 // Third is Identity, because Second should rank us worse than any other 1949 // conversion. This could also be ICK_Qualification, but it's simpler to just 1950 // lump everything in with the second conversion, and we don't gain anything 1951 // from making this ICK_Qualification. 1952 SCS.Third = ICK_Identity; 1953 SCS.setToType(2, ToType); 1954 return true; 1955 } 1956 1957 static bool 1958 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1959 QualType &ToType, 1960 bool InOverloadResolution, 1961 StandardConversionSequence &SCS, 1962 bool CStyle) { 1963 1964 const RecordType *UT = ToType->getAsUnionType(); 1965 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1966 return false; 1967 // The field to initialize within the transparent union. 1968 RecordDecl *UD = UT->getDecl(); 1969 // It's compatible if the expression matches any of the fields. 1970 for (const auto *it : UD->fields()) { 1971 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1972 CStyle, /*ObjCWritebackConversion=*/false)) { 1973 ToType = it->getType(); 1974 return true; 1975 } 1976 } 1977 return false; 1978 } 1979 1980 /// IsIntegralPromotion - Determines whether the conversion from the 1981 /// expression From (whose potentially-adjusted type is FromType) to 1982 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1983 /// sets PromotedType to the promoted type. 1984 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1985 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1986 // All integers are built-in. 1987 if (!To) { 1988 return false; 1989 } 1990 1991 // An rvalue of type char, signed char, unsigned char, short int, or 1992 // unsigned short int can be converted to an rvalue of type int if 1993 // int can represent all the values of the source type; otherwise, 1994 // the source rvalue can be converted to an rvalue of type unsigned 1995 // int (C++ 4.5p1). 1996 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1997 !FromType->isEnumeralType()) { 1998 if (// We can promote any signed, promotable integer type to an int 1999 (FromType->isSignedIntegerType() || 2000 // We can promote any unsigned integer type whose size is 2001 // less than int to an int. 2002 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2003 return To->getKind() == BuiltinType::Int; 2004 } 2005 2006 return To->getKind() == BuiltinType::UInt; 2007 } 2008 2009 // C++11 [conv.prom]p3: 2010 // A prvalue of an unscoped enumeration type whose underlying type is not 2011 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2012 // following types that can represent all the values of the enumeration 2013 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2014 // unsigned int, long int, unsigned long int, long long int, or unsigned 2015 // long long int. If none of the types in that list can represent all the 2016 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2017 // type can be converted to an rvalue a prvalue of the extended integer type 2018 // with lowest integer conversion rank (4.13) greater than the rank of long 2019 // long in which all the values of the enumeration can be represented. If 2020 // there are two such extended types, the signed one is chosen. 2021 // C++11 [conv.prom]p4: 2022 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2023 // can be converted to a prvalue of its underlying type. Moreover, if 2024 // integral promotion can be applied to its underlying type, a prvalue of an 2025 // unscoped enumeration type whose underlying type is fixed can also be 2026 // converted to a prvalue of the promoted underlying type. 2027 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2028 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2029 // provided for a scoped enumeration. 2030 if (FromEnumType->getDecl()->isScoped()) 2031 return false; 2032 2033 // We can perform an integral promotion to the underlying type of the enum, 2034 // even if that's not the promoted type. Note that the check for promoting 2035 // the underlying type is based on the type alone, and does not consider 2036 // the bitfield-ness of the actual source expression. 2037 if (FromEnumType->getDecl()->isFixed()) { 2038 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2039 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2040 IsIntegralPromotion(nullptr, Underlying, ToType); 2041 } 2042 2043 // We have already pre-calculated the promotion type, so this is trivial. 2044 if (ToType->isIntegerType() && 2045 isCompleteType(From->getBeginLoc(), FromType)) 2046 return Context.hasSameUnqualifiedType( 2047 ToType, FromEnumType->getDecl()->getPromotionType()); 2048 2049 // C++ [conv.prom]p5: 2050 // If the bit-field has an enumerated type, it is treated as any other 2051 // value of that type for promotion purposes. 2052 // 2053 // ... so do not fall through into the bit-field checks below in C++. 2054 if (getLangOpts().CPlusPlus) 2055 return false; 2056 } 2057 2058 // C++0x [conv.prom]p2: 2059 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2060 // to an rvalue a prvalue of the first of the following types that can 2061 // represent all the values of its underlying type: int, unsigned int, 2062 // long int, unsigned long int, long long int, or unsigned long long int. 2063 // If none of the types in that list can represent all the values of its 2064 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2065 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2066 // type. 2067 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2068 ToType->isIntegerType()) { 2069 // Determine whether the type we're converting from is signed or 2070 // unsigned. 2071 bool FromIsSigned = FromType->isSignedIntegerType(); 2072 uint64_t FromSize = Context.getTypeSize(FromType); 2073 2074 // The types we'll try to promote to, in the appropriate 2075 // order. Try each of these types. 2076 QualType PromoteTypes[6] = { 2077 Context.IntTy, Context.UnsignedIntTy, 2078 Context.LongTy, Context.UnsignedLongTy , 2079 Context.LongLongTy, Context.UnsignedLongLongTy 2080 }; 2081 for (int Idx = 0; Idx < 6; ++Idx) { 2082 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2083 if (FromSize < ToSize || 2084 (FromSize == ToSize && 2085 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2086 // We found the type that we can promote to. If this is the 2087 // type we wanted, we have a promotion. Otherwise, no 2088 // promotion. 2089 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2090 } 2091 } 2092 } 2093 2094 // An rvalue for an integral bit-field (9.6) can be converted to an 2095 // rvalue of type int if int can represent all the values of the 2096 // bit-field; otherwise, it can be converted to unsigned int if 2097 // unsigned int can represent all the values of the bit-field. If 2098 // the bit-field is larger yet, no integral promotion applies to 2099 // it. If the bit-field has an enumerated type, it is treated as any 2100 // other value of that type for promotion purposes (C++ 4.5p3). 2101 // FIXME: We should delay checking of bit-fields until we actually perform the 2102 // conversion. 2103 // 2104 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2105 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2106 // bit-fields and those whose underlying type is larger than int) for GCC 2107 // compatibility. 2108 if (From) { 2109 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2110 llvm::APSInt BitWidth; 2111 if (FromType->isIntegralType(Context) && 2112 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2113 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2114 ToSize = Context.getTypeSize(ToType); 2115 2116 // Are we promoting to an int from a bitfield that fits in an int? 2117 if (BitWidth < ToSize || 2118 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2119 return To->getKind() == BuiltinType::Int; 2120 } 2121 2122 // Are we promoting to an unsigned int from an unsigned bitfield 2123 // that fits into an unsigned int? 2124 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2125 return To->getKind() == BuiltinType::UInt; 2126 } 2127 2128 return false; 2129 } 2130 } 2131 } 2132 2133 // An rvalue of type bool can be converted to an rvalue of type int, 2134 // with false becoming zero and true becoming one (C++ 4.5p4). 2135 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2136 return true; 2137 } 2138 2139 return false; 2140 } 2141 2142 /// IsFloatingPointPromotion - Determines whether the conversion from 2143 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2144 /// returns true and sets PromotedType to the promoted type. 2145 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2146 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2147 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2148 /// An rvalue of type float can be converted to an rvalue of type 2149 /// double. (C++ 4.6p1). 2150 if (FromBuiltin->getKind() == BuiltinType::Float && 2151 ToBuiltin->getKind() == BuiltinType::Double) 2152 return true; 2153 2154 // C99 6.3.1.5p1: 2155 // When a float is promoted to double or long double, or a 2156 // double is promoted to long double [...]. 2157 if (!getLangOpts().CPlusPlus && 2158 (FromBuiltin->getKind() == BuiltinType::Float || 2159 FromBuiltin->getKind() == BuiltinType::Double) && 2160 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2161 ToBuiltin->getKind() == BuiltinType::Float128)) 2162 return true; 2163 2164 // Half can be promoted to float. 2165 if (!getLangOpts().NativeHalfType && 2166 FromBuiltin->getKind() == BuiltinType::Half && 2167 ToBuiltin->getKind() == BuiltinType::Float) 2168 return true; 2169 } 2170 2171 return false; 2172 } 2173 2174 /// Determine if a conversion is a complex promotion. 2175 /// 2176 /// A complex promotion is defined as a complex -> complex conversion 2177 /// where the conversion between the underlying real types is a 2178 /// floating-point or integral promotion. 2179 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2180 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2181 if (!FromComplex) 2182 return false; 2183 2184 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2185 if (!ToComplex) 2186 return false; 2187 2188 return IsFloatingPointPromotion(FromComplex->getElementType(), 2189 ToComplex->getElementType()) || 2190 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2191 ToComplex->getElementType()); 2192 } 2193 2194 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2195 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2196 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2197 /// if non-empty, will be a pointer to ToType that may or may not have 2198 /// the right set of qualifiers on its pointee. 2199 /// 2200 static QualType 2201 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2202 QualType ToPointee, QualType ToType, 2203 ASTContext &Context, 2204 bool StripObjCLifetime = false) { 2205 assert((FromPtr->getTypeClass() == Type::Pointer || 2206 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2207 "Invalid similarly-qualified pointer type"); 2208 2209 /// Conversions to 'id' subsume cv-qualifier conversions. 2210 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2211 return ToType.getUnqualifiedType(); 2212 2213 QualType CanonFromPointee 2214 = Context.getCanonicalType(FromPtr->getPointeeType()); 2215 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2216 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2217 2218 if (StripObjCLifetime) 2219 Quals.removeObjCLifetime(); 2220 2221 // Exact qualifier match -> return the pointer type we're converting to. 2222 if (CanonToPointee.getLocalQualifiers() == Quals) { 2223 // ToType is exactly what we need. Return it. 2224 if (!ToType.isNull()) 2225 return ToType.getUnqualifiedType(); 2226 2227 // Build a pointer to ToPointee. It has the right qualifiers 2228 // already. 2229 if (isa<ObjCObjectPointerType>(ToType)) 2230 return Context.getObjCObjectPointerType(ToPointee); 2231 return Context.getPointerType(ToPointee); 2232 } 2233 2234 // Just build a canonical type that has the right qualifiers. 2235 QualType QualifiedCanonToPointee 2236 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2237 2238 if (isa<ObjCObjectPointerType>(ToType)) 2239 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2240 return Context.getPointerType(QualifiedCanonToPointee); 2241 } 2242 2243 static bool isNullPointerConstantForConversion(Expr *Expr, 2244 bool InOverloadResolution, 2245 ASTContext &Context) { 2246 // Handle value-dependent integral null pointer constants correctly. 2247 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2248 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2249 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2250 return !InOverloadResolution; 2251 2252 return Expr->isNullPointerConstant(Context, 2253 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2254 : Expr::NPC_ValueDependentIsNull); 2255 } 2256 2257 /// IsPointerConversion - Determines whether the conversion of the 2258 /// expression From, which has the (possibly adjusted) type FromType, 2259 /// can be converted to the type ToType via a pointer conversion (C++ 2260 /// 4.10). If so, returns true and places the converted type (that 2261 /// might differ from ToType in its cv-qualifiers at some level) into 2262 /// ConvertedType. 2263 /// 2264 /// This routine also supports conversions to and from block pointers 2265 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2266 /// pointers to interfaces. FIXME: Once we've determined the 2267 /// appropriate overloading rules for Objective-C, we may want to 2268 /// split the Objective-C checks into a different routine; however, 2269 /// GCC seems to consider all of these conversions to be pointer 2270 /// conversions, so for now they live here. IncompatibleObjC will be 2271 /// set if the conversion is an allowed Objective-C conversion that 2272 /// should result in a warning. 2273 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2274 bool InOverloadResolution, 2275 QualType& ConvertedType, 2276 bool &IncompatibleObjC) { 2277 IncompatibleObjC = false; 2278 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2279 IncompatibleObjC)) 2280 return true; 2281 2282 // Conversion from a null pointer constant to any Objective-C pointer type. 2283 if (ToType->isObjCObjectPointerType() && 2284 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2285 ConvertedType = ToType; 2286 return true; 2287 } 2288 2289 // Blocks: Block pointers can be converted to void*. 2290 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2291 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2292 ConvertedType = ToType; 2293 return true; 2294 } 2295 // Blocks: A null pointer constant can be converted to a block 2296 // pointer type. 2297 if (ToType->isBlockPointerType() && 2298 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2299 ConvertedType = ToType; 2300 return true; 2301 } 2302 2303 // If the left-hand-side is nullptr_t, the right side can be a null 2304 // pointer constant. 2305 if (ToType->isNullPtrType() && 2306 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2307 ConvertedType = ToType; 2308 return true; 2309 } 2310 2311 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2312 if (!ToTypePtr) 2313 return false; 2314 2315 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2316 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2317 ConvertedType = ToType; 2318 return true; 2319 } 2320 2321 // Beyond this point, both types need to be pointers 2322 // , including objective-c pointers. 2323 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2324 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2325 !getLangOpts().ObjCAutoRefCount) { 2326 ConvertedType = BuildSimilarlyQualifiedPointerType( 2327 FromType->getAs<ObjCObjectPointerType>(), 2328 ToPointeeType, 2329 ToType, Context); 2330 return true; 2331 } 2332 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2333 if (!FromTypePtr) 2334 return false; 2335 2336 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2337 2338 // If the unqualified pointee types are the same, this can't be a 2339 // pointer conversion, so don't do all of the work below. 2340 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2341 return false; 2342 2343 // An rvalue of type "pointer to cv T," where T is an object type, 2344 // can be converted to an rvalue of type "pointer to cv void" (C++ 2345 // 4.10p2). 2346 if (FromPointeeType->isIncompleteOrObjectType() && 2347 ToPointeeType->isVoidType()) { 2348 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2349 ToPointeeType, 2350 ToType, Context, 2351 /*StripObjCLifetime=*/true); 2352 return true; 2353 } 2354 2355 // MSVC allows implicit function to void* type conversion. 2356 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2357 ToPointeeType->isVoidType()) { 2358 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2359 ToPointeeType, 2360 ToType, Context); 2361 return true; 2362 } 2363 2364 // When we're overloading in C, we allow a special kind of pointer 2365 // conversion for compatible-but-not-identical pointee types. 2366 if (!getLangOpts().CPlusPlus && 2367 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2368 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2369 ToPointeeType, 2370 ToType, Context); 2371 return true; 2372 } 2373 2374 // C++ [conv.ptr]p3: 2375 // 2376 // An rvalue of type "pointer to cv D," where D is a class type, 2377 // can be converted to an rvalue of type "pointer to cv B," where 2378 // B is a base class (clause 10) of D. If B is an inaccessible 2379 // (clause 11) or ambiguous (10.2) base class of D, a program that 2380 // necessitates this conversion is ill-formed. The result of the 2381 // conversion is a pointer to the base class sub-object of the 2382 // derived class object. The null pointer value is converted to 2383 // the null pointer value of the destination type. 2384 // 2385 // Note that we do not check for ambiguity or inaccessibility 2386 // here. That is handled by CheckPointerConversion. 2387 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2388 ToPointeeType->isRecordType() && 2389 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2390 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2391 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2392 ToPointeeType, 2393 ToType, Context); 2394 return true; 2395 } 2396 2397 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2398 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2399 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2400 ToPointeeType, 2401 ToType, Context); 2402 return true; 2403 } 2404 2405 return false; 2406 } 2407 2408 /// Adopt the given qualifiers for the given type. 2409 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2410 Qualifiers TQs = T.getQualifiers(); 2411 2412 // Check whether qualifiers already match. 2413 if (TQs == Qs) 2414 return T; 2415 2416 if (Qs.compatiblyIncludes(TQs)) 2417 return Context.getQualifiedType(T, Qs); 2418 2419 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2420 } 2421 2422 /// isObjCPointerConversion - Determines whether this is an 2423 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2424 /// with the same arguments and return values. 2425 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2426 QualType& ConvertedType, 2427 bool &IncompatibleObjC) { 2428 if (!getLangOpts().ObjC) 2429 return false; 2430 2431 // The set of qualifiers on the type we're converting from. 2432 Qualifiers FromQualifiers = FromType.getQualifiers(); 2433 2434 // First, we handle all conversions on ObjC object pointer types. 2435 const ObjCObjectPointerType* ToObjCPtr = 2436 ToType->getAs<ObjCObjectPointerType>(); 2437 const ObjCObjectPointerType *FromObjCPtr = 2438 FromType->getAs<ObjCObjectPointerType>(); 2439 2440 if (ToObjCPtr && FromObjCPtr) { 2441 // If the pointee types are the same (ignoring qualifications), 2442 // then this is not a pointer conversion. 2443 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2444 FromObjCPtr->getPointeeType())) 2445 return false; 2446 2447 // Conversion between Objective-C pointers. 2448 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2449 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2450 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2451 if (getLangOpts().CPlusPlus && LHS && RHS && 2452 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2453 FromObjCPtr->getPointeeType())) 2454 return false; 2455 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2456 ToObjCPtr->getPointeeType(), 2457 ToType, Context); 2458 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2459 return true; 2460 } 2461 2462 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2463 // Okay: this is some kind of implicit downcast of Objective-C 2464 // interfaces, which is permitted. However, we're going to 2465 // complain about it. 2466 IncompatibleObjC = true; 2467 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2468 ToObjCPtr->getPointeeType(), 2469 ToType, Context); 2470 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2471 return true; 2472 } 2473 } 2474 // Beyond this point, both types need to be C pointers or block pointers. 2475 QualType ToPointeeType; 2476 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2477 ToPointeeType = ToCPtr->getPointeeType(); 2478 else if (const BlockPointerType *ToBlockPtr = 2479 ToType->getAs<BlockPointerType>()) { 2480 // Objective C++: We're able to convert from a pointer to any object 2481 // to a block pointer type. 2482 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2483 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2484 return true; 2485 } 2486 ToPointeeType = ToBlockPtr->getPointeeType(); 2487 } 2488 else if (FromType->getAs<BlockPointerType>() && 2489 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2490 // Objective C++: We're able to convert from a block pointer type to a 2491 // pointer to any object. 2492 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2493 return true; 2494 } 2495 else 2496 return false; 2497 2498 QualType FromPointeeType; 2499 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2500 FromPointeeType = FromCPtr->getPointeeType(); 2501 else if (const BlockPointerType *FromBlockPtr = 2502 FromType->getAs<BlockPointerType>()) 2503 FromPointeeType = FromBlockPtr->getPointeeType(); 2504 else 2505 return false; 2506 2507 // If we have pointers to pointers, recursively check whether this 2508 // is an Objective-C conversion. 2509 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2510 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2511 IncompatibleObjC)) { 2512 // We always complain about this conversion. 2513 IncompatibleObjC = true; 2514 ConvertedType = Context.getPointerType(ConvertedType); 2515 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2516 return true; 2517 } 2518 // Allow conversion of pointee being objective-c pointer to another one; 2519 // as in I* to id. 2520 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2521 ToPointeeType->getAs<ObjCObjectPointerType>() && 2522 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2523 IncompatibleObjC)) { 2524 2525 ConvertedType = Context.getPointerType(ConvertedType); 2526 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2527 return true; 2528 } 2529 2530 // If we have pointers to functions or blocks, check whether the only 2531 // differences in the argument and result types are in Objective-C 2532 // pointer conversions. If so, we permit the conversion (but 2533 // complain about it). 2534 const FunctionProtoType *FromFunctionType 2535 = FromPointeeType->getAs<FunctionProtoType>(); 2536 const FunctionProtoType *ToFunctionType 2537 = ToPointeeType->getAs<FunctionProtoType>(); 2538 if (FromFunctionType && ToFunctionType) { 2539 // If the function types are exactly the same, this isn't an 2540 // Objective-C pointer conversion. 2541 if (Context.getCanonicalType(FromPointeeType) 2542 == Context.getCanonicalType(ToPointeeType)) 2543 return false; 2544 2545 // Perform the quick checks that will tell us whether these 2546 // function types are obviously different. 2547 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2548 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2549 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2550 return false; 2551 2552 bool HasObjCConversion = false; 2553 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2554 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2555 // Okay, the types match exactly. Nothing to do. 2556 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2557 ToFunctionType->getReturnType(), 2558 ConvertedType, IncompatibleObjC)) { 2559 // Okay, we have an Objective-C pointer conversion. 2560 HasObjCConversion = true; 2561 } else { 2562 // Function types are too different. Abort. 2563 return false; 2564 } 2565 2566 // Check argument types. 2567 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2568 ArgIdx != NumArgs; ++ArgIdx) { 2569 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2570 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2571 if (Context.getCanonicalType(FromArgType) 2572 == Context.getCanonicalType(ToArgType)) { 2573 // Okay, the types match exactly. Nothing to do. 2574 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2575 ConvertedType, IncompatibleObjC)) { 2576 // Okay, we have an Objective-C pointer conversion. 2577 HasObjCConversion = true; 2578 } else { 2579 // Argument types are too different. Abort. 2580 return false; 2581 } 2582 } 2583 2584 if (HasObjCConversion) { 2585 // We had an Objective-C conversion. Allow this pointer 2586 // conversion, but complain about it. 2587 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2588 IncompatibleObjC = true; 2589 return true; 2590 } 2591 } 2592 2593 return false; 2594 } 2595 2596 /// Determine whether this is an Objective-C writeback conversion, 2597 /// used for parameter passing when performing automatic reference counting. 2598 /// 2599 /// \param FromType The type we're converting form. 2600 /// 2601 /// \param ToType The type we're converting to. 2602 /// 2603 /// \param ConvertedType The type that will be produced after applying 2604 /// this conversion. 2605 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2606 QualType &ConvertedType) { 2607 if (!getLangOpts().ObjCAutoRefCount || 2608 Context.hasSameUnqualifiedType(FromType, ToType)) 2609 return false; 2610 2611 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2612 QualType ToPointee; 2613 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2614 ToPointee = ToPointer->getPointeeType(); 2615 else 2616 return false; 2617 2618 Qualifiers ToQuals = ToPointee.getQualifiers(); 2619 if (!ToPointee->isObjCLifetimeType() || 2620 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2621 !ToQuals.withoutObjCLifetime().empty()) 2622 return false; 2623 2624 // Argument must be a pointer to __strong to __weak. 2625 QualType FromPointee; 2626 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2627 FromPointee = FromPointer->getPointeeType(); 2628 else 2629 return false; 2630 2631 Qualifiers FromQuals = FromPointee.getQualifiers(); 2632 if (!FromPointee->isObjCLifetimeType() || 2633 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2634 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2635 return false; 2636 2637 // Make sure that we have compatible qualifiers. 2638 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2639 if (!ToQuals.compatiblyIncludes(FromQuals)) 2640 return false; 2641 2642 // Remove qualifiers from the pointee type we're converting from; they 2643 // aren't used in the compatibility check belong, and we'll be adding back 2644 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2645 FromPointee = FromPointee.getUnqualifiedType(); 2646 2647 // The unqualified form of the pointee types must be compatible. 2648 ToPointee = ToPointee.getUnqualifiedType(); 2649 bool IncompatibleObjC; 2650 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2651 FromPointee = ToPointee; 2652 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2653 IncompatibleObjC)) 2654 return false; 2655 2656 /// Construct the type we're converting to, which is a pointer to 2657 /// __autoreleasing pointee. 2658 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2659 ConvertedType = Context.getPointerType(FromPointee); 2660 return true; 2661 } 2662 2663 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2664 QualType& ConvertedType) { 2665 QualType ToPointeeType; 2666 if (const BlockPointerType *ToBlockPtr = 2667 ToType->getAs<BlockPointerType>()) 2668 ToPointeeType = ToBlockPtr->getPointeeType(); 2669 else 2670 return false; 2671 2672 QualType FromPointeeType; 2673 if (const BlockPointerType *FromBlockPtr = 2674 FromType->getAs<BlockPointerType>()) 2675 FromPointeeType = FromBlockPtr->getPointeeType(); 2676 else 2677 return false; 2678 // We have pointer to blocks, check whether the only 2679 // differences in the argument and result types are in Objective-C 2680 // pointer conversions. If so, we permit the conversion. 2681 2682 const FunctionProtoType *FromFunctionType 2683 = FromPointeeType->getAs<FunctionProtoType>(); 2684 const FunctionProtoType *ToFunctionType 2685 = ToPointeeType->getAs<FunctionProtoType>(); 2686 2687 if (!FromFunctionType || !ToFunctionType) 2688 return false; 2689 2690 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2691 return true; 2692 2693 // Perform the quick checks that will tell us whether these 2694 // function types are obviously different. 2695 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2696 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2697 return false; 2698 2699 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2700 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2701 if (FromEInfo != ToEInfo) 2702 return false; 2703 2704 bool IncompatibleObjC = false; 2705 if (Context.hasSameType(FromFunctionType->getReturnType(), 2706 ToFunctionType->getReturnType())) { 2707 // Okay, the types match exactly. Nothing to do. 2708 } else { 2709 QualType RHS = FromFunctionType->getReturnType(); 2710 QualType LHS = ToFunctionType->getReturnType(); 2711 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2712 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2713 LHS = LHS.getUnqualifiedType(); 2714 2715 if (Context.hasSameType(RHS,LHS)) { 2716 // OK exact match. 2717 } else if (isObjCPointerConversion(RHS, LHS, 2718 ConvertedType, IncompatibleObjC)) { 2719 if (IncompatibleObjC) 2720 return false; 2721 // Okay, we have an Objective-C pointer conversion. 2722 } 2723 else 2724 return false; 2725 } 2726 2727 // Check argument types. 2728 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2729 ArgIdx != NumArgs; ++ArgIdx) { 2730 IncompatibleObjC = false; 2731 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2732 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2733 if (Context.hasSameType(FromArgType, ToArgType)) { 2734 // Okay, the types match exactly. Nothing to do. 2735 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2736 ConvertedType, IncompatibleObjC)) { 2737 if (IncompatibleObjC) 2738 return false; 2739 // Okay, we have an Objective-C pointer conversion. 2740 } else 2741 // Argument types are too different. Abort. 2742 return false; 2743 } 2744 2745 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2746 bool CanUseToFPT, CanUseFromFPT; 2747 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2748 CanUseToFPT, CanUseFromFPT, 2749 NewParamInfos)) 2750 return false; 2751 2752 ConvertedType = ToType; 2753 return true; 2754 } 2755 2756 enum { 2757 ft_default, 2758 ft_different_class, 2759 ft_parameter_arity, 2760 ft_parameter_mismatch, 2761 ft_return_type, 2762 ft_qualifer_mismatch, 2763 ft_noexcept 2764 }; 2765 2766 /// Attempts to get the FunctionProtoType from a Type. Handles 2767 /// MemberFunctionPointers properly. 2768 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2769 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2770 return FPT; 2771 2772 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2773 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2774 2775 return nullptr; 2776 } 2777 2778 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2779 /// function types. Catches different number of parameter, mismatch in 2780 /// parameter types, and different return types. 2781 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2782 QualType FromType, QualType ToType) { 2783 // If either type is not valid, include no extra info. 2784 if (FromType.isNull() || ToType.isNull()) { 2785 PDiag << ft_default; 2786 return; 2787 } 2788 2789 // Get the function type from the pointers. 2790 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2791 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2792 *ToMember = ToType->getAs<MemberPointerType>(); 2793 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2794 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2795 << QualType(FromMember->getClass(), 0); 2796 return; 2797 } 2798 FromType = FromMember->getPointeeType(); 2799 ToType = ToMember->getPointeeType(); 2800 } 2801 2802 if (FromType->isPointerType()) 2803 FromType = FromType->getPointeeType(); 2804 if (ToType->isPointerType()) 2805 ToType = ToType->getPointeeType(); 2806 2807 // Remove references. 2808 FromType = FromType.getNonReferenceType(); 2809 ToType = ToType.getNonReferenceType(); 2810 2811 // Don't print extra info for non-specialized template functions. 2812 if (FromType->isInstantiationDependentType() && 2813 !FromType->getAs<TemplateSpecializationType>()) { 2814 PDiag << ft_default; 2815 return; 2816 } 2817 2818 // No extra info for same types. 2819 if (Context.hasSameType(FromType, ToType)) { 2820 PDiag << ft_default; 2821 return; 2822 } 2823 2824 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2825 *ToFunction = tryGetFunctionProtoType(ToType); 2826 2827 // Both types need to be function types. 2828 if (!FromFunction || !ToFunction) { 2829 PDiag << ft_default; 2830 return; 2831 } 2832 2833 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2834 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2835 << FromFunction->getNumParams(); 2836 return; 2837 } 2838 2839 // Handle different parameter types. 2840 unsigned ArgPos; 2841 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2842 PDiag << ft_parameter_mismatch << ArgPos + 1 2843 << ToFunction->getParamType(ArgPos) 2844 << FromFunction->getParamType(ArgPos); 2845 return; 2846 } 2847 2848 // Handle different return type. 2849 if (!Context.hasSameType(FromFunction->getReturnType(), 2850 ToFunction->getReturnType())) { 2851 PDiag << ft_return_type << ToFunction->getReturnType() 2852 << FromFunction->getReturnType(); 2853 return; 2854 } 2855 2856 if (FromFunction->getTypeQuals() != ToFunction->getTypeQuals()) { 2857 PDiag << ft_qualifer_mismatch << ToFunction->getTypeQuals() 2858 << FromFunction->getTypeQuals(); 2859 return; 2860 } 2861 2862 // Handle exception specification differences on canonical type (in C++17 2863 // onwards). 2864 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2865 ->isNothrow() != 2866 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2867 ->isNothrow()) { 2868 PDiag << ft_noexcept; 2869 return; 2870 } 2871 2872 // Unable to find a difference, so add no extra info. 2873 PDiag << ft_default; 2874 } 2875 2876 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2877 /// for equality of their argument types. Caller has already checked that 2878 /// they have same number of arguments. If the parameters are different, 2879 /// ArgPos will have the parameter index of the first different parameter. 2880 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2881 const FunctionProtoType *NewType, 2882 unsigned *ArgPos) { 2883 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2884 N = NewType->param_type_begin(), 2885 E = OldType->param_type_end(); 2886 O && (O != E); ++O, ++N) { 2887 if (!Context.hasSameType(O->getUnqualifiedType(), 2888 N->getUnqualifiedType())) { 2889 if (ArgPos) 2890 *ArgPos = O - OldType->param_type_begin(); 2891 return false; 2892 } 2893 } 2894 return true; 2895 } 2896 2897 /// CheckPointerConversion - Check the pointer conversion from the 2898 /// expression From to the type ToType. This routine checks for 2899 /// ambiguous or inaccessible derived-to-base pointer 2900 /// conversions for which IsPointerConversion has already returned 2901 /// true. It returns true and produces a diagnostic if there was an 2902 /// error, or returns false otherwise. 2903 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2904 CastKind &Kind, 2905 CXXCastPath& BasePath, 2906 bool IgnoreBaseAccess, 2907 bool Diagnose) { 2908 QualType FromType = From->getType(); 2909 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2910 2911 Kind = CK_BitCast; 2912 2913 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2914 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2915 Expr::NPCK_ZeroExpression) { 2916 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2917 DiagRuntimeBehavior(From->getExprLoc(), From, 2918 PDiag(diag::warn_impcast_bool_to_null_pointer) 2919 << ToType << From->getSourceRange()); 2920 else if (!isUnevaluatedContext()) 2921 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2922 << ToType << From->getSourceRange(); 2923 } 2924 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2925 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2926 QualType FromPointeeType = FromPtrType->getPointeeType(), 2927 ToPointeeType = ToPtrType->getPointeeType(); 2928 2929 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2930 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2931 // We must have a derived-to-base conversion. Check an 2932 // ambiguous or inaccessible conversion. 2933 unsigned InaccessibleID = 0; 2934 unsigned AmbigiousID = 0; 2935 if (Diagnose) { 2936 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2937 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2938 } 2939 if (CheckDerivedToBaseConversion( 2940 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2941 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2942 &BasePath, IgnoreBaseAccess)) 2943 return true; 2944 2945 // The conversion was successful. 2946 Kind = CK_DerivedToBase; 2947 } 2948 2949 if (Diagnose && !IsCStyleOrFunctionalCast && 2950 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2951 assert(getLangOpts().MSVCCompat && 2952 "this should only be possible with MSVCCompat!"); 2953 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2954 << From->getSourceRange(); 2955 } 2956 } 2957 } else if (const ObjCObjectPointerType *ToPtrType = 2958 ToType->getAs<ObjCObjectPointerType>()) { 2959 if (const ObjCObjectPointerType *FromPtrType = 2960 FromType->getAs<ObjCObjectPointerType>()) { 2961 // Objective-C++ conversions are always okay. 2962 // FIXME: We should have a different class of conversions for the 2963 // Objective-C++ implicit conversions. 2964 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2965 return false; 2966 } else if (FromType->isBlockPointerType()) { 2967 Kind = CK_BlockPointerToObjCPointerCast; 2968 } else { 2969 Kind = CK_CPointerToObjCPointerCast; 2970 } 2971 } else if (ToType->isBlockPointerType()) { 2972 if (!FromType->isBlockPointerType()) 2973 Kind = CK_AnyPointerToBlockPointerCast; 2974 } 2975 2976 // We shouldn't fall into this case unless it's valid for other 2977 // reasons. 2978 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2979 Kind = CK_NullToPointer; 2980 2981 return false; 2982 } 2983 2984 /// IsMemberPointerConversion - Determines whether the conversion of the 2985 /// expression From, which has the (possibly adjusted) type FromType, can be 2986 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2987 /// If so, returns true and places the converted type (that might differ from 2988 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2989 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2990 QualType ToType, 2991 bool InOverloadResolution, 2992 QualType &ConvertedType) { 2993 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2994 if (!ToTypePtr) 2995 return false; 2996 2997 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2998 if (From->isNullPointerConstant(Context, 2999 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3000 : Expr::NPC_ValueDependentIsNull)) { 3001 ConvertedType = ToType; 3002 return true; 3003 } 3004 3005 // Otherwise, both types have to be member pointers. 3006 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3007 if (!FromTypePtr) 3008 return false; 3009 3010 // A pointer to member of B can be converted to a pointer to member of D, 3011 // where D is derived from B (C++ 4.11p2). 3012 QualType FromClass(FromTypePtr->getClass(), 0); 3013 QualType ToClass(ToTypePtr->getClass(), 0); 3014 3015 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3016 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3017 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3018 ToClass.getTypePtr()); 3019 return true; 3020 } 3021 3022 return false; 3023 } 3024 3025 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3026 /// expression From to the type ToType. This routine checks for ambiguous or 3027 /// virtual or inaccessible base-to-derived member pointer conversions 3028 /// for which IsMemberPointerConversion has already returned true. It returns 3029 /// true and produces a diagnostic if there was an error, or returns false 3030 /// otherwise. 3031 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3032 CastKind &Kind, 3033 CXXCastPath &BasePath, 3034 bool IgnoreBaseAccess) { 3035 QualType FromType = From->getType(); 3036 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3037 if (!FromPtrType) { 3038 // This must be a null pointer to member pointer conversion 3039 assert(From->isNullPointerConstant(Context, 3040 Expr::NPC_ValueDependentIsNull) && 3041 "Expr must be null pointer constant!"); 3042 Kind = CK_NullToMemberPointer; 3043 return false; 3044 } 3045 3046 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3047 assert(ToPtrType && "No member pointer cast has a target type " 3048 "that is not a member pointer."); 3049 3050 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3051 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3052 3053 // FIXME: What about dependent types? 3054 assert(FromClass->isRecordType() && "Pointer into non-class."); 3055 assert(ToClass->isRecordType() && "Pointer into non-class."); 3056 3057 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3058 /*DetectVirtual=*/true); 3059 bool DerivationOkay = 3060 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3061 assert(DerivationOkay && 3062 "Should not have been called if derivation isn't OK."); 3063 (void)DerivationOkay; 3064 3065 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3066 getUnqualifiedType())) { 3067 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3068 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3069 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3070 return true; 3071 } 3072 3073 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3074 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3075 << FromClass << ToClass << QualType(VBase, 0) 3076 << From->getSourceRange(); 3077 return true; 3078 } 3079 3080 if (!IgnoreBaseAccess) 3081 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3082 Paths.front(), 3083 diag::err_downcast_from_inaccessible_base); 3084 3085 // Must be a base to derived member conversion. 3086 BuildBasePathArray(Paths, BasePath); 3087 Kind = CK_BaseToDerivedMemberPointer; 3088 return false; 3089 } 3090 3091 /// Determine whether the lifetime conversion between the two given 3092 /// qualifiers sets is nontrivial. 3093 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3094 Qualifiers ToQuals) { 3095 // Converting anything to const __unsafe_unretained is trivial. 3096 if (ToQuals.hasConst() && 3097 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3098 return false; 3099 3100 return true; 3101 } 3102 3103 /// IsQualificationConversion - Determines whether the conversion from 3104 /// an rvalue of type FromType to ToType is a qualification conversion 3105 /// (C++ 4.4). 3106 /// 3107 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3108 /// when the qualification conversion involves a change in the Objective-C 3109 /// object lifetime. 3110 bool 3111 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3112 bool CStyle, bool &ObjCLifetimeConversion) { 3113 FromType = Context.getCanonicalType(FromType); 3114 ToType = Context.getCanonicalType(ToType); 3115 ObjCLifetimeConversion = false; 3116 3117 // If FromType and ToType are the same type, this is not a 3118 // qualification conversion. 3119 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3120 return false; 3121 3122 // (C++ 4.4p4): 3123 // A conversion can add cv-qualifiers at levels other than the first 3124 // in multi-level pointers, subject to the following rules: [...] 3125 bool PreviousToQualsIncludeConst = true; 3126 bool UnwrappedAnyPointer = false; 3127 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3128 // Within each iteration of the loop, we check the qualifiers to 3129 // determine if this still looks like a qualification 3130 // conversion. Then, if all is well, we unwrap one more level of 3131 // pointers or pointers-to-members and do it all again 3132 // until there are no more pointers or pointers-to-members left to 3133 // unwrap. 3134 UnwrappedAnyPointer = true; 3135 3136 Qualifiers FromQuals = FromType.getQualifiers(); 3137 Qualifiers ToQuals = ToType.getQualifiers(); 3138 3139 // Ignore __unaligned qualifier if this type is void. 3140 if (ToType.getUnqualifiedType()->isVoidType()) 3141 FromQuals.removeUnaligned(); 3142 3143 // Objective-C ARC: 3144 // Check Objective-C lifetime conversions. 3145 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3146 UnwrappedAnyPointer) { 3147 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3148 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3149 ObjCLifetimeConversion = true; 3150 FromQuals.removeObjCLifetime(); 3151 ToQuals.removeObjCLifetime(); 3152 } else { 3153 // Qualification conversions cannot cast between different 3154 // Objective-C lifetime qualifiers. 3155 return false; 3156 } 3157 } 3158 3159 // Allow addition/removal of GC attributes but not changing GC attributes. 3160 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3161 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3162 FromQuals.removeObjCGCAttr(); 3163 ToQuals.removeObjCGCAttr(); 3164 } 3165 3166 // -- for every j > 0, if const is in cv 1,j then const is in cv 3167 // 2,j, and similarly for volatile. 3168 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3169 return false; 3170 3171 // -- if the cv 1,j and cv 2,j are different, then const is in 3172 // every cv for 0 < k < j. 3173 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3174 && !PreviousToQualsIncludeConst) 3175 return false; 3176 3177 // Keep track of whether all prior cv-qualifiers in the "to" type 3178 // include const. 3179 PreviousToQualsIncludeConst 3180 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3181 } 3182 3183 // Allows address space promotion by language rules implemented in 3184 // Type::Qualifiers::isAddressSpaceSupersetOf. 3185 Qualifiers FromQuals = FromType.getQualifiers(); 3186 Qualifiers ToQuals = ToType.getQualifiers(); 3187 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3188 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3189 return false; 3190 } 3191 3192 // We are left with FromType and ToType being the pointee types 3193 // after unwrapping the original FromType and ToType the same number 3194 // of types. If we unwrapped any pointers, and if FromType and 3195 // ToType have the same unqualified type (since we checked 3196 // qualifiers above), then this is a qualification conversion. 3197 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3198 } 3199 3200 /// - Determine whether this is a conversion from a scalar type to an 3201 /// atomic type. 3202 /// 3203 /// If successful, updates \c SCS's second and third steps in the conversion 3204 /// sequence to finish the conversion. 3205 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3206 bool InOverloadResolution, 3207 StandardConversionSequence &SCS, 3208 bool CStyle) { 3209 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3210 if (!ToAtomic) 3211 return false; 3212 3213 StandardConversionSequence InnerSCS; 3214 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3215 InOverloadResolution, InnerSCS, 3216 CStyle, /*AllowObjCWritebackConversion=*/false)) 3217 return false; 3218 3219 SCS.Second = InnerSCS.Second; 3220 SCS.setToType(1, InnerSCS.getToType(1)); 3221 SCS.Third = InnerSCS.Third; 3222 SCS.QualificationIncludesObjCLifetime 3223 = InnerSCS.QualificationIncludesObjCLifetime; 3224 SCS.setToType(2, InnerSCS.getToType(2)); 3225 return true; 3226 } 3227 3228 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3229 CXXConstructorDecl *Constructor, 3230 QualType Type) { 3231 const FunctionProtoType *CtorType = 3232 Constructor->getType()->getAs<FunctionProtoType>(); 3233 if (CtorType->getNumParams() > 0) { 3234 QualType FirstArg = CtorType->getParamType(0); 3235 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3236 return true; 3237 } 3238 return false; 3239 } 3240 3241 static OverloadingResult 3242 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3243 CXXRecordDecl *To, 3244 UserDefinedConversionSequence &User, 3245 OverloadCandidateSet &CandidateSet, 3246 bool AllowExplicit) { 3247 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3248 for (auto *D : S.LookupConstructors(To)) { 3249 auto Info = getConstructorInfo(D); 3250 if (!Info) 3251 continue; 3252 3253 bool Usable = !Info.Constructor->isInvalidDecl() && 3254 S.isInitListConstructor(Info.Constructor) && 3255 (AllowExplicit || !Info.Constructor->isExplicit()); 3256 if (Usable) { 3257 // If the first argument is (a reference to) the target type, 3258 // suppress conversions. 3259 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3260 S.Context, Info.Constructor, ToType); 3261 if (Info.ConstructorTmpl) 3262 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3263 /*ExplicitArgs*/ nullptr, From, 3264 CandidateSet, SuppressUserConversions); 3265 else 3266 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3267 CandidateSet, SuppressUserConversions); 3268 } 3269 } 3270 3271 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3272 3273 OverloadCandidateSet::iterator Best; 3274 switch (auto Result = 3275 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3276 case OR_Deleted: 3277 case OR_Success: { 3278 // Record the standard conversion we used and the conversion function. 3279 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3280 QualType ThisType = Constructor->getThisType(S.Context); 3281 // Initializer lists don't have conversions as such. 3282 User.Before.setAsIdentityConversion(); 3283 User.HadMultipleCandidates = HadMultipleCandidates; 3284 User.ConversionFunction = Constructor; 3285 User.FoundConversionFunction = Best->FoundDecl; 3286 User.After.setAsIdentityConversion(); 3287 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3288 User.After.setAllToTypes(ToType); 3289 return Result; 3290 } 3291 3292 case OR_No_Viable_Function: 3293 return OR_No_Viable_Function; 3294 case OR_Ambiguous: 3295 return OR_Ambiguous; 3296 } 3297 3298 llvm_unreachable("Invalid OverloadResult!"); 3299 } 3300 3301 /// Determines whether there is a user-defined conversion sequence 3302 /// (C++ [over.ics.user]) that converts expression From to the type 3303 /// ToType. If such a conversion exists, User will contain the 3304 /// user-defined conversion sequence that performs such a conversion 3305 /// and this routine will return true. Otherwise, this routine returns 3306 /// false and User is unspecified. 3307 /// 3308 /// \param AllowExplicit true if the conversion should consider C++0x 3309 /// "explicit" conversion functions as well as non-explicit conversion 3310 /// functions (C++0x [class.conv.fct]p2). 3311 /// 3312 /// \param AllowObjCConversionOnExplicit true if the conversion should 3313 /// allow an extra Objective-C pointer conversion on uses of explicit 3314 /// constructors. Requires \c AllowExplicit to also be set. 3315 static OverloadingResult 3316 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3317 UserDefinedConversionSequence &User, 3318 OverloadCandidateSet &CandidateSet, 3319 bool AllowExplicit, 3320 bool AllowObjCConversionOnExplicit) { 3321 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3322 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3323 3324 // Whether we will only visit constructors. 3325 bool ConstructorsOnly = false; 3326 3327 // If the type we are conversion to is a class type, enumerate its 3328 // constructors. 3329 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3330 // C++ [over.match.ctor]p1: 3331 // When objects of class type are direct-initialized (8.5), or 3332 // copy-initialized from an expression of the same or a 3333 // derived class type (8.5), overload resolution selects the 3334 // constructor. [...] For copy-initialization, the candidate 3335 // functions are all the converting constructors (12.3.1) of 3336 // that class. The argument list is the expression-list within 3337 // the parentheses of the initializer. 3338 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3339 (From->getType()->getAs<RecordType>() && 3340 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3341 ConstructorsOnly = true; 3342 3343 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3344 // We're not going to find any constructors. 3345 } else if (CXXRecordDecl *ToRecordDecl 3346 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3347 3348 Expr **Args = &From; 3349 unsigned NumArgs = 1; 3350 bool ListInitializing = false; 3351 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3352 // But first, see if there is an init-list-constructor that will work. 3353 OverloadingResult Result = IsInitializerListConstructorConversion( 3354 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3355 if (Result != OR_No_Viable_Function) 3356 return Result; 3357 // Never mind. 3358 CandidateSet.clear( 3359 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3360 3361 // If we're list-initializing, we pass the individual elements as 3362 // arguments, not the entire list. 3363 Args = InitList->getInits(); 3364 NumArgs = InitList->getNumInits(); 3365 ListInitializing = true; 3366 } 3367 3368 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3369 auto Info = getConstructorInfo(D); 3370 if (!Info) 3371 continue; 3372 3373 bool Usable = !Info.Constructor->isInvalidDecl(); 3374 if (ListInitializing) 3375 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3376 else 3377 Usable = Usable && 3378 Info.Constructor->isConvertingConstructor(AllowExplicit); 3379 if (Usable) { 3380 bool SuppressUserConversions = !ConstructorsOnly; 3381 if (SuppressUserConversions && ListInitializing) { 3382 SuppressUserConversions = false; 3383 if (NumArgs == 1) { 3384 // If the first argument is (a reference to) the target type, 3385 // suppress conversions. 3386 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3387 S.Context, Info.Constructor, ToType); 3388 } 3389 } 3390 if (Info.ConstructorTmpl) 3391 S.AddTemplateOverloadCandidate( 3392 Info.ConstructorTmpl, Info.FoundDecl, 3393 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3394 CandidateSet, SuppressUserConversions); 3395 else 3396 // Allow one user-defined conversion when user specifies a 3397 // From->ToType conversion via an static cast (c-style, etc). 3398 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3399 llvm::makeArrayRef(Args, NumArgs), 3400 CandidateSet, SuppressUserConversions); 3401 } 3402 } 3403 } 3404 } 3405 3406 // Enumerate conversion functions, if we're allowed to. 3407 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3408 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3409 // No conversion functions from incomplete types. 3410 } else if (const RecordType *FromRecordType = 3411 From->getType()->getAs<RecordType>()) { 3412 if (CXXRecordDecl *FromRecordDecl 3413 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3414 // Add all of the conversion functions as candidates. 3415 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3416 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3417 DeclAccessPair FoundDecl = I.getPair(); 3418 NamedDecl *D = FoundDecl.getDecl(); 3419 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3420 if (isa<UsingShadowDecl>(D)) 3421 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3422 3423 CXXConversionDecl *Conv; 3424 FunctionTemplateDecl *ConvTemplate; 3425 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3426 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3427 else 3428 Conv = cast<CXXConversionDecl>(D); 3429 3430 if (AllowExplicit || !Conv->isExplicit()) { 3431 if (ConvTemplate) 3432 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3433 ActingContext, From, ToType, 3434 CandidateSet, 3435 AllowObjCConversionOnExplicit); 3436 else 3437 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3438 From, ToType, CandidateSet, 3439 AllowObjCConversionOnExplicit); 3440 } 3441 } 3442 } 3443 } 3444 3445 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3446 3447 OverloadCandidateSet::iterator Best; 3448 switch (auto Result = 3449 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3450 case OR_Success: 3451 case OR_Deleted: 3452 // Record the standard conversion we used and the conversion function. 3453 if (CXXConstructorDecl *Constructor 3454 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3455 // C++ [over.ics.user]p1: 3456 // If the user-defined conversion is specified by a 3457 // constructor (12.3.1), the initial standard conversion 3458 // sequence converts the source type to the type required by 3459 // the argument of the constructor. 3460 // 3461 QualType ThisType = Constructor->getThisType(S.Context); 3462 if (isa<InitListExpr>(From)) { 3463 // Initializer lists don't have conversions as such. 3464 User.Before.setAsIdentityConversion(); 3465 } else { 3466 if (Best->Conversions[0].isEllipsis()) 3467 User.EllipsisConversion = true; 3468 else { 3469 User.Before = Best->Conversions[0].Standard; 3470 User.EllipsisConversion = false; 3471 } 3472 } 3473 User.HadMultipleCandidates = HadMultipleCandidates; 3474 User.ConversionFunction = Constructor; 3475 User.FoundConversionFunction = Best->FoundDecl; 3476 User.After.setAsIdentityConversion(); 3477 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3478 User.After.setAllToTypes(ToType); 3479 return Result; 3480 } 3481 if (CXXConversionDecl *Conversion 3482 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3483 // C++ [over.ics.user]p1: 3484 // 3485 // [...] If the user-defined conversion is specified by a 3486 // conversion function (12.3.2), the initial standard 3487 // conversion sequence converts the source type to the 3488 // implicit object parameter of the conversion function. 3489 User.Before = Best->Conversions[0].Standard; 3490 User.HadMultipleCandidates = HadMultipleCandidates; 3491 User.ConversionFunction = Conversion; 3492 User.FoundConversionFunction = Best->FoundDecl; 3493 User.EllipsisConversion = false; 3494 3495 // C++ [over.ics.user]p2: 3496 // The second standard conversion sequence converts the 3497 // result of the user-defined conversion to the target type 3498 // for the sequence. Since an implicit conversion sequence 3499 // is an initialization, the special rules for 3500 // initialization by user-defined conversion apply when 3501 // selecting the best user-defined conversion for a 3502 // user-defined conversion sequence (see 13.3.3 and 3503 // 13.3.3.1). 3504 User.After = Best->FinalConversion; 3505 return Result; 3506 } 3507 llvm_unreachable("Not a constructor or conversion function?"); 3508 3509 case OR_No_Viable_Function: 3510 return OR_No_Viable_Function; 3511 3512 case OR_Ambiguous: 3513 return OR_Ambiguous; 3514 } 3515 3516 llvm_unreachable("Invalid OverloadResult!"); 3517 } 3518 3519 bool 3520 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3521 ImplicitConversionSequence ICS; 3522 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3523 OverloadCandidateSet::CSK_Normal); 3524 OverloadingResult OvResult = 3525 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3526 CandidateSet, false, false); 3527 if (OvResult == OR_Ambiguous) 3528 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3529 << From->getType() << ToType << From->getSourceRange(); 3530 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3531 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3532 diag::err_typecheck_nonviable_condition_incomplete, 3533 From->getType(), From->getSourceRange())) 3534 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3535 << false << From->getType() << From->getSourceRange() << ToType; 3536 } else 3537 return false; 3538 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3539 return true; 3540 } 3541 3542 /// Compare the user-defined conversion functions or constructors 3543 /// of two user-defined conversion sequences to determine whether any ordering 3544 /// is possible. 3545 static ImplicitConversionSequence::CompareKind 3546 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3547 FunctionDecl *Function2) { 3548 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3549 return ImplicitConversionSequence::Indistinguishable; 3550 3551 // Objective-C++: 3552 // If both conversion functions are implicitly-declared conversions from 3553 // a lambda closure type to a function pointer and a block pointer, 3554 // respectively, always prefer the conversion to a function pointer, 3555 // because the function pointer is more lightweight and is more likely 3556 // to keep code working. 3557 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3558 if (!Conv1) 3559 return ImplicitConversionSequence::Indistinguishable; 3560 3561 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3562 if (!Conv2) 3563 return ImplicitConversionSequence::Indistinguishable; 3564 3565 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3566 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3567 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3568 if (Block1 != Block2) 3569 return Block1 ? ImplicitConversionSequence::Worse 3570 : ImplicitConversionSequence::Better; 3571 } 3572 3573 return ImplicitConversionSequence::Indistinguishable; 3574 } 3575 3576 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3577 const ImplicitConversionSequence &ICS) { 3578 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3579 (ICS.isUserDefined() && 3580 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3581 } 3582 3583 /// CompareImplicitConversionSequences - Compare two implicit 3584 /// conversion sequences to determine whether one is better than the 3585 /// other or if they are indistinguishable (C++ 13.3.3.2). 3586 static ImplicitConversionSequence::CompareKind 3587 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3588 const ImplicitConversionSequence& ICS1, 3589 const ImplicitConversionSequence& ICS2) 3590 { 3591 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3592 // conversion sequences (as defined in 13.3.3.1) 3593 // -- a standard conversion sequence (13.3.3.1.1) is a better 3594 // conversion sequence than a user-defined conversion sequence or 3595 // an ellipsis conversion sequence, and 3596 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3597 // conversion sequence than an ellipsis conversion sequence 3598 // (13.3.3.1.3). 3599 // 3600 // C++0x [over.best.ics]p10: 3601 // For the purpose of ranking implicit conversion sequences as 3602 // described in 13.3.3.2, the ambiguous conversion sequence is 3603 // treated as a user-defined sequence that is indistinguishable 3604 // from any other user-defined conversion sequence. 3605 3606 // String literal to 'char *' conversion has been deprecated in C++03. It has 3607 // been removed from C++11. We still accept this conversion, if it happens at 3608 // the best viable function. Otherwise, this conversion is considered worse 3609 // than ellipsis conversion. Consider this as an extension; this is not in the 3610 // standard. For example: 3611 // 3612 // int &f(...); // #1 3613 // void f(char*); // #2 3614 // void g() { int &r = f("foo"); } 3615 // 3616 // In C++03, we pick #2 as the best viable function. 3617 // In C++11, we pick #1 as the best viable function, because ellipsis 3618 // conversion is better than string-literal to char* conversion (since there 3619 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3620 // convert arguments, #2 would be the best viable function in C++11. 3621 // If the best viable function has this conversion, a warning will be issued 3622 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3623 3624 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3625 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3626 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3627 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3628 ? ImplicitConversionSequence::Worse 3629 : ImplicitConversionSequence::Better; 3630 3631 if (ICS1.getKindRank() < ICS2.getKindRank()) 3632 return ImplicitConversionSequence::Better; 3633 if (ICS2.getKindRank() < ICS1.getKindRank()) 3634 return ImplicitConversionSequence::Worse; 3635 3636 // The following checks require both conversion sequences to be of 3637 // the same kind. 3638 if (ICS1.getKind() != ICS2.getKind()) 3639 return ImplicitConversionSequence::Indistinguishable; 3640 3641 ImplicitConversionSequence::CompareKind Result = 3642 ImplicitConversionSequence::Indistinguishable; 3643 3644 // Two implicit conversion sequences of the same form are 3645 // indistinguishable conversion sequences unless one of the 3646 // following rules apply: (C++ 13.3.3.2p3): 3647 3648 // List-initialization sequence L1 is a better conversion sequence than 3649 // list-initialization sequence L2 if: 3650 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3651 // if not that, 3652 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3653 // and N1 is smaller than N2., 3654 // even if one of the other rules in this paragraph would otherwise apply. 3655 if (!ICS1.isBad()) { 3656 if (ICS1.isStdInitializerListElement() && 3657 !ICS2.isStdInitializerListElement()) 3658 return ImplicitConversionSequence::Better; 3659 if (!ICS1.isStdInitializerListElement() && 3660 ICS2.isStdInitializerListElement()) 3661 return ImplicitConversionSequence::Worse; 3662 } 3663 3664 if (ICS1.isStandard()) 3665 // Standard conversion sequence S1 is a better conversion sequence than 3666 // standard conversion sequence S2 if [...] 3667 Result = CompareStandardConversionSequences(S, Loc, 3668 ICS1.Standard, ICS2.Standard); 3669 else if (ICS1.isUserDefined()) { 3670 // User-defined conversion sequence U1 is a better conversion 3671 // sequence than another user-defined conversion sequence U2 if 3672 // they contain the same user-defined conversion function or 3673 // constructor and if the second standard conversion sequence of 3674 // U1 is better than the second standard conversion sequence of 3675 // U2 (C++ 13.3.3.2p3). 3676 if (ICS1.UserDefined.ConversionFunction == 3677 ICS2.UserDefined.ConversionFunction) 3678 Result = CompareStandardConversionSequences(S, Loc, 3679 ICS1.UserDefined.After, 3680 ICS2.UserDefined.After); 3681 else 3682 Result = compareConversionFunctions(S, 3683 ICS1.UserDefined.ConversionFunction, 3684 ICS2.UserDefined.ConversionFunction); 3685 } 3686 3687 return Result; 3688 } 3689 3690 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3691 // determine if one is a proper subset of the other. 3692 static ImplicitConversionSequence::CompareKind 3693 compareStandardConversionSubsets(ASTContext &Context, 3694 const StandardConversionSequence& SCS1, 3695 const StandardConversionSequence& SCS2) { 3696 ImplicitConversionSequence::CompareKind Result 3697 = ImplicitConversionSequence::Indistinguishable; 3698 3699 // the identity conversion sequence is considered to be a subsequence of 3700 // any non-identity conversion sequence 3701 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3702 return ImplicitConversionSequence::Better; 3703 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3704 return ImplicitConversionSequence::Worse; 3705 3706 if (SCS1.Second != SCS2.Second) { 3707 if (SCS1.Second == ICK_Identity) 3708 Result = ImplicitConversionSequence::Better; 3709 else if (SCS2.Second == ICK_Identity) 3710 Result = ImplicitConversionSequence::Worse; 3711 else 3712 return ImplicitConversionSequence::Indistinguishable; 3713 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3714 return ImplicitConversionSequence::Indistinguishable; 3715 3716 if (SCS1.Third == SCS2.Third) { 3717 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3718 : ImplicitConversionSequence::Indistinguishable; 3719 } 3720 3721 if (SCS1.Third == ICK_Identity) 3722 return Result == ImplicitConversionSequence::Worse 3723 ? ImplicitConversionSequence::Indistinguishable 3724 : ImplicitConversionSequence::Better; 3725 3726 if (SCS2.Third == ICK_Identity) 3727 return Result == ImplicitConversionSequence::Better 3728 ? ImplicitConversionSequence::Indistinguishable 3729 : ImplicitConversionSequence::Worse; 3730 3731 return ImplicitConversionSequence::Indistinguishable; 3732 } 3733 3734 /// Determine whether one of the given reference bindings is better 3735 /// than the other based on what kind of bindings they are. 3736 static bool 3737 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3738 const StandardConversionSequence &SCS2) { 3739 // C++0x [over.ics.rank]p3b4: 3740 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3741 // implicit object parameter of a non-static member function declared 3742 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3743 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3744 // lvalue reference to a function lvalue and S2 binds an rvalue 3745 // reference*. 3746 // 3747 // FIXME: Rvalue references. We're going rogue with the above edits, 3748 // because the semantics in the current C++0x working paper (N3225 at the 3749 // time of this writing) break the standard definition of std::forward 3750 // and std::reference_wrapper when dealing with references to functions. 3751 // Proposed wording changes submitted to CWG for consideration. 3752 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3753 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3754 return false; 3755 3756 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3757 SCS2.IsLvalueReference) || 3758 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3759 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3760 } 3761 3762 /// CompareStandardConversionSequences - Compare two standard 3763 /// conversion sequences to determine whether one is better than the 3764 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3765 static ImplicitConversionSequence::CompareKind 3766 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3767 const StandardConversionSequence& SCS1, 3768 const StandardConversionSequence& SCS2) 3769 { 3770 // Standard conversion sequence S1 is a better conversion sequence 3771 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3772 3773 // -- S1 is a proper subsequence of S2 (comparing the conversion 3774 // sequences in the canonical form defined by 13.3.3.1.1, 3775 // excluding any Lvalue Transformation; the identity conversion 3776 // sequence is considered to be a subsequence of any 3777 // non-identity conversion sequence) or, if not that, 3778 if (ImplicitConversionSequence::CompareKind CK 3779 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3780 return CK; 3781 3782 // -- the rank of S1 is better than the rank of S2 (by the rules 3783 // defined below), or, if not that, 3784 ImplicitConversionRank Rank1 = SCS1.getRank(); 3785 ImplicitConversionRank Rank2 = SCS2.getRank(); 3786 if (Rank1 < Rank2) 3787 return ImplicitConversionSequence::Better; 3788 else if (Rank2 < Rank1) 3789 return ImplicitConversionSequence::Worse; 3790 3791 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3792 // are indistinguishable unless one of the following rules 3793 // applies: 3794 3795 // A conversion that is not a conversion of a pointer, or 3796 // pointer to member, to bool is better than another conversion 3797 // that is such a conversion. 3798 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3799 return SCS2.isPointerConversionToBool() 3800 ? ImplicitConversionSequence::Better 3801 : ImplicitConversionSequence::Worse; 3802 3803 // C++ [over.ics.rank]p4b2: 3804 // 3805 // If class B is derived directly or indirectly from class A, 3806 // conversion of B* to A* is better than conversion of B* to 3807 // void*, and conversion of A* to void* is better than conversion 3808 // of B* to void*. 3809 bool SCS1ConvertsToVoid 3810 = SCS1.isPointerConversionToVoidPointer(S.Context); 3811 bool SCS2ConvertsToVoid 3812 = SCS2.isPointerConversionToVoidPointer(S.Context); 3813 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3814 // Exactly one of the conversion sequences is a conversion to 3815 // a void pointer; it's the worse conversion. 3816 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3817 : ImplicitConversionSequence::Worse; 3818 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3819 // Neither conversion sequence converts to a void pointer; compare 3820 // their derived-to-base conversions. 3821 if (ImplicitConversionSequence::CompareKind DerivedCK 3822 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3823 return DerivedCK; 3824 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3825 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3826 // Both conversion sequences are conversions to void 3827 // pointers. Compare the source types to determine if there's an 3828 // inheritance relationship in their sources. 3829 QualType FromType1 = SCS1.getFromType(); 3830 QualType FromType2 = SCS2.getFromType(); 3831 3832 // Adjust the types we're converting from via the array-to-pointer 3833 // conversion, if we need to. 3834 if (SCS1.First == ICK_Array_To_Pointer) 3835 FromType1 = S.Context.getArrayDecayedType(FromType1); 3836 if (SCS2.First == ICK_Array_To_Pointer) 3837 FromType2 = S.Context.getArrayDecayedType(FromType2); 3838 3839 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3840 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3841 3842 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3843 return ImplicitConversionSequence::Better; 3844 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3845 return ImplicitConversionSequence::Worse; 3846 3847 // Objective-C++: If one interface is more specific than the 3848 // other, it is the better one. 3849 const ObjCObjectPointerType* FromObjCPtr1 3850 = FromType1->getAs<ObjCObjectPointerType>(); 3851 const ObjCObjectPointerType* FromObjCPtr2 3852 = FromType2->getAs<ObjCObjectPointerType>(); 3853 if (FromObjCPtr1 && FromObjCPtr2) { 3854 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3855 FromObjCPtr2); 3856 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3857 FromObjCPtr1); 3858 if (AssignLeft != AssignRight) { 3859 return AssignLeft? ImplicitConversionSequence::Better 3860 : ImplicitConversionSequence::Worse; 3861 } 3862 } 3863 } 3864 3865 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3866 // bullet 3). 3867 if (ImplicitConversionSequence::CompareKind QualCK 3868 = CompareQualificationConversions(S, SCS1, SCS2)) 3869 return QualCK; 3870 3871 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3872 // Check for a better reference binding based on the kind of bindings. 3873 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3874 return ImplicitConversionSequence::Better; 3875 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3876 return ImplicitConversionSequence::Worse; 3877 3878 // C++ [over.ics.rank]p3b4: 3879 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3880 // which the references refer are the same type except for 3881 // top-level cv-qualifiers, and the type to which the reference 3882 // initialized by S2 refers is more cv-qualified than the type 3883 // to which the reference initialized by S1 refers. 3884 QualType T1 = SCS1.getToType(2); 3885 QualType T2 = SCS2.getToType(2); 3886 T1 = S.Context.getCanonicalType(T1); 3887 T2 = S.Context.getCanonicalType(T2); 3888 Qualifiers T1Quals, T2Quals; 3889 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3890 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3891 if (UnqualT1 == UnqualT2) { 3892 // Objective-C++ ARC: If the references refer to objects with different 3893 // lifetimes, prefer bindings that don't change lifetime. 3894 if (SCS1.ObjCLifetimeConversionBinding != 3895 SCS2.ObjCLifetimeConversionBinding) { 3896 return SCS1.ObjCLifetimeConversionBinding 3897 ? ImplicitConversionSequence::Worse 3898 : ImplicitConversionSequence::Better; 3899 } 3900 3901 // If the type is an array type, promote the element qualifiers to the 3902 // type for comparison. 3903 if (isa<ArrayType>(T1) && T1Quals) 3904 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3905 if (isa<ArrayType>(T2) && T2Quals) 3906 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3907 if (T2.isMoreQualifiedThan(T1)) 3908 return ImplicitConversionSequence::Better; 3909 else if (T1.isMoreQualifiedThan(T2)) 3910 return ImplicitConversionSequence::Worse; 3911 } 3912 } 3913 3914 // In Microsoft mode, prefer an integral conversion to a 3915 // floating-to-integral conversion if the integral conversion 3916 // is between types of the same size. 3917 // For example: 3918 // void f(float); 3919 // void f(int); 3920 // int main { 3921 // long a; 3922 // f(a); 3923 // } 3924 // Here, MSVC will call f(int) instead of generating a compile error 3925 // as clang will do in standard mode. 3926 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3927 SCS2.Second == ICK_Floating_Integral && 3928 S.Context.getTypeSize(SCS1.getFromType()) == 3929 S.Context.getTypeSize(SCS1.getToType(2))) 3930 return ImplicitConversionSequence::Better; 3931 3932 // Prefer a compatible vector conversion over a lax vector conversion 3933 // For example: 3934 // 3935 // typedef float __v4sf __attribute__((__vector_size__(16))); 3936 // void f(vector float); 3937 // void f(vector signed int); 3938 // int main() { 3939 // __v4sf a; 3940 // f(a); 3941 // } 3942 // Here, we'd like to choose f(vector float) and not 3943 // report an ambiguous call error 3944 if (SCS1.Second == ICK_Vector_Conversion && 3945 SCS2.Second == ICK_Vector_Conversion) { 3946 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3947 SCS1.getFromType(), SCS1.getToType(2)); 3948 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3949 SCS2.getFromType(), SCS2.getToType(2)); 3950 3951 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3952 return SCS1IsCompatibleVectorConversion 3953 ? ImplicitConversionSequence::Better 3954 : ImplicitConversionSequence::Worse; 3955 } 3956 3957 return ImplicitConversionSequence::Indistinguishable; 3958 } 3959 3960 /// CompareQualificationConversions - Compares two standard conversion 3961 /// sequences to determine whether they can be ranked based on their 3962 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3963 static ImplicitConversionSequence::CompareKind 3964 CompareQualificationConversions(Sema &S, 3965 const StandardConversionSequence& SCS1, 3966 const StandardConversionSequence& SCS2) { 3967 // C++ 13.3.3.2p3: 3968 // -- S1 and S2 differ only in their qualification conversion and 3969 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3970 // cv-qualification signature of type T1 is a proper subset of 3971 // the cv-qualification signature of type T2, and S1 is not the 3972 // deprecated string literal array-to-pointer conversion (4.2). 3973 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3974 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3975 return ImplicitConversionSequence::Indistinguishable; 3976 3977 // FIXME: the example in the standard doesn't use a qualification 3978 // conversion (!) 3979 QualType T1 = SCS1.getToType(2); 3980 QualType T2 = SCS2.getToType(2); 3981 T1 = S.Context.getCanonicalType(T1); 3982 T2 = S.Context.getCanonicalType(T2); 3983 Qualifiers T1Quals, T2Quals; 3984 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3985 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3986 3987 // If the types are the same, we won't learn anything by unwrapped 3988 // them. 3989 if (UnqualT1 == UnqualT2) 3990 return ImplicitConversionSequence::Indistinguishable; 3991 3992 // If the type is an array type, promote the element qualifiers to the type 3993 // for comparison. 3994 if (isa<ArrayType>(T1) && T1Quals) 3995 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3996 if (isa<ArrayType>(T2) && T2Quals) 3997 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3998 3999 ImplicitConversionSequence::CompareKind Result 4000 = ImplicitConversionSequence::Indistinguishable; 4001 4002 // Objective-C++ ARC: 4003 // Prefer qualification conversions not involving a change in lifetime 4004 // to qualification conversions that do not change lifetime. 4005 if (SCS1.QualificationIncludesObjCLifetime != 4006 SCS2.QualificationIncludesObjCLifetime) { 4007 Result = SCS1.QualificationIncludesObjCLifetime 4008 ? ImplicitConversionSequence::Worse 4009 : ImplicitConversionSequence::Better; 4010 } 4011 4012 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4013 // Within each iteration of the loop, we check the qualifiers to 4014 // determine if this still looks like a qualification 4015 // conversion. Then, if all is well, we unwrap one more level of 4016 // pointers or pointers-to-members and do it all again 4017 // until there are no more pointers or pointers-to-members left 4018 // to unwrap. This essentially mimics what 4019 // IsQualificationConversion does, but here we're checking for a 4020 // strict subset of qualifiers. 4021 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 4022 // The qualifiers are the same, so this doesn't tell us anything 4023 // about how the sequences rank. 4024 ; 4025 else if (T2.isMoreQualifiedThan(T1)) { 4026 // T1 has fewer qualifiers, so it could be the better sequence. 4027 if (Result == ImplicitConversionSequence::Worse) 4028 // Neither has qualifiers that are a subset of the other's 4029 // qualifiers. 4030 return ImplicitConversionSequence::Indistinguishable; 4031 4032 Result = ImplicitConversionSequence::Better; 4033 } else if (T1.isMoreQualifiedThan(T2)) { 4034 // T2 has fewer qualifiers, so it could be the better sequence. 4035 if (Result == ImplicitConversionSequence::Better) 4036 // Neither has qualifiers that are a subset of the other's 4037 // qualifiers. 4038 return ImplicitConversionSequence::Indistinguishable; 4039 4040 Result = ImplicitConversionSequence::Worse; 4041 } else { 4042 // Qualifiers are disjoint. 4043 return ImplicitConversionSequence::Indistinguishable; 4044 } 4045 4046 // If the types after this point are equivalent, we're done. 4047 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4048 break; 4049 } 4050 4051 // Check that the winning standard conversion sequence isn't using 4052 // the deprecated string literal array to pointer conversion. 4053 switch (Result) { 4054 case ImplicitConversionSequence::Better: 4055 if (SCS1.DeprecatedStringLiteralToCharPtr) 4056 Result = ImplicitConversionSequence::Indistinguishable; 4057 break; 4058 4059 case ImplicitConversionSequence::Indistinguishable: 4060 break; 4061 4062 case ImplicitConversionSequence::Worse: 4063 if (SCS2.DeprecatedStringLiteralToCharPtr) 4064 Result = ImplicitConversionSequence::Indistinguishable; 4065 break; 4066 } 4067 4068 return Result; 4069 } 4070 4071 /// CompareDerivedToBaseConversions - Compares two standard conversion 4072 /// sequences to determine whether they can be ranked based on their 4073 /// various kinds of derived-to-base conversions (C++ 4074 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4075 /// conversions between Objective-C interface types. 4076 static ImplicitConversionSequence::CompareKind 4077 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4078 const StandardConversionSequence& SCS1, 4079 const StandardConversionSequence& SCS2) { 4080 QualType FromType1 = SCS1.getFromType(); 4081 QualType ToType1 = SCS1.getToType(1); 4082 QualType FromType2 = SCS2.getFromType(); 4083 QualType ToType2 = SCS2.getToType(1); 4084 4085 // Adjust the types we're converting from via the array-to-pointer 4086 // conversion, if we need to. 4087 if (SCS1.First == ICK_Array_To_Pointer) 4088 FromType1 = S.Context.getArrayDecayedType(FromType1); 4089 if (SCS2.First == ICK_Array_To_Pointer) 4090 FromType2 = S.Context.getArrayDecayedType(FromType2); 4091 4092 // Canonicalize all of the types. 4093 FromType1 = S.Context.getCanonicalType(FromType1); 4094 ToType1 = S.Context.getCanonicalType(ToType1); 4095 FromType2 = S.Context.getCanonicalType(FromType2); 4096 ToType2 = S.Context.getCanonicalType(ToType2); 4097 4098 // C++ [over.ics.rank]p4b3: 4099 // 4100 // If class B is derived directly or indirectly from class A and 4101 // class C is derived directly or indirectly from B, 4102 // 4103 // Compare based on pointer conversions. 4104 if (SCS1.Second == ICK_Pointer_Conversion && 4105 SCS2.Second == ICK_Pointer_Conversion && 4106 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4107 FromType1->isPointerType() && FromType2->isPointerType() && 4108 ToType1->isPointerType() && ToType2->isPointerType()) { 4109 QualType FromPointee1 4110 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4111 QualType ToPointee1 4112 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4113 QualType FromPointee2 4114 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4115 QualType ToPointee2 4116 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4117 4118 // -- conversion of C* to B* is better than conversion of C* to A*, 4119 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4120 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4121 return ImplicitConversionSequence::Better; 4122 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4123 return ImplicitConversionSequence::Worse; 4124 } 4125 4126 // -- conversion of B* to A* is better than conversion of C* to A*, 4127 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4128 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4129 return ImplicitConversionSequence::Better; 4130 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4131 return ImplicitConversionSequence::Worse; 4132 } 4133 } else if (SCS1.Second == ICK_Pointer_Conversion && 4134 SCS2.Second == ICK_Pointer_Conversion) { 4135 const ObjCObjectPointerType *FromPtr1 4136 = FromType1->getAs<ObjCObjectPointerType>(); 4137 const ObjCObjectPointerType *FromPtr2 4138 = FromType2->getAs<ObjCObjectPointerType>(); 4139 const ObjCObjectPointerType *ToPtr1 4140 = ToType1->getAs<ObjCObjectPointerType>(); 4141 const ObjCObjectPointerType *ToPtr2 4142 = ToType2->getAs<ObjCObjectPointerType>(); 4143 4144 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4145 // Apply the same conversion ranking rules for Objective-C pointer types 4146 // that we do for C++ pointers to class types. However, we employ the 4147 // Objective-C pseudo-subtyping relationship used for assignment of 4148 // Objective-C pointer types. 4149 bool FromAssignLeft 4150 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4151 bool FromAssignRight 4152 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4153 bool ToAssignLeft 4154 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4155 bool ToAssignRight 4156 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4157 4158 // A conversion to an a non-id object pointer type or qualified 'id' 4159 // type is better than a conversion to 'id'. 4160 if (ToPtr1->isObjCIdType() && 4161 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4162 return ImplicitConversionSequence::Worse; 4163 if (ToPtr2->isObjCIdType() && 4164 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4165 return ImplicitConversionSequence::Better; 4166 4167 // A conversion to a non-id object pointer type is better than a 4168 // conversion to a qualified 'id' type 4169 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4170 return ImplicitConversionSequence::Worse; 4171 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4172 return ImplicitConversionSequence::Better; 4173 4174 // A conversion to an a non-Class object pointer type or qualified 'Class' 4175 // type is better than a conversion to 'Class'. 4176 if (ToPtr1->isObjCClassType() && 4177 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4178 return ImplicitConversionSequence::Worse; 4179 if (ToPtr2->isObjCClassType() && 4180 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4181 return ImplicitConversionSequence::Better; 4182 4183 // A conversion to a non-Class object pointer type is better than a 4184 // conversion to a qualified 'Class' type. 4185 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4186 return ImplicitConversionSequence::Worse; 4187 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4188 return ImplicitConversionSequence::Better; 4189 4190 // -- "conversion of C* to B* is better than conversion of C* to A*," 4191 if (S.Context.hasSameType(FromType1, FromType2) && 4192 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4193 (ToAssignLeft != ToAssignRight)) { 4194 if (FromPtr1->isSpecialized()) { 4195 // "conversion of B<A> * to B * is better than conversion of B * to 4196 // C *. 4197 bool IsFirstSame = 4198 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4199 bool IsSecondSame = 4200 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4201 if (IsFirstSame) { 4202 if (!IsSecondSame) 4203 return ImplicitConversionSequence::Better; 4204 } else if (IsSecondSame) 4205 return ImplicitConversionSequence::Worse; 4206 } 4207 return ToAssignLeft? ImplicitConversionSequence::Worse 4208 : ImplicitConversionSequence::Better; 4209 } 4210 4211 // -- "conversion of B* to A* is better than conversion of C* to A*," 4212 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4213 (FromAssignLeft != FromAssignRight)) 4214 return FromAssignLeft? ImplicitConversionSequence::Better 4215 : ImplicitConversionSequence::Worse; 4216 } 4217 } 4218 4219 // Ranking of member-pointer types. 4220 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4221 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4222 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4223 const MemberPointerType * FromMemPointer1 = 4224 FromType1->getAs<MemberPointerType>(); 4225 const MemberPointerType * ToMemPointer1 = 4226 ToType1->getAs<MemberPointerType>(); 4227 const MemberPointerType * FromMemPointer2 = 4228 FromType2->getAs<MemberPointerType>(); 4229 const MemberPointerType * ToMemPointer2 = 4230 ToType2->getAs<MemberPointerType>(); 4231 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4232 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4233 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4234 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4235 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4236 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4237 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4238 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4239 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4240 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4241 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4242 return ImplicitConversionSequence::Worse; 4243 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4244 return ImplicitConversionSequence::Better; 4245 } 4246 // conversion of B::* to C::* is better than conversion of A::* to C::* 4247 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4248 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4249 return ImplicitConversionSequence::Better; 4250 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4251 return ImplicitConversionSequence::Worse; 4252 } 4253 } 4254 4255 if (SCS1.Second == ICK_Derived_To_Base) { 4256 // -- conversion of C to B is better than conversion of C to A, 4257 // -- binding of an expression of type C to a reference of type 4258 // B& is better than binding an expression of type C to a 4259 // reference of type A&, 4260 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4261 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4262 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4263 return ImplicitConversionSequence::Better; 4264 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4265 return ImplicitConversionSequence::Worse; 4266 } 4267 4268 // -- conversion of B to A is better than conversion of C to A. 4269 // -- binding of an expression of type B to a reference of type 4270 // A& is better than binding an expression of type C to a 4271 // reference of type A&, 4272 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4273 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4274 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4275 return ImplicitConversionSequence::Better; 4276 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4277 return ImplicitConversionSequence::Worse; 4278 } 4279 } 4280 4281 return ImplicitConversionSequence::Indistinguishable; 4282 } 4283 4284 /// Determine whether the given type is valid, e.g., it is not an invalid 4285 /// C++ class. 4286 static bool isTypeValid(QualType T) { 4287 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4288 return !Record->isInvalidDecl(); 4289 4290 return true; 4291 } 4292 4293 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4294 /// determine whether they are reference-related, 4295 /// reference-compatible, reference-compatible with added 4296 /// qualification, or incompatible, for use in C++ initialization by 4297 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4298 /// type, and the first type (T1) is the pointee type of the reference 4299 /// type being initialized. 4300 Sema::ReferenceCompareResult 4301 Sema::CompareReferenceRelationship(SourceLocation Loc, 4302 QualType OrigT1, QualType OrigT2, 4303 bool &DerivedToBase, 4304 bool &ObjCConversion, 4305 bool &ObjCLifetimeConversion) { 4306 assert(!OrigT1->isReferenceType() && 4307 "T1 must be the pointee type of the reference type"); 4308 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4309 4310 QualType T1 = Context.getCanonicalType(OrigT1); 4311 QualType T2 = Context.getCanonicalType(OrigT2); 4312 Qualifiers T1Quals, T2Quals; 4313 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4314 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4315 4316 // C++ [dcl.init.ref]p4: 4317 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4318 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4319 // T1 is a base class of T2. 4320 DerivedToBase = false; 4321 ObjCConversion = false; 4322 ObjCLifetimeConversion = false; 4323 QualType ConvertedT2; 4324 if (UnqualT1 == UnqualT2) { 4325 // Nothing to do. 4326 } else if (isCompleteType(Loc, OrigT2) && 4327 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4328 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4329 DerivedToBase = true; 4330 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4331 UnqualT2->isObjCObjectOrInterfaceType() && 4332 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4333 ObjCConversion = true; 4334 else if (UnqualT2->isFunctionType() && 4335 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4336 // C++1z [dcl.init.ref]p4: 4337 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4338 // function" and T1 is "function" 4339 // 4340 // We extend this to also apply to 'noreturn', so allow any function 4341 // conversion between function types. 4342 return Ref_Compatible; 4343 else 4344 return Ref_Incompatible; 4345 4346 // At this point, we know that T1 and T2 are reference-related (at 4347 // least). 4348 4349 // If the type is an array type, promote the element qualifiers to the type 4350 // for comparison. 4351 if (isa<ArrayType>(T1) && T1Quals) 4352 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4353 if (isa<ArrayType>(T2) && T2Quals) 4354 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4355 4356 // C++ [dcl.init.ref]p4: 4357 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4358 // reference-related to T2 and cv1 is the same cv-qualification 4359 // as, or greater cv-qualification than, cv2. For purposes of 4360 // overload resolution, cases for which cv1 is greater 4361 // cv-qualification than cv2 are identified as 4362 // reference-compatible with added qualification (see 13.3.3.2). 4363 // 4364 // Note that we also require equivalence of Objective-C GC and address-space 4365 // qualifiers when performing these computations, so that e.g., an int in 4366 // address space 1 is not reference-compatible with an int in address 4367 // space 2. 4368 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4369 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4370 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4371 ObjCLifetimeConversion = true; 4372 4373 T1Quals.removeObjCLifetime(); 4374 T2Quals.removeObjCLifetime(); 4375 } 4376 4377 // MS compiler ignores __unaligned qualifier for references; do the same. 4378 T1Quals.removeUnaligned(); 4379 T2Quals.removeUnaligned(); 4380 4381 if (T1Quals.compatiblyIncludes(T2Quals)) 4382 return Ref_Compatible; 4383 else 4384 return Ref_Related; 4385 } 4386 4387 /// Look for a user-defined conversion to a value reference-compatible 4388 /// with DeclType. Return true if something definite is found. 4389 static bool 4390 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4391 QualType DeclType, SourceLocation DeclLoc, 4392 Expr *Init, QualType T2, bool AllowRvalues, 4393 bool AllowExplicit) { 4394 assert(T2->isRecordType() && "Can only find conversions of record types."); 4395 CXXRecordDecl *T2RecordDecl 4396 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4397 4398 OverloadCandidateSet CandidateSet( 4399 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4400 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4401 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4402 NamedDecl *D = *I; 4403 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4404 if (isa<UsingShadowDecl>(D)) 4405 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4406 4407 FunctionTemplateDecl *ConvTemplate 4408 = dyn_cast<FunctionTemplateDecl>(D); 4409 CXXConversionDecl *Conv; 4410 if (ConvTemplate) 4411 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4412 else 4413 Conv = cast<CXXConversionDecl>(D); 4414 4415 // If this is an explicit conversion, and we're not allowed to consider 4416 // explicit conversions, skip it. 4417 if (!AllowExplicit && Conv->isExplicit()) 4418 continue; 4419 4420 if (AllowRvalues) { 4421 bool DerivedToBase = false; 4422 bool ObjCConversion = false; 4423 bool ObjCLifetimeConversion = false; 4424 4425 // If we are initializing an rvalue reference, don't permit conversion 4426 // functions that return lvalues. 4427 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4428 const ReferenceType *RefType 4429 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4430 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4431 continue; 4432 } 4433 4434 if (!ConvTemplate && 4435 S.CompareReferenceRelationship( 4436 DeclLoc, 4437 Conv->getConversionType().getNonReferenceType() 4438 .getUnqualifiedType(), 4439 DeclType.getNonReferenceType().getUnqualifiedType(), 4440 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4441 Sema::Ref_Incompatible) 4442 continue; 4443 } else { 4444 // If the conversion function doesn't return a reference type, 4445 // it can't be considered for this conversion. An rvalue reference 4446 // is only acceptable if its referencee is a function type. 4447 4448 const ReferenceType *RefType = 4449 Conv->getConversionType()->getAs<ReferenceType>(); 4450 if (!RefType || 4451 (!RefType->isLValueReferenceType() && 4452 !RefType->getPointeeType()->isFunctionType())) 4453 continue; 4454 } 4455 4456 if (ConvTemplate) 4457 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4458 Init, DeclType, CandidateSet, 4459 /*AllowObjCConversionOnExplicit=*/false); 4460 else 4461 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4462 DeclType, CandidateSet, 4463 /*AllowObjCConversionOnExplicit=*/false); 4464 } 4465 4466 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4467 4468 OverloadCandidateSet::iterator Best; 4469 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4470 case OR_Success: 4471 // C++ [over.ics.ref]p1: 4472 // 4473 // [...] If the parameter binds directly to the result of 4474 // applying a conversion function to the argument 4475 // expression, the implicit conversion sequence is a 4476 // user-defined conversion sequence (13.3.3.1.2), with the 4477 // second standard conversion sequence either an identity 4478 // conversion or, if the conversion function returns an 4479 // entity of a type that is a derived class of the parameter 4480 // type, a derived-to-base Conversion. 4481 if (!Best->FinalConversion.DirectBinding) 4482 return false; 4483 4484 ICS.setUserDefined(); 4485 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4486 ICS.UserDefined.After = Best->FinalConversion; 4487 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4488 ICS.UserDefined.ConversionFunction = Best->Function; 4489 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4490 ICS.UserDefined.EllipsisConversion = false; 4491 assert(ICS.UserDefined.After.ReferenceBinding && 4492 ICS.UserDefined.After.DirectBinding && 4493 "Expected a direct reference binding!"); 4494 return true; 4495 4496 case OR_Ambiguous: 4497 ICS.setAmbiguous(); 4498 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4499 Cand != CandidateSet.end(); ++Cand) 4500 if (Cand->Viable) 4501 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4502 return true; 4503 4504 case OR_No_Viable_Function: 4505 case OR_Deleted: 4506 // There was no suitable conversion, or we found a deleted 4507 // conversion; continue with other checks. 4508 return false; 4509 } 4510 4511 llvm_unreachable("Invalid OverloadResult!"); 4512 } 4513 4514 /// Compute an implicit conversion sequence for reference 4515 /// initialization. 4516 static ImplicitConversionSequence 4517 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4518 SourceLocation DeclLoc, 4519 bool SuppressUserConversions, 4520 bool AllowExplicit) { 4521 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4522 4523 // Most paths end in a failed conversion. 4524 ImplicitConversionSequence ICS; 4525 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4526 4527 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4528 QualType T2 = Init->getType(); 4529 4530 // If the initializer is the address of an overloaded function, try 4531 // to resolve the overloaded function. If all goes well, T2 is the 4532 // type of the resulting function. 4533 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4534 DeclAccessPair Found; 4535 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4536 false, Found)) 4537 T2 = Fn->getType(); 4538 } 4539 4540 // Compute some basic properties of the types and the initializer. 4541 bool isRValRef = DeclType->isRValueReferenceType(); 4542 bool DerivedToBase = false; 4543 bool ObjCConversion = false; 4544 bool ObjCLifetimeConversion = false; 4545 Expr::Classification InitCategory = Init->Classify(S.Context); 4546 Sema::ReferenceCompareResult RefRelationship 4547 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4548 ObjCConversion, ObjCLifetimeConversion); 4549 4550 4551 // C++0x [dcl.init.ref]p5: 4552 // A reference to type "cv1 T1" is initialized by an expression 4553 // of type "cv2 T2" as follows: 4554 4555 // -- If reference is an lvalue reference and the initializer expression 4556 if (!isRValRef) { 4557 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4558 // reference-compatible with "cv2 T2," or 4559 // 4560 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4561 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4562 // C++ [over.ics.ref]p1: 4563 // When a parameter of reference type binds directly (8.5.3) 4564 // to an argument expression, the implicit conversion sequence 4565 // is the identity conversion, unless the argument expression 4566 // has a type that is a derived class of the parameter type, 4567 // in which case the implicit conversion sequence is a 4568 // derived-to-base Conversion (13.3.3.1). 4569 ICS.setStandard(); 4570 ICS.Standard.First = ICK_Identity; 4571 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4572 : ObjCConversion? ICK_Compatible_Conversion 4573 : ICK_Identity; 4574 ICS.Standard.Third = ICK_Identity; 4575 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4576 ICS.Standard.setToType(0, T2); 4577 ICS.Standard.setToType(1, T1); 4578 ICS.Standard.setToType(2, T1); 4579 ICS.Standard.ReferenceBinding = true; 4580 ICS.Standard.DirectBinding = true; 4581 ICS.Standard.IsLvalueReference = !isRValRef; 4582 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4583 ICS.Standard.BindsToRvalue = false; 4584 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4585 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4586 ICS.Standard.CopyConstructor = nullptr; 4587 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4588 4589 // Nothing more to do: the inaccessibility/ambiguity check for 4590 // derived-to-base conversions is suppressed when we're 4591 // computing the implicit conversion sequence (C++ 4592 // [over.best.ics]p2). 4593 return ICS; 4594 } 4595 4596 // -- has a class type (i.e., T2 is a class type), where T1 is 4597 // not reference-related to T2, and can be implicitly 4598 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4599 // is reference-compatible with "cv3 T3" 92) (this 4600 // conversion is selected by enumerating the applicable 4601 // conversion functions (13.3.1.6) and choosing the best 4602 // one through overload resolution (13.3)), 4603 if (!SuppressUserConversions && T2->isRecordType() && 4604 S.isCompleteType(DeclLoc, T2) && 4605 RefRelationship == Sema::Ref_Incompatible) { 4606 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4607 Init, T2, /*AllowRvalues=*/false, 4608 AllowExplicit)) 4609 return ICS; 4610 } 4611 } 4612 4613 // -- Otherwise, the reference shall be an lvalue reference to a 4614 // non-volatile const type (i.e., cv1 shall be const), or the reference 4615 // shall be an rvalue reference. 4616 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4617 return ICS; 4618 4619 // -- If the initializer expression 4620 // 4621 // -- is an xvalue, class prvalue, array prvalue or function 4622 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4623 if (RefRelationship == Sema::Ref_Compatible && 4624 (InitCategory.isXValue() || 4625 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4626 (InitCategory.isLValue() && T2->isFunctionType()))) { 4627 ICS.setStandard(); 4628 ICS.Standard.First = ICK_Identity; 4629 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4630 : ObjCConversion? ICK_Compatible_Conversion 4631 : ICK_Identity; 4632 ICS.Standard.Third = ICK_Identity; 4633 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4634 ICS.Standard.setToType(0, T2); 4635 ICS.Standard.setToType(1, T1); 4636 ICS.Standard.setToType(2, T1); 4637 ICS.Standard.ReferenceBinding = true; 4638 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4639 // binding unless we're binding to a class prvalue. 4640 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4641 // allow the use of rvalue references in C++98/03 for the benefit of 4642 // standard library implementors; therefore, we need the xvalue check here. 4643 ICS.Standard.DirectBinding = 4644 S.getLangOpts().CPlusPlus11 || 4645 !(InitCategory.isPRValue() || T2->isRecordType()); 4646 ICS.Standard.IsLvalueReference = !isRValRef; 4647 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4648 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4649 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4650 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4651 ICS.Standard.CopyConstructor = nullptr; 4652 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4653 return ICS; 4654 } 4655 4656 // -- has a class type (i.e., T2 is a class type), where T1 is not 4657 // reference-related to T2, and can be implicitly converted to 4658 // an xvalue, class prvalue, or function lvalue of type 4659 // "cv3 T3", where "cv1 T1" is reference-compatible with 4660 // "cv3 T3", 4661 // 4662 // then the reference is bound to the value of the initializer 4663 // expression in the first case and to the result of the conversion 4664 // in the second case (or, in either case, to an appropriate base 4665 // class subobject). 4666 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4667 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4668 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4669 Init, T2, /*AllowRvalues=*/true, 4670 AllowExplicit)) { 4671 // In the second case, if the reference is an rvalue reference 4672 // and the second standard conversion sequence of the 4673 // user-defined conversion sequence includes an lvalue-to-rvalue 4674 // conversion, the program is ill-formed. 4675 if (ICS.isUserDefined() && isRValRef && 4676 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4677 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4678 4679 return ICS; 4680 } 4681 4682 // A temporary of function type cannot be created; don't even try. 4683 if (T1->isFunctionType()) 4684 return ICS; 4685 4686 // -- Otherwise, a temporary of type "cv1 T1" is created and 4687 // initialized from the initializer expression using the 4688 // rules for a non-reference copy initialization (8.5). The 4689 // reference is then bound to the temporary. If T1 is 4690 // reference-related to T2, cv1 must be the same 4691 // cv-qualification as, or greater cv-qualification than, 4692 // cv2; otherwise, the program is ill-formed. 4693 if (RefRelationship == Sema::Ref_Related) { 4694 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4695 // we would be reference-compatible or reference-compatible with 4696 // added qualification. But that wasn't the case, so the reference 4697 // initialization fails. 4698 // 4699 // Note that we only want to check address spaces and cvr-qualifiers here. 4700 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4701 Qualifiers T1Quals = T1.getQualifiers(); 4702 Qualifiers T2Quals = T2.getQualifiers(); 4703 T1Quals.removeObjCGCAttr(); 4704 T1Quals.removeObjCLifetime(); 4705 T2Quals.removeObjCGCAttr(); 4706 T2Quals.removeObjCLifetime(); 4707 // MS compiler ignores __unaligned qualifier for references; do the same. 4708 T1Quals.removeUnaligned(); 4709 T2Quals.removeUnaligned(); 4710 if (!T1Quals.compatiblyIncludes(T2Quals)) 4711 return ICS; 4712 } 4713 4714 // If at least one of the types is a class type, the types are not 4715 // related, and we aren't allowed any user conversions, the 4716 // reference binding fails. This case is important for breaking 4717 // recursion, since TryImplicitConversion below will attempt to 4718 // create a temporary through the use of a copy constructor. 4719 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4720 (T1->isRecordType() || T2->isRecordType())) 4721 return ICS; 4722 4723 // If T1 is reference-related to T2 and the reference is an rvalue 4724 // reference, the initializer expression shall not be an lvalue. 4725 if (RefRelationship >= Sema::Ref_Related && 4726 isRValRef && Init->Classify(S.Context).isLValue()) 4727 return ICS; 4728 4729 // C++ [over.ics.ref]p2: 4730 // When a parameter of reference type is not bound directly to 4731 // an argument expression, the conversion sequence is the one 4732 // required to convert the argument expression to the 4733 // underlying type of the reference according to 4734 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4735 // to copy-initializing a temporary of the underlying type with 4736 // the argument expression. Any difference in top-level 4737 // cv-qualification is subsumed by the initialization itself 4738 // and does not constitute a conversion. 4739 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4740 /*AllowExplicit=*/false, 4741 /*InOverloadResolution=*/false, 4742 /*CStyle=*/false, 4743 /*AllowObjCWritebackConversion=*/false, 4744 /*AllowObjCConversionOnExplicit=*/false); 4745 4746 // Of course, that's still a reference binding. 4747 if (ICS.isStandard()) { 4748 ICS.Standard.ReferenceBinding = true; 4749 ICS.Standard.IsLvalueReference = !isRValRef; 4750 ICS.Standard.BindsToFunctionLvalue = false; 4751 ICS.Standard.BindsToRvalue = true; 4752 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4753 ICS.Standard.ObjCLifetimeConversionBinding = false; 4754 } else if (ICS.isUserDefined()) { 4755 const ReferenceType *LValRefType = 4756 ICS.UserDefined.ConversionFunction->getReturnType() 4757 ->getAs<LValueReferenceType>(); 4758 4759 // C++ [over.ics.ref]p3: 4760 // Except for an implicit object parameter, for which see 13.3.1, a 4761 // standard conversion sequence cannot be formed if it requires [...] 4762 // binding an rvalue reference to an lvalue other than a function 4763 // lvalue. 4764 // Note that the function case is not possible here. 4765 if (DeclType->isRValueReferenceType() && LValRefType) { 4766 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4767 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4768 // reference to an rvalue! 4769 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4770 return ICS; 4771 } 4772 4773 ICS.UserDefined.After.ReferenceBinding = true; 4774 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4775 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4776 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4777 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4778 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4779 } 4780 4781 return ICS; 4782 } 4783 4784 static ImplicitConversionSequence 4785 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4786 bool SuppressUserConversions, 4787 bool InOverloadResolution, 4788 bool AllowObjCWritebackConversion, 4789 bool AllowExplicit = false); 4790 4791 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4792 /// initializer list From. 4793 static ImplicitConversionSequence 4794 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4795 bool SuppressUserConversions, 4796 bool InOverloadResolution, 4797 bool AllowObjCWritebackConversion) { 4798 // C++11 [over.ics.list]p1: 4799 // When an argument is an initializer list, it is not an expression and 4800 // special rules apply for converting it to a parameter type. 4801 4802 ImplicitConversionSequence Result; 4803 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4804 4805 // We need a complete type for what follows. Incomplete types can never be 4806 // initialized from init lists. 4807 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4808 return Result; 4809 4810 // Per DR1467: 4811 // If the parameter type is a class X and the initializer list has a single 4812 // element of type cv U, where U is X or a class derived from X, the 4813 // implicit conversion sequence is the one required to convert the element 4814 // to the parameter type. 4815 // 4816 // Otherwise, if the parameter type is a character array [... ] 4817 // and the initializer list has a single element that is an 4818 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4819 // implicit conversion sequence is the identity conversion. 4820 if (From->getNumInits() == 1) { 4821 if (ToType->isRecordType()) { 4822 QualType InitType = From->getInit(0)->getType(); 4823 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4824 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4825 return TryCopyInitialization(S, From->getInit(0), ToType, 4826 SuppressUserConversions, 4827 InOverloadResolution, 4828 AllowObjCWritebackConversion); 4829 } 4830 // FIXME: Check the other conditions here: array of character type, 4831 // initializer is a string literal. 4832 if (ToType->isArrayType()) { 4833 InitializedEntity Entity = 4834 InitializedEntity::InitializeParameter(S.Context, ToType, 4835 /*Consumed=*/false); 4836 if (S.CanPerformCopyInitialization(Entity, From)) { 4837 Result.setStandard(); 4838 Result.Standard.setAsIdentityConversion(); 4839 Result.Standard.setFromType(ToType); 4840 Result.Standard.setAllToTypes(ToType); 4841 return Result; 4842 } 4843 } 4844 } 4845 4846 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4847 // C++11 [over.ics.list]p2: 4848 // If the parameter type is std::initializer_list<X> or "array of X" and 4849 // all the elements can be implicitly converted to X, the implicit 4850 // conversion sequence is the worst conversion necessary to convert an 4851 // element of the list to X. 4852 // 4853 // C++14 [over.ics.list]p3: 4854 // Otherwise, if the parameter type is "array of N X", if the initializer 4855 // list has exactly N elements or if it has fewer than N elements and X is 4856 // default-constructible, and if all the elements of the initializer list 4857 // can be implicitly converted to X, the implicit conversion sequence is 4858 // the worst conversion necessary to convert an element of the list to X. 4859 // 4860 // FIXME: We're missing a lot of these checks. 4861 bool toStdInitializerList = false; 4862 QualType X; 4863 if (ToType->isArrayType()) 4864 X = S.Context.getAsArrayType(ToType)->getElementType(); 4865 else 4866 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4867 if (!X.isNull()) { 4868 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4869 Expr *Init = From->getInit(i); 4870 ImplicitConversionSequence ICS = 4871 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4872 InOverloadResolution, 4873 AllowObjCWritebackConversion); 4874 // If a single element isn't convertible, fail. 4875 if (ICS.isBad()) { 4876 Result = ICS; 4877 break; 4878 } 4879 // Otherwise, look for the worst conversion. 4880 if (Result.isBad() || CompareImplicitConversionSequences( 4881 S, From->getBeginLoc(), ICS, Result) == 4882 ImplicitConversionSequence::Worse) 4883 Result = ICS; 4884 } 4885 4886 // For an empty list, we won't have computed any conversion sequence. 4887 // Introduce the identity conversion sequence. 4888 if (From->getNumInits() == 0) { 4889 Result.setStandard(); 4890 Result.Standard.setAsIdentityConversion(); 4891 Result.Standard.setFromType(ToType); 4892 Result.Standard.setAllToTypes(ToType); 4893 } 4894 4895 Result.setStdInitializerListElement(toStdInitializerList); 4896 return Result; 4897 } 4898 4899 // C++14 [over.ics.list]p4: 4900 // C++11 [over.ics.list]p3: 4901 // Otherwise, if the parameter is a non-aggregate class X and overload 4902 // resolution chooses a single best constructor [...] the implicit 4903 // conversion sequence is a user-defined conversion sequence. If multiple 4904 // constructors are viable but none is better than the others, the 4905 // implicit conversion sequence is a user-defined conversion sequence. 4906 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4907 // This function can deal with initializer lists. 4908 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4909 /*AllowExplicit=*/false, 4910 InOverloadResolution, /*CStyle=*/false, 4911 AllowObjCWritebackConversion, 4912 /*AllowObjCConversionOnExplicit=*/false); 4913 } 4914 4915 // C++14 [over.ics.list]p5: 4916 // C++11 [over.ics.list]p4: 4917 // Otherwise, if the parameter has an aggregate type which can be 4918 // initialized from the initializer list [...] the implicit conversion 4919 // sequence is a user-defined conversion sequence. 4920 if (ToType->isAggregateType()) { 4921 // Type is an aggregate, argument is an init list. At this point it comes 4922 // down to checking whether the initialization works. 4923 // FIXME: Find out whether this parameter is consumed or not. 4924 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4925 // need to call into the initialization code here; overload resolution 4926 // should not be doing that. 4927 InitializedEntity Entity = 4928 InitializedEntity::InitializeParameter(S.Context, ToType, 4929 /*Consumed=*/false); 4930 if (S.CanPerformCopyInitialization(Entity, From)) { 4931 Result.setUserDefined(); 4932 Result.UserDefined.Before.setAsIdentityConversion(); 4933 // Initializer lists don't have a type. 4934 Result.UserDefined.Before.setFromType(QualType()); 4935 Result.UserDefined.Before.setAllToTypes(QualType()); 4936 4937 Result.UserDefined.After.setAsIdentityConversion(); 4938 Result.UserDefined.After.setFromType(ToType); 4939 Result.UserDefined.After.setAllToTypes(ToType); 4940 Result.UserDefined.ConversionFunction = nullptr; 4941 } 4942 return Result; 4943 } 4944 4945 // C++14 [over.ics.list]p6: 4946 // C++11 [over.ics.list]p5: 4947 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4948 if (ToType->isReferenceType()) { 4949 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4950 // mention initializer lists in any way. So we go by what list- 4951 // initialization would do and try to extrapolate from that. 4952 4953 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4954 4955 // If the initializer list has a single element that is reference-related 4956 // to the parameter type, we initialize the reference from that. 4957 if (From->getNumInits() == 1) { 4958 Expr *Init = From->getInit(0); 4959 4960 QualType T2 = Init->getType(); 4961 4962 // If the initializer is the address of an overloaded function, try 4963 // to resolve the overloaded function. If all goes well, T2 is the 4964 // type of the resulting function. 4965 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4966 DeclAccessPair Found; 4967 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4968 Init, ToType, false, Found)) 4969 T2 = Fn->getType(); 4970 } 4971 4972 // Compute some basic properties of the types and the initializer. 4973 bool dummy1 = false; 4974 bool dummy2 = false; 4975 bool dummy3 = false; 4976 Sema::ReferenceCompareResult RefRelationship = 4977 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4978 dummy2, dummy3); 4979 4980 if (RefRelationship >= Sema::Ref_Related) { 4981 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4982 SuppressUserConversions, 4983 /*AllowExplicit=*/false); 4984 } 4985 } 4986 4987 // Otherwise, we bind the reference to a temporary created from the 4988 // initializer list. 4989 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4990 InOverloadResolution, 4991 AllowObjCWritebackConversion); 4992 if (Result.isFailure()) 4993 return Result; 4994 assert(!Result.isEllipsis() && 4995 "Sub-initialization cannot result in ellipsis conversion."); 4996 4997 // Can we even bind to a temporary? 4998 if (ToType->isRValueReferenceType() || 4999 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5000 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5001 Result.UserDefined.After; 5002 SCS.ReferenceBinding = true; 5003 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5004 SCS.BindsToRvalue = true; 5005 SCS.BindsToFunctionLvalue = false; 5006 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5007 SCS.ObjCLifetimeConversionBinding = false; 5008 } else 5009 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5010 From, ToType); 5011 return Result; 5012 } 5013 5014 // C++14 [over.ics.list]p7: 5015 // C++11 [over.ics.list]p6: 5016 // Otherwise, if the parameter type is not a class: 5017 if (!ToType->isRecordType()) { 5018 // - if the initializer list has one element that is not itself an 5019 // initializer list, the implicit conversion sequence is the one 5020 // required to convert the element to the parameter type. 5021 unsigned NumInits = From->getNumInits(); 5022 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5023 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5024 SuppressUserConversions, 5025 InOverloadResolution, 5026 AllowObjCWritebackConversion); 5027 // - if the initializer list has no elements, the implicit conversion 5028 // sequence is the identity conversion. 5029 else if (NumInits == 0) { 5030 Result.setStandard(); 5031 Result.Standard.setAsIdentityConversion(); 5032 Result.Standard.setFromType(ToType); 5033 Result.Standard.setAllToTypes(ToType); 5034 } 5035 return Result; 5036 } 5037 5038 // C++14 [over.ics.list]p8: 5039 // C++11 [over.ics.list]p7: 5040 // In all cases other than those enumerated above, no conversion is possible 5041 return Result; 5042 } 5043 5044 /// TryCopyInitialization - Try to copy-initialize a value of type 5045 /// ToType from the expression From. Return the implicit conversion 5046 /// sequence required to pass this argument, which may be a bad 5047 /// conversion sequence (meaning that the argument cannot be passed to 5048 /// a parameter of this type). If @p SuppressUserConversions, then we 5049 /// do not permit any user-defined conversion sequences. 5050 static ImplicitConversionSequence 5051 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5052 bool SuppressUserConversions, 5053 bool InOverloadResolution, 5054 bool AllowObjCWritebackConversion, 5055 bool AllowExplicit) { 5056 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5057 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5058 InOverloadResolution,AllowObjCWritebackConversion); 5059 5060 if (ToType->isReferenceType()) 5061 return TryReferenceInit(S, From, ToType, 5062 /*FIXME:*/ From->getBeginLoc(), 5063 SuppressUserConversions, AllowExplicit); 5064 5065 return TryImplicitConversion(S, From, ToType, 5066 SuppressUserConversions, 5067 /*AllowExplicit=*/false, 5068 InOverloadResolution, 5069 /*CStyle=*/false, 5070 AllowObjCWritebackConversion, 5071 /*AllowObjCConversionOnExplicit=*/false); 5072 } 5073 5074 static bool TryCopyInitialization(const CanQualType FromQTy, 5075 const CanQualType ToQTy, 5076 Sema &S, 5077 SourceLocation Loc, 5078 ExprValueKind FromVK) { 5079 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5080 ImplicitConversionSequence ICS = 5081 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5082 5083 return !ICS.isBad(); 5084 } 5085 5086 /// TryObjectArgumentInitialization - Try to initialize the object 5087 /// parameter of the given member function (@c Method) from the 5088 /// expression @p From. 5089 static ImplicitConversionSequence 5090 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5091 Expr::Classification FromClassification, 5092 CXXMethodDecl *Method, 5093 CXXRecordDecl *ActingContext) { 5094 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5095 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5096 // const volatile object. 5097 Qualifiers Quals; 5098 if (isa<CXXDestructorDecl>(Method)) { 5099 Quals.addConst(); 5100 Quals.addVolatile(); 5101 } else { 5102 Quals = Method->getTypeQualifiers(); 5103 } 5104 5105 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5106 5107 // Set up the conversion sequence as a "bad" conversion, to allow us 5108 // to exit early. 5109 ImplicitConversionSequence ICS; 5110 5111 // We need to have an object of class type. 5112 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5113 FromType = PT->getPointeeType(); 5114 5115 // When we had a pointer, it's implicitly dereferenced, so we 5116 // better have an lvalue. 5117 assert(FromClassification.isLValue()); 5118 } 5119 5120 assert(FromType->isRecordType()); 5121 5122 // C++0x [over.match.funcs]p4: 5123 // For non-static member functions, the type of the implicit object 5124 // parameter is 5125 // 5126 // - "lvalue reference to cv X" for functions declared without a 5127 // ref-qualifier or with the & ref-qualifier 5128 // - "rvalue reference to cv X" for functions declared with the && 5129 // ref-qualifier 5130 // 5131 // where X is the class of which the function is a member and cv is the 5132 // cv-qualification on the member function declaration. 5133 // 5134 // However, when finding an implicit conversion sequence for the argument, we 5135 // are not allowed to perform user-defined conversions 5136 // (C++ [over.match.funcs]p5). We perform a simplified version of 5137 // reference binding here, that allows class rvalues to bind to 5138 // non-constant references. 5139 5140 // First check the qualifiers. 5141 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5142 if (ImplicitParamType.getCVRQualifiers() 5143 != FromTypeCanon.getLocalCVRQualifiers() && 5144 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5145 ICS.setBad(BadConversionSequence::bad_qualifiers, 5146 FromType, ImplicitParamType); 5147 return ICS; 5148 } 5149 5150 // Check that we have either the same type or a derived type. It 5151 // affects the conversion rank. 5152 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5153 ImplicitConversionKind SecondKind; 5154 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5155 SecondKind = ICK_Identity; 5156 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5157 SecondKind = ICK_Derived_To_Base; 5158 else { 5159 ICS.setBad(BadConversionSequence::unrelated_class, 5160 FromType, ImplicitParamType); 5161 return ICS; 5162 } 5163 5164 // Check the ref-qualifier. 5165 switch (Method->getRefQualifier()) { 5166 case RQ_None: 5167 // Do nothing; we don't care about lvalueness or rvalueness. 5168 break; 5169 5170 case RQ_LValue: 5171 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5172 // non-const lvalue reference cannot bind to an rvalue 5173 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5174 ImplicitParamType); 5175 return ICS; 5176 } 5177 break; 5178 5179 case RQ_RValue: 5180 if (!FromClassification.isRValue()) { 5181 // rvalue reference cannot bind to an lvalue 5182 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5183 ImplicitParamType); 5184 return ICS; 5185 } 5186 break; 5187 } 5188 5189 // Success. Mark this as a reference binding. 5190 ICS.setStandard(); 5191 ICS.Standard.setAsIdentityConversion(); 5192 ICS.Standard.Second = SecondKind; 5193 ICS.Standard.setFromType(FromType); 5194 ICS.Standard.setAllToTypes(ImplicitParamType); 5195 ICS.Standard.ReferenceBinding = true; 5196 ICS.Standard.DirectBinding = true; 5197 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5198 ICS.Standard.BindsToFunctionLvalue = false; 5199 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5200 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5201 = (Method->getRefQualifier() == RQ_None); 5202 return ICS; 5203 } 5204 5205 /// PerformObjectArgumentInitialization - Perform initialization of 5206 /// the implicit object parameter for the given Method with the given 5207 /// expression. 5208 ExprResult 5209 Sema::PerformObjectArgumentInitialization(Expr *From, 5210 NestedNameSpecifier *Qualifier, 5211 NamedDecl *FoundDecl, 5212 CXXMethodDecl *Method) { 5213 QualType FromRecordType, DestType; 5214 QualType ImplicitParamRecordType = 5215 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5216 5217 Expr::Classification FromClassification; 5218 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5219 FromRecordType = PT->getPointeeType(); 5220 DestType = Method->getThisType(Context); 5221 FromClassification = Expr::Classification::makeSimpleLValue(); 5222 } else { 5223 FromRecordType = From->getType(); 5224 DestType = ImplicitParamRecordType; 5225 FromClassification = From->Classify(Context); 5226 5227 // When performing member access on an rvalue, materialize a temporary. 5228 if (From->isRValue()) { 5229 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5230 Method->getRefQualifier() != 5231 RefQualifierKind::RQ_RValue); 5232 } 5233 } 5234 5235 // Note that we always use the true parent context when performing 5236 // the actual argument initialization. 5237 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5238 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5239 Method->getParent()); 5240 if (ICS.isBad()) { 5241 switch (ICS.Bad.Kind) { 5242 case BadConversionSequence::bad_qualifiers: { 5243 Qualifiers FromQs = FromRecordType.getQualifiers(); 5244 Qualifiers ToQs = DestType.getQualifiers(); 5245 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5246 if (CVR) { 5247 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5248 << Method->getDeclName() << FromRecordType << (CVR - 1) 5249 << From->getSourceRange(); 5250 Diag(Method->getLocation(), diag::note_previous_decl) 5251 << Method->getDeclName(); 5252 return ExprError(); 5253 } 5254 break; 5255 } 5256 5257 case BadConversionSequence::lvalue_ref_to_rvalue: 5258 case BadConversionSequence::rvalue_ref_to_lvalue: { 5259 bool IsRValueQualified = 5260 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5261 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5262 << Method->getDeclName() << FromClassification.isRValue() 5263 << IsRValueQualified; 5264 Diag(Method->getLocation(), diag::note_previous_decl) 5265 << Method->getDeclName(); 5266 return ExprError(); 5267 } 5268 5269 case BadConversionSequence::no_conversion: 5270 case BadConversionSequence::unrelated_class: 5271 break; 5272 } 5273 5274 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5275 << ImplicitParamRecordType << FromRecordType 5276 << From->getSourceRange(); 5277 } 5278 5279 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5280 ExprResult FromRes = 5281 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5282 if (FromRes.isInvalid()) 5283 return ExprError(); 5284 From = FromRes.get(); 5285 } 5286 5287 if (!Context.hasSameType(From->getType(), DestType)) { 5288 if (From->getType().getAddressSpace() != DestType.getAddressSpace()) 5289 From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion, 5290 From->getValueKind()).get(); 5291 else 5292 From = ImpCastExprToType(From, DestType, CK_NoOp, 5293 From->getValueKind()).get(); 5294 } 5295 return From; 5296 } 5297 5298 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5299 /// expression From to bool (C++0x [conv]p3). 5300 static ImplicitConversionSequence 5301 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5302 return TryImplicitConversion(S, From, S.Context.BoolTy, 5303 /*SuppressUserConversions=*/false, 5304 /*AllowExplicit=*/true, 5305 /*InOverloadResolution=*/false, 5306 /*CStyle=*/false, 5307 /*AllowObjCWritebackConversion=*/false, 5308 /*AllowObjCConversionOnExplicit=*/false); 5309 } 5310 5311 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5312 /// of the expression From to bool (C++0x [conv]p3). 5313 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5314 if (checkPlaceholderForOverload(*this, From)) 5315 return ExprError(); 5316 5317 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5318 if (!ICS.isBad()) 5319 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5320 5321 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5322 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5323 << From->getType() << From->getSourceRange(); 5324 return ExprError(); 5325 } 5326 5327 /// Check that the specified conversion is permitted in a converted constant 5328 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5329 /// is acceptable. 5330 static bool CheckConvertedConstantConversions(Sema &S, 5331 StandardConversionSequence &SCS) { 5332 // Since we know that the target type is an integral or unscoped enumeration 5333 // type, most conversion kinds are impossible. All possible First and Third 5334 // conversions are fine. 5335 switch (SCS.Second) { 5336 case ICK_Identity: 5337 case ICK_Function_Conversion: 5338 case ICK_Integral_Promotion: 5339 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5340 case ICK_Zero_Queue_Conversion: 5341 return true; 5342 5343 case ICK_Boolean_Conversion: 5344 // Conversion from an integral or unscoped enumeration type to bool is 5345 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5346 // conversion, so we allow it in a converted constant expression. 5347 // 5348 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5349 // a lot of popular code. We should at least add a warning for this 5350 // (non-conforming) extension. 5351 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5352 SCS.getToType(2)->isBooleanType(); 5353 5354 case ICK_Pointer_Conversion: 5355 case ICK_Pointer_Member: 5356 // C++1z: null pointer conversions and null member pointer conversions are 5357 // only permitted if the source type is std::nullptr_t. 5358 return SCS.getFromType()->isNullPtrType(); 5359 5360 case ICK_Floating_Promotion: 5361 case ICK_Complex_Promotion: 5362 case ICK_Floating_Conversion: 5363 case ICK_Complex_Conversion: 5364 case ICK_Floating_Integral: 5365 case ICK_Compatible_Conversion: 5366 case ICK_Derived_To_Base: 5367 case ICK_Vector_Conversion: 5368 case ICK_Vector_Splat: 5369 case ICK_Complex_Real: 5370 case ICK_Block_Pointer_Conversion: 5371 case ICK_TransparentUnionConversion: 5372 case ICK_Writeback_Conversion: 5373 case ICK_Zero_Event_Conversion: 5374 case ICK_C_Only_Conversion: 5375 case ICK_Incompatible_Pointer_Conversion: 5376 return false; 5377 5378 case ICK_Lvalue_To_Rvalue: 5379 case ICK_Array_To_Pointer: 5380 case ICK_Function_To_Pointer: 5381 llvm_unreachable("found a first conversion kind in Second"); 5382 5383 case ICK_Qualification: 5384 llvm_unreachable("found a third conversion kind in Second"); 5385 5386 case ICK_Num_Conversion_Kinds: 5387 break; 5388 } 5389 5390 llvm_unreachable("unknown conversion kind"); 5391 } 5392 5393 /// CheckConvertedConstantExpression - Check that the expression From is a 5394 /// converted constant expression of type T, perform the conversion and produce 5395 /// the converted expression, per C++11 [expr.const]p3. 5396 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5397 QualType T, APValue &Value, 5398 Sema::CCEKind CCE, 5399 bool RequireInt) { 5400 assert(S.getLangOpts().CPlusPlus11 && 5401 "converted constant expression outside C++11"); 5402 5403 if (checkPlaceholderForOverload(S, From)) 5404 return ExprError(); 5405 5406 // C++1z [expr.const]p3: 5407 // A converted constant expression of type T is an expression, 5408 // implicitly converted to type T, where the converted 5409 // expression is a constant expression and the implicit conversion 5410 // sequence contains only [... list of conversions ...]. 5411 // C++1z [stmt.if]p2: 5412 // If the if statement is of the form if constexpr, the value of the 5413 // condition shall be a contextually converted constant expression of type 5414 // bool. 5415 ImplicitConversionSequence ICS = 5416 CCE == Sema::CCEK_ConstexprIf 5417 ? TryContextuallyConvertToBool(S, From) 5418 : TryCopyInitialization(S, From, T, 5419 /*SuppressUserConversions=*/false, 5420 /*InOverloadResolution=*/false, 5421 /*AllowObjcWritebackConversion=*/false, 5422 /*AllowExplicit=*/false); 5423 StandardConversionSequence *SCS = nullptr; 5424 switch (ICS.getKind()) { 5425 case ImplicitConversionSequence::StandardConversion: 5426 SCS = &ICS.Standard; 5427 break; 5428 case ImplicitConversionSequence::UserDefinedConversion: 5429 // We are converting to a non-class type, so the Before sequence 5430 // must be trivial. 5431 SCS = &ICS.UserDefined.After; 5432 break; 5433 case ImplicitConversionSequence::AmbiguousConversion: 5434 case ImplicitConversionSequence::BadConversion: 5435 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5436 return S.Diag(From->getBeginLoc(), 5437 diag::err_typecheck_converted_constant_expression) 5438 << From->getType() << From->getSourceRange() << T; 5439 return ExprError(); 5440 5441 case ImplicitConversionSequence::EllipsisConversion: 5442 llvm_unreachable("ellipsis conversion in converted constant expression"); 5443 } 5444 5445 // Check that we would only use permitted conversions. 5446 if (!CheckConvertedConstantConversions(S, *SCS)) { 5447 return S.Diag(From->getBeginLoc(), 5448 diag::err_typecheck_converted_constant_expression_disallowed) 5449 << From->getType() << From->getSourceRange() << T; 5450 } 5451 // [...] and where the reference binding (if any) binds directly. 5452 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5453 return S.Diag(From->getBeginLoc(), 5454 diag::err_typecheck_converted_constant_expression_indirect) 5455 << From->getType() << From->getSourceRange() << T; 5456 } 5457 5458 ExprResult Result = 5459 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5460 if (Result.isInvalid()) 5461 return Result; 5462 5463 // Check for a narrowing implicit conversion. 5464 APValue PreNarrowingValue; 5465 QualType PreNarrowingType; 5466 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5467 PreNarrowingType)) { 5468 case NK_Dependent_Narrowing: 5469 // Implicit conversion to a narrower type, but the expression is 5470 // value-dependent so we can't tell whether it's actually narrowing. 5471 case NK_Variable_Narrowing: 5472 // Implicit conversion to a narrower type, and the value is not a constant 5473 // expression. We'll diagnose this in a moment. 5474 case NK_Not_Narrowing: 5475 break; 5476 5477 case NK_Constant_Narrowing: 5478 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5479 << CCE << /*Constant*/ 1 5480 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5481 break; 5482 5483 case NK_Type_Narrowing: 5484 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5485 << CCE << /*Constant*/ 0 << From->getType() << T; 5486 break; 5487 } 5488 5489 if (Result.get()->isValueDependent()) { 5490 Value = APValue(); 5491 return Result; 5492 } 5493 5494 // Check the expression is a constant expression. 5495 SmallVector<PartialDiagnosticAt, 8> Notes; 5496 Expr::EvalResult Eval; 5497 Eval.Diag = &Notes; 5498 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5499 ? Expr::EvaluateForMangling 5500 : Expr::EvaluateForCodeGen; 5501 5502 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5503 (RequireInt && !Eval.Val.isInt())) { 5504 // The expression can't be folded, so we can't keep it at this position in 5505 // the AST. 5506 Result = ExprError(); 5507 } else { 5508 Value = Eval.Val; 5509 5510 if (Notes.empty()) { 5511 // It's a constant expression. 5512 return ConstantExpr::Create(S.Context, Result.get()); 5513 } 5514 } 5515 5516 // It's not a constant expression. Produce an appropriate diagnostic. 5517 if (Notes.size() == 1 && 5518 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5519 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5520 else { 5521 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5522 << CCE << From->getSourceRange(); 5523 for (unsigned I = 0; I < Notes.size(); ++I) 5524 S.Diag(Notes[I].first, Notes[I].second); 5525 } 5526 return ExprError(); 5527 } 5528 5529 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5530 APValue &Value, CCEKind CCE) { 5531 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5532 } 5533 5534 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5535 llvm::APSInt &Value, 5536 CCEKind CCE) { 5537 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5538 5539 APValue V; 5540 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5541 if (!R.isInvalid() && !R.get()->isValueDependent()) 5542 Value = V.getInt(); 5543 return R; 5544 } 5545 5546 5547 /// dropPointerConversions - If the given standard conversion sequence 5548 /// involves any pointer conversions, remove them. This may change 5549 /// the result type of the conversion sequence. 5550 static void dropPointerConversion(StandardConversionSequence &SCS) { 5551 if (SCS.Second == ICK_Pointer_Conversion) { 5552 SCS.Second = ICK_Identity; 5553 SCS.Third = ICK_Identity; 5554 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5555 } 5556 } 5557 5558 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5559 /// convert the expression From to an Objective-C pointer type. 5560 static ImplicitConversionSequence 5561 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5562 // Do an implicit conversion to 'id'. 5563 QualType Ty = S.Context.getObjCIdType(); 5564 ImplicitConversionSequence ICS 5565 = TryImplicitConversion(S, From, Ty, 5566 // FIXME: Are these flags correct? 5567 /*SuppressUserConversions=*/false, 5568 /*AllowExplicit=*/true, 5569 /*InOverloadResolution=*/false, 5570 /*CStyle=*/false, 5571 /*AllowObjCWritebackConversion=*/false, 5572 /*AllowObjCConversionOnExplicit=*/true); 5573 5574 // Strip off any final conversions to 'id'. 5575 switch (ICS.getKind()) { 5576 case ImplicitConversionSequence::BadConversion: 5577 case ImplicitConversionSequence::AmbiguousConversion: 5578 case ImplicitConversionSequence::EllipsisConversion: 5579 break; 5580 5581 case ImplicitConversionSequence::UserDefinedConversion: 5582 dropPointerConversion(ICS.UserDefined.After); 5583 break; 5584 5585 case ImplicitConversionSequence::StandardConversion: 5586 dropPointerConversion(ICS.Standard); 5587 break; 5588 } 5589 5590 return ICS; 5591 } 5592 5593 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5594 /// conversion of the expression From to an Objective-C pointer type. 5595 /// Returns a valid but null ExprResult if no conversion sequence exists. 5596 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5597 if (checkPlaceholderForOverload(*this, From)) 5598 return ExprError(); 5599 5600 QualType Ty = Context.getObjCIdType(); 5601 ImplicitConversionSequence ICS = 5602 TryContextuallyConvertToObjCPointer(*this, From); 5603 if (!ICS.isBad()) 5604 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5605 return ExprResult(); 5606 } 5607 5608 /// Determine whether the provided type is an integral type, or an enumeration 5609 /// type of a permitted flavor. 5610 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5611 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5612 : T->isIntegralOrUnscopedEnumerationType(); 5613 } 5614 5615 static ExprResult 5616 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5617 Sema::ContextualImplicitConverter &Converter, 5618 QualType T, UnresolvedSetImpl &ViableConversions) { 5619 5620 if (Converter.Suppress) 5621 return ExprError(); 5622 5623 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5624 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5625 CXXConversionDecl *Conv = 5626 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5627 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5628 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5629 } 5630 return From; 5631 } 5632 5633 static bool 5634 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5635 Sema::ContextualImplicitConverter &Converter, 5636 QualType T, bool HadMultipleCandidates, 5637 UnresolvedSetImpl &ExplicitConversions) { 5638 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5639 DeclAccessPair Found = ExplicitConversions[0]; 5640 CXXConversionDecl *Conversion = 5641 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5642 5643 // The user probably meant to invoke the given explicit 5644 // conversion; use it. 5645 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5646 std::string TypeStr; 5647 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5648 5649 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5650 << FixItHint::CreateInsertion(From->getBeginLoc(), 5651 "static_cast<" + TypeStr + ">(") 5652 << FixItHint::CreateInsertion( 5653 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5654 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5655 5656 // If we aren't in a SFINAE context, build a call to the 5657 // explicit conversion function. 5658 if (SemaRef.isSFINAEContext()) 5659 return true; 5660 5661 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5662 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5663 HadMultipleCandidates); 5664 if (Result.isInvalid()) 5665 return true; 5666 // Record usage of conversion in an implicit cast. 5667 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5668 CK_UserDefinedConversion, Result.get(), 5669 nullptr, Result.get()->getValueKind()); 5670 } 5671 return false; 5672 } 5673 5674 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5675 Sema::ContextualImplicitConverter &Converter, 5676 QualType T, bool HadMultipleCandidates, 5677 DeclAccessPair &Found) { 5678 CXXConversionDecl *Conversion = 5679 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5680 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5681 5682 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5683 if (!Converter.SuppressConversion) { 5684 if (SemaRef.isSFINAEContext()) 5685 return true; 5686 5687 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5688 << From->getSourceRange(); 5689 } 5690 5691 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5692 HadMultipleCandidates); 5693 if (Result.isInvalid()) 5694 return true; 5695 // Record usage of conversion in an implicit cast. 5696 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5697 CK_UserDefinedConversion, Result.get(), 5698 nullptr, Result.get()->getValueKind()); 5699 return false; 5700 } 5701 5702 static ExprResult finishContextualImplicitConversion( 5703 Sema &SemaRef, SourceLocation Loc, Expr *From, 5704 Sema::ContextualImplicitConverter &Converter) { 5705 if (!Converter.match(From->getType()) && !Converter.Suppress) 5706 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5707 << From->getSourceRange(); 5708 5709 return SemaRef.DefaultLvalueConversion(From); 5710 } 5711 5712 static void 5713 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5714 UnresolvedSetImpl &ViableConversions, 5715 OverloadCandidateSet &CandidateSet) { 5716 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5717 DeclAccessPair FoundDecl = ViableConversions[I]; 5718 NamedDecl *D = FoundDecl.getDecl(); 5719 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5720 if (isa<UsingShadowDecl>(D)) 5721 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5722 5723 CXXConversionDecl *Conv; 5724 FunctionTemplateDecl *ConvTemplate; 5725 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5726 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5727 else 5728 Conv = cast<CXXConversionDecl>(D); 5729 5730 if (ConvTemplate) 5731 SemaRef.AddTemplateConversionCandidate( 5732 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5733 /*AllowObjCConversionOnExplicit=*/false); 5734 else 5735 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5736 ToType, CandidateSet, 5737 /*AllowObjCConversionOnExplicit=*/false); 5738 } 5739 } 5740 5741 /// Attempt to convert the given expression to a type which is accepted 5742 /// by the given converter. 5743 /// 5744 /// This routine will attempt to convert an expression of class type to a 5745 /// type accepted by the specified converter. In C++11 and before, the class 5746 /// must have a single non-explicit conversion function converting to a matching 5747 /// type. In C++1y, there can be multiple such conversion functions, but only 5748 /// one target type. 5749 /// 5750 /// \param Loc The source location of the construct that requires the 5751 /// conversion. 5752 /// 5753 /// \param From The expression we're converting from. 5754 /// 5755 /// \param Converter Used to control and diagnose the conversion process. 5756 /// 5757 /// \returns The expression, converted to an integral or enumeration type if 5758 /// successful. 5759 ExprResult Sema::PerformContextualImplicitConversion( 5760 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5761 // We can't perform any more checking for type-dependent expressions. 5762 if (From->isTypeDependent()) 5763 return From; 5764 5765 // Process placeholders immediately. 5766 if (From->hasPlaceholderType()) { 5767 ExprResult result = CheckPlaceholderExpr(From); 5768 if (result.isInvalid()) 5769 return result; 5770 From = result.get(); 5771 } 5772 5773 // If the expression already has a matching type, we're golden. 5774 QualType T = From->getType(); 5775 if (Converter.match(T)) 5776 return DefaultLvalueConversion(From); 5777 5778 // FIXME: Check for missing '()' if T is a function type? 5779 5780 // We can only perform contextual implicit conversions on objects of class 5781 // type. 5782 const RecordType *RecordTy = T->getAs<RecordType>(); 5783 if (!RecordTy || !getLangOpts().CPlusPlus) { 5784 if (!Converter.Suppress) 5785 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5786 return From; 5787 } 5788 5789 // We must have a complete class type. 5790 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5791 ContextualImplicitConverter &Converter; 5792 Expr *From; 5793 5794 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5795 : Converter(Converter), From(From) {} 5796 5797 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5798 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5799 } 5800 } IncompleteDiagnoser(Converter, From); 5801 5802 if (Converter.Suppress ? !isCompleteType(Loc, T) 5803 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5804 return From; 5805 5806 // Look for a conversion to an integral or enumeration type. 5807 UnresolvedSet<4> 5808 ViableConversions; // These are *potentially* viable in C++1y. 5809 UnresolvedSet<4> ExplicitConversions; 5810 const auto &Conversions = 5811 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5812 5813 bool HadMultipleCandidates = 5814 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5815 5816 // To check that there is only one target type, in C++1y: 5817 QualType ToType; 5818 bool HasUniqueTargetType = true; 5819 5820 // Collect explicit or viable (potentially in C++1y) conversions. 5821 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5822 NamedDecl *D = (*I)->getUnderlyingDecl(); 5823 CXXConversionDecl *Conversion; 5824 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5825 if (ConvTemplate) { 5826 if (getLangOpts().CPlusPlus14) 5827 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5828 else 5829 continue; // C++11 does not consider conversion operator templates(?). 5830 } else 5831 Conversion = cast<CXXConversionDecl>(D); 5832 5833 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5834 "Conversion operator templates are considered potentially " 5835 "viable in C++1y"); 5836 5837 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5838 if (Converter.match(CurToType) || ConvTemplate) { 5839 5840 if (Conversion->isExplicit()) { 5841 // FIXME: For C++1y, do we need this restriction? 5842 // cf. diagnoseNoViableConversion() 5843 if (!ConvTemplate) 5844 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5845 } else { 5846 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5847 if (ToType.isNull()) 5848 ToType = CurToType.getUnqualifiedType(); 5849 else if (HasUniqueTargetType && 5850 (CurToType.getUnqualifiedType() != ToType)) 5851 HasUniqueTargetType = false; 5852 } 5853 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5854 } 5855 } 5856 } 5857 5858 if (getLangOpts().CPlusPlus14) { 5859 // C++1y [conv]p6: 5860 // ... An expression e of class type E appearing in such a context 5861 // is said to be contextually implicitly converted to a specified 5862 // type T and is well-formed if and only if e can be implicitly 5863 // converted to a type T that is determined as follows: E is searched 5864 // for conversion functions whose return type is cv T or reference to 5865 // cv T such that T is allowed by the context. There shall be 5866 // exactly one such T. 5867 5868 // If no unique T is found: 5869 if (ToType.isNull()) { 5870 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5871 HadMultipleCandidates, 5872 ExplicitConversions)) 5873 return ExprError(); 5874 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5875 } 5876 5877 // If more than one unique Ts are found: 5878 if (!HasUniqueTargetType) 5879 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5880 ViableConversions); 5881 5882 // If one unique T is found: 5883 // First, build a candidate set from the previously recorded 5884 // potentially viable conversions. 5885 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5886 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5887 CandidateSet); 5888 5889 // Then, perform overload resolution over the candidate set. 5890 OverloadCandidateSet::iterator Best; 5891 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5892 case OR_Success: { 5893 // Apply this conversion. 5894 DeclAccessPair Found = 5895 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5896 if (recordConversion(*this, Loc, From, Converter, T, 5897 HadMultipleCandidates, Found)) 5898 return ExprError(); 5899 break; 5900 } 5901 case OR_Ambiguous: 5902 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5903 ViableConversions); 5904 case OR_No_Viable_Function: 5905 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5906 HadMultipleCandidates, 5907 ExplicitConversions)) 5908 return ExprError(); 5909 LLVM_FALLTHROUGH; 5910 case OR_Deleted: 5911 // We'll complain below about a non-integral condition type. 5912 break; 5913 } 5914 } else { 5915 switch (ViableConversions.size()) { 5916 case 0: { 5917 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5918 HadMultipleCandidates, 5919 ExplicitConversions)) 5920 return ExprError(); 5921 5922 // We'll complain below about a non-integral condition type. 5923 break; 5924 } 5925 case 1: { 5926 // Apply this conversion. 5927 DeclAccessPair Found = ViableConversions[0]; 5928 if (recordConversion(*this, Loc, From, Converter, T, 5929 HadMultipleCandidates, Found)) 5930 return ExprError(); 5931 break; 5932 } 5933 default: 5934 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5935 ViableConversions); 5936 } 5937 } 5938 5939 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5940 } 5941 5942 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5943 /// an acceptable non-member overloaded operator for a call whose 5944 /// arguments have types T1 (and, if non-empty, T2). This routine 5945 /// implements the check in C++ [over.match.oper]p3b2 concerning 5946 /// enumeration types. 5947 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5948 FunctionDecl *Fn, 5949 ArrayRef<Expr *> Args) { 5950 QualType T1 = Args[0]->getType(); 5951 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5952 5953 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5954 return true; 5955 5956 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5957 return true; 5958 5959 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5960 if (Proto->getNumParams() < 1) 5961 return false; 5962 5963 if (T1->isEnumeralType()) { 5964 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5965 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5966 return true; 5967 } 5968 5969 if (Proto->getNumParams() < 2) 5970 return false; 5971 5972 if (!T2.isNull() && T2->isEnumeralType()) { 5973 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5974 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5975 return true; 5976 } 5977 5978 return false; 5979 } 5980 5981 /// AddOverloadCandidate - Adds the given function to the set of 5982 /// candidate functions, using the given function call arguments. If 5983 /// @p SuppressUserConversions, then don't allow user-defined 5984 /// conversions via constructors or conversion operators. 5985 /// 5986 /// \param PartialOverloading true if we are performing "partial" overloading 5987 /// based on an incomplete set of function arguments. This feature is used by 5988 /// code completion. 5989 void Sema::AddOverloadCandidate(FunctionDecl *Function, 5990 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 5991 OverloadCandidateSet &CandidateSet, 5992 bool SuppressUserConversions, 5993 bool PartialOverloading, bool AllowExplicit, 5994 ADLCallKind IsADLCandidate, 5995 ConversionSequenceList EarlyConversions) { 5996 const FunctionProtoType *Proto 5997 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5998 assert(Proto && "Functions without a prototype cannot be overloaded"); 5999 assert(!Function->getDescribedFunctionTemplate() && 6000 "Use AddTemplateOverloadCandidate for function templates"); 6001 6002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6003 if (!isa<CXXConstructorDecl>(Method)) { 6004 // If we get here, it's because we're calling a member function 6005 // that is named without a member access expression (e.g., 6006 // "this->f") that was either written explicitly or created 6007 // implicitly. This can happen with a qualified call to a member 6008 // function, e.g., X::f(). We use an empty type for the implied 6009 // object argument (C++ [over.call.func]p3), and the acting context 6010 // is irrelevant. 6011 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6012 Expr::Classification::makeSimpleLValue(), Args, 6013 CandidateSet, SuppressUserConversions, 6014 PartialOverloading, EarlyConversions); 6015 return; 6016 } 6017 // We treat a constructor like a non-member function, since its object 6018 // argument doesn't participate in overload resolution. 6019 } 6020 6021 if (!CandidateSet.isNewCandidate(Function)) 6022 return; 6023 6024 // C++ [over.match.oper]p3: 6025 // if no operand has a class type, only those non-member functions in the 6026 // lookup set that have a first parameter of type T1 or "reference to 6027 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6028 // is a right operand) a second parameter of type T2 or "reference to 6029 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6030 // candidate functions. 6031 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6032 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6033 return; 6034 6035 // C++11 [class.copy]p11: [DR1402] 6036 // A defaulted move constructor that is defined as deleted is ignored by 6037 // overload resolution. 6038 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6039 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6040 Constructor->isMoveConstructor()) 6041 return; 6042 6043 // Overload resolution is always an unevaluated context. 6044 EnterExpressionEvaluationContext Unevaluated( 6045 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6046 6047 // Add this candidate 6048 OverloadCandidate &Candidate = 6049 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6050 Candidate.FoundDecl = FoundDecl; 6051 Candidate.Function = Function; 6052 Candidate.Viable = true; 6053 Candidate.IsSurrogate = false; 6054 Candidate.IsADLCandidate = IsADLCandidate; 6055 Candidate.IgnoreObjectArgument = false; 6056 Candidate.ExplicitCallArguments = Args.size(); 6057 6058 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6059 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6060 Candidate.Viable = false; 6061 Candidate.FailureKind = ovl_non_default_multiversion_function; 6062 return; 6063 } 6064 6065 if (Constructor) { 6066 // C++ [class.copy]p3: 6067 // A member function template is never instantiated to perform the copy 6068 // of a class object to an object of its class type. 6069 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6070 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6071 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6072 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6073 ClassType))) { 6074 Candidate.Viable = false; 6075 Candidate.FailureKind = ovl_fail_illegal_constructor; 6076 return; 6077 } 6078 6079 // C++ [over.match.funcs]p8: (proposed DR resolution) 6080 // A constructor inherited from class type C that has a first parameter 6081 // of type "reference to P" (including such a constructor instantiated 6082 // from a template) is excluded from the set of candidate functions when 6083 // constructing an object of type cv D if the argument list has exactly 6084 // one argument and D is reference-related to P and P is reference-related 6085 // to C. 6086 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6087 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6088 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6089 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6090 QualType C = Context.getRecordType(Constructor->getParent()); 6091 QualType D = Context.getRecordType(Shadow->getParent()); 6092 SourceLocation Loc = Args.front()->getExprLoc(); 6093 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6094 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6095 Candidate.Viable = false; 6096 Candidate.FailureKind = ovl_fail_inhctor_slice; 6097 return; 6098 } 6099 } 6100 } 6101 6102 unsigned NumParams = Proto->getNumParams(); 6103 6104 // (C++ 13.3.2p2): A candidate function having fewer than m 6105 // parameters is viable only if it has an ellipsis in its parameter 6106 // list (8.3.5). 6107 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6108 !Proto->isVariadic()) { 6109 Candidate.Viable = false; 6110 Candidate.FailureKind = ovl_fail_too_many_arguments; 6111 return; 6112 } 6113 6114 // (C++ 13.3.2p2): A candidate function having more than m parameters 6115 // is viable only if the (m+1)st parameter has a default argument 6116 // (8.3.6). For the purposes of overload resolution, the 6117 // parameter list is truncated on the right, so that there are 6118 // exactly m parameters. 6119 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6120 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6121 // Not enough arguments. 6122 Candidate.Viable = false; 6123 Candidate.FailureKind = ovl_fail_too_few_arguments; 6124 return; 6125 } 6126 6127 // (CUDA B.1): Check for invalid calls between targets. 6128 if (getLangOpts().CUDA) 6129 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6130 // Skip the check for callers that are implicit members, because in this 6131 // case we may not yet know what the member's target is; the target is 6132 // inferred for the member automatically, based on the bases and fields of 6133 // the class. 6134 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6135 Candidate.Viable = false; 6136 Candidate.FailureKind = ovl_fail_bad_target; 6137 return; 6138 } 6139 6140 // Determine the implicit conversion sequences for each of the 6141 // arguments. 6142 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6143 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6144 // We already formed a conversion sequence for this parameter during 6145 // template argument deduction. 6146 } else if (ArgIdx < NumParams) { 6147 // (C++ 13.3.2p3): for F to be a viable function, there shall 6148 // exist for each argument an implicit conversion sequence 6149 // (13.3.3.1) that converts that argument to the corresponding 6150 // parameter of F. 6151 QualType ParamType = Proto->getParamType(ArgIdx); 6152 Candidate.Conversions[ArgIdx] 6153 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6154 SuppressUserConversions, 6155 /*InOverloadResolution=*/true, 6156 /*AllowObjCWritebackConversion=*/ 6157 getLangOpts().ObjCAutoRefCount, 6158 AllowExplicit); 6159 if (Candidate.Conversions[ArgIdx].isBad()) { 6160 Candidate.Viable = false; 6161 Candidate.FailureKind = ovl_fail_bad_conversion; 6162 return; 6163 } 6164 } else { 6165 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6166 // argument for which there is no corresponding parameter is 6167 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6168 Candidate.Conversions[ArgIdx].setEllipsis(); 6169 } 6170 } 6171 6172 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6173 Candidate.Viable = false; 6174 Candidate.FailureKind = ovl_fail_enable_if; 6175 Candidate.DeductionFailure.Data = FailedAttr; 6176 return; 6177 } 6178 6179 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6180 Candidate.Viable = false; 6181 Candidate.FailureKind = ovl_fail_ext_disabled; 6182 return; 6183 } 6184 } 6185 6186 ObjCMethodDecl * 6187 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6188 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6189 if (Methods.size() <= 1) 6190 return nullptr; 6191 6192 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6193 bool Match = true; 6194 ObjCMethodDecl *Method = Methods[b]; 6195 unsigned NumNamedArgs = Sel.getNumArgs(); 6196 // Method might have more arguments than selector indicates. This is due 6197 // to addition of c-style arguments in method. 6198 if (Method->param_size() > NumNamedArgs) 6199 NumNamedArgs = Method->param_size(); 6200 if (Args.size() < NumNamedArgs) 6201 continue; 6202 6203 for (unsigned i = 0; i < NumNamedArgs; i++) { 6204 // We can't do any type-checking on a type-dependent argument. 6205 if (Args[i]->isTypeDependent()) { 6206 Match = false; 6207 break; 6208 } 6209 6210 ParmVarDecl *param = Method->parameters()[i]; 6211 Expr *argExpr = Args[i]; 6212 assert(argExpr && "SelectBestMethod(): missing expression"); 6213 6214 // Strip the unbridged-cast placeholder expression off unless it's 6215 // a consumed argument. 6216 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6217 !param->hasAttr<CFConsumedAttr>()) 6218 argExpr = stripARCUnbridgedCast(argExpr); 6219 6220 // If the parameter is __unknown_anytype, move on to the next method. 6221 if (param->getType() == Context.UnknownAnyTy) { 6222 Match = false; 6223 break; 6224 } 6225 6226 ImplicitConversionSequence ConversionState 6227 = TryCopyInitialization(*this, argExpr, param->getType(), 6228 /*SuppressUserConversions*/false, 6229 /*InOverloadResolution=*/true, 6230 /*AllowObjCWritebackConversion=*/ 6231 getLangOpts().ObjCAutoRefCount, 6232 /*AllowExplicit*/false); 6233 // This function looks for a reasonably-exact match, so we consider 6234 // incompatible pointer conversions to be a failure here. 6235 if (ConversionState.isBad() || 6236 (ConversionState.isStandard() && 6237 ConversionState.Standard.Second == 6238 ICK_Incompatible_Pointer_Conversion)) { 6239 Match = false; 6240 break; 6241 } 6242 } 6243 // Promote additional arguments to variadic methods. 6244 if (Match && Method->isVariadic()) { 6245 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6246 if (Args[i]->isTypeDependent()) { 6247 Match = false; 6248 break; 6249 } 6250 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6251 nullptr); 6252 if (Arg.isInvalid()) { 6253 Match = false; 6254 break; 6255 } 6256 } 6257 } else { 6258 // Check for extra arguments to non-variadic methods. 6259 if (Args.size() != NumNamedArgs) 6260 Match = false; 6261 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6262 // Special case when selectors have no argument. In this case, select 6263 // one with the most general result type of 'id'. 6264 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6265 QualType ReturnT = Methods[b]->getReturnType(); 6266 if (ReturnT->isObjCIdType()) 6267 return Methods[b]; 6268 } 6269 } 6270 } 6271 6272 if (Match) 6273 return Method; 6274 } 6275 return nullptr; 6276 } 6277 6278 static bool 6279 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6280 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6281 bool MissingImplicitThis, Expr *&ConvertedThis, 6282 SmallVectorImpl<Expr *> &ConvertedArgs) { 6283 if (ThisArg) { 6284 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6285 assert(!isa<CXXConstructorDecl>(Method) && 6286 "Shouldn't have `this` for ctors!"); 6287 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6288 ExprResult R = S.PerformObjectArgumentInitialization( 6289 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6290 if (R.isInvalid()) 6291 return false; 6292 ConvertedThis = R.get(); 6293 } else { 6294 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6295 (void)MD; 6296 assert((MissingImplicitThis || MD->isStatic() || 6297 isa<CXXConstructorDecl>(MD)) && 6298 "Expected `this` for non-ctor instance methods"); 6299 } 6300 ConvertedThis = nullptr; 6301 } 6302 6303 // Ignore any variadic arguments. Converting them is pointless, since the 6304 // user can't refer to them in the function condition. 6305 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6306 6307 // Convert the arguments. 6308 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6309 ExprResult R; 6310 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6311 S.Context, Function->getParamDecl(I)), 6312 SourceLocation(), Args[I]); 6313 6314 if (R.isInvalid()) 6315 return false; 6316 6317 ConvertedArgs.push_back(R.get()); 6318 } 6319 6320 if (Trap.hasErrorOccurred()) 6321 return false; 6322 6323 // Push default arguments if needed. 6324 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6325 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6326 ParmVarDecl *P = Function->getParamDecl(i); 6327 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6328 ? P->getUninstantiatedDefaultArg() 6329 : P->getDefaultArg(); 6330 // This can only happen in code completion, i.e. when PartialOverloading 6331 // is true. 6332 if (!DefArg) 6333 return false; 6334 ExprResult R = 6335 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6336 S.Context, Function->getParamDecl(i)), 6337 SourceLocation(), DefArg); 6338 if (R.isInvalid()) 6339 return false; 6340 ConvertedArgs.push_back(R.get()); 6341 } 6342 6343 if (Trap.hasErrorOccurred()) 6344 return false; 6345 } 6346 return true; 6347 } 6348 6349 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6350 bool MissingImplicitThis) { 6351 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6352 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6353 return nullptr; 6354 6355 SFINAETrap Trap(*this); 6356 SmallVector<Expr *, 16> ConvertedArgs; 6357 // FIXME: We should look into making enable_if late-parsed. 6358 Expr *DiscardedThis; 6359 if (!convertArgsForAvailabilityChecks( 6360 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6361 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6362 return *EnableIfAttrs.begin(); 6363 6364 for (auto *EIA : EnableIfAttrs) { 6365 APValue Result; 6366 // FIXME: This doesn't consider value-dependent cases, because doing so is 6367 // very difficult. Ideally, we should handle them more gracefully. 6368 if (!EIA->getCond()->EvaluateWithSubstitution( 6369 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6370 return EIA; 6371 6372 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6373 return EIA; 6374 } 6375 return nullptr; 6376 } 6377 6378 template <typename CheckFn> 6379 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6380 bool ArgDependent, SourceLocation Loc, 6381 CheckFn &&IsSuccessful) { 6382 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6383 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6384 if (ArgDependent == DIA->getArgDependent()) 6385 Attrs.push_back(DIA); 6386 } 6387 6388 // Common case: No diagnose_if attributes, so we can quit early. 6389 if (Attrs.empty()) 6390 return false; 6391 6392 auto WarningBegin = std::stable_partition( 6393 Attrs.begin(), Attrs.end(), 6394 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6395 6396 // Note that diagnose_if attributes are late-parsed, so they appear in the 6397 // correct order (unlike enable_if attributes). 6398 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6399 IsSuccessful); 6400 if (ErrAttr != WarningBegin) { 6401 const DiagnoseIfAttr *DIA = *ErrAttr; 6402 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6403 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6404 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6405 return true; 6406 } 6407 6408 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6409 if (IsSuccessful(DIA)) { 6410 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6411 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6412 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6413 } 6414 6415 return false; 6416 } 6417 6418 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6419 const Expr *ThisArg, 6420 ArrayRef<const Expr *> Args, 6421 SourceLocation Loc) { 6422 return diagnoseDiagnoseIfAttrsWith( 6423 *this, Function, /*ArgDependent=*/true, Loc, 6424 [&](const DiagnoseIfAttr *DIA) { 6425 APValue Result; 6426 // It's sane to use the same Args for any redecl of this function, since 6427 // EvaluateWithSubstitution only cares about the position of each 6428 // argument in the arg list, not the ParmVarDecl* it maps to. 6429 if (!DIA->getCond()->EvaluateWithSubstitution( 6430 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6431 return false; 6432 return Result.isInt() && Result.getInt().getBoolValue(); 6433 }); 6434 } 6435 6436 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6437 SourceLocation Loc) { 6438 return diagnoseDiagnoseIfAttrsWith( 6439 *this, ND, /*ArgDependent=*/false, Loc, 6440 [&](const DiagnoseIfAttr *DIA) { 6441 bool Result; 6442 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6443 Result; 6444 }); 6445 } 6446 6447 /// Add all of the function declarations in the given function set to 6448 /// the overload candidate set. 6449 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6450 ArrayRef<Expr *> Args, 6451 OverloadCandidateSet &CandidateSet, 6452 TemplateArgumentListInfo *ExplicitTemplateArgs, 6453 bool SuppressUserConversions, 6454 bool PartialOverloading, 6455 bool FirstArgumentIsBase) { 6456 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6457 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6458 ArrayRef<Expr *> FunctionArgs = Args; 6459 6460 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6461 FunctionDecl *FD = 6462 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6463 6464 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6465 QualType ObjectType; 6466 Expr::Classification ObjectClassification; 6467 if (Args.size() > 0) { 6468 if (Expr *E = Args[0]) { 6469 // Use the explicit base to restrict the lookup: 6470 ObjectType = E->getType(); 6471 // Pointers in the object arguments are implicitly dereferenced, so we 6472 // always classify them as l-values. 6473 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6474 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6475 else 6476 ObjectClassification = E->Classify(Context); 6477 } // .. else there is an implicit base. 6478 FunctionArgs = Args.slice(1); 6479 } 6480 if (FunTmpl) { 6481 AddMethodTemplateCandidate( 6482 FunTmpl, F.getPair(), 6483 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6484 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6485 FunctionArgs, CandidateSet, SuppressUserConversions, 6486 PartialOverloading); 6487 } else { 6488 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6489 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6490 ObjectClassification, FunctionArgs, CandidateSet, 6491 SuppressUserConversions, PartialOverloading); 6492 } 6493 } else { 6494 // This branch handles both standalone functions and static methods. 6495 6496 // Slice the first argument (which is the base) when we access 6497 // static method as non-static. 6498 if (Args.size() > 0 && 6499 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6500 !isa<CXXConstructorDecl>(FD)))) { 6501 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6502 FunctionArgs = Args.slice(1); 6503 } 6504 if (FunTmpl) { 6505 AddTemplateOverloadCandidate( 6506 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6507 CandidateSet, SuppressUserConversions, PartialOverloading); 6508 } else { 6509 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6510 SuppressUserConversions, PartialOverloading); 6511 } 6512 } 6513 } 6514 } 6515 6516 /// AddMethodCandidate - Adds a named decl (which is some kind of 6517 /// method) as a method candidate to the given overload set. 6518 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6519 QualType ObjectType, 6520 Expr::Classification ObjectClassification, 6521 ArrayRef<Expr *> Args, 6522 OverloadCandidateSet& CandidateSet, 6523 bool SuppressUserConversions) { 6524 NamedDecl *Decl = FoundDecl.getDecl(); 6525 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6526 6527 if (isa<UsingShadowDecl>(Decl)) 6528 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6529 6530 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6531 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6532 "Expected a member function template"); 6533 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6534 /*ExplicitArgs*/ nullptr, ObjectType, 6535 ObjectClassification, Args, CandidateSet, 6536 SuppressUserConversions); 6537 } else { 6538 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6539 ObjectType, ObjectClassification, Args, CandidateSet, 6540 SuppressUserConversions); 6541 } 6542 } 6543 6544 /// AddMethodCandidate - Adds the given C++ member function to the set 6545 /// of candidate functions, using the given function call arguments 6546 /// and the object argument (@c Object). For example, in a call 6547 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6548 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6549 /// allow user-defined conversions via constructors or conversion 6550 /// operators. 6551 void 6552 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6553 CXXRecordDecl *ActingContext, QualType ObjectType, 6554 Expr::Classification ObjectClassification, 6555 ArrayRef<Expr *> Args, 6556 OverloadCandidateSet &CandidateSet, 6557 bool SuppressUserConversions, 6558 bool PartialOverloading, 6559 ConversionSequenceList EarlyConversions) { 6560 const FunctionProtoType *Proto 6561 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6562 assert(Proto && "Methods without a prototype cannot be overloaded"); 6563 assert(!isa<CXXConstructorDecl>(Method) && 6564 "Use AddOverloadCandidate for constructors"); 6565 6566 if (!CandidateSet.isNewCandidate(Method)) 6567 return; 6568 6569 // C++11 [class.copy]p23: [DR1402] 6570 // A defaulted move assignment operator that is defined as deleted is 6571 // ignored by overload resolution. 6572 if (Method->isDefaulted() && Method->isDeleted() && 6573 Method->isMoveAssignmentOperator()) 6574 return; 6575 6576 // Overload resolution is always an unevaluated context. 6577 EnterExpressionEvaluationContext Unevaluated( 6578 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6579 6580 // Add this candidate 6581 OverloadCandidate &Candidate = 6582 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6583 Candidate.FoundDecl = FoundDecl; 6584 Candidate.Function = Method; 6585 Candidate.IsSurrogate = false; 6586 Candidate.IgnoreObjectArgument = false; 6587 Candidate.ExplicitCallArguments = Args.size(); 6588 6589 unsigned NumParams = Proto->getNumParams(); 6590 6591 // (C++ 13.3.2p2): A candidate function having fewer than m 6592 // parameters is viable only if it has an ellipsis in its parameter 6593 // list (8.3.5). 6594 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6595 !Proto->isVariadic()) { 6596 Candidate.Viable = false; 6597 Candidate.FailureKind = ovl_fail_too_many_arguments; 6598 return; 6599 } 6600 6601 // (C++ 13.3.2p2): A candidate function having more than m parameters 6602 // is viable only if the (m+1)st parameter has a default argument 6603 // (8.3.6). For the purposes of overload resolution, the 6604 // parameter list is truncated on the right, so that there are 6605 // exactly m parameters. 6606 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6607 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6608 // Not enough arguments. 6609 Candidate.Viable = false; 6610 Candidate.FailureKind = ovl_fail_too_few_arguments; 6611 return; 6612 } 6613 6614 Candidate.Viable = true; 6615 6616 if (Method->isStatic() || ObjectType.isNull()) 6617 // The implicit object argument is ignored. 6618 Candidate.IgnoreObjectArgument = true; 6619 else { 6620 // Determine the implicit conversion sequence for the object 6621 // parameter. 6622 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6623 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6624 Method, ActingContext); 6625 if (Candidate.Conversions[0].isBad()) { 6626 Candidate.Viable = false; 6627 Candidate.FailureKind = ovl_fail_bad_conversion; 6628 return; 6629 } 6630 } 6631 6632 // (CUDA B.1): Check for invalid calls between targets. 6633 if (getLangOpts().CUDA) 6634 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6635 if (!IsAllowedCUDACall(Caller, Method)) { 6636 Candidate.Viable = false; 6637 Candidate.FailureKind = ovl_fail_bad_target; 6638 return; 6639 } 6640 6641 // Determine the implicit conversion sequences for each of the 6642 // arguments. 6643 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6644 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6645 // We already formed a conversion sequence for this parameter during 6646 // template argument deduction. 6647 } else if (ArgIdx < NumParams) { 6648 // (C++ 13.3.2p3): for F to be a viable function, there shall 6649 // exist for each argument an implicit conversion sequence 6650 // (13.3.3.1) that converts that argument to the corresponding 6651 // parameter of F. 6652 QualType ParamType = Proto->getParamType(ArgIdx); 6653 Candidate.Conversions[ArgIdx + 1] 6654 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6655 SuppressUserConversions, 6656 /*InOverloadResolution=*/true, 6657 /*AllowObjCWritebackConversion=*/ 6658 getLangOpts().ObjCAutoRefCount); 6659 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6660 Candidate.Viable = false; 6661 Candidate.FailureKind = ovl_fail_bad_conversion; 6662 return; 6663 } 6664 } else { 6665 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6666 // argument for which there is no corresponding parameter is 6667 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6668 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6669 } 6670 } 6671 6672 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6673 Candidate.Viable = false; 6674 Candidate.FailureKind = ovl_fail_enable_if; 6675 Candidate.DeductionFailure.Data = FailedAttr; 6676 return; 6677 } 6678 6679 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6680 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6681 Candidate.Viable = false; 6682 Candidate.FailureKind = ovl_non_default_multiversion_function; 6683 } 6684 } 6685 6686 /// Add a C++ member function template as a candidate to the candidate 6687 /// set, using template argument deduction to produce an appropriate member 6688 /// function template specialization. 6689 void 6690 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6691 DeclAccessPair FoundDecl, 6692 CXXRecordDecl *ActingContext, 6693 TemplateArgumentListInfo *ExplicitTemplateArgs, 6694 QualType ObjectType, 6695 Expr::Classification ObjectClassification, 6696 ArrayRef<Expr *> Args, 6697 OverloadCandidateSet& CandidateSet, 6698 bool SuppressUserConversions, 6699 bool PartialOverloading) { 6700 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6701 return; 6702 6703 // C++ [over.match.funcs]p7: 6704 // In each case where a candidate is a function template, candidate 6705 // function template specializations are generated using template argument 6706 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6707 // candidate functions in the usual way.113) A given name can refer to one 6708 // or more function templates and also to a set of overloaded non-template 6709 // functions. In such a case, the candidate functions generated from each 6710 // function template are combined with the set of non-template candidate 6711 // functions. 6712 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6713 FunctionDecl *Specialization = nullptr; 6714 ConversionSequenceList Conversions; 6715 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6716 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6717 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6718 return CheckNonDependentConversions( 6719 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6720 SuppressUserConversions, ActingContext, ObjectType, 6721 ObjectClassification); 6722 })) { 6723 OverloadCandidate &Candidate = 6724 CandidateSet.addCandidate(Conversions.size(), Conversions); 6725 Candidate.FoundDecl = FoundDecl; 6726 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6727 Candidate.Viable = false; 6728 Candidate.IsSurrogate = false; 6729 Candidate.IgnoreObjectArgument = 6730 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6731 ObjectType.isNull(); 6732 Candidate.ExplicitCallArguments = Args.size(); 6733 if (Result == TDK_NonDependentConversionFailure) 6734 Candidate.FailureKind = ovl_fail_bad_conversion; 6735 else { 6736 Candidate.FailureKind = ovl_fail_bad_deduction; 6737 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6738 Info); 6739 } 6740 return; 6741 } 6742 6743 // Add the function template specialization produced by template argument 6744 // deduction as a candidate. 6745 assert(Specialization && "Missing member function template specialization?"); 6746 assert(isa<CXXMethodDecl>(Specialization) && 6747 "Specialization is not a member function?"); 6748 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6749 ActingContext, ObjectType, ObjectClassification, Args, 6750 CandidateSet, SuppressUserConversions, PartialOverloading, 6751 Conversions); 6752 } 6753 6754 /// Add a C++ function template specialization as a candidate 6755 /// in the candidate set, using template argument deduction to produce 6756 /// an appropriate function template specialization. 6757 void Sema::AddTemplateOverloadCandidate( 6758 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6759 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6760 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6761 bool PartialOverloading, ADLCallKind IsADLCandidate) { 6762 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6763 return; 6764 6765 // C++ [over.match.funcs]p7: 6766 // In each case where a candidate is a function template, candidate 6767 // function template specializations are generated using template argument 6768 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6769 // candidate functions in the usual way.113) A given name can refer to one 6770 // or more function templates and also to a set of overloaded non-template 6771 // functions. In such a case, the candidate functions generated from each 6772 // function template are combined with the set of non-template candidate 6773 // functions. 6774 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6775 FunctionDecl *Specialization = nullptr; 6776 ConversionSequenceList Conversions; 6777 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6778 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6779 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6780 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6781 Args, CandidateSet, Conversions, 6782 SuppressUserConversions); 6783 })) { 6784 OverloadCandidate &Candidate = 6785 CandidateSet.addCandidate(Conversions.size(), Conversions); 6786 Candidate.FoundDecl = FoundDecl; 6787 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6788 Candidate.Viable = false; 6789 Candidate.IsSurrogate = false; 6790 Candidate.IsADLCandidate = IsADLCandidate; 6791 // Ignore the object argument if there is one, since we don't have an object 6792 // type. 6793 Candidate.IgnoreObjectArgument = 6794 isa<CXXMethodDecl>(Candidate.Function) && 6795 !isa<CXXConstructorDecl>(Candidate.Function); 6796 Candidate.ExplicitCallArguments = Args.size(); 6797 if (Result == TDK_NonDependentConversionFailure) 6798 Candidate.FailureKind = ovl_fail_bad_conversion; 6799 else { 6800 Candidate.FailureKind = ovl_fail_bad_deduction; 6801 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6802 Info); 6803 } 6804 return; 6805 } 6806 6807 // Add the function template specialization produced by template argument 6808 // deduction as a candidate. 6809 assert(Specialization && "Missing function template specialization?"); 6810 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6811 SuppressUserConversions, PartialOverloading, 6812 /*AllowExplicit*/ false, IsADLCandidate, Conversions); 6813 } 6814 6815 /// Check that implicit conversion sequences can be formed for each argument 6816 /// whose corresponding parameter has a non-dependent type, per DR1391's 6817 /// [temp.deduct.call]p10. 6818 bool Sema::CheckNonDependentConversions( 6819 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6820 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6821 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6822 CXXRecordDecl *ActingContext, QualType ObjectType, 6823 Expr::Classification ObjectClassification) { 6824 // FIXME: The cases in which we allow explicit conversions for constructor 6825 // arguments never consider calling a constructor template. It's not clear 6826 // that is correct. 6827 const bool AllowExplicit = false; 6828 6829 auto *FD = FunctionTemplate->getTemplatedDecl(); 6830 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6831 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6832 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6833 6834 Conversions = 6835 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6836 6837 // Overload resolution is always an unevaluated context. 6838 EnterExpressionEvaluationContext Unevaluated( 6839 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6840 6841 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6842 // require that, but this check should never result in a hard error, and 6843 // overload resolution is permitted to sidestep instantiations. 6844 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6845 !ObjectType.isNull()) { 6846 Conversions[0] = TryObjectArgumentInitialization( 6847 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6848 Method, ActingContext); 6849 if (Conversions[0].isBad()) 6850 return true; 6851 } 6852 6853 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6854 ++I) { 6855 QualType ParamType = ParamTypes[I]; 6856 if (!ParamType->isDependentType()) { 6857 Conversions[ThisConversions + I] 6858 = TryCopyInitialization(*this, Args[I], ParamType, 6859 SuppressUserConversions, 6860 /*InOverloadResolution=*/true, 6861 /*AllowObjCWritebackConversion=*/ 6862 getLangOpts().ObjCAutoRefCount, 6863 AllowExplicit); 6864 if (Conversions[ThisConversions + I].isBad()) 6865 return true; 6866 } 6867 } 6868 6869 return false; 6870 } 6871 6872 /// Determine whether this is an allowable conversion from the result 6873 /// of an explicit conversion operator to the expected type, per C++ 6874 /// [over.match.conv]p1 and [over.match.ref]p1. 6875 /// 6876 /// \param ConvType The return type of the conversion function. 6877 /// 6878 /// \param ToType The type we are converting to. 6879 /// 6880 /// \param AllowObjCPointerConversion Allow a conversion from one 6881 /// Objective-C pointer to another. 6882 /// 6883 /// \returns true if the conversion is allowable, false otherwise. 6884 static bool isAllowableExplicitConversion(Sema &S, 6885 QualType ConvType, QualType ToType, 6886 bool AllowObjCPointerConversion) { 6887 QualType ToNonRefType = ToType.getNonReferenceType(); 6888 6889 // Easy case: the types are the same. 6890 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6891 return true; 6892 6893 // Allow qualification conversions. 6894 bool ObjCLifetimeConversion; 6895 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6896 ObjCLifetimeConversion)) 6897 return true; 6898 6899 // If we're not allowed to consider Objective-C pointer conversions, 6900 // we're done. 6901 if (!AllowObjCPointerConversion) 6902 return false; 6903 6904 // Is this an Objective-C pointer conversion? 6905 bool IncompatibleObjC = false; 6906 QualType ConvertedType; 6907 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6908 IncompatibleObjC); 6909 } 6910 6911 /// AddConversionCandidate - Add a C++ conversion function as a 6912 /// candidate in the candidate set (C++ [over.match.conv], 6913 /// C++ [over.match.copy]). From is the expression we're converting from, 6914 /// and ToType is the type that we're eventually trying to convert to 6915 /// (which may or may not be the same type as the type that the 6916 /// conversion function produces). 6917 void 6918 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6919 DeclAccessPair FoundDecl, 6920 CXXRecordDecl *ActingContext, 6921 Expr *From, QualType ToType, 6922 OverloadCandidateSet& CandidateSet, 6923 bool AllowObjCConversionOnExplicit, 6924 bool AllowResultConversion) { 6925 assert(!Conversion->getDescribedFunctionTemplate() && 6926 "Conversion function templates use AddTemplateConversionCandidate"); 6927 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6928 if (!CandidateSet.isNewCandidate(Conversion)) 6929 return; 6930 6931 // If the conversion function has an undeduced return type, trigger its 6932 // deduction now. 6933 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6934 if (DeduceReturnType(Conversion, From->getExprLoc())) 6935 return; 6936 ConvType = Conversion->getConversionType().getNonReferenceType(); 6937 } 6938 6939 // If we don't allow any conversion of the result type, ignore conversion 6940 // functions that don't convert to exactly (possibly cv-qualified) T. 6941 if (!AllowResultConversion && 6942 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6943 return; 6944 6945 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6946 // operator is only a candidate if its return type is the target type or 6947 // can be converted to the target type with a qualification conversion. 6948 if (Conversion->isExplicit() && 6949 !isAllowableExplicitConversion(*this, ConvType, ToType, 6950 AllowObjCConversionOnExplicit)) 6951 return; 6952 6953 // Overload resolution is always an unevaluated context. 6954 EnterExpressionEvaluationContext Unevaluated( 6955 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6956 6957 // Add this candidate 6958 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6959 Candidate.FoundDecl = FoundDecl; 6960 Candidate.Function = Conversion; 6961 Candidate.IsSurrogate = false; 6962 Candidate.IgnoreObjectArgument = false; 6963 Candidate.FinalConversion.setAsIdentityConversion(); 6964 Candidate.FinalConversion.setFromType(ConvType); 6965 Candidate.FinalConversion.setAllToTypes(ToType); 6966 Candidate.Viable = true; 6967 Candidate.ExplicitCallArguments = 1; 6968 6969 // C++ [over.match.funcs]p4: 6970 // For conversion functions, the function is considered to be a member of 6971 // the class of the implicit implied object argument for the purpose of 6972 // defining the type of the implicit object parameter. 6973 // 6974 // Determine the implicit conversion sequence for the implicit 6975 // object parameter. 6976 QualType ImplicitParamType = From->getType(); 6977 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6978 ImplicitParamType = FromPtrType->getPointeeType(); 6979 CXXRecordDecl *ConversionContext 6980 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6981 6982 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6983 *this, CandidateSet.getLocation(), From->getType(), 6984 From->Classify(Context), Conversion, ConversionContext); 6985 6986 if (Candidate.Conversions[0].isBad()) { 6987 Candidate.Viable = false; 6988 Candidate.FailureKind = ovl_fail_bad_conversion; 6989 return; 6990 } 6991 6992 // We won't go through a user-defined type conversion function to convert a 6993 // derived to base as such conversions are given Conversion Rank. They only 6994 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6995 QualType FromCanon 6996 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6997 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6998 if (FromCanon == ToCanon || 6999 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7000 Candidate.Viable = false; 7001 Candidate.FailureKind = ovl_fail_trivial_conversion; 7002 return; 7003 } 7004 7005 // To determine what the conversion from the result of calling the 7006 // conversion function to the type we're eventually trying to 7007 // convert to (ToType), we need to synthesize a call to the 7008 // conversion function and attempt copy initialization from it. This 7009 // makes sure that we get the right semantics with respect to 7010 // lvalues/rvalues and the type. Fortunately, we can allocate this 7011 // call on the stack and we don't need its arguments to be 7012 // well-formed. 7013 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7014 VK_LValue, From->getBeginLoc()); 7015 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7016 Context.getPointerType(Conversion->getType()), 7017 CK_FunctionToPointerDecay, 7018 &ConversionRef, VK_RValue); 7019 7020 QualType ConversionType = Conversion->getConversionType(); 7021 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7022 Candidate.Viable = false; 7023 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7024 return; 7025 } 7026 7027 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7028 7029 // Note that it is safe to allocate CallExpr on the stack here because 7030 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7031 // allocator). 7032 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7033 7034 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)> 7035 Buffer; 7036 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7037 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7038 7039 ImplicitConversionSequence ICS = 7040 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7041 /*SuppressUserConversions=*/true, 7042 /*InOverloadResolution=*/false, 7043 /*AllowObjCWritebackConversion=*/false); 7044 7045 switch (ICS.getKind()) { 7046 case ImplicitConversionSequence::StandardConversion: 7047 Candidate.FinalConversion = ICS.Standard; 7048 7049 // C++ [over.ics.user]p3: 7050 // If the user-defined conversion is specified by a specialization of a 7051 // conversion function template, the second standard conversion sequence 7052 // shall have exact match rank. 7053 if (Conversion->getPrimaryTemplate() && 7054 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7055 Candidate.Viable = false; 7056 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7057 return; 7058 } 7059 7060 // C++0x [dcl.init.ref]p5: 7061 // In the second case, if the reference is an rvalue reference and 7062 // the second standard conversion sequence of the user-defined 7063 // conversion sequence includes an lvalue-to-rvalue conversion, the 7064 // program is ill-formed. 7065 if (ToType->isRValueReferenceType() && 7066 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7067 Candidate.Viable = false; 7068 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7069 return; 7070 } 7071 break; 7072 7073 case ImplicitConversionSequence::BadConversion: 7074 Candidate.Viable = false; 7075 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7076 return; 7077 7078 default: 7079 llvm_unreachable( 7080 "Can only end up with a standard conversion sequence or failure"); 7081 } 7082 7083 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7084 Candidate.Viable = false; 7085 Candidate.FailureKind = ovl_fail_enable_if; 7086 Candidate.DeductionFailure.Data = FailedAttr; 7087 return; 7088 } 7089 7090 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7091 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7092 Candidate.Viable = false; 7093 Candidate.FailureKind = ovl_non_default_multiversion_function; 7094 } 7095 } 7096 7097 /// Adds a conversion function template specialization 7098 /// candidate to the overload set, using template argument deduction 7099 /// to deduce the template arguments of the conversion function 7100 /// template from the type that we are converting to (C++ 7101 /// [temp.deduct.conv]). 7102 void 7103 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7104 DeclAccessPair FoundDecl, 7105 CXXRecordDecl *ActingDC, 7106 Expr *From, QualType ToType, 7107 OverloadCandidateSet &CandidateSet, 7108 bool AllowObjCConversionOnExplicit, 7109 bool AllowResultConversion) { 7110 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7111 "Only conversion function templates permitted here"); 7112 7113 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7114 return; 7115 7116 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7117 CXXConversionDecl *Specialization = nullptr; 7118 if (TemplateDeductionResult Result 7119 = DeduceTemplateArguments(FunctionTemplate, ToType, 7120 Specialization, Info)) { 7121 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7122 Candidate.FoundDecl = FoundDecl; 7123 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7124 Candidate.Viable = false; 7125 Candidate.FailureKind = ovl_fail_bad_deduction; 7126 Candidate.IsSurrogate = false; 7127 Candidate.IgnoreObjectArgument = false; 7128 Candidate.ExplicitCallArguments = 1; 7129 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7130 Info); 7131 return; 7132 } 7133 7134 // Add the conversion function template specialization produced by 7135 // template argument deduction as a candidate. 7136 assert(Specialization && "Missing function template specialization?"); 7137 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7138 CandidateSet, AllowObjCConversionOnExplicit, 7139 AllowResultConversion); 7140 } 7141 7142 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7143 /// converts the given @c Object to a function pointer via the 7144 /// conversion function @c Conversion, and then attempts to call it 7145 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7146 /// the type of function that we'll eventually be calling. 7147 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7148 DeclAccessPair FoundDecl, 7149 CXXRecordDecl *ActingContext, 7150 const FunctionProtoType *Proto, 7151 Expr *Object, 7152 ArrayRef<Expr *> Args, 7153 OverloadCandidateSet& CandidateSet) { 7154 if (!CandidateSet.isNewCandidate(Conversion)) 7155 return; 7156 7157 // Overload resolution is always an unevaluated context. 7158 EnterExpressionEvaluationContext Unevaluated( 7159 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7160 7161 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7162 Candidate.FoundDecl = FoundDecl; 7163 Candidate.Function = nullptr; 7164 Candidate.Surrogate = Conversion; 7165 Candidate.Viable = true; 7166 Candidate.IsSurrogate = true; 7167 Candidate.IgnoreObjectArgument = false; 7168 Candidate.ExplicitCallArguments = Args.size(); 7169 7170 // Determine the implicit conversion sequence for the implicit 7171 // object parameter. 7172 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7173 *this, CandidateSet.getLocation(), Object->getType(), 7174 Object->Classify(Context), Conversion, ActingContext); 7175 if (ObjectInit.isBad()) { 7176 Candidate.Viable = false; 7177 Candidate.FailureKind = ovl_fail_bad_conversion; 7178 Candidate.Conversions[0] = ObjectInit; 7179 return; 7180 } 7181 7182 // The first conversion is actually a user-defined conversion whose 7183 // first conversion is ObjectInit's standard conversion (which is 7184 // effectively a reference binding). Record it as such. 7185 Candidate.Conversions[0].setUserDefined(); 7186 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7187 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7188 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7189 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7190 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7191 Candidate.Conversions[0].UserDefined.After 7192 = Candidate.Conversions[0].UserDefined.Before; 7193 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7194 7195 // Find the 7196 unsigned NumParams = Proto->getNumParams(); 7197 7198 // (C++ 13.3.2p2): A candidate function having fewer than m 7199 // parameters is viable only if it has an ellipsis in its parameter 7200 // list (8.3.5). 7201 if (Args.size() > NumParams && !Proto->isVariadic()) { 7202 Candidate.Viable = false; 7203 Candidate.FailureKind = ovl_fail_too_many_arguments; 7204 return; 7205 } 7206 7207 // Function types don't have any default arguments, so just check if 7208 // we have enough arguments. 7209 if (Args.size() < NumParams) { 7210 // Not enough arguments. 7211 Candidate.Viable = false; 7212 Candidate.FailureKind = ovl_fail_too_few_arguments; 7213 return; 7214 } 7215 7216 // Determine the implicit conversion sequences for each of the 7217 // arguments. 7218 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7219 if (ArgIdx < NumParams) { 7220 // (C++ 13.3.2p3): for F to be a viable function, there shall 7221 // exist for each argument an implicit conversion sequence 7222 // (13.3.3.1) that converts that argument to the corresponding 7223 // parameter of F. 7224 QualType ParamType = Proto->getParamType(ArgIdx); 7225 Candidate.Conversions[ArgIdx + 1] 7226 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7227 /*SuppressUserConversions=*/false, 7228 /*InOverloadResolution=*/false, 7229 /*AllowObjCWritebackConversion=*/ 7230 getLangOpts().ObjCAutoRefCount); 7231 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7232 Candidate.Viable = false; 7233 Candidate.FailureKind = ovl_fail_bad_conversion; 7234 return; 7235 } 7236 } else { 7237 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7238 // argument for which there is no corresponding parameter is 7239 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7240 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7241 } 7242 } 7243 7244 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7245 Candidate.Viable = false; 7246 Candidate.FailureKind = ovl_fail_enable_if; 7247 Candidate.DeductionFailure.Data = FailedAttr; 7248 return; 7249 } 7250 } 7251 7252 /// Add overload candidates for overloaded operators that are 7253 /// member functions. 7254 /// 7255 /// Add the overloaded operator candidates that are member functions 7256 /// for the operator Op that was used in an operator expression such 7257 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7258 /// CandidateSet will store the added overload candidates. (C++ 7259 /// [over.match.oper]). 7260 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7261 SourceLocation OpLoc, 7262 ArrayRef<Expr *> Args, 7263 OverloadCandidateSet& CandidateSet, 7264 SourceRange OpRange) { 7265 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7266 7267 // C++ [over.match.oper]p3: 7268 // For a unary operator @ with an operand of a type whose 7269 // cv-unqualified version is T1, and for a binary operator @ with 7270 // a left operand of a type whose cv-unqualified version is T1 and 7271 // a right operand of a type whose cv-unqualified version is T2, 7272 // three sets of candidate functions, designated member 7273 // candidates, non-member candidates and built-in candidates, are 7274 // constructed as follows: 7275 QualType T1 = Args[0]->getType(); 7276 7277 // -- If T1 is a complete class type or a class currently being 7278 // defined, the set of member candidates is the result of the 7279 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7280 // the set of member candidates is empty. 7281 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7282 // Complete the type if it can be completed. 7283 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7284 return; 7285 // If the type is neither complete nor being defined, bail out now. 7286 if (!T1Rec->getDecl()->getDefinition()) 7287 return; 7288 7289 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7290 LookupQualifiedName(Operators, T1Rec->getDecl()); 7291 Operators.suppressDiagnostics(); 7292 7293 for (LookupResult::iterator Oper = Operators.begin(), 7294 OperEnd = Operators.end(); 7295 Oper != OperEnd; 7296 ++Oper) 7297 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7298 Args[0]->Classify(Context), Args.slice(1), 7299 CandidateSet, /*SuppressUserConversions=*/false); 7300 } 7301 } 7302 7303 /// AddBuiltinCandidate - Add a candidate for a built-in 7304 /// operator. ResultTy and ParamTys are the result and parameter types 7305 /// of the built-in candidate, respectively. Args and NumArgs are the 7306 /// arguments being passed to the candidate. IsAssignmentOperator 7307 /// should be true when this built-in candidate is an assignment 7308 /// operator. NumContextualBoolArguments is the number of arguments 7309 /// (at the beginning of the argument list) that will be contextually 7310 /// converted to bool. 7311 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7312 OverloadCandidateSet& CandidateSet, 7313 bool IsAssignmentOperator, 7314 unsigned NumContextualBoolArguments) { 7315 // Overload resolution is always an unevaluated context. 7316 EnterExpressionEvaluationContext Unevaluated( 7317 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7318 7319 // Add this candidate 7320 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7321 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7322 Candidate.Function = nullptr; 7323 Candidate.IsSurrogate = false; 7324 Candidate.IgnoreObjectArgument = false; 7325 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7326 7327 // Determine the implicit conversion sequences for each of the 7328 // arguments. 7329 Candidate.Viable = true; 7330 Candidate.ExplicitCallArguments = Args.size(); 7331 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7332 // C++ [over.match.oper]p4: 7333 // For the built-in assignment operators, conversions of the 7334 // left operand are restricted as follows: 7335 // -- no temporaries are introduced to hold the left operand, and 7336 // -- no user-defined conversions are applied to the left 7337 // operand to achieve a type match with the left-most 7338 // parameter of a built-in candidate. 7339 // 7340 // We block these conversions by turning off user-defined 7341 // conversions, since that is the only way that initialization of 7342 // a reference to a non-class type can occur from something that 7343 // is not of the same type. 7344 if (ArgIdx < NumContextualBoolArguments) { 7345 assert(ParamTys[ArgIdx] == Context.BoolTy && 7346 "Contextual conversion to bool requires bool type"); 7347 Candidate.Conversions[ArgIdx] 7348 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7349 } else { 7350 Candidate.Conversions[ArgIdx] 7351 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7352 ArgIdx == 0 && IsAssignmentOperator, 7353 /*InOverloadResolution=*/false, 7354 /*AllowObjCWritebackConversion=*/ 7355 getLangOpts().ObjCAutoRefCount); 7356 } 7357 if (Candidate.Conversions[ArgIdx].isBad()) { 7358 Candidate.Viable = false; 7359 Candidate.FailureKind = ovl_fail_bad_conversion; 7360 break; 7361 } 7362 } 7363 } 7364 7365 namespace { 7366 7367 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7368 /// candidate operator functions for built-in operators (C++ 7369 /// [over.built]). The types are separated into pointer types and 7370 /// enumeration types. 7371 class BuiltinCandidateTypeSet { 7372 /// TypeSet - A set of types. 7373 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7374 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7375 7376 /// PointerTypes - The set of pointer types that will be used in the 7377 /// built-in candidates. 7378 TypeSet PointerTypes; 7379 7380 /// MemberPointerTypes - The set of member pointer types that will be 7381 /// used in the built-in candidates. 7382 TypeSet MemberPointerTypes; 7383 7384 /// EnumerationTypes - The set of enumeration types that will be 7385 /// used in the built-in candidates. 7386 TypeSet EnumerationTypes; 7387 7388 /// The set of vector types that will be used in the built-in 7389 /// candidates. 7390 TypeSet VectorTypes; 7391 7392 /// A flag indicating non-record types are viable candidates 7393 bool HasNonRecordTypes; 7394 7395 /// A flag indicating whether either arithmetic or enumeration types 7396 /// were present in the candidate set. 7397 bool HasArithmeticOrEnumeralTypes; 7398 7399 /// A flag indicating whether the nullptr type was present in the 7400 /// candidate set. 7401 bool HasNullPtrType; 7402 7403 /// Sema - The semantic analysis instance where we are building the 7404 /// candidate type set. 7405 Sema &SemaRef; 7406 7407 /// Context - The AST context in which we will build the type sets. 7408 ASTContext &Context; 7409 7410 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7411 const Qualifiers &VisibleQuals); 7412 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7413 7414 public: 7415 /// iterator - Iterates through the types that are part of the set. 7416 typedef TypeSet::iterator iterator; 7417 7418 BuiltinCandidateTypeSet(Sema &SemaRef) 7419 : HasNonRecordTypes(false), 7420 HasArithmeticOrEnumeralTypes(false), 7421 HasNullPtrType(false), 7422 SemaRef(SemaRef), 7423 Context(SemaRef.Context) { } 7424 7425 void AddTypesConvertedFrom(QualType Ty, 7426 SourceLocation Loc, 7427 bool AllowUserConversions, 7428 bool AllowExplicitConversions, 7429 const Qualifiers &VisibleTypeConversionsQuals); 7430 7431 /// pointer_begin - First pointer type found; 7432 iterator pointer_begin() { return PointerTypes.begin(); } 7433 7434 /// pointer_end - Past the last pointer type found; 7435 iterator pointer_end() { return PointerTypes.end(); } 7436 7437 /// member_pointer_begin - First member pointer type found; 7438 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7439 7440 /// member_pointer_end - Past the last member pointer type found; 7441 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7442 7443 /// enumeration_begin - First enumeration type found; 7444 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7445 7446 /// enumeration_end - Past the last enumeration type found; 7447 iterator enumeration_end() { return EnumerationTypes.end(); } 7448 7449 iterator vector_begin() { return VectorTypes.begin(); } 7450 iterator vector_end() { return VectorTypes.end(); } 7451 7452 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7453 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7454 bool hasNullPtrType() const { return HasNullPtrType; } 7455 }; 7456 7457 } // end anonymous namespace 7458 7459 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7460 /// the set of pointer types along with any more-qualified variants of 7461 /// that type. For example, if @p Ty is "int const *", this routine 7462 /// will add "int const *", "int const volatile *", "int const 7463 /// restrict *", and "int const volatile restrict *" to the set of 7464 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7465 /// false otherwise. 7466 /// 7467 /// FIXME: what to do about extended qualifiers? 7468 bool 7469 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7470 const Qualifiers &VisibleQuals) { 7471 7472 // Insert this type. 7473 if (!PointerTypes.insert(Ty)) 7474 return false; 7475 7476 QualType PointeeTy; 7477 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7478 bool buildObjCPtr = false; 7479 if (!PointerTy) { 7480 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7481 PointeeTy = PTy->getPointeeType(); 7482 buildObjCPtr = true; 7483 } else { 7484 PointeeTy = PointerTy->getPointeeType(); 7485 } 7486 7487 // Don't add qualified variants of arrays. For one, they're not allowed 7488 // (the qualifier would sink to the element type), and for another, the 7489 // only overload situation where it matters is subscript or pointer +- int, 7490 // and those shouldn't have qualifier variants anyway. 7491 if (PointeeTy->isArrayType()) 7492 return true; 7493 7494 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7495 bool hasVolatile = VisibleQuals.hasVolatile(); 7496 bool hasRestrict = VisibleQuals.hasRestrict(); 7497 7498 // Iterate through all strict supersets of BaseCVR. 7499 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7500 if ((CVR | BaseCVR) != CVR) continue; 7501 // Skip over volatile if no volatile found anywhere in the types. 7502 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7503 7504 // Skip over restrict if no restrict found anywhere in the types, or if 7505 // the type cannot be restrict-qualified. 7506 if ((CVR & Qualifiers::Restrict) && 7507 (!hasRestrict || 7508 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7509 continue; 7510 7511 // Build qualified pointee type. 7512 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7513 7514 // Build qualified pointer type. 7515 QualType QPointerTy; 7516 if (!buildObjCPtr) 7517 QPointerTy = Context.getPointerType(QPointeeTy); 7518 else 7519 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7520 7521 // Insert qualified pointer type. 7522 PointerTypes.insert(QPointerTy); 7523 } 7524 7525 return true; 7526 } 7527 7528 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7529 /// to the set of pointer types along with any more-qualified variants of 7530 /// that type. For example, if @p Ty is "int const *", this routine 7531 /// will add "int const *", "int const volatile *", "int const 7532 /// restrict *", and "int const volatile restrict *" to the set of 7533 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7534 /// false otherwise. 7535 /// 7536 /// FIXME: what to do about extended qualifiers? 7537 bool 7538 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7539 QualType Ty) { 7540 // Insert this type. 7541 if (!MemberPointerTypes.insert(Ty)) 7542 return false; 7543 7544 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7545 assert(PointerTy && "type was not a member pointer type!"); 7546 7547 QualType PointeeTy = PointerTy->getPointeeType(); 7548 // Don't add qualified variants of arrays. For one, they're not allowed 7549 // (the qualifier would sink to the element type), and for another, the 7550 // only overload situation where it matters is subscript or pointer +- int, 7551 // and those shouldn't have qualifier variants anyway. 7552 if (PointeeTy->isArrayType()) 7553 return true; 7554 const Type *ClassTy = PointerTy->getClass(); 7555 7556 // Iterate through all strict supersets of the pointee type's CVR 7557 // qualifiers. 7558 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7559 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7560 if ((CVR | BaseCVR) != CVR) continue; 7561 7562 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7563 MemberPointerTypes.insert( 7564 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7565 } 7566 7567 return true; 7568 } 7569 7570 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7571 /// Ty can be implicit converted to the given set of @p Types. We're 7572 /// primarily interested in pointer types and enumeration types. We also 7573 /// take member pointer types, for the conditional operator. 7574 /// AllowUserConversions is true if we should look at the conversion 7575 /// functions of a class type, and AllowExplicitConversions if we 7576 /// should also include the explicit conversion functions of a class 7577 /// type. 7578 void 7579 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7580 SourceLocation Loc, 7581 bool AllowUserConversions, 7582 bool AllowExplicitConversions, 7583 const Qualifiers &VisibleQuals) { 7584 // Only deal with canonical types. 7585 Ty = Context.getCanonicalType(Ty); 7586 7587 // Look through reference types; they aren't part of the type of an 7588 // expression for the purposes of conversions. 7589 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7590 Ty = RefTy->getPointeeType(); 7591 7592 // If we're dealing with an array type, decay to the pointer. 7593 if (Ty->isArrayType()) 7594 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7595 7596 // Otherwise, we don't care about qualifiers on the type. 7597 Ty = Ty.getLocalUnqualifiedType(); 7598 7599 // Flag if we ever add a non-record type. 7600 const RecordType *TyRec = Ty->getAs<RecordType>(); 7601 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7602 7603 // Flag if we encounter an arithmetic type. 7604 HasArithmeticOrEnumeralTypes = 7605 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7606 7607 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7608 PointerTypes.insert(Ty); 7609 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7610 // Insert our type, and its more-qualified variants, into the set 7611 // of types. 7612 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7613 return; 7614 } else if (Ty->isMemberPointerType()) { 7615 // Member pointers are far easier, since the pointee can't be converted. 7616 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7617 return; 7618 } else if (Ty->isEnumeralType()) { 7619 HasArithmeticOrEnumeralTypes = true; 7620 EnumerationTypes.insert(Ty); 7621 } else if (Ty->isVectorType()) { 7622 // We treat vector types as arithmetic types in many contexts as an 7623 // extension. 7624 HasArithmeticOrEnumeralTypes = true; 7625 VectorTypes.insert(Ty); 7626 } else if (Ty->isNullPtrType()) { 7627 HasNullPtrType = true; 7628 } else if (AllowUserConversions && TyRec) { 7629 // No conversion functions in incomplete types. 7630 if (!SemaRef.isCompleteType(Loc, Ty)) 7631 return; 7632 7633 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7634 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7635 if (isa<UsingShadowDecl>(D)) 7636 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7637 7638 // Skip conversion function templates; they don't tell us anything 7639 // about which builtin types we can convert to. 7640 if (isa<FunctionTemplateDecl>(D)) 7641 continue; 7642 7643 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7644 if (AllowExplicitConversions || !Conv->isExplicit()) { 7645 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7646 VisibleQuals); 7647 } 7648 } 7649 } 7650 } 7651 7652 /// Helper function for AddBuiltinOperatorCandidates() that adds 7653 /// the volatile- and non-volatile-qualified assignment operators for the 7654 /// given type to the candidate set. 7655 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7656 QualType T, 7657 ArrayRef<Expr *> Args, 7658 OverloadCandidateSet &CandidateSet) { 7659 QualType ParamTypes[2]; 7660 7661 // T& operator=(T&, T) 7662 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7663 ParamTypes[1] = T; 7664 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7665 /*IsAssignmentOperator=*/true); 7666 7667 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7668 // volatile T& operator=(volatile T&, T) 7669 ParamTypes[0] 7670 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7671 ParamTypes[1] = T; 7672 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7673 /*IsAssignmentOperator=*/true); 7674 } 7675 } 7676 7677 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7678 /// if any, found in visible type conversion functions found in ArgExpr's type. 7679 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7680 Qualifiers VRQuals; 7681 const RecordType *TyRec; 7682 if (const MemberPointerType *RHSMPType = 7683 ArgExpr->getType()->getAs<MemberPointerType>()) 7684 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7685 else 7686 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7687 if (!TyRec) { 7688 // Just to be safe, assume the worst case. 7689 VRQuals.addVolatile(); 7690 VRQuals.addRestrict(); 7691 return VRQuals; 7692 } 7693 7694 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7695 if (!ClassDecl->hasDefinition()) 7696 return VRQuals; 7697 7698 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7699 if (isa<UsingShadowDecl>(D)) 7700 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7701 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7702 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7703 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7704 CanTy = ResTypeRef->getPointeeType(); 7705 // Need to go down the pointer/mempointer chain and add qualifiers 7706 // as see them. 7707 bool done = false; 7708 while (!done) { 7709 if (CanTy.isRestrictQualified()) 7710 VRQuals.addRestrict(); 7711 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7712 CanTy = ResTypePtr->getPointeeType(); 7713 else if (const MemberPointerType *ResTypeMPtr = 7714 CanTy->getAs<MemberPointerType>()) 7715 CanTy = ResTypeMPtr->getPointeeType(); 7716 else 7717 done = true; 7718 if (CanTy.isVolatileQualified()) 7719 VRQuals.addVolatile(); 7720 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7721 return VRQuals; 7722 } 7723 } 7724 } 7725 return VRQuals; 7726 } 7727 7728 namespace { 7729 7730 /// Helper class to manage the addition of builtin operator overload 7731 /// candidates. It provides shared state and utility methods used throughout 7732 /// the process, as well as a helper method to add each group of builtin 7733 /// operator overloads from the standard to a candidate set. 7734 class BuiltinOperatorOverloadBuilder { 7735 // Common instance state available to all overload candidate addition methods. 7736 Sema &S; 7737 ArrayRef<Expr *> Args; 7738 Qualifiers VisibleTypeConversionsQuals; 7739 bool HasArithmeticOrEnumeralCandidateType; 7740 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7741 OverloadCandidateSet &CandidateSet; 7742 7743 static constexpr int ArithmeticTypesCap = 24; 7744 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7745 7746 // Define some indices used to iterate over the arithemetic types in 7747 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7748 // types are that preserved by promotion (C++ [over.built]p2). 7749 unsigned FirstIntegralType, 7750 LastIntegralType; 7751 unsigned FirstPromotedIntegralType, 7752 LastPromotedIntegralType; 7753 unsigned FirstPromotedArithmeticType, 7754 LastPromotedArithmeticType; 7755 unsigned NumArithmeticTypes; 7756 7757 void InitArithmeticTypes() { 7758 // Start of promoted types. 7759 FirstPromotedArithmeticType = 0; 7760 ArithmeticTypes.push_back(S.Context.FloatTy); 7761 ArithmeticTypes.push_back(S.Context.DoubleTy); 7762 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7763 if (S.Context.getTargetInfo().hasFloat128Type()) 7764 ArithmeticTypes.push_back(S.Context.Float128Ty); 7765 7766 // Start of integral types. 7767 FirstIntegralType = ArithmeticTypes.size(); 7768 FirstPromotedIntegralType = ArithmeticTypes.size(); 7769 ArithmeticTypes.push_back(S.Context.IntTy); 7770 ArithmeticTypes.push_back(S.Context.LongTy); 7771 ArithmeticTypes.push_back(S.Context.LongLongTy); 7772 if (S.Context.getTargetInfo().hasInt128Type()) 7773 ArithmeticTypes.push_back(S.Context.Int128Ty); 7774 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7775 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7776 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7777 if (S.Context.getTargetInfo().hasInt128Type()) 7778 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7779 LastPromotedIntegralType = ArithmeticTypes.size(); 7780 LastPromotedArithmeticType = ArithmeticTypes.size(); 7781 // End of promoted types. 7782 7783 ArithmeticTypes.push_back(S.Context.BoolTy); 7784 ArithmeticTypes.push_back(S.Context.CharTy); 7785 ArithmeticTypes.push_back(S.Context.WCharTy); 7786 if (S.Context.getLangOpts().Char8) 7787 ArithmeticTypes.push_back(S.Context.Char8Ty); 7788 ArithmeticTypes.push_back(S.Context.Char16Ty); 7789 ArithmeticTypes.push_back(S.Context.Char32Ty); 7790 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7791 ArithmeticTypes.push_back(S.Context.ShortTy); 7792 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7793 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7794 LastIntegralType = ArithmeticTypes.size(); 7795 NumArithmeticTypes = ArithmeticTypes.size(); 7796 // End of integral types. 7797 // FIXME: What about complex? What about half? 7798 7799 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7800 "Enough inline storage for all arithmetic types."); 7801 } 7802 7803 /// Helper method to factor out the common pattern of adding overloads 7804 /// for '++' and '--' builtin operators. 7805 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7806 bool HasVolatile, 7807 bool HasRestrict) { 7808 QualType ParamTypes[2] = { 7809 S.Context.getLValueReferenceType(CandidateTy), 7810 S.Context.IntTy 7811 }; 7812 7813 // Non-volatile version. 7814 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7815 7816 // Use a heuristic to reduce number of builtin candidates in the set: 7817 // add volatile version only if there are conversions to a volatile type. 7818 if (HasVolatile) { 7819 ParamTypes[0] = 7820 S.Context.getLValueReferenceType( 7821 S.Context.getVolatileType(CandidateTy)); 7822 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7823 } 7824 7825 // Add restrict version only if there are conversions to a restrict type 7826 // and our candidate type is a non-restrict-qualified pointer. 7827 if (HasRestrict && CandidateTy->isAnyPointerType() && 7828 !CandidateTy.isRestrictQualified()) { 7829 ParamTypes[0] 7830 = S.Context.getLValueReferenceType( 7831 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7832 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7833 7834 if (HasVolatile) { 7835 ParamTypes[0] 7836 = S.Context.getLValueReferenceType( 7837 S.Context.getCVRQualifiedType(CandidateTy, 7838 (Qualifiers::Volatile | 7839 Qualifiers::Restrict))); 7840 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7841 } 7842 } 7843 7844 } 7845 7846 public: 7847 BuiltinOperatorOverloadBuilder( 7848 Sema &S, ArrayRef<Expr *> Args, 7849 Qualifiers VisibleTypeConversionsQuals, 7850 bool HasArithmeticOrEnumeralCandidateType, 7851 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7852 OverloadCandidateSet &CandidateSet) 7853 : S(S), Args(Args), 7854 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7855 HasArithmeticOrEnumeralCandidateType( 7856 HasArithmeticOrEnumeralCandidateType), 7857 CandidateTypes(CandidateTypes), 7858 CandidateSet(CandidateSet) { 7859 7860 InitArithmeticTypes(); 7861 } 7862 7863 // Increment is deprecated for bool since C++17. 7864 // 7865 // C++ [over.built]p3: 7866 // 7867 // For every pair (T, VQ), where T is an arithmetic type other 7868 // than bool, and VQ is either volatile or empty, there exist 7869 // candidate operator functions of the form 7870 // 7871 // VQ T& operator++(VQ T&); 7872 // T operator++(VQ T&, int); 7873 // 7874 // C++ [over.built]p4: 7875 // 7876 // For every pair (T, VQ), where T is an arithmetic type other 7877 // than bool, and VQ is either volatile or empty, there exist 7878 // candidate operator functions of the form 7879 // 7880 // VQ T& operator--(VQ T&); 7881 // T operator--(VQ T&, int); 7882 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7883 if (!HasArithmeticOrEnumeralCandidateType) 7884 return; 7885 7886 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7887 const auto TypeOfT = ArithmeticTypes[Arith]; 7888 if (TypeOfT == S.Context.BoolTy) { 7889 if (Op == OO_MinusMinus) 7890 continue; 7891 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7892 continue; 7893 } 7894 addPlusPlusMinusMinusStyleOverloads( 7895 TypeOfT, 7896 VisibleTypeConversionsQuals.hasVolatile(), 7897 VisibleTypeConversionsQuals.hasRestrict()); 7898 } 7899 } 7900 7901 // C++ [over.built]p5: 7902 // 7903 // For every pair (T, VQ), where T is a cv-qualified or 7904 // cv-unqualified object type, and VQ is either volatile or 7905 // empty, there exist candidate operator functions of the form 7906 // 7907 // T*VQ& operator++(T*VQ&); 7908 // T*VQ& operator--(T*VQ&); 7909 // T* operator++(T*VQ&, int); 7910 // T* operator--(T*VQ&, int); 7911 void addPlusPlusMinusMinusPointerOverloads() { 7912 for (BuiltinCandidateTypeSet::iterator 7913 Ptr = CandidateTypes[0].pointer_begin(), 7914 PtrEnd = CandidateTypes[0].pointer_end(); 7915 Ptr != PtrEnd; ++Ptr) { 7916 // Skip pointer types that aren't pointers to object types. 7917 if (!(*Ptr)->getPointeeType()->isObjectType()) 7918 continue; 7919 7920 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7921 (!(*Ptr).isVolatileQualified() && 7922 VisibleTypeConversionsQuals.hasVolatile()), 7923 (!(*Ptr).isRestrictQualified() && 7924 VisibleTypeConversionsQuals.hasRestrict())); 7925 } 7926 } 7927 7928 // C++ [over.built]p6: 7929 // For every cv-qualified or cv-unqualified object type T, there 7930 // exist candidate operator functions of the form 7931 // 7932 // T& operator*(T*); 7933 // 7934 // C++ [over.built]p7: 7935 // For every function type T that does not have cv-qualifiers or a 7936 // ref-qualifier, there exist candidate operator functions of the form 7937 // T& operator*(T*); 7938 void addUnaryStarPointerOverloads() { 7939 for (BuiltinCandidateTypeSet::iterator 7940 Ptr = CandidateTypes[0].pointer_begin(), 7941 PtrEnd = CandidateTypes[0].pointer_end(); 7942 Ptr != PtrEnd; ++Ptr) { 7943 QualType ParamTy = *Ptr; 7944 QualType PointeeTy = ParamTy->getPointeeType(); 7945 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7946 continue; 7947 7948 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7949 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7950 continue; 7951 7952 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7953 } 7954 } 7955 7956 // C++ [over.built]p9: 7957 // For every promoted arithmetic type T, there exist candidate 7958 // operator functions of the form 7959 // 7960 // T operator+(T); 7961 // T operator-(T); 7962 void addUnaryPlusOrMinusArithmeticOverloads() { 7963 if (!HasArithmeticOrEnumeralCandidateType) 7964 return; 7965 7966 for (unsigned Arith = FirstPromotedArithmeticType; 7967 Arith < LastPromotedArithmeticType; ++Arith) { 7968 QualType ArithTy = ArithmeticTypes[Arith]; 7969 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7970 } 7971 7972 // Extension: We also add these operators for vector types. 7973 for (BuiltinCandidateTypeSet::iterator 7974 Vec = CandidateTypes[0].vector_begin(), 7975 VecEnd = CandidateTypes[0].vector_end(); 7976 Vec != VecEnd; ++Vec) { 7977 QualType VecTy = *Vec; 7978 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7979 } 7980 } 7981 7982 // C++ [over.built]p8: 7983 // For every type T, there exist candidate operator functions of 7984 // the form 7985 // 7986 // T* operator+(T*); 7987 void addUnaryPlusPointerOverloads() { 7988 for (BuiltinCandidateTypeSet::iterator 7989 Ptr = CandidateTypes[0].pointer_begin(), 7990 PtrEnd = CandidateTypes[0].pointer_end(); 7991 Ptr != PtrEnd; ++Ptr) { 7992 QualType ParamTy = *Ptr; 7993 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7994 } 7995 } 7996 7997 // C++ [over.built]p10: 7998 // For every promoted integral type T, there exist candidate 7999 // operator functions of the form 8000 // 8001 // T operator~(T); 8002 void addUnaryTildePromotedIntegralOverloads() { 8003 if (!HasArithmeticOrEnumeralCandidateType) 8004 return; 8005 8006 for (unsigned Int = FirstPromotedIntegralType; 8007 Int < LastPromotedIntegralType; ++Int) { 8008 QualType IntTy = ArithmeticTypes[Int]; 8009 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8010 } 8011 8012 // Extension: We also add this operator for vector types. 8013 for (BuiltinCandidateTypeSet::iterator 8014 Vec = CandidateTypes[0].vector_begin(), 8015 VecEnd = CandidateTypes[0].vector_end(); 8016 Vec != VecEnd; ++Vec) { 8017 QualType VecTy = *Vec; 8018 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8019 } 8020 } 8021 8022 // C++ [over.match.oper]p16: 8023 // For every pointer to member type T or type std::nullptr_t, there 8024 // exist candidate operator functions of the form 8025 // 8026 // bool operator==(T,T); 8027 // bool operator!=(T,T); 8028 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8029 /// Set of (canonical) types that we've already handled. 8030 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8031 8032 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8033 for (BuiltinCandidateTypeSet::iterator 8034 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8035 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8036 MemPtr != MemPtrEnd; 8037 ++MemPtr) { 8038 // Don't add the same builtin candidate twice. 8039 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8040 continue; 8041 8042 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8043 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8044 } 8045 8046 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8047 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8048 if (AddedTypes.insert(NullPtrTy).second) { 8049 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8050 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8051 } 8052 } 8053 } 8054 } 8055 8056 // C++ [over.built]p15: 8057 // 8058 // For every T, where T is an enumeration type or a pointer type, 8059 // there exist candidate operator functions of the form 8060 // 8061 // bool operator<(T, T); 8062 // bool operator>(T, T); 8063 // bool operator<=(T, T); 8064 // bool operator>=(T, T); 8065 // bool operator==(T, T); 8066 // bool operator!=(T, T); 8067 // R operator<=>(T, T) 8068 void addGenericBinaryPointerOrEnumeralOverloads() { 8069 // C++ [over.match.oper]p3: 8070 // [...]the built-in candidates include all of the candidate operator 8071 // functions defined in 13.6 that, compared to the given operator, [...] 8072 // do not have the same parameter-type-list as any non-template non-member 8073 // candidate. 8074 // 8075 // Note that in practice, this only affects enumeration types because there 8076 // aren't any built-in candidates of record type, and a user-defined operator 8077 // must have an operand of record or enumeration type. Also, the only other 8078 // overloaded operator with enumeration arguments, operator=, 8079 // cannot be overloaded for enumeration types, so this is the only place 8080 // where we must suppress candidates like this. 8081 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8082 UserDefinedBinaryOperators; 8083 8084 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8085 if (CandidateTypes[ArgIdx].enumeration_begin() != 8086 CandidateTypes[ArgIdx].enumeration_end()) { 8087 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8088 CEnd = CandidateSet.end(); 8089 C != CEnd; ++C) { 8090 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8091 continue; 8092 8093 if (C->Function->isFunctionTemplateSpecialization()) 8094 continue; 8095 8096 QualType FirstParamType = 8097 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8098 QualType SecondParamType = 8099 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8100 8101 // Skip if either parameter isn't of enumeral type. 8102 if (!FirstParamType->isEnumeralType() || 8103 !SecondParamType->isEnumeralType()) 8104 continue; 8105 8106 // Add this operator to the set of known user-defined operators. 8107 UserDefinedBinaryOperators.insert( 8108 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8109 S.Context.getCanonicalType(SecondParamType))); 8110 } 8111 } 8112 } 8113 8114 /// Set of (canonical) types that we've already handled. 8115 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8116 8117 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8118 for (BuiltinCandidateTypeSet::iterator 8119 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8120 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8121 Ptr != PtrEnd; ++Ptr) { 8122 // Don't add the same builtin candidate twice. 8123 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8124 continue; 8125 8126 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8127 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8128 } 8129 for (BuiltinCandidateTypeSet::iterator 8130 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8131 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8132 Enum != EnumEnd; ++Enum) { 8133 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8134 8135 // Don't add the same builtin candidate twice, or if a user defined 8136 // candidate exists. 8137 if (!AddedTypes.insert(CanonType).second || 8138 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8139 CanonType))) 8140 continue; 8141 QualType ParamTypes[2] = { *Enum, *Enum }; 8142 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8143 } 8144 } 8145 } 8146 8147 // C++ [over.built]p13: 8148 // 8149 // For every cv-qualified or cv-unqualified object type T 8150 // there exist candidate operator functions of the form 8151 // 8152 // T* operator+(T*, ptrdiff_t); 8153 // T& operator[](T*, ptrdiff_t); [BELOW] 8154 // T* operator-(T*, ptrdiff_t); 8155 // T* operator+(ptrdiff_t, T*); 8156 // T& operator[](ptrdiff_t, T*); [BELOW] 8157 // 8158 // C++ [over.built]p14: 8159 // 8160 // For every T, where T is a pointer to object type, there 8161 // exist candidate operator functions of the form 8162 // 8163 // ptrdiff_t operator-(T, T); 8164 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8165 /// Set of (canonical) types that we've already handled. 8166 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8167 8168 for (int Arg = 0; Arg < 2; ++Arg) { 8169 QualType AsymmetricParamTypes[2] = { 8170 S.Context.getPointerDiffType(), 8171 S.Context.getPointerDiffType(), 8172 }; 8173 for (BuiltinCandidateTypeSet::iterator 8174 Ptr = CandidateTypes[Arg].pointer_begin(), 8175 PtrEnd = CandidateTypes[Arg].pointer_end(); 8176 Ptr != PtrEnd; ++Ptr) { 8177 QualType PointeeTy = (*Ptr)->getPointeeType(); 8178 if (!PointeeTy->isObjectType()) 8179 continue; 8180 8181 AsymmetricParamTypes[Arg] = *Ptr; 8182 if (Arg == 0 || Op == OO_Plus) { 8183 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8184 // T* operator+(ptrdiff_t, T*); 8185 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8186 } 8187 if (Op == OO_Minus) { 8188 // ptrdiff_t operator-(T, T); 8189 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8190 continue; 8191 8192 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8193 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8194 } 8195 } 8196 } 8197 } 8198 8199 // C++ [over.built]p12: 8200 // 8201 // For every pair of promoted arithmetic types L and R, there 8202 // exist candidate operator functions of the form 8203 // 8204 // LR operator*(L, R); 8205 // LR operator/(L, R); 8206 // LR operator+(L, R); 8207 // LR operator-(L, R); 8208 // bool operator<(L, R); 8209 // bool operator>(L, R); 8210 // bool operator<=(L, R); 8211 // bool operator>=(L, R); 8212 // bool operator==(L, R); 8213 // bool operator!=(L, R); 8214 // 8215 // where LR is the result of the usual arithmetic conversions 8216 // between types L and R. 8217 // 8218 // C++ [over.built]p24: 8219 // 8220 // For every pair of promoted arithmetic types L and R, there exist 8221 // candidate operator functions of the form 8222 // 8223 // LR operator?(bool, L, R); 8224 // 8225 // where LR is the result of the usual arithmetic conversions 8226 // between types L and R. 8227 // Our candidates ignore the first parameter. 8228 void addGenericBinaryArithmeticOverloads() { 8229 if (!HasArithmeticOrEnumeralCandidateType) 8230 return; 8231 8232 for (unsigned Left = FirstPromotedArithmeticType; 8233 Left < LastPromotedArithmeticType; ++Left) { 8234 for (unsigned Right = FirstPromotedArithmeticType; 8235 Right < LastPromotedArithmeticType; ++Right) { 8236 QualType LandR[2] = { ArithmeticTypes[Left], 8237 ArithmeticTypes[Right] }; 8238 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8239 } 8240 } 8241 8242 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8243 // conditional operator for vector types. 8244 for (BuiltinCandidateTypeSet::iterator 8245 Vec1 = CandidateTypes[0].vector_begin(), 8246 Vec1End = CandidateTypes[0].vector_end(); 8247 Vec1 != Vec1End; ++Vec1) { 8248 for (BuiltinCandidateTypeSet::iterator 8249 Vec2 = CandidateTypes[1].vector_begin(), 8250 Vec2End = CandidateTypes[1].vector_end(); 8251 Vec2 != Vec2End; ++Vec2) { 8252 QualType LandR[2] = { *Vec1, *Vec2 }; 8253 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8254 } 8255 } 8256 } 8257 8258 // C++2a [over.built]p14: 8259 // 8260 // For every integral type T there exists a candidate operator function 8261 // of the form 8262 // 8263 // std::strong_ordering operator<=>(T, T) 8264 // 8265 // C++2a [over.built]p15: 8266 // 8267 // For every pair of floating-point types L and R, there exists a candidate 8268 // operator function of the form 8269 // 8270 // std::partial_ordering operator<=>(L, R); 8271 // 8272 // FIXME: The current specification for integral types doesn't play nice with 8273 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8274 // comparisons. Under the current spec this can lead to ambiguity during 8275 // overload resolution. For example: 8276 // 8277 // enum A : int {a}; 8278 // auto x = (a <=> (long)42); 8279 // 8280 // error: call is ambiguous for arguments 'A' and 'long'. 8281 // note: candidate operator<=>(int, int) 8282 // note: candidate operator<=>(long, long) 8283 // 8284 // To avoid this error, this function deviates from the specification and adds 8285 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8286 // arithmetic types (the same as the generic relational overloads). 8287 // 8288 // For now this function acts as a placeholder. 8289 void addThreeWayArithmeticOverloads() { 8290 addGenericBinaryArithmeticOverloads(); 8291 } 8292 8293 // C++ [over.built]p17: 8294 // 8295 // For every pair of promoted integral types L and R, there 8296 // exist candidate operator functions of the form 8297 // 8298 // LR operator%(L, R); 8299 // LR operator&(L, R); 8300 // LR operator^(L, R); 8301 // LR operator|(L, R); 8302 // L operator<<(L, R); 8303 // L operator>>(L, R); 8304 // 8305 // where LR is the result of the usual arithmetic conversions 8306 // between types L and R. 8307 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8308 if (!HasArithmeticOrEnumeralCandidateType) 8309 return; 8310 8311 for (unsigned Left = FirstPromotedIntegralType; 8312 Left < LastPromotedIntegralType; ++Left) { 8313 for (unsigned Right = FirstPromotedIntegralType; 8314 Right < LastPromotedIntegralType; ++Right) { 8315 QualType LandR[2] = { ArithmeticTypes[Left], 8316 ArithmeticTypes[Right] }; 8317 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8318 } 8319 } 8320 } 8321 8322 // C++ [over.built]p20: 8323 // 8324 // For every pair (T, VQ), where T is an enumeration or 8325 // pointer to member type and VQ is either volatile or 8326 // empty, there exist candidate operator functions of the form 8327 // 8328 // VQ T& operator=(VQ T&, T); 8329 void addAssignmentMemberPointerOrEnumeralOverloads() { 8330 /// Set of (canonical) types that we've already handled. 8331 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8332 8333 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8334 for (BuiltinCandidateTypeSet::iterator 8335 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8336 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8337 Enum != EnumEnd; ++Enum) { 8338 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8339 continue; 8340 8341 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8342 } 8343 8344 for (BuiltinCandidateTypeSet::iterator 8345 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8346 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8347 MemPtr != MemPtrEnd; ++MemPtr) { 8348 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8349 continue; 8350 8351 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8352 } 8353 } 8354 } 8355 8356 // C++ [over.built]p19: 8357 // 8358 // For every pair (T, VQ), where T is any type and VQ is either 8359 // volatile or empty, there exist candidate operator functions 8360 // of the form 8361 // 8362 // T*VQ& operator=(T*VQ&, T*); 8363 // 8364 // C++ [over.built]p21: 8365 // 8366 // For every pair (T, VQ), where T is a cv-qualified or 8367 // cv-unqualified object type and VQ is either volatile or 8368 // empty, there exist candidate operator functions of the form 8369 // 8370 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8371 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8372 void addAssignmentPointerOverloads(bool isEqualOp) { 8373 /// Set of (canonical) types that we've already handled. 8374 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8375 8376 for (BuiltinCandidateTypeSet::iterator 8377 Ptr = CandidateTypes[0].pointer_begin(), 8378 PtrEnd = CandidateTypes[0].pointer_end(); 8379 Ptr != PtrEnd; ++Ptr) { 8380 // If this is operator=, keep track of the builtin candidates we added. 8381 if (isEqualOp) 8382 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8383 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8384 continue; 8385 8386 // non-volatile version 8387 QualType ParamTypes[2] = { 8388 S.Context.getLValueReferenceType(*Ptr), 8389 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8390 }; 8391 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8392 /*IsAssigmentOperator=*/ isEqualOp); 8393 8394 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8395 VisibleTypeConversionsQuals.hasVolatile(); 8396 if (NeedVolatile) { 8397 // volatile version 8398 ParamTypes[0] = 8399 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8400 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8401 /*IsAssigmentOperator=*/isEqualOp); 8402 } 8403 8404 if (!(*Ptr).isRestrictQualified() && 8405 VisibleTypeConversionsQuals.hasRestrict()) { 8406 // restrict version 8407 ParamTypes[0] 8408 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8409 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8410 /*IsAssigmentOperator=*/isEqualOp); 8411 8412 if (NeedVolatile) { 8413 // volatile restrict version 8414 ParamTypes[0] 8415 = S.Context.getLValueReferenceType( 8416 S.Context.getCVRQualifiedType(*Ptr, 8417 (Qualifiers::Volatile | 8418 Qualifiers::Restrict))); 8419 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8420 /*IsAssigmentOperator=*/isEqualOp); 8421 } 8422 } 8423 } 8424 8425 if (isEqualOp) { 8426 for (BuiltinCandidateTypeSet::iterator 8427 Ptr = CandidateTypes[1].pointer_begin(), 8428 PtrEnd = CandidateTypes[1].pointer_end(); 8429 Ptr != PtrEnd; ++Ptr) { 8430 // Make sure we don't add the same candidate twice. 8431 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8432 continue; 8433 8434 QualType ParamTypes[2] = { 8435 S.Context.getLValueReferenceType(*Ptr), 8436 *Ptr, 8437 }; 8438 8439 // non-volatile version 8440 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8441 /*IsAssigmentOperator=*/true); 8442 8443 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8444 VisibleTypeConversionsQuals.hasVolatile(); 8445 if (NeedVolatile) { 8446 // volatile version 8447 ParamTypes[0] = 8448 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8449 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8450 /*IsAssigmentOperator=*/true); 8451 } 8452 8453 if (!(*Ptr).isRestrictQualified() && 8454 VisibleTypeConversionsQuals.hasRestrict()) { 8455 // restrict version 8456 ParamTypes[0] 8457 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8458 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8459 /*IsAssigmentOperator=*/true); 8460 8461 if (NeedVolatile) { 8462 // volatile restrict version 8463 ParamTypes[0] 8464 = S.Context.getLValueReferenceType( 8465 S.Context.getCVRQualifiedType(*Ptr, 8466 (Qualifiers::Volatile | 8467 Qualifiers::Restrict))); 8468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8469 /*IsAssigmentOperator=*/true); 8470 } 8471 } 8472 } 8473 } 8474 } 8475 8476 // C++ [over.built]p18: 8477 // 8478 // For every triple (L, VQ, R), where L is an arithmetic type, 8479 // VQ is either volatile or empty, and R is a promoted 8480 // arithmetic type, there exist candidate operator functions of 8481 // the form 8482 // 8483 // VQ L& operator=(VQ L&, R); 8484 // VQ L& operator*=(VQ L&, R); 8485 // VQ L& operator/=(VQ L&, R); 8486 // VQ L& operator+=(VQ L&, R); 8487 // VQ L& operator-=(VQ L&, R); 8488 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8489 if (!HasArithmeticOrEnumeralCandidateType) 8490 return; 8491 8492 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8493 for (unsigned Right = FirstPromotedArithmeticType; 8494 Right < LastPromotedArithmeticType; ++Right) { 8495 QualType ParamTypes[2]; 8496 ParamTypes[1] = ArithmeticTypes[Right]; 8497 8498 // Add this built-in operator as a candidate (VQ is empty). 8499 ParamTypes[0] = 8500 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8501 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8502 /*IsAssigmentOperator=*/isEqualOp); 8503 8504 // Add this built-in operator as a candidate (VQ is 'volatile'). 8505 if (VisibleTypeConversionsQuals.hasVolatile()) { 8506 ParamTypes[0] = 8507 S.Context.getVolatileType(ArithmeticTypes[Left]); 8508 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8509 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8510 /*IsAssigmentOperator=*/isEqualOp); 8511 } 8512 } 8513 } 8514 8515 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8516 for (BuiltinCandidateTypeSet::iterator 8517 Vec1 = CandidateTypes[0].vector_begin(), 8518 Vec1End = CandidateTypes[0].vector_end(); 8519 Vec1 != Vec1End; ++Vec1) { 8520 for (BuiltinCandidateTypeSet::iterator 8521 Vec2 = CandidateTypes[1].vector_begin(), 8522 Vec2End = CandidateTypes[1].vector_end(); 8523 Vec2 != Vec2End; ++Vec2) { 8524 QualType ParamTypes[2]; 8525 ParamTypes[1] = *Vec2; 8526 // Add this built-in operator as a candidate (VQ is empty). 8527 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8528 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8529 /*IsAssigmentOperator=*/isEqualOp); 8530 8531 // Add this built-in operator as a candidate (VQ is 'volatile'). 8532 if (VisibleTypeConversionsQuals.hasVolatile()) { 8533 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8534 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8535 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8536 /*IsAssigmentOperator=*/isEqualOp); 8537 } 8538 } 8539 } 8540 } 8541 8542 // C++ [over.built]p22: 8543 // 8544 // For every triple (L, VQ, R), where L is an integral type, VQ 8545 // is either volatile or empty, and R is a promoted integral 8546 // type, there exist candidate operator functions of the form 8547 // 8548 // VQ L& operator%=(VQ L&, R); 8549 // VQ L& operator<<=(VQ L&, R); 8550 // VQ L& operator>>=(VQ L&, R); 8551 // VQ L& operator&=(VQ L&, R); 8552 // VQ L& operator^=(VQ L&, R); 8553 // VQ L& operator|=(VQ L&, R); 8554 void addAssignmentIntegralOverloads() { 8555 if (!HasArithmeticOrEnumeralCandidateType) 8556 return; 8557 8558 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8559 for (unsigned Right = FirstPromotedIntegralType; 8560 Right < LastPromotedIntegralType; ++Right) { 8561 QualType ParamTypes[2]; 8562 ParamTypes[1] = ArithmeticTypes[Right]; 8563 8564 // Add this built-in operator as a candidate (VQ is empty). 8565 ParamTypes[0] = 8566 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8568 if (VisibleTypeConversionsQuals.hasVolatile()) { 8569 // Add this built-in operator as a candidate (VQ is 'volatile'). 8570 ParamTypes[0] = ArithmeticTypes[Left]; 8571 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8572 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8573 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8574 } 8575 } 8576 } 8577 } 8578 8579 // C++ [over.operator]p23: 8580 // 8581 // There also exist candidate operator functions of the form 8582 // 8583 // bool operator!(bool); 8584 // bool operator&&(bool, bool); 8585 // bool operator||(bool, bool); 8586 void addExclaimOverload() { 8587 QualType ParamTy = S.Context.BoolTy; 8588 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8589 /*IsAssignmentOperator=*/false, 8590 /*NumContextualBoolArguments=*/1); 8591 } 8592 void addAmpAmpOrPipePipeOverload() { 8593 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8594 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8595 /*IsAssignmentOperator=*/false, 8596 /*NumContextualBoolArguments=*/2); 8597 } 8598 8599 // C++ [over.built]p13: 8600 // 8601 // For every cv-qualified or cv-unqualified object type T there 8602 // exist candidate operator functions of the form 8603 // 8604 // T* operator+(T*, ptrdiff_t); [ABOVE] 8605 // T& operator[](T*, ptrdiff_t); 8606 // T* operator-(T*, ptrdiff_t); [ABOVE] 8607 // T* operator+(ptrdiff_t, T*); [ABOVE] 8608 // T& operator[](ptrdiff_t, T*); 8609 void addSubscriptOverloads() { 8610 for (BuiltinCandidateTypeSet::iterator 8611 Ptr = CandidateTypes[0].pointer_begin(), 8612 PtrEnd = CandidateTypes[0].pointer_end(); 8613 Ptr != PtrEnd; ++Ptr) { 8614 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8615 QualType PointeeType = (*Ptr)->getPointeeType(); 8616 if (!PointeeType->isObjectType()) 8617 continue; 8618 8619 // T& operator[](T*, ptrdiff_t) 8620 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8621 } 8622 8623 for (BuiltinCandidateTypeSet::iterator 8624 Ptr = CandidateTypes[1].pointer_begin(), 8625 PtrEnd = CandidateTypes[1].pointer_end(); 8626 Ptr != PtrEnd; ++Ptr) { 8627 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8628 QualType PointeeType = (*Ptr)->getPointeeType(); 8629 if (!PointeeType->isObjectType()) 8630 continue; 8631 8632 // T& operator[](ptrdiff_t, T*) 8633 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8634 } 8635 } 8636 8637 // C++ [over.built]p11: 8638 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8639 // C1 is the same type as C2 or is a derived class of C2, T is an object 8640 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8641 // there exist candidate operator functions of the form 8642 // 8643 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8644 // 8645 // where CV12 is the union of CV1 and CV2. 8646 void addArrowStarOverloads() { 8647 for (BuiltinCandidateTypeSet::iterator 8648 Ptr = CandidateTypes[0].pointer_begin(), 8649 PtrEnd = CandidateTypes[0].pointer_end(); 8650 Ptr != PtrEnd; ++Ptr) { 8651 QualType C1Ty = (*Ptr); 8652 QualType C1; 8653 QualifierCollector Q1; 8654 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8655 if (!isa<RecordType>(C1)) 8656 continue; 8657 // heuristic to reduce number of builtin candidates in the set. 8658 // Add volatile/restrict version only if there are conversions to a 8659 // volatile/restrict type. 8660 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8661 continue; 8662 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8663 continue; 8664 for (BuiltinCandidateTypeSet::iterator 8665 MemPtr = CandidateTypes[1].member_pointer_begin(), 8666 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8667 MemPtr != MemPtrEnd; ++MemPtr) { 8668 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8669 QualType C2 = QualType(mptr->getClass(), 0); 8670 C2 = C2.getUnqualifiedType(); 8671 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8672 break; 8673 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8674 // build CV12 T& 8675 QualType T = mptr->getPointeeType(); 8676 if (!VisibleTypeConversionsQuals.hasVolatile() && 8677 T.isVolatileQualified()) 8678 continue; 8679 if (!VisibleTypeConversionsQuals.hasRestrict() && 8680 T.isRestrictQualified()) 8681 continue; 8682 T = Q1.apply(S.Context, T); 8683 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8684 } 8685 } 8686 } 8687 8688 // Note that we don't consider the first argument, since it has been 8689 // contextually converted to bool long ago. The candidates below are 8690 // therefore added as binary. 8691 // 8692 // C++ [over.built]p25: 8693 // For every type T, where T is a pointer, pointer-to-member, or scoped 8694 // enumeration type, there exist candidate operator functions of the form 8695 // 8696 // T operator?(bool, T, T); 8697 // 8698 void addConditionalOperatorOverloads() { 8699 /// Set of (canonical) types that we've already handled. 8700 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8701 8702 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8703 for (BuiltinCandidateTypeSet::iterator 8704 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8705 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8706 Ptr != PtrEnd; ++Ptr) { 8707 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8708 continue; 8709 8710 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8711 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8712 } 8713 8714 for (BuiltinCandidateTypeSet::iterator 8715 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8716 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8717 MemPtr != MemPtrEnd; ++MemPtr) { 8718 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8719 continue; 8720 8721 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8722 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8723 } 8724 8725 if (S.getLangOpts().CPlusPlus11) { 8726 for (BuiltinCandidateTypeSet::iterator 8727 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8728 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8729 Enum != EnumEnd; ++Enum) { 8730 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8731 continue; 8732 8733 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8734 continue; 8735 8736 QualType ParamTypes[2] = { *Enum, *Enum }; 8737 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8738 } 8739 } 8740 } 8741 } 8742 }; 8743 8744 } // end anonymous namespace 8745 8746 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8747 /// operator overloads to the candidate set (C++ [over.built]), based 8748 /// on the operator @p Op and the arguments given. For example, if the 8749 /// operator is a binary '+', this routine might add "int 8750 /// operator+(int, int)" to cover integer addition. 8751 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8752 SourceLocation OpLoc, 8753 ArrayRef<Expr *> Args, 8754 OverloadCandidateSet &CandidateSet) { 8755 // Find all of the types that the arguments can convert to, but only 8756 // if the operator we're looking at has built-in operator candidates 8757 // that make use of these types. Also record whether we encounter non-record 8758 // candidate types or either arithmetic or enumeral candidate types. 8759 Qualifiers VisibleTypeConversionsQuals; 8760 VisibleTypeConversionsQuals.addConst(); 8761 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8762 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8763 8764 bool HasNonRecordCandidateType = false; 8765 bool HasArithmeticOrEnumeralCandidateType = false; 8766 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8767 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8768 CandidateTypes.emplace_back(*this); 8769 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8770 OpLoc, 8771 true, 8772 (Op == OO_Exclaim || 8773 Op == OO_AmpAmp || 8774 Op == OO_PipePipe), 8775 VisibleTypeConversionsQuals); 8776 HasNonRecordCandidateType = HasNonRecordCandidateType || 8777 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8778 HasArithmeticOrEnumeralCandidateType = 8779 HasArithmeticOrEnumeralCandidateType || 8780 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8781 } 8782 8783 // Exit early when no non-record types have been added to the candidate set 8784 // for any of the arguments to the operator. 8785 // 8786 // We can't exit early for !, ||, or &&, since there we have always have 8787 // 'bool' overloads. 8788 if (!HasNonRecordCandidateType && 8789 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8790 return; 8791 8792 // Setup an object to manage the common state for building overloads. 8793 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8794 VisibleTypeConversionsQuals, 8795 HasArithmeticOrEnumeralCandidateType, 8796 CandidateTypes, CandidateSet); 8797 8798 // Dispatch over the operation to add in only those overloads which apply. 8799 switch (Op) { 8800 case OO_None: 8801 case NUM_OVERLOADED_OPERATORS: 8802 llvm_unreachable("Expected an overloaded operator"); 8803 8804 case OO_New: 8805 case OO_Delete: 8806 case OO_Array_New: 8807 case OO_Array_Delete: 8808 case OO_Call: 8809 llvm_unreachable( 8810 "Special operators don't use AddBuiltinOperatorCandidates"); 8811 8812 case OO_Comma: 8813 case OO_Arrow: 8814 case OO_Coawait: 8815 // C++ [over.match.oper]p3: 8816 // -- For the operator ',', the unary operator '&', the 8817 // operator '->', or the operator 'co_await', the 8818 // built-in candidates set is empty. 8819 break; 8820 8821 case OO_Plus: // '+' is either unary or binary 8822 if (Args.size() == 1) 8823 OpBuilder.addUnaryPlusPointerOverloads(); 8824 LLVM_FALLTHROUGH; 8825 8826 case OO_Minus: // '-' is either unary or binary 8827 if (Args.size() == 1) { 8828 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8829 } else { 8830 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8831 OpBuilder.addGenericBinaryArithmeticOverloads(); 8832 } 8833 break; 8834 8835 case OO_Star: // '*' is either unary or binary 8836 if (Args.size() == 1) 8837 OpBuilder.addUnaryStarPointerOverloads(); 8838 else 8839 OpBuilder.addGenericBinaryArithmeticOverloads(); 8840 break; 8841 8842 case OO_Slash: 8843 OpBuilder.addGenericBinaryArithmeticOverloads(); 8844 break; 8845 8846 case OO_PlusPlus: 8847 case OO_MinusMinus: 8848 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8849 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8850 break; 8851 8852 case OO_EqualEqual: 8853 case OO_ExclaimEqual: 8854 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8855 LLVM_FALLTHROUGH; 8856 8857 case OO_Less: 8858 case OO_Greater: 8859 case OO_LessEqual: 8860 case OO_GreaterEqual: 8861 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8862 OpBuilder.addGenericBinaryArithmeticOverloads(); 8863 break; 8864 8865 case OO_Spaceship: 8866 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8867 OpBuilder.addThreeWayArithmeticOverloads(); 8868 break; 8869 8870 case OO_Percent: 8871 case OO_Caret: 8872 case OO_Pipe: 8873 case OO_LessLess: 8874 case OO_GreaterGreater: 8875 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8876 break; 8877 8878 case OO_Amp: // '&' is either unary or binary 8879 if (Args.size() == 1) 8880 // C++ [over.match.oper]p3: 8881 // -- For the operator ',', the unary operator '&', or the 8882 // operator '->', the built-in candidates set is empty. 8883 break; 8884 8885 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8886 break; 8887 8888 case OO_Tilde: 8889 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8890 break; 8891 8892 case OO_Equal: 8893 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8894 LLVM_FALLTHROUGH; 8895 8896 case OO_PlusEqual: 8897 case OO_MinusEqual: 8898 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8899 LLVM_FALLTHROUGH; 8900 8901 case OO_StarEqual: 8902 case OO_SlashEqual: 8903 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8904 break; 8905 8906 case OO_PercentEqual: 8907 case OO_LessLessEqual: 8908 case OO_GreaterGreaterEqual: 8909 case OO_AmpEqual: 8910 case OO_CaretEqual: 8911 case OO_PipeEqual: 8912 OpBuilder.addAssignmentIntegralOverloads(); 8913 break; 8914 8915 case OO_Exclaim: 8916 OpBuilder.addExclaimOverload(); 8917 break; 8918 8919 case OO_AmpAmp: 8920 case OO_PipePipe: 8921 OpBuilder.addAmpAmpOrPipePipeOverload(); 8922 break; 8923 8924 case OO_Subscript: 8925 OpBuilder.addSubscriptOverloads(); 8926 break; 8927 8928 case OO_ArrowStar: 8929 OpBuilder.addArrowStarOverloads(); 8930 break; 8931 8932 case OO_Conditional: 8933 OpBuilder.addConditionalOperatorOverloads(); 8934 OpBuilder.addGenericBinaryArithmeticOverloads(); 8935 break; 8936 } 8937 } 8938 8939 /// Add function candidates found via argument-dependent lookup 8940 /// to the set of overloading candidates. 8941 /// 8942 /// This routine performs argument-dependent name lookup based on the 8943 /// given function name (which may also be an operator name) and adds 8944 /// all of the overload candidates found by ADL to the overload 8945 /// candidate set (C++ [basic.lookup.argdep]). 8946 void 8947 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8948 SourceLocation Loc, 8949 ArrayRef<Expr *> Args, 8950 TemplateArgumentListInfo *ExplicitTemplateArgs, 8951 OverloadCandidateSet& CandidateSet, 8952 bool PartialOverloading) { 8953 ADLResult Fns; 8954 8955 // FIXME: This approach for uniquing ADL results (and removing 8956 // redundant candidates from the set) relies on pointer-equality, 8957 // which means we need to key off the canonical decl. However, 8958 // always going back to the canonical decl might not get us the 8959 // right set of default arguments. What default arguments are 8960 // we supposed to consider on ADL candidates, anyway? 8961 8962 // FIXME: Pass in the explicit template arguments? 8963 ArgumentDependentLookup(Name, Loc, Args, Fns); 8964 8965 // Erase all of the candidates we already knew about. 8966 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8967 CandEnd = CandidateSet.end(); 8968 Cand != CandEnd; ++Cand) 8969 if (Cand->Function) { 8970 Fns.erase(Cand->Function); 8971 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8972 Fns.erase(FunTmpl); 8973 } 8974 8975 // For each of the ADL candidates we found, add it to the overload 8976 // set. 8977 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8978 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8979 8980 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8981 if (ExplicitTemplateArgs) 8982 continue; 8983 8984 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 8985 /*SupressUserConversions=*/false, PartialOverloading, 8986 /*AllowExplicit=*/false, ADLCallKind::UsesADL); 8987 } else { 8988 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl, 8989 ExplicitTemplateArgs, Args, CandidateSet, 8990 /*SupressUserConversions=*/false, 8991 PartialOverloading, ADLCallKind::UsesADL); 8992 } 8993 } 8994 } 8995 8996 namespace { 8997 enum class Comparison { Equal, Better, Worse }; 8998 } 8999 9000 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9001 /// overload resolution. 9002 /// 9003 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9004 /// Cand1's first N enable_if attributes have precisely the same conditions as 9005 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9006 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9007 /// 9008 /// Note that you can have a pair of candidates such that Cand1's enable_if 9009 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9010 /// worse than Cand1's. 9011 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9012 const FunctionDecl *Cand2) { 9013 // Common case: One (or both) decls don't have enable_if attrs. 9014 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9015 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9016 if (!Cand1Attr || !Cand2Attr) { 9017 if (Cand1Attr == Cand2Attr) 9018 return Comparison::Equal; 9019 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9020 } 9021 9022 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9023 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9024 9025 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9026 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9027 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9028 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9029 9030 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9031 // has fewer enable_if attributes than Cand2, and vice versa. 9032 if (!Cand1A) 9033 return Comparison::Worse; 9034 if (!Cand2A) 9035 return Comparison::Better; 9036 9037 Cand1ID.clear(); 9038 Cand2ID.clear(); 9039 9040 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9041 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9042 if (Cand1ID != Cand2ID) 9043 return Comparison::Worse; 9044 } 9045 9046 return Comparison::Equal; 9047 } 9048 9049 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9050 const OverloadCandidate &Cand2) { 9051 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9052 !Cand2.Function->isMultiVersion()) 9053 return false; 9054 9055 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9056 // is obviously better. 9057 if (Cand1.Function->isInvalidDecl()) return false; 9058 if (Cand2.Function->isInvalidDecl()) return true; 9059 9060 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9061 // cpu_dispatch, else arbitrarily based on the identifiers. 9062 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9063 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9064 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9065 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9066 9067 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9068 return false; 9069 9070 if (Cand1CPUDisp && !Cand2CPUDisp) 9071 return true; 9072 if (Cand2CPUDisp && !Cand1CPUDisp) 9073 return false; 9074 9075 if (Cand1CPUSpec && Cand2CPUSpec) { 9076 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9077 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9078 9079 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9080 FirstDiff = std::mismatch( 9081 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9082 Cand2CPUSpec->cpus_begin(), 9083 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9084 return LHS->getName() == RHS->getName(); 9085 }); 9086 9087 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9088 "Two different cpu-specific versions should not have the same " 9089 "identifier list, otherwise they'd be the same decl!"); 9090 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9091 } 9092 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9093 } 9094 9095 /// isBetterOverloadCandidate - Determines whether the first overload 9096 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9097 bool clang::isBetterOverloadCandidate( 9098 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9099 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9100 // Define viable functions to be better candidates than non-viable 9101 // functions. 9102 if (!Cand2.Viable) 9103 return Cand1.Viable; 9104 else if (!Cand1.Viable) 9105 return false; 9106 9107 // C++ [over.match.best]p1: 9108 // 9109 // -- if F is a static member function, ICS1(F) is defined such 9110 // that ICS1(F) is neither better nor worse than ICS1(G) for 9111 // any function G, and, symmetrically, ICS1(G) is neither 9112 // better nor worse than ICS1(F). 9113 unsigned StartArg = 0; 9114 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9115 StartArg = 1; 9116 9117 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9118 // We don't allow incompatible pointer conversions in C++. 9119 if (!S.getLangOpts().CPlusPlus) 9120 return ICS.isStandard() && 9121 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9122 9123 // The only ill-formed conversion we allow in C++ is the string literal to 9124 // char* conversion, which is only considered ill-formed after C++11. 9125 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9126 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9127 }; 9128 9129 // Define functions that don't require ill-formed conversions for a given 9130 // argument to be better candidates than functions that do. 9131 unsigned NumArgs = Cand1.Conversions.size(); 9132 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9133 bool HasBetterConversion = false; 9134 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9135 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9136 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9137 if (Cand1Bad != Cand2Bad) { 9138 if (Cand1Bad) 9139 return false; 9140 HasBetterConversion = true; 9141 } 9142 } 9143 9144 if (HasBetterConversion) 9145 return true; 9146 9147 // C++ [over.match.best]p1: 9148 // A viable function F1 is defined to be a better function than another 9149 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9150 // conversion sequence than ICSi(F2), and then... 9151 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9152 switch (CompareImplicitConversionSequences(S, Loc, 9153 Cand1.Conversions[ArgIdx], 9154 Cand2.Conversions[ArgIdx])) { 9155 case ImplicitConversionSequence::Better: 9156 // Cand1 has a better conversion sequence. 9157 HasBetterConversion = true; 9158 break; 9159 9160 case ImplicitConversionSequence::Worse: 9161 // Cand1 can't be better than Cand2. 9162 return false; 9163 9164 case ImplicitConversionSequence::Indistinguishable: 9165 // Do nothing. 9166 break; 9167 } 9168 } 9169 9170 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9171 // ICSj(F2), or, if not that, 9172 if (HasBetterConversion) 9173 return true; 9174 9175 // -- the context is an initialization by user-defined conversion 9176 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9177 // from the return type of F1 to the destination type (i.e., 9178 // the type of the entity being initialized) is a better 9179 // conversion sequence than the standard conversion sequence 9180 // from the return type of F2 to the destination type. 9181 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9182 Cand1.Function && Cand2.Function && 9183 isa<CXXConversionDecl>(Cand1.Function) && 9184 isa<CXXConversionDecl>(Cand2.Function)) { 9185 // First check whether we prefer one of the conversion functions over the 9186 // other. This only distinguishes the results in non-standard, extension 9187 // cases such as the conversion from a lambda closure type to a function 9188 // pointer or block. 9189 ImplicitConversionSequence::CompareKind Result = 9190 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9191 if (Result == ImplicitConversionSequence::Indistinguishable) 9192 Result = CompareStandardConversionSequences(S, Loc, 9193 Cand1.FinalConversion, 9194 Cand2.FinalConversion); 9195 9196 if (Result != ImplicitConversionSequence::Indistinguishable) 9197 return Result == ImplicitConversionSequence::Better; 9198 9199 // FIXME: Compare kind of reference binding if conversion functions 9200 // convert to a reference type used in direct reference binding, per 9201 // C++14 [over.match.best]p1 section 2 bullet 3. 9202 } 9203 9204 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9205 // as combined with the resolution to CWG issue 243. 9206 // 9207 // When the context is initialization by constructor ([over.match.ctor] or 9208 // either phase of [over.match.list]), a constructor is preferred over 9209 // a conversion function. 9210 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9211 Cand1.Function && Cand2.Function && 9212 isa<CXXConstructorDecl>(Cand1.Function) != 9213 isa<CXXConstructorDecl>(Cand2.Function)) 9214 return isa<CXXConstructorDecl>(Cand1.Function); 9215 9216 // -- F1 is a non-template function and F2 is a function template 9217 // specialization, or, if not that, 9218 bool Cand1IsSpecialization = Cand1.Function && 9219 Cand1.Function->getPrimaryTemplate(); 9220 bool Cand2IsSpecialization = Cand2.Function && 9221 Cand2.Function->getPrimaryTemplate(); 9222 if (Cand1IsSpecialization != Cand2IsSpecialization) 9223 return Cand2IsSpecialization; 9224 9225 // -- F1 and F2 are function template specializations, and the function 9226 // template for F1 is more specialized than the template for F2 9227 // according to the partial ordering rules described in 14.5.5.2, or, 9228 // if not that, 9229 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9230 if (FunctionTemplateDecl *BetterTemplate 9231 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9232 Cand2.Function->getPrimaryTemplate(), 9233 Loc, 9234 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9235 : TPOC_Call, 9236 Cand1.ExplicitCallArguments, 9237 Cand2.ExplicitCallArguments)) 9238 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9239 } 9240 9241 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9242 // A derived-class constructor beats an (inherited) base class constructor. 9243 bool Cand1IsInherited = 9244 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9245 bool Cand2IsInherited = 9246 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9247 if (Cand1IsInherited != Cand2IsInherited) 9248 return Cand2IsInherited; 9249 else if (Cand1IsInherited) { 9250 assert(Cand2IsInherited); 9251 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9252 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9253 if (Cand1Class->isDerivedFrom(Cand2Class)) 9254 return true; 9255 if (Cand2Class->isDerivedFrom(Cand1Class)) 9256 return false; 9257 // Inherited from sibling base classes: still ambiguous. 9258 } 9259 9260 // Check C++17 tie-breakers for deduction guides. 9261 { 9262 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9263 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9264 if (Guide1 && Guide2) { 9265 // -- F1 is generated from a deduction-guide and F2 is not 9266 if (Guide1->isImplicit() != Guide2->isImplicit()) 9267 return Guide2->isImplicit(); 9268 9269 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9270 if (Guide1->isCopyDeductionCandidate()) 9271 return true; 9272 } 9273 } 9274 9275 // Check for enable_if value-based overload resolution. 9276 if (Cand1.Function && Cand2.Function) { 9277 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9278 if (Cmp != Comparison::Equal) 9279 return Cmp == Comparison::Better; 9280 } 9281 9282 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9283 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9284 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9285 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9286 } 9287 9288 bool HasPS1 = Cand1.Function != nullptr && 9289 functionHasPassObjectSizeParams(Cand1.Function); 9290 bool HasPS2 = Cand2.Function != nullptr && 9291 functionHasPassObjectSizeParams(Cand2.Function); 9292 if (HasPS1 != HasPS2 && HasPS1) 9293 return true; 9294 9295 return isBetterMultiversionCandidate(Cand1, Cand2); 9296 } 9297 9298 /// Determine whether two declarations are "equivalent" for the purposes of 9299 /// name lookup and overload resolution. This applies when the same internal/no 9300 /// linkage entity is defined by two modules (probably by textually including 9301 /// the same header). In such a case, we don't consider the declarations to 9302 /// declare the same entity, but we also don't want lookups with both 9303 /// declarations visible to be ambiguous in some cases (this happens when using 9304 /// a modularized libstdc++). 9305 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9306 const NamedDecl *B) { 9307 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9308 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9309 if (!VA || !VB) 9310 return false; 9311 9312 // The declarations must be declaring the same name as an internal linkage 9313 // entity in different modules. 9314 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9315 VB->getDeclContext()->getRedeclContext()) || 9316 getOwningModule(const_cast<ValueDecl *>(VA)) == 9317 getOwningModule(const_cast<ValueDecl *>(VB)) || 9318 VA->isExternallyVisible() || VB->isExternallyVisible()) 9319 return false; 9320 9321 // Check that the declarations appear to be equivalent. 9322 // 9323 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9324 // For constants and functions, we should check the initializer or body is 9325 // the same. For non-constant variables, we shouldn't allow it at all. 9326 if (Context.hasSameType(VA->getType(), VB->getType())) 9327 return true; 9328 9329 // Enum constants within unnamed enumerations will have different types, but 9330 // may still be similar enough to be interchangeable for our purposes. 9331 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9332 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9333 // Only handle anonymous enums. If the enumerations were named and 9334 // equivalent, they would have been merged to the same type. 9335 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9336 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9337 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9338 !Context.hasSameType(EnumA->getIntegerType(), 9339 EnumB->getIntegerType())) 9340 return false; 9341 // Allow this only if the value is the same for both enumerators. 9342 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9343 } 9344 } 9345 9346 // Nothing else is sufficiently similar. 9347 return false; 9348 } 9349 9350 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9351 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9352 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9353 9354 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9355 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9356 << !M << (M ? M->getFullModuleName() : ""); 9357 9358 for (auto *E : Equiv) { 9359 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9360 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9361 << !M << (M ? M->getFullModuleName() : ""); 9362 } 9363 } 9364 9365 /// Computes the best viable function (C++ 13.3.3) 9366 /// within an overload candidate set. 9367 /// 9368 /// \param Loc The location of the function name (or operator symbol) for 9369 /// which overload resolution occurs. 9370 /// 9371 /// \param Best If overload resolution was successful or found a deleted 9372 /// function, \p Best points to the candidate function found. 9373 /// 9374 /// \returns The result of overload resolution. 9375 OverloadingResult 9376 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9377 iterator &Best) { 9378 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9379 std::transform(begin(), end(), std::back_inserter(Candidates), 9380 [](OverloadCandidate &Cand) { return &Cand; }); 9381 9382 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9383 // are accepted by both clang and NVCC. However, during a particular 9384 // compilation mode only one call variant is viable. We need to 9385 // exclude non-viable overload candidates from consideration based 9386 // only on their host/device attributes. Specifically, if one 9387 // candidate call is WrongSide and the other is SameSide, we ignore 9388 // the WrongSide candidate. 9389 if (S.getLangOpts().CUDA) { 9390 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9391 bool ContainsSameSideCandidate = 9392 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9393 return Cand->Function && 9394 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9395 Sema::CFP_SameSide; 9396 }); 9397 if (ContainsSameSideCandidate) { 9398 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9399 return Cand->Function && 9400 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9401 Sema::CFP_WrongSide; 9402 }; 9403 llvm::erase_if(Candidates, IsWrongSideCandidate); 9404 } 9405 } 9406 9407 // Find the best viable function. 9408 Best = end(); 9409 for (auto *Cand : Candidates) 9410 if (Cand->Viable) 9411 if (Best == end() || 9412 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9413 Best = Cand; 9414 9415 // If we didn't find any viable functions, abort. 9416 if (Best == end()) 9417 return OR_No_Viable_Function; 9418 9419 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9420 9421 // Make sure that this function is better than every other viable 9422 // function. If not, we have an ambiguity. 9423 for (auto *Cand : Candidates) { 9424 if (Cand->Viable && Cand != Best && 9425 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9426 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9427 Cand->Function)) { 9428 EquivalentCands.push_back(Cand->Function); 9429 continue; 9430 } 9431 9432 Best = end(); 9433 return OR_Ambiguous; 9434 } 9435 } 9436 9437 // Best is the best viable function. 9438 if (Best->Function && 9439 (Best->Function->isDeleted() || 9440 S.isFunctionConsideredUnavailable(Best->Function))) 9441 return OR_Deleted; 9442 9443 if (!EquivalentCands.empty()) 9444 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9445 EquivalentCands); 9446 9447 return OR_Success; 9448 } 9449 9450 namespace { 9451 9452 enum OverloadCandidateKind { 9453 oc_function, 9454 oc_method, 9455 oc_constructor, 9456 oc_implicit_default_constructor, 9457 oc_implicit_copy_constructor, 9458 oc_implicit_move_constructor, 9459 oc_implicit_copy_assignment, 9460 oc_implicit_move_assignment, 9461 oc_inherited_constructor 9462 }; 9463 9464 enum OverloadCandidateSelect { 9465 ocs_non_template, 9466 ocs_template, 9467 ocs_described_template, 9468 }; 9469 9470 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9471 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9472 std::string &Description) { 9473 9474 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9475 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9476 isTemplate = true; 9477 Description = S.getTemplateArgumentBindingsText( 9478 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9479 } 9480 9481 OverloadCandidateSelect Select = [&]() { 9482 if (!Description.empty()) 9483 return ocs_described_template; 9484 return isTemplate ? ocs_template : ocs_non_template; 9485 }(); 9486 9487 OverloadCandidateKind Kind = [&]() { 9488 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9489 if (!Ctor->isImplicit()) { 9490 if (isa<ConstructorUsingShadowDecl>(Found)) 9491 return oc_inherited_constructor; 9492 else 9493 return oc_constructor; 9494 } 9495 9496 if (Ctor->isDefaultConstructor()) 9497 return oc_implicit_default_constructor; 9498 9499 if (Ctor->isMoveConstructor()) 9500 return oc_implicit_move_constructor; 9501 9502 assert(Ctor->isCopyConstructor() && 9503 "unexpected sort of implicit constructor"); 9504 return oc_implicit_copy_constructor; 9505 } 9506 9507 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9508 // This actually gets spelled 'candidate function' for now, but 9509 // it doesn't hurt to split it out. 9510 if (!Meth->isImplicit()) 9511 return oc_method; 9512 9513 if (Meth->isMoveAssignmentOperator()) 9514 return oc_implicit_move_assignment; 9515 9516 if (Meth->isCopyAssignmentOperator()) 9517 return oc_implicit_copy_assignment; 9518 9519 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9520 return oc_method; 9521 } 9522 9523 return oc_function; 9524 }(); 9525 9526 return std::make_pair(Kind, Select); 9527 } 9528 9529 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9530 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9531 // set. 9532 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9533 S.Diag(FoundDecl->getLocation(), 9534 diag::note_ovl_candidate_inherited_constructor) 9535 << Shadow->getNominatedBaseClass(); 9536 } 9537 9538 } // end anonymous namespace 9539 9540 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9541 const FunctionDecl *FD) { 9542 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9543 bool AlwaysTrue; 9544 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9545 return false; 9546 if (!AlwaysTrue) 9547 return false; 9548 } 9549 return true; 9550 } 9551 9552 /// Returns true if we can take the address of the function. 9553 /// 9554 /// \param Complain - If true, we'll emit a diagnostic 9555 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9556 /// we in overload resolution? 9557 /// \param Loc - The location of the statement we're complaining about. Ignored 9558 /// if we're not complaining, or if we're in overload resolution. 9559 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9560 bool Complain, 9561 bool InOverloadResolution, 9562 SourceLocation Loc) { 9563 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9564 if (Complain) { 9565 if (InOverloadResolution) 9566 S.Diag(FD->getBeginLoc(), 9567 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9568 else 9569 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9570 } 9571 return false; 9572 } 9573 9574 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9575 return P->hasAttr<PassObjectSizeAttr>(); 9576 }); 9577 if (I == FD->param_end()) 9578 return true; 9579 9580 if (Complain) { 9581 // Add one to ParamNo because it's user-facing 9582 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9583 if (InOverloadResolution) 9584 S.Diag(FD->getLocation(), 9585 diag::note_ovl_candidate_has_pass_object_size_params) 9586 << ParamNo; 9587 else 9588 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9589 << FD << ParamNo; 9590 } 9591 return false; 9592 } 9593 9594 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9595 const FunctionDecl *FD) { 9596 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9597 /*InOverloadResolution=*/true, 9598 /*Loc=*/SourceLocation()); 9599 } 9600 9601 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9602 bool Complain, 9603 SourceLocation Loc) { 9604 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9605 /*InOverloadResolution=*/false, 9606 Loc); 9607 } 9608 9609 // Notes the location of an overload candidate. 9610 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9611 QualType DestType, bool TakingAddress) { 9612 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9613 return; 9614 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9615 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9616 return; 9617 9618 std::string FnDesc; 9619 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9620 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9621 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9622 << (unsigned)KSPair.first << (unsigned)KSPair.second 9623 << Fn << FnDesc; 9624 9625 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9626 Diag(Fn->getLocation(), PD); 9627 MaybeEmitInheritedConstructorNote(*this, Found); 9628 } 9629 9630 // Notes the location of all overload candidates designated through 9631 // OverloadedExpr 9632 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9633 bool TakingAddress) { 9634 assert(OverloadedExpr->getType() == Context.OverloadTy); 9635 9636 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9637 OverloadExpr *OvlExpr = Ovl.Expression; 9638 9639 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9640 IEnd = OvlExpr->decls_end(); 9641 I != IEnd; ++I) { 9642 if (FunctionTemplateDecl *FunTmpl = 9643 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9644 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9645 TakingAddress); 9646 } else if (FunctionDecl *Fun 9647 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9648 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9649 } 9650 } 9651 } 9652 9653 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9654 /// "lead" diagnostic; it will be given two arguments, the source and 9655 /// target types of the conversion. 9656 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9657 Sema &S, 9658 SourceLocation CaretLoc, 9659 const PartialDiagnostic &PDiag) const { 9660 S.Diag(CaretLoc, PDiag) 9661 << Ambiguous.getFromType() << Ambiguous.getToType(); 9662 // FIXME: The note limiting machinery is borrowed from 9663 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9664 // refactoring here. 9665 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9666 unsigned CandsShown = 0; 9667 AmbiguousConversionSequence::const_iterator I, E; 9668 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9669 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9670 break; 9671 ++CandsShown; 9672 S.NoteOverloadCandidate(I->first, I->second); 9673 } 9674 if (I != E) 9675 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9676 } 9677 9678 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9679 unsigned I, bool TakingCandidateAddress) { 9680 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9681 assert(Conv.isBad()); 9682 assert(Cand->Function && "for now, candidate must be a function"); 9683 FunctionDecl *Fn = Cand->Function; 9684 9685 // There's a conversion slot for the object argument if this is a 9686 // non-constructor method. Note that 'I' corresponds the 9687 // conversion-slot index. 9688 bool isObjectArgument = false; 9689 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9690 if (I == 0) 9691 isObjectArgument = true; 9692 else 9693 I--; 9694 } 9695 9696 std::string FnDesc; 9697 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9698 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9699 9700 Expr *FromExpr = Conv.Bad.FromExpr; 9701 QualType FromTy = Conv.Bad.getFromType(); 9702 QualType ToTy = Conv.Bad.getToType(); 9703 9704 if (FromTy == S.Context.OverloadTy) { 9705 assert(FromExpr && "overload set argument came from implicit argument?"); 9706 Expr *E = FromExpr->IgnoreParens(); 9707 if (isa<UnaryOperator>(E)) 9708 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9709 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9710 9711 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9712 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9713 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9714 << Name << I + 1; 9715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9716 return; 9717 } 9718 9719 // Do some hand-waving analysis to see if the non-viability is due 9720 // to a qualifier mismatch. 9721 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9722 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9723 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9724 CToTy = RT->getPointeeType(); 9725 else { 9726 // TODO: detect and diagnose the full richness of const mismatches. 9727 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9728 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9729 CFromTy = FromPT->getPointeeType(); 9730 CToTy = ToPT->getPointeeType(); 9731 } 9732 } 9733 9734 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9735 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9736 Qualifiers FromQs = CFromTy.getQualifiers(); 9737 Qualifiers ToQs = CToTy.getQualifiers(); 9738 9739 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9741 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9743 << ToTy << (unsigned)isObjectArgument << I + 1; 9744 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9745 return; 9746 } 9747 9748 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9750 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9752 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9753 << (unsigned)isObjectArgument << I + 1; 9754 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9755 return; 9756 } 9757 9758 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9759 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9760 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9761 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9762 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9763 << (unsigned)isObjectArgument << I + 1; 9764 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9765 return; 9766 } 9767 9768 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9769 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9770 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9771 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9772 << FromQs.hasUnaligned() << I + 1; 9773 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9774 return; 9775 } 9776 9777 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9778 assert(CVR && "unexpected qualifiers mismatch"); 9779 9780 if (isObjectArgument) { 9781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9782 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9783 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9784 << (CVR - 1); 9785 } else { 9786 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9787 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9788 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9789 << (CVR - 1) << I + 1; 9790 } 9791 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9792 return; 9793 } 9794 9795 // Special diagnostic for failure to convert an initializer list, since 9796 // telling the user that it has type void is not useful. 9797 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9798 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9799 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9800 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9801 << ToTy << (unsigned)isObjectArgument << I + 1; 9802 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9803 return; 9804 } 9805 9806 // Diagnose references or pointers to incomplete types differently, 9807 // since it's far from impossible that the incompleteness triggered 9808 // the failure. 9809 QualType TempFromTy = FromTy.getNonReferenceType(); 9810 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9811 TempFromTy = PTy->getPointeeType(); 9812 if (TempFromTy->isIncompleteType()) { 9813 // Emit the generic diagnostic and, optionally, add the hints to it. 9814 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9815 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9816 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9817 << ToTy << (unsigned)isObjectArgument << I + 1 9818 << (unsigned)(Cand->Fix.Kind); 9819 9820 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9821 return; 9822 } 9823 9824 // Diagnose base -> derived pointer conversions. 9825 unsigned BaseToDerivedConversion = 0; 9826 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9827 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9828 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9829 FromPtrTy->getPointeeType()) && 9830 !FromPtrTy->getPointeeType()->isIncompleteType() && 9831 !ToPtrTy->getPointeeType()->isIncompleteType() && 9832 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9833 FromPtrTy->getPointeeType())) 9834 BaseToDerivedConversion = 1; 9835 } 9836 } else if (const ObjCObjectPointerType *FromPtrTy 9837 = FromTy->getAs<ObjCObjectPointerType>()) { 9838 if (const ObjCObjectPointerType *ToPtrTy 9839 = ToTy->getAs<ObjCObjectPointerType>()) 9840 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9841 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9842 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9843 FromPtrTy->getPointeeType()) && 9844 FromIface->isSuperClassOf(ToIface)) 9845 BaseToDerivedConversion = 2; 9846 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9847 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9848 !FromTy->isIncompleteType() && 9849 !ToRefTy->getPointeeType()->isIncompleteType() && 9850 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9851 BaseToDerivedConversion = 3; 9852 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9853 ToTy.getNonReferenceType().getCanonicalType() == 9854 FromTy.getNonReferenceType().getCanonicalType()) { 9855 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9856 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9857 << (unsigned)isObjectArgument << I + 1 9858 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9859 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9860 return; 9861 } 9862 } 9863 9864 if (BaseToDerivedConversion) { 9865 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9866 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9867 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9868 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9869 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9870 return; 9871 } 9872 9873 if (isa<ObjCObjectPointerType>(CFromTy) && 9874 isa<PointerType>(CToTy)) { 9875 Qualifiers FromQs = CFromTy.getQualifiers(); 9876 Qualifiers ToQs = CToTy.getQualifiers(); 9877 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9878 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9879 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9880 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9881 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9882 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9883 return; 9884 } 9885 } 9886 9887 if (TakingCandidateAddress && 9888 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9889 return; 9890 9891 // Emit the generic diagnostic and, optionally, add the hints to it. 9892 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9893 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9894 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9895 << ToTy << (unsigned)isObjectArgument << I + 1 9896 << (unsigned)(Cand->Fix.Kind); 9897 9898 // If we can fix the conversion, suggest the FixIts. 9899 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9900 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9901 FDiag << *HI; 9902 S.Diag(Fn->getLocation(), FDiag); 9903 9904 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9905 } 9906 9907 /// Additional arity mismatch diagnosis specific to a function overload 9908 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9909 /// over a candidate in any candidate set. 9910 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9911 unsigned NumArgs) { 9912 FunctionDecl *Fn = Cand->Function; 9913 unsigned MinParams = Fn->getMinRequiredArguments(); 9914 9915 // With invalid overloaded operators, it's possible that we think we 9916 // have an arity mismatch when in fact it looks like we have the 9917 // right number of arguments, because only overloaded operators have 9918 // the weird behavior of overloading member and non-member functions. 9919 // Just don't report anything. 9920 if (Fn->isInvalidDecl() && 9921 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9922 return true; 9923 9924 if (NumArgs < MinParams) { 9925 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9926 (Cand->FailureKind == ovl_fail_bad_deduction && 9927 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9928 } else { 9929 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9930 (Cand->FailureKind == ovl_fail_bad_deduction && 9931 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9932 } 9933 9934 return false; 9935 } 9936 9937 /// General arity mismatch diagnosis over a candidate in a candidate set. 9938 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9939 unsigned NumFormalArgs) { 9940 assert(isa<FunctionDecl>(D) && 9941 "The templated declaration should at least be a function" 9942 " when diagnosing bad template argument deduction due to too many" 9943 " or too few arguments"); 9944 9945 FunctionDecl *Fn = cast<FunctionDecl>(D); 9946 9947 // TODO: treat calls to a missing default constructor as a special case 9948 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9949 unsigned MinParams = Fn->getMinRequiredArguments(); 9950 9951 // at least / at most / exactly 9952 unsigned mode, modeCount; 9953 if (NumFormalArgs < MinParams) { 9954 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9955 FnTy->isTemplateVariadic()) 9956 mode = 0; // "at least" 9957 else 9958 mode = 2; // "exactly" 9959 modeCount = MinParams; 9960 } else { 9961 if (MinParams != FnTy->getNumParams()) 9962 mode = 1; // "at most" 9963 else 9964 mode = 2; // "exactly" 9965 modeCount = FnTy->getNumParams(); 9966 } 9967 9968 std::string Description; 9969 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9970 ClassifyOverloadCandidate(S, Found, Fn, Description); 9971 9972 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9973 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9974 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9975 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9976 else 9977 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9978 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9979 << Description << mode << modeCount << NumFormalArgs; 9980 9981 MaybeEmitInheritedConstructorNote(S, Found); 9982 } 9983 9984 /// Arity mismatch diagnosis specific to a function overload candidate. 9985 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9986 unsigned NumFormalArgs) { 9987 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9988 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9989 } 9990 9991 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9992 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9993 return TD; 9994 llvm_unreachable("Unsupported: Getting the described template declaration" 9995 " for bad deduction diagnosis"); 9996 } 9997 9998 /// Diagnose a failed template-argument deduction. 9999 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10000 DeductionFailureInfo &DeductionFailure, 10001 unsigned NumArgs, 10002 bool TakingCandidateAddress) { 10003 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10004 NamedDecl *ParamD; 10005 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10006 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10007 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10008 switch (DeductionFailure.Result) { 10009 case Sema::TDK_Success: 10010 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10011 10012 case Sema::TDK_Incomplete: { 10013 assert(ParamD && "no parameter found for incomplete deduction result"); 10014 S.Diag(Templated->getLocation(), 10015 diag::note_ovl_candidate_incomplete_deduction) 10016 << ParamD->getDeclName(); 10017 MaybeEmitInheritedConstructorNote(S, Found); 10018 return; 10019 } 10020 10021 case Sema::TDK_IncompletePack: { 10022 assert(ParamD && "no parameter found for incomplete deduction result"); 10023 S.Diag(Templated->getLocation(), 10024 diag::note_ovl_candidate_incomplete_deduction_pack) 10025 << ParamD->getDeclName() 10026 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10027 << *DeductionFailure.getFirstArg(); 10028 MaybeEmitInheritedConstructorNote(S, Found); 10029 return; 10030 } 10031 10032 case Sema::TDK_Underqualified: { 10033 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10034 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10035 10036 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10037 10038 // Param will have been canonicalized, but it should just be a 10039 // qualified version of ParamD, so move the qualifiers to that. 10040 QualifierCollector Qs; 10041 Qs.strip(Param); 10042 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10043 assert(S.Context.hasSameType(Param, NonCanonParam)); 10044 10045 // Arg has also been canonicalized, but there's nothing we can do 10046 // about that. It also doesn't matter as much, because it won't 10047 // have any template parameters in it (because deduction isn't 10048 // done on dependent types). 10049 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10050 10051 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10052 << ParamD->getDeclName() << Arg << NonCanonParam; 10053 MaybeEmitInheritedConstructorNote(S, Found); 10054 return; 10055 } 10056 10057 case Sema::TDK_Inconsistent: { 10058 assert(ParamD && "no parameter found for inconsistent deduction result"); 10059 int which = 0; 10060 if (isa<TemplateTypeParmDecl>(ParamD)) 10061 which = 0; 10062 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10063 // Deduction might have failed because we deduced arguments of two 10064 // different types for a non-type template parameter. 10065 // FIXME: Use a different TDK value for this. 10066 QualType T1 = 10067 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10068 QualType T2 = 10069 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10070 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10071 S.Diag(Templated->getLocation(), 10072 diag::note_ovl_candidate_inconsistent_deduction_types) 10073 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10074 << *DeductionFailure.getSecondArg() << T2; 10075 MaybeEmitInheritedConstructorNote(S, Found); 10076 return; 10077 } 10078 10079 which = 1; 10080 } else { 10081 which = 2; 10082 } 10083 10084 S.Diag(Templated->getLocation(), 10085 diag::note_ovl_candidate_inconsistent_deduction) 10086 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10087 << *DeductionFailure.getSecondArg(); 10088 MaybeEmitInheritedConstructorNote(S, Found); 10089 return; 10090 } 10091 10092 case Sema::TDK_InvalidExplicitArguments: 10093 assert(ParamD && "no parameter found for invalid explicit arguments"); 10094 if (ParamD->getDeclName()) 10095 S.Diag(Templated->getLocation(), 10096 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10097 << ParamD->getDeclName(); 10098 else { 10099 int index = 0; 10100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10101 index = TTP->getIndex(); 10102 else if (NonTypeTemplateParmDecl *NTTP 10103 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10104 index = NTTP->getIndex(); 10105 else 10106 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10107 S.Diag(Templated->getLocation(), 10108 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10109 << (index + 1); 10110 } 10111 MaybeEmitInheritedConstructorNote(S, Found); 10112 return; 10113 10114 case Sema::TDK_TooManyArguments: 10115 case Sema::TDK_TooFewArguments: 10116 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10117 return; 10118 10119 case Sema::TDK_InstantiationDepth: 10120 S.Diag(Templated->getLocation(), 10121 diag::note_ovl_candidate_instantiation_depth); 10122 MaybeEmitInheritedConstructorNote(S, Found); 10123 return; 10124 10125 case Sema::TDK_SubstitutionFailure: { 10126 // Format the template argument list into the argument string. 10127 SmallString<128> TemplateArgString; 10128 if (TemplateArgumentList *Args = 10129 DeductionFailure.getTemplateArgumentList()) { 10130 TemplateArgString = " "; 10131 TemplateArgString += S.getTemplateArgumentBindingsText( 10132 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10133 } 10134 10135 // If this candidate was disabled by enable_if, say so. 10136 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10137 if (PDiag && PDiag->second.getDiagID() == 10138 diag::err_typename_nested_not_found_enable_if) { 10139 // FIXME: Use the source range of the condition, and the fully-qualified 10140 // name of the enable_if template. These are both present in PDiag. 10141 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10142 << "'enable_if'" << TemplateArgString; 10143 return; 10144 } 10145 10146 // We found a specific requirement that disabled the enable_if. 10147 if (PDiag && PDiag->second.getDiagID() == 10148 diag::err_typename_nested_not_found_requirement) { 10149 S.Diag(Templated->getLocation(), 10150 diag::note_ovl_candidate_disabled_by_requirement) 10151 << PDiag->second.getStringArg(0) << TemplateArgString; 10152 return; 10153 } 10154 10155 // Format the SFINAE diagnostic into the argument string. 10156 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10157 // formatted message in another diagnostic. 10158 SmallString<128> SFINAEArgString; 10159 SourceRange R; 10160 if (PDiag) { 10161 SFINAEArgString = ": "; 10162 R = SourceRange(PDiag->first, PDiag->first); 10163 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10164 } 10165 10166 S.Diag(Templated->getLocation(), 10167 diag::note_ovl_candidate_substitution_failure) 10168 << TemplateArgString << SFINAEArgString << R; 10169 MaybeEmitInheritedConstructorNote(S, Found); 10170 return; 10171 } 10172 10173 case Sema::TDK_DeducedMismatch: 10174 case Sema::TDK_DeducedMismatchNested: { 10175 // Format the template argument list into the argument string. 10176 SmallString<128> TemplateArgString; 10177 if (TemplateArgumentList *Args = 10178 DeductionFailure.getTemplateArgumentList()) { 10179 TemplateArgString = " "; 10180 TemplateArgString += S.getTemplateArgumentBindingsText( 10181 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10182 } 10183 10184 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10185 << (*DeductionFailure.getCallArgIndex() + 1) 10186 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10187 << TemplateArgString 10188 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10189 break; 10190 } 10191 10192 case Sema::TDK_NonDeducedMismatch: { 10193 // FIXME: Provide a source location to indicate what we couldn't match. 10194 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10195 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10196 if (FirstTA.getKind() == TemplateArgument::Template && 10197 SecondTA.getKind() == TemplateArgument::Template) { 10198 TemplateName FirstTN = FirstTA.getAsTemplate(); 10199 TemplateName SecondTN = SecondTA.getAsTemplate(); 10200 if (FirstTN.getKind() == TemplateName::Template && 10201 SecondTN.getKind() == TemplateName::Template) { 10202 if (FirstTN.getAsTemplateDecl()->getName() == 10203 SecondTN.getAsTemplateDecl()->getName()) { 10204 // FIXME: This fixes a bad diagnostic where both templates are named 10205 // the same. This particular case is a bit difficult since: 10206 // 1) It is passed as a string to the diagnostic printer. 10207 // 2) The diagnostic printer only attempts to find a better 10208 // name for types, not decls. 10209 // Ideally, this should folded into the diagnostic printer. 10210 S.Diag(Templated->getLocation(), 10211 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10212 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10213 return; 10214 } 10215 } 10216 } 10217 10218 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10219 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10220 return; 10221 10222 // FIXME: For generic lambda parameters, check if the function is a lambda 10223 // call operator, and if so, emit a prettier and more informative 10224 // diagnostic that mentions 'auto' and lambda in addition to 10225 // (or instead of?) the canonical template type parameters. 10226 S.Diag(Templated->getLocation(), 10227 diag::note_ovl_candidate_non_deduced_mismatch) 10228 << FirstTA << SecondTA; 10229 return; 10230 } 10231 // TODO: diagnose these individually, then kill off 10232 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10233 case Sema::TDK_MiscellaneousDeductionFailure: 10234 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10235 MaybeEmitInheritedConstructorNote(S, Found); 10236 return; 10237 case Sema::TDK_CUDATargetMismatch: 10238 S.Diag(Templated->getLocation(), 10239 diag::note_cuda_ovl_candidate_target_mismatch); 10240 return; 10241 } 10242 } 10243 10244 /// Diagnose a failed template-argument deduction, for function calls. 10245 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10246 unsigned NumArgs, 10247 bool TakingCandidateAddress) { 10248 unsigned TDK = Cand->DeductionFailure.Result; 10249 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10250 if (CheckArityMismatch(S, Cand, NumArgs)) 10251 return; 10252 } 10253 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10254 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10255 } 10256 10257 /// CUDA: diagnose an invalid call across targets. 10258 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10259 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10260 FunctionDecl *Callee = Cand->Function; 10261 10262 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10263 CalleeTarget = S.IdentifyCUDATarget(Callee); 10264 10265 std::string FnDesc; 10266 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10267 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10268 10269 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10270 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10271 << FnDesc /* Ignored */ 10272 << CalleeTarget << CallerTarget; 10273 10274 // This could be an implicit constructor for which we could not infer the 10275 // target due to a collsion. Diagnose that case. 10276 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10277 if (Meth != nullptr && Meth->isImplicit()) { 10278 CXXRecordDecl *ParentClass = Meth->getParent(); 10279 Sema::CXXSpecialMember CSM; 10280 10281 switch (FnKindPair.first) { 10282 default: 10283 return; 10284 case oc_implicit_default_constructor: 10285 CSM = Sema::CXXDefaultConstructor; 10286 break; 10287 case oc_implicit_copy_constructor: 10288 CSM = Sema::CXXCopyConstructor; 10289 break; 10290 case oc_implicit_move_constructor: 10291 CSM = Sema::CXXMoveConstructor; 10292 break; 10293 case oc_implicit_copy_assignment: 10294 CSM = Sema::CXXCopyAssignment; 10295 break; 10296 case oc_implicit_move_assignment: 10297 CSM = Sema::CXXMoveAssignment; 10298 break; 10299 }; 10300 10301 bool ConstRHS = false; 10302 if (Meth->getNumParams()) { 10303 if (const ReferenceType *RT = 10304 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10305 ConstRHS = RT->getPointeeType().isConstQualified(); 10306 } 10307 } 10308 10309 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10310 /* ConstRHS */ ConstRHS, 10311 /* Diagnose */ true); 10312 } 10313 } 10314 10315 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10316 FunctionDecl *Callee = Cand->Function; 10317 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10318 10319 S.Diag(Callee->getLocation(), 10320 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10321 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10322 } 10323 10324 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10325 FunctionDecl *Callee = Cand->Function; 10326 10327 S.Diag(Callee->getLocation(), 10328 diag::note_ovl_candidate_disabled_by_extension) 10329 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10330 } 10331 10332 /// Generates a 'note' diagnostic for an overload candidate. We've 10333 /// already generated a primary error at the call site. 10334 /// 10335 /// It really does need to be a single diagnostic with its caret 10336 /// pointed at the candidate declaration. Yes, this creates some 10337 /// major challenges of technical writing. Yes, this makes pointing 10338 /// out problems with specific arguments quite awkward. It's still 10339 /// better than generating twenty screens of text for every failed 10340 /// overload. 10341 /// 10342 /// It would be great to be able to express per-candidate problems 10343 /// more richly for those diagnostic clients that cared, but we'd 10344 /// still have to be just as careful with the default diagnostics. 10345 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10346 unsigned NumArgs, 10347 bool TakingCandidateAddress) { 10348 FunctionDecl *Fn = Cand->Function; 10349 10350 // Note deleted candidates, but only if they're viable. 10351 if (Cand->Viable) { 10352 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10353 std::string FnDesc; 10354 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10355 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10356 10357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10358 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10359 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10360 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10361 return; 10362 } 10363 10364 // We don't really have anything else to say about viable candidates. 10365 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10366 return; 10367 } 10368 10369 switch (Cand->FailureKind) { 10370 case ovl_fail_too_many_arguments: 10371 case ovl_fail_too_few_arguments: 10372 return DiagnoseArityMismatch(S, Cand, NumArgs); 10373 10374 case ovl_fail_bad_deduction: 10375 return DiagnoseBadDeduction(S, Cand, NumArgs, 10376 TakingCandidateAddress); 10377 10378 case ovl_fail_illegal_constructor: { 10379 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10380 << (Fn->getPrimaryTemplate() ? 1 : 0); 10381 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10382 return; 10383 } 10384 10385 case ovl_fail_trivial_conversion: 10386 case ovl_fail_bad_final_conversion: 10387 case ovl_fail_final_conversion_not_exact: 10388 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10389 10390 case ovl_fail_bad_conversion: { 10391 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10392 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10393 if (Cand->Conversions[I].isBad()) 10394 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10395 10396 // FIXME: this currently happens when we're called from SemaInit 10397 // when user-conversion overload fails. Figure out how to handle 10398 // those conditions and diagnose them well. 10399 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10400 } 10401 10402 case ovl_fail_bad_target: 10403 return DiagnoseBadTarget(S, Cand); 10404 10405 case ovl_fail_enable_if: 10406 return DiagnoseFailedEnableIfAttr(S, Cand); 10407 10408 case ovl_fail_ext_disabled: 10409 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10410 10411 case ovl_fail_inhctor_slice: 10412 // It's generally not interesting to note copy/move constructors here. 10413 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10414 return; 10415 S.Diag(Fn->getLocation(), 10416 diag::note_ovl_candidate_inherited_constructor_slice) 10417 << (Fn->getPrimaryTemplate() ? 1 : 0) 10418 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10419 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10420 return; 10421 10422 case ovl_fail_addr_not_available: { 10423 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10424 (void)Available; 10425 assert(!Available); 10426 break; 10427 } 10428 case ovl_non_default_multiversion_function: 10429 // Do nothing, these should simply be ignored. 10430 break; 10431 } 10432 } 10433 10434 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10435 // Desugar the type of the surrogate down to a function type, 10436 // retaining as many typedefs as possible while still showing 10437 // the function type (and, therefore, its parameter types). 10438 QualType FnType = Cand->Surrogate->getConversionType(); 10439 bool isLValueReference = false; 10440 bool isRValueReference = false; 10441 bool isPointer = false; 10442 if (const LValueReferenceType *FnTypeRef = 10443 FnType->getAs<LValueReferenceType>()) { 10444 FnType = FnTypeRef->getPointeeType(); 10445 isLValueReference = true; 10446 } else if (const RValueReferenceType *FnTypeRef = 10447 FnType->getAs<RValueReferenceType>()) { 10448 FnType = FnTypeRef->getPointeeType(); 10449 isRValueReference = true; 10450 } 10451 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10452 FnType = FnTypePtr->getPointeeType(); 10453 isPointer = true; 10454 } 10455 // Desugar down to a function type. 10456 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10457 // Reconstruct the pointer/reference as appropriate. 10458 if (isPointer) FnType = S.Context.getPointerType(FnType); 10459 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10460 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10461 10462 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10463 << FnType; 10464 } 10465 10466 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10467 SourceLocation OpLoc, 10468 OverloadCandidate *Cand) { 10469 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10470 std::string TypeStr("operator"); 10471 TypeStr += Opc; 10472 TypeStr += "("; 10473 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10474 if (Cand->Conversions.size() == 1) { 10475 TypeStr += ")"; 10476 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10477 } else { 10478 TypeStr += ", "; 10479 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10480 TypeStr += ")"; 10481 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10482 } 10483 } 10484 10485 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10486 OverloadCandidate *Cand) { 10487 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10488 if (ICS.isBad()) break; // all meaningless after first invalid 10489 if (!ICS.isAmbiguous()) continue; 10490 10491 ICS.DiagnoseAmbiguousConversion( 10492 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10493 } 10494 } 10495 10496 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10497 if (Cand->Function) 10498 return Cand->Function->getLocation(); 10499 if (Cand->IsSurrogate) 10500 return Cand->Surrogate->getLocation(); 10501 return SourceLocation(); 10502 } 10503 10504 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10505 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10506 case Sema::TDK_Success: 10507 case Sema::TDK_NonDependentConversionFailure: 10508 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10509 10510 case Sema::TDK_Invalid: 10511 case Sema::TDK_Incomplete: 10512 case Sema::TDK_IncompletePack: 10513 return 1; 10514 10515 case Sema::TDK_Underqualified: 10516 case Sema::TDK_Inconsistent: 10517 return 2; 10518 10519 case Sema::TDK_SubstitutionFailure: 10520 case Sema::TDK_DeducedMismatch: 10521 case Sema::TDK_DeducedMismatchNested: 10522 case Sema::TDK_NonDeducedMismatch: 10523 case Sema::TDK_MiscellaneousDeductionFailure: 10524 case Sema::TDK_CUDATargetMismatch: 10525 return 3; 10526 10527 case Sema::TDK_InstantiationDepth: 10528 return 4; 10529 10530 case Sema::TDK_InvalidExplicitArguments: 10531 return 5; 10532 10533 case Sema::TDK_TooManyArguments: 10534 case Sema::TDK_TooFewArguments: 10535 return 6; 10536 } 10537 llvm_unreachable("Unhandled deduction result"); 10538 } 10539 10540 namespace { 10541 struct CompareOverloadCandidatesForDisplay { 10542 Sema &S; 10543 SourceLocation Loc; 10544 size_t NumArgs; 10545 OverloadCandidateSet::CandidateSetKind CSK; 10546 10547 CompareOverloadCandidatesForDisplay( 10548 Sema &S, SourceLocation Loc, size_t NArgs, 10549 OverloadCandidateSet::CandidateSetKind CSK) 10550 : S(S), NumArgs(NArgs), CSK(CSK) {} 10551 10552 bool operator()(const OverloadCandidate *L, 10553 const OverloadCandidate *R) { 10554 // Fast-path this check. 10555 if (L == R) return false; 10556 10557 // Order first by viability. 10558 if (L->Viable) { 10559 if (!R->Viable) return true; 10560 10561 // TODO: introduce a tri-valued comparison for overload 10562 // candidates. Would be more worthwhile if we had a sort 10563 // that could exploit it. 10564 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10565 return true; 10566 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10567 return false; 10568 } else if (R->Viable) 10569 return false; 10570 10571 assert(L->Viable == R->Viable); 10572 10573 // Criteria by which we can sort non-viable candidates: 10574 if (!L->Viable) { 10575 // 1. Arity mismatches come after other candidates. 10576 if (L->FailureKind == ovl_fail_too_many_arguments || 10577 L->FailureKind == ovl_fail_too_few_arguments) { 10578 if (R->FailureKind == ovl_fail_too_many_arguments || 10579 R->FailureKind == ovl_fail_too_few_arguments) { 10580 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10581 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10582 if (LDist == RDist) { 10583 if (L->FailureKind == R->FailureKind) 10584 // Sort non-surrogates before surrogates. 10585 return !L->IsSurrogate && R->IsSurrogate; 10586 // Sort candidates requiring fewer parameters than there were 10587 // arguments given after candidates requiring more parameters 10588 // than there were arguments given. 10589 return L->FailureKind == ovl_fail_too_many_arguments; 10590 } 10591 return LDist < RDist; 10592 } 10593 return false; 10594 } 10595 if (R->FailureKind == ovl_fail_too_many_arguments || 10596 R->FailureKind == ovl_fail_too_few_arguments) 10597 return true; 10598 10599 // 2. Bad conversions come first and are ordered by the number 10600 // of bad conversions and quality of good conversions. 10601 if (L->FailureKind == ovl_fail_bad_conversion) { 10602 if (R->FailureKind != ovl_fail_bad_conversion) 10603 return true; 10604 10605 // The conversion that can be fixed with a smaller number of changes, 10606 // comes first. 10607 unsigned numLFixes = L->Fix.NumConversionsFixed; 10608 unsigned numRFixes = R->Fix.NumConversionsFixed; 10609 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10610 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10611 if (numLFixes != numRFixes) { 10612 return numLFixes < numRFixes; 10613 } 10614 10615 // If there's any ordering between the defined conversions... 10616 // FIXME: this might not be transitive. 10617 assert(L->Conversions.size() == R->Conversions.size()); 10618 10619 int leftBetter = 0; 10620 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10621 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10622 switch (CompareImplicitConversionSequences(S, Loc, 10623 L->Conversions[I], 10624 R->Conversions[I])) { 10625 case ImplicitConversionSequence::Better: 10626 leftBetter++; 10627 break; 10628 10629 case ImplicitConversionSequence::Worse: 10630 leftBetter--; 10631 break; 10632 10633 case ImplicitConversionSequence::Indistinguishable: 10634 break; 10635 } 10636 } 10637 if (leftBetter > 0) return true; 10638 if (leftBetter < 0) return false; 10639 10640 } else if (R->FailureKind == ovl_fail_bad_conversion) 10641 return false; 10642 10643 if (L->FailureKind == ovl_fail_bad_deduction) { 10644 if (R->FailureKind != ovl_fail_bad_deduction) 10645 return true; 10646 10647 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10648 return RankDeductionFailure(L->DeductionFailure) 10649 < RankDeductionFailure(R->DeductionFailure); 10650 } else if (R->FailureKind == ovl_fail_bad_deduction) 10651 return false; 10652 10653 // TODO: others? 10654 } 10655 10656 // Sort everything else by location. 10657 SourceLocation LLoc = GetLocationForCandidate(L); 10658 SourceLocation RLoc = GetLocationForCandidate(R); 10659 10660 // Put candidates without locations (e.g. builtins) at the end. 10661 if (LLoc.isInvalid()) return false; 10662 if (RLoc.isInvalid()) return true; 10663 10664 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10665 } 10666 }; 10667 } 10668 10669 /// CompleteNonViableCandidate - Normally, overload resolution only 10670 /// computes up to the first bad conversion. Produces the FixIt set if 10671 /// possible. 10672 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10673 ArrayRef<Expr *> Args) { 10674 assert(!Cand->Viable); 10675 10676 // Don't do anything on failures other than bad conversion. 10677 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10678 10679 // We only want the FixIts if all the arguments can be corrected. 10680 bool Unfixable = false; 10681 // Use a implicit copy initialization to check conversion fixes. 10682 Cand->Fix.setConversionChecker(TryCopyInitialization); 10683 10684 // Attempt to fix the bad conversion. 10685 unsigned ConvCount = Cand->Conversions.size(); 10686 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10687 ++ConvIdx) { 10688 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10689 if (Cand->Conversions[ConvIdx].isInitialized() && 10690 Cand->Conversions[ConvIdx].isBad()) { 10691 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10692 break; 10693 } 10694 } 10695 10696 // FIXME: this should probably be preserved from the overload 10697 // operation somehow. 10698 bool SuppressUserConversions = false; 10699 10700 unsigned ConvIdx = 0; 10701 ArrayRef<QualType> ParamTypes; 10702 10703 if (Cand->IsSurrogate) { 10704 QualType ConvType 10705 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10706 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10707 ConvType = ConvPtrType->getPointeeType(); 10708 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10709 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10710 ConvIdx = 1; 10711 } else if (Cand->Function) { 10712 ParamTypes = 10713 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10714 if (isa<CXXMethodDecl>(Cand->Function) && 10715 !isa<CXXConstructorDecl>(Cand->Function)) { 10716 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10717 ConvIdx = 1; 10718 } 10719 } else { 10720 // Builtin operator. 10721 assert(ConvCount <= 3); 10722 ParamTypes = Cand->BuiltinParamTypes; 10723 } 10724 10725 // Fill in the rest of the conversions. 10726 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10727 if (Cand->Conversions[ConvIdx].isInitialized()) { 10728 // We've already checked this conversion. 10729 } else if (ArgIdx < ParamTypes.size()) { 10730 if (ParamTypes[ArgIdx]->isDependentType()) 10731 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10732 Args[ArgIdx]->getType()); 10733 else { 10734 Cand->Conversions[ConvIdx] = 10735 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10736 SuppressUserConversions, 10737 /*InOverloadResolution=*/true, 10738 /*AllowObjCWritebackConversion=*/ 10739 S.getLangOpts().ObjCAutoRefCount); 10740 // Store the FixIt in the candidate if it exists. 10741 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10742 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10743 } 10744 } else 10745 Cand->Conversions[ConvIdx].setEllipsis(); 10746 } 10747 } 10748 10749 /// When overload resolution fails, prints diagnostic messages containing the 10750 /// candidates in the candidate set. 10751 void OverloadCandidateSet::NoteCandidates( 10752 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10753 StringRef Opc, SourceLocation OpLoc, 10754 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10755 // Sort the candidates by viability and position. Sorting directly would 10756 // be prohibitive, so we make a set of pointers and sort those. 10757 SmallVector<OverloadCandidate*, 32> Cands; 10758 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10759 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10760 if (!Filter(*Cand)) 10761 continue; 10762 if (Cand->Viable) 10763 Cands.push_back(Cand); 10764 else if (OCD == OCD_AllCandidates) { 10765 CompleteNonViableCandidate(S, Cand, Args); 10766 if (Cand->Function || Cand->IsSurrogate) 10767 Cands.push_back(Cand); 10768 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10769 // want to list every possible builtin candidate. 10770 } 10771 } 10772 10773 std::stable_sort(Cands.begin(), Cands.end(), 10774 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10775 10776 bool ReportedAmbiguousConversions = false; 10777 10778 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10779 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10780 unsigned CandsShown = 0; 10781 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10782 OverloadCandidate *Cand = *I; 10783 10784 // Set an arbitrary limit on the number of candidate functions we'll spam 10785 // the user with. FIXME: This limit should depend on details of the 10786 // candidate list. 10787 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10788 break; 10789 } 10790 ++CandsShown; 10791 10792 if (Cand->Function) 10793 NoteFunctionCandidate(S, Cand, Args.size(), 10794 /*TakingCandidateAddress=*/false); 10795 else if (Cand->IsSurrogate) 10796 NoteSurrogateCandidate(S, Cand); 10797 else { 10798 assert(Cand->Viable && 10799 "Non-viable built-in candidates are not added to Cands."); 10800 // Generally we only see ambiguities including viable builtin 10801 // operators if overload resolution got screwed up by an 10802 // ambiguous user-defined conversion. 10803 // 10804 // FIXME: It's quite possible for different conversions to see 10805 // different ambiguities, though. 10806 if (!ReportedAmbiguousConversions) { 10807 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10808 ReportedAmbiguousConversions = true; 10809 } 10810 10811 // If this is a viable builtin, print it. 10812 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10813 } 10814 } 10815 10816 if (I != E) 10817 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10818 } 10819 10820 static SourceLocation 10821 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10822 return Cand->Specialization ? Cand->Specialization->getLocation() 10823 : SourceLocation(); 10824 } 10825 10826 namespace { 10827 struct CompareTemplateSpecCandidatesForDisplay { 10828 Sema &S; 10829 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10830 10831 bool operator()(const TemplateSpecCandidate *L, 10832 const TemplateSpecCandidate *R) { 10833 // Fast-path this check. 10834 if (L == R) 10835 return false; 10836 10837 // Assuming that both candidates are not matches... 10838 10839 // Sort by the ranking of deduction failures. 10840 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10841 return RankDeductionFailure(L->DeductionFailure) < 10842 RankDeductionFailure(R->DeductionFailure); 10843 10844 // Sort everything else by location. 10845 SourceLocation LLoc = GetLocationForCandidate(L); 10846 SourceLocation RLoc = GetLocationForCandidate(R); 10847 10848 // Put candidates without locations (e.g. builtins) at the end. 10849 if (LLoc.isInvalid()) 10850 return false; 10851 if (RLoc.isInvalid()) 10852 return true; 10853 10854 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10855 } 10856 }; 10857 } 10858 10859 /// Diagnose a template argument deduction failure. 10860 /// We are treating these failures as overload failures due to bad 10861 /// deductions. 10862 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10863 bool ForTakingAddress) { 10864 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10865 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10866 } 10867 10868 void TemplateSpecCandidateSet::destroyCandidates() { 10869 for (iterator i = begin(), e = end(); i != e; ++i) { 10870 i->DeductionFailure.Destroy(); 10871 } 10872 } 10873 10874 void TemplateSpecCandidateSet::clear() { 10875 destroyCandidates(); 10876 Candidates.clear(); 10877 } 10878 10879 /// NoteCandidates - When no template specialization match is found, prints 10880 /// diagnostic messages containing the non-matching specializations that form 10881 /// the candidate set. 10882 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10883 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10884 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10885 // Sort the candidates by position (assuming no candidate is a match). 10886 // Sorting directly would be prohibitive, so we make a set of pointers 10887 // and sort those. 10888 SmallVector<TemplateSpecCandidate *, 32> Cands; 10889 Cands.reserve(size()); 10890 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10891 if (Cand->Specialization) 10892 Cands.push_back(Cand); 10893 // Otherwise, this is a non-matching builtin candidate. We do not, 10894 // in general, want to list every possible builtin candidate. 10895 } 10896 10897 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10898 10899 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10900 // for generalization purposes (?). 10901 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10902 10903 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10904 unsigned CandsShown = 0; 10905 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10906 TemplateSpecCandidate *Cand = *I; 10907 10908 // Set an arbitrary limit on the number of candidates we'll spam 10909 // the user with. FIXME: This limit should depend on details of the 10910 // candidate list. 10911 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10912 break; 10913 ++CandsShown; 10914 10915 assert(Cand->Specialization && 10916 "Non-matching built-in candidates are not added to Cands."); 10917 Cand->NoteDeductionFailure(S, ForTakingAddress); 10918 } 10919 10920 if (I != E) 10921 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10922 } 10923 10924 // [PossiblyAFunctionType] --> [Return] 10925 // NonFunctionType --> NonFunctionType 10926 // R (A) --> R(A) 10927 // R (*)(A) --> R (A) 10928 // R (&)(A) --> R (A) 10929 // R (S::*)(A) --> R (A) 10930 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10931 QualType Ret = PossiblyAFunctionType; 10932 if (const PointerType *ToTypePtr = 10933 PossiblyAFunctionType->getAs<PointerType>()) 10934 Ret = ToTypePtr->getPointeeType(); 10935 else if (const ReferenceType *ToTypeRef = 10936 PossiblyAFunctionType->getAs<ReferenceType>()) 10937 Ret = ToTypeRef->getPointeeType(); 10938 else if (const MemberPointerType *MemTypePtr = 10939 PossiblyAFunctionType->getAs<MemberPointerType>()) 10940 Ret = MemTypePtr->getPointeeType(); 10941 Ret = 10942 Context.getCanonicalType(Ret).getUnqualifiedType(); 10943 return Ret; 10944 } 10945 10946 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10947 bool Complain = true) { 10948 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10949 S.DeduceReturnType(FD, Loc, Complain)) 10950 return true; 10951 10952 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10953 if (S.getLangOpts().CPlusPlus17 && 10954 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10955 !S.ResolveExceptionSpec(Loc, FPT)) 10956 return true; 10957 10958 return false; 10959 } 10960 10961 namespace { 10962 // A helper class to help with address of function resolution 10963 // - allows us to avoid passing around all those ugly parameters 10964 class AddressOfFunctionResolver { 10965 Sema& S; 10966 Expr* SourceExpr; 10967 const QualType& TargetType; 10968 QualType TargetFunctionType; // Extracted function type from target type 10969 10970 bool Complain; 10971 //DeclAccessPair& ResultFunctionAccessPair; 10972 ASTContext& Context; 10973 10974 bool TargetTypeIsNonStaticMemberFunction; 10975 bool FoundNonTemplateFunction; 10976 bool StaticMemberFunctionFromBoundPointer; 10977 bool HasComplained; 10978 10979 OverloadExpr::FindResult OvlExprInfo; 10980 OverloadExpr *OvlExpr; 10981 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10982 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10983 TemplateSpecCandidateSet FailedCandidates; 10984 10985 public: 10986 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10987 const QualType &TargetType, bool Complain) 10988 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10989 Complain(Complain), Context(S.getASTContext()), 10990 TargetTypeIsNonStaticMemberFunction( 10991 !!TargetType->getAs<MemberPointerType>()), 10992 FoundNonTemplateFunction(false), 10993 StaticMemberFunctionFromBoundPointer(false), 10994 HasComplained(false), 10995 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10996 OvlExpr(OvlExprInfo.Expression), 10997 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10998 ExtractUnqualifiedFunctionTypeFromTargetType(); 10999 11000 if (TargetFunctionType->isFunctionType()) { 11001 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11002 if (!UME->isImplicitAccess() && 11003 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11004 StaticMemberFunctionFromBoundPointer = true; 11005 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11006 DeclAccessPair dap; 11007 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11008 OvlExpr, false, &dap)) { 11009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11010 if (!Method->isStatic()) { 11011 // If the target type is a non-function type and the function found 11012 // is a non-static member function, pretend as if that was the 11013 // target, it's the only possible type to end up with. 11014 TargetTypeIsNonStaticMemberFunction = true; 11015 11016 // And skip adding the function if its not in the proper form. 11017 // We'll diagnose this due to an empty set of functions. 11018 if (!OvlExprInfo.HasFormOfMemberPointer) 11019 return; 11020 } 11021 11022 Matches.push_back(std::make_pair(dap, Fn)); 11023 } 11024 return; 11025 } 11026 11027 if (OvlExpr->hasExplicitTemplateArgs()) 11028 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11029 11030 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11031 // C++ [over.over]p4: 11032 // If more than one function is selected, [...] 11033 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11034 if (FoundNonTemplateFunction) 11035 EliminateAllTemplateMatches(); 11036 else 11037 EliminateAllExceptMostSpecializedTemplate(); 11038 } 11039 } 11040 11041 if (S.getLangOpts().CUDA && Matches.size() > 1) 11042 EliminateSuboptimalCudaMatches(); 11043 } 11044 11045 bool hasComplained() const { return HasComplained; } 11046 11047 private: 11048 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11049 QualType Discard; 11050 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11051 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11052 } 11053 11054 /// \return true if A is considered a better overload candidate for the 11055 /// desired type than B. 11056 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11057 // If A doesn't have exactly the correct type, we don't want to classify it 11058 // as "better" than anything else. This way, the user is required to 11059 // disambiguate for us if there are multiple candidates and no exact match. 11060 return candidateHasExactlyCorrectType(A) && 11061 (!candidateHasExactlyCorrectType(B) || 11062 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11063 } 11064 11065 /// \return true if we were able to eliminate all but one overload candidate, 11066 /// false otherwise. 11067 bool eliminiateSuboptimalOverloadCandidates() { 11068 // Same algorithm as overload resolution -- one pass to pick the "best", 11069 // another pass to be sure that nothing is better than the best. 11070 auto Best = Matches.begin(); 11071 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11072 if (isBetterCandidate(I->second, Best->second)) 11073 Best = I; 11074 11075 const FunctionDecl *BestFn = Best->second; 11076 auto IsBestOrInferiorToBest = [this, BestFn]( 11077 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11078 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11079 }; 11080 11081 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11082 // option, so we can potentially give the user a better error 11083 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11084 return false; 11085 Matches[0] = *Best; 11086 Matches.resize(1); 11087 return true; 11088 } 11089 11090 bool isTargetTypeAFunction() const { 11091 return TargetFunctionType->isFunctionType(); 11092 } 11093 11094 // [ToType] [Return] 11095 11096 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11097 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11098 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11099 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11100 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11101 } 11102 11103 // return true if any matching specializations were found 11104 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11105 const DeclAccessPair& CurAccessFunPair) { 11106 if (CXXMethodDecl *Method 11107 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11108 // Skip non-static function templates when converting to pointer, and 11109 // static when converting to member pointer. 11110 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11111 return false; 11112 } 11113 else if (TargetTypeIsNonStaticMemberFunction) 11114 return false; 11115 11116 // C++ [over.over]p2: 11117 // If the name is a function template, template argument deduction is 11118 // done (14.8.2.2), and if the argument deduction succeeds, the 11119 // resulting template argument list is used to generate a single 11120 // function template specialization, which is added to the set of 11121 // overloaded functions considered. 11122 FunctionDecl *Specialization = nullptr; 11123 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11124 if (Sema::TemplateDeductionResult Result 11125 = S.DeduceTemplateArguments(FunctionTemplate, 11126 &OvlExplicitTemplateArgs, 11127 TargetFunctionType, Specialization, 11128 Info, /*IsAddressOfFunction*/true)) { 11129 // Make a note of the failed deduction for diagnostics. 11130 FailedCandidates.addCandidate() 11131 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11132 MakeDeductionFailureInfo(Context, Result, Info)); 11133 return false; 11134 } 11135 11136 // Template argument deduction ensures that we have an exact match or 11137 // compatible pointer-to-function arguments that would be adjusted by ICS. 11138 // This function template specicalization works. 11139 assert(S.isSameOrCompatibleFunctionType( 11140 Context.getCanonicalType(Specialization->getType()), 11141 Context.getCanonicalType(TargetFunctionType))); 11142 11143 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11144 return false; 11145 11146 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11147 return true; 11148 } 11149 11150 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11151 const DeclAccessPair& CurAccessFunPair) { 11152 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11153 // Skip non-static functions when converting to pointer, and static 11154 // when converting to member pointer. 11155 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11156 return false; 11157 } 11158 else if (TargetTypeIsNonStaticMemberFunction) 11159 return false; 11160 11161 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11162 if (S.getLangOpts().CUDA) 11163 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11164 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11165 return false; 11166 if (FunDecl->isMultiVersion()) { 11167 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11168 if (TA && !TA->isDefaultVersion()) 11169 return false; 11170 } 11171 11172 // If any candidate has a placeholder return type, trigger its deduction 11173 // now. 11174 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11175 Complain)) { 11176 HasComplained |= Complain; 11177 return false; 11178 } 11179 11180 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11181 return false; 11182 11183 // If we're in C, we need to support types that aren't exactly identical. 11184 if (!S.getLangOpts().CPlusPlus || 11185 candidateHasExactlyCorrectType(FunDecl)) { 11186 Matches.push_back(std::make_pair( 11187 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11188 FoundNonTemplateFunction = true; 11189 return true; 11190 } 11191 } 11192 11193 return false; 11194 } 11195 11196 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11197 bool Ret = false; 11198 11199 // If the overload expression doesn't have the form of a pointer to 11200 // member, don't try to convert it to a pointer-to-member type. 11201 if (IsInvalidFormOfPointerToMemberFunction()) 11202 return false; 11203 11204 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11205 E = OvlExpr->decls_end(); 11206 I != E; ++I) { 11207 // Look through any using declarations to find the underlying function. 11208 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11209 11210 // C++ [over.over]p3: 11211 // Non-member functions and static member functions match 11212 // targets of type "pointer-to-function" or "reference-to-function." 11213 // Nonstatic member functions match targets of 11214 // type "pointer-to-member-function." 11215 // Note that according to DR 247, the containing class does not matter. 11216 if (FunctionTemplateDecl *FunctionTemplate 11217 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11218 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11219 Ret = true; 11220 } 11221 // If we have explicit template arguments supplied, skip non-templates. 11222 else if (!OvlExpr->hasExplicitTemplateArgs() && 11223 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11224 Ret = true; 11225 } 11226 assert(Ret || Matches.empty()); 11227 return Ret; 11228 } 11229 11230 void EliminateAllExceptMostSpecializedTemplate() { 11231 // [...] and any given function template specialization F1 is 11232 // eliminated if the set contains a second function template 11233 // specialization whose function template is more specialized 11234 // than the function template of F1 according to the partial 11235 // ordering rules of 14.5.5.2. 11236 11237 // The algorithm specified above is quadratic. We instead use a 11238 // two-pass algorithm (similar to the one used to identify the 11239 // best viable function in an overload set) that identifies the 11240 // best function template (if it exists). 11241 11242 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11243 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11244 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11245 11246 // TODO: It looks like FailedCandidates does not serve much purpose 11247 // here, since the no_viable diagnostic has index 0. 11248 UnresolvedSetIterator Result = S.getMostSpecialized( 11249 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11250 SourceExpr->getBeginLoc(), S.PDiag(), 11251 S.PDiag(diag::err_addr_ovl_ambiguous) 11252 << Matches[0].second->getDeclName(), 11253 S.PDiag(diag::note_ovl_candidate) 11254 << (unsigned)oc_function << (unsigned)ocs_described_template, 11255 Complain, TargetFunctionType); 11256 11257 if (Result != MatchesCopy.end()) { 11258 // Make it the first and only element 11259 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11260 Matches[0].second = cast<FunctionDecl>(*Result); 11261 Matches.resize(1); 11262 } else 11263 HasComplained |= Complain; 11264 } 11265 11266 void EliminateAllTemplateMatches() { 11267 // [...] any function template specializations in the set are 11268 // eliminated if the set also contains a non-template function, [...] 11269 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11270 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11271 ++I; 11272 else { 11273 Matches[I] = Matches[--N]; 11274 Matches.resize(N); 11275 } 11276 } 11277 } 11278 11279 void EliminateSuboptimalCudaMatches() { 11280 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11281 } 11282 11283 public: 11284 void ComplainNoMatchesFound() const { 11285 assert(Matches.empty()); 11286 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11287 << OvlExpr->getName() << TargetFunctionType 11288 << OvlExpr->getSourceRange(); 11289 if (FailedCandidates.empty()) 11290 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11291 /*TakingAddress=*/true); 11292 else { 11293 // We have some deduction failure messages. Use them to diagnose 11294 // the function templates, and diagnose the non-template candidates 11295 // normally. 11296 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11297 IEnd = OvlExpr->decls_end(); 11298 I != IEnd; ++I) 11299 if (FunctionDecl *Fun = 11300 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11301 if (!functionHasPassObjectSizeParams(Fun)) 11302 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11303 /*TakingAddress=*/true); 11304 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11305 } 11306 } 11307 11308 bool IsInvalidFormOfPointerToMemberFunction() const { 11309 return TargetTypeIsNonStaticMemberFunction && 11310 !OvlExprInfo.HasFormOfMemberPointer; 11311 } 11312 11313 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11314 // TODO: Should we condition this on whether any functions might 11315 // have matched, or is it more appropriate to do that in callers? 11316 // TODO: a fixit wouldn't hurt. 11317 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11318 << TargetType << OvlExpr->getSourceRange(); 11319 } 11320 11321 bool IsStaticMemberFunctionFromBoundPointer() const { 11322 return StaticMemberFunctionFromBoundPointer; 11323 } 11324 11325 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11326 S.Diag(OvlExpr->getBeginLoc(), 11327 diag::err_invalid_form_pointer_member_function) 11328 << OvlExpr->getSourceRange(); 11329 } 11330 11331 void ComplainOfInvalidConversion() const { 11332 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11333 << OvlExpr->getName() << TargetType; 11334 } 11335 11336 void ComplainMultipleMatchesFound() const { 11337 assert(Matches.size() > 1); 11338 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11339 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11340 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11341 /*TakingAddress=*/true); 11342 } 11343 11344 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11345 11346 int getNumMatches() const { return Matches.size(); } 11347 11348 FunctionDecl* getMatchingFunctionDecl() const { 11349 if (Matches.size() != 1) return nullptr; 11350 return Matches[0].second; 11351 } 11352 11353 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11354 if (Matches.size() != 1) return nullptr; 11355 return &Matches[0].first; 11356 } 11357 }; 11358 } 11359 11360 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11361 /// an overloaded function (C++ [over.over]), where @p From is an 11362 /// expression with overloaded function type and @p ToType is the type 11363 /// we're trying to resolve to. For example: 11364 /// 11365 /// @code 11366 /// int f(double); 11367 /// int f(int); 11368 /// 11369 /// int (*pfd)(double) = f; // selects f(double) 11370 /// @endcode 11371 /// 11372 /// This routine returns the resulting FunctionDecl if it could be 11373 /// resolved, and NULL otherwise. When @p Complain is true, this 11374 /// routine will emit diagnostics if there is an error. 11375 FunctionDecl * 11376 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11377 QualType TargetType, 11378 bool Complain, 11379 DeclAccessPair &FoundResult, 11380 bool *pHadMultipleCandidates) { 11381 assert(AddressOfExpr->getType() == Context.OverloadTy); 11382 11383 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11384 Complain); 11385 int NumMatches = Resolver.getNumMatches(); 11386 FunctionDecl *Fn = nullptr; 11387 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11388 if (NumMatches == 0 && ShouldComplain) { 11389 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11390 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11391 else 11392 Resolver.ComplainNoMatchesFound(); 11393 } 11394 else if (NumMatches > 1 && ShouldComplain) 11395 Resolver.ComplainMultipleMatchesFound(); 11396 else if (NumMatches == 1) { 11397 Fn = Resolver.getMatchingFunctionDecl(); 11398 assert(Fn); 11399 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11400 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11401 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11402 if (Complain) { 11403 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11404 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11405 else 11406 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11407 } 11408 } 11409 11410 if (pHadMultipleCandidates) 11411 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11412 return Fn; 11413 } 11414 11415 /// Given an expression that refers to an overloaded function, try to 11416 /// resolve that function to a single function that can have its address taken. 11417 /// This will modify `Pair` iff it returns non-null. 11418 /// 11419 /// This routine can only realistically succeed if all but one candidates in the 11420 /// overload set for SrcExpr cannot have their addresses taken. 11421 FunctionDecl * 11422 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11423 DeclAccessPair &Pair) { 11424 OverloadExpr::FindResult R = OverloadExpr::find(E); 11425 OverloadExpr *Ovl = R.Expression; 11426 FunctionDecl *Result = nullptr; 11427 DeclAccessPair DAP; 11428 // Don't use the AddressOfResolver because we're specifically looking for 11429 // cases where we have one overload candidate that lacks 11430 // enable_if/pass_object_size/... 11431 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11432 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11433 if (!FD) 11434 return nullptr; 11435 11436 if (!checkAddressOfFunctionIsAvailable(FD)) 11437 continue; 11438 11439 // We have more than one result; quit. 11440 if (Result) 11441 return nullptr; 11442 DAP = I.getPair(); 11443 Result = FD; 11444 } 11445 11446 if (Result) 11447 Pair = DAP; 11448 return Result; 11449 } 11450 11451 /// Given an overloaded function, tries to turn it into a non-overloaded 11452 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11453 /// will perform access checks, diagnose the use of the resultant decl, and, if 11454 /// requested, potentially perform a function-to-pointer decay. 11455 /// 11456 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11457 /// Otherwise, returns true. This may emit diagnostics and return true. 11458 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11459 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11460 Expr *E = SrcExpr.get(); 11461 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11462 11463 DeclAccessPair DAP; 11464 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11465 if (!Found || Found->isCPUDispatchMultiVersion() || 11466 Found->isCPUSpecificMultiVersion()) 11467 return false; 11468 11469 // Emitting multiple diagnostics for a function that is both inaccessible and 11470 // unavailable is consistent with our behavior elsewhere. So, always check 11471 // for both. 11472 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11473 CheckAddressOfMemberAccess(E, DAP); 11474 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11475 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11476 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11477 else 11478 SrcExpr = Fixed; 11479 return true; 11480 } 11481 11482 /// Given an expression that refers to an overloaded function, try to 11483 /// resolve that overloaded function expression down to a single function. 11484 /// 11485 /// This routine can only resolve template-ids that refer to a single function 11486 /// template, where that template-id refers to a single template whose template 11487 /// arguments are either provided by the template-id or have defaults, 11488 /// as described in C++0x [temp.arg.explicit]p3. 11489 /// 11490 /// If no template-ids are found, no diagnostics are emitted and NULL is 11491 /// returned. 11492 FunctionDecl * 11493 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11494 bool Complain, 11495 DeclAccessPair *FoundResult) { 11496 // C++ [over.over]p1: 11497 // [...] [Note: any redundant set of parentheses surrounding the 11498 // overloaded function name is ignored (5.1). ] 11499 // C++ [over.over]p1: 11500 // [...] The overloaded function name can be preceded by the & 11501 // operator. 11502 11503 // If we didn't actually find any template-ids, we're done. 11504 if (!ovl->hasExplicitTemplateArgs()) 11505 return nullptr; 11506 11507 TemplateArgumentListInfo ExplicitTemplateArgs; 11508 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11509 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11510 11511 // Look through all of the overloaded functions, searching for one 11512 // whose type matches exactly. 11513 FunctionDecl *Matched = nullptr; 11514 for (UnresolvedSetIterator I = ovl->decls_begin(), 11515 E = ovl->decls_end(); I != E; ++I) { 11516 // C++0x [temp.arg.explicit]p3: 11517 // [...] In contexts where deduction is done and fails, or in contexts 11518 // where deduction is not done, if a template argument list is 11519 // specified and it, along with any default template arguments, 11520 // identifies a single function template specialization, then the 11521 // template-id is an lvalue for the function template specialization. 11522 FunctionTemplateDecl *FunctionTemplate 11523 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11524 11525 // C++ [over.over]p2: 11526 // If the name is a function template, template argument deduction is 11527 // done (14.8.2.2), and if the argument deduction succeeds, the 11528 // resulting template argument list is used to generate a single 11529 // function template specialization, which is added to the set of 11530 // overloaded functions considered. 11531 FunctionDecl *Specialization = nullptr; 11532 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11533 if (TemplateDeductionResult Result 11534 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11535 Specialization, Info, 11536 /*IsAddressOfFunction*/true)) { 11537 // Make a note of the failed deduction for diagnostics. 11538 // TODO: Actually use the failed-deduction info? 11539 FailedCandidates.addCandidate() 11540 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11541 MakeDeductionFailureInfo(Context, Result, Info)); 11542 continue; 11543 } 11544 11545 assert(Specialization && "no specialization and no error?"); 11546 11547 // Multiple matches; we can't resolve to a single declaration. 11548 if (Matched) { 11549 if (Complain) { 11550 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11551 << ovl->getName(); 11552 NoteAllOverloadCandidates(ovl); 11553 } 11554 return nullptr; 11555 } 11556 11557 Matched = Specialization; 11558 if (FoundResult) *FoundResult = I.getPair(); 11559 } 11560 11561 if (Matched && 11562 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11563 return nullptr; 11564 11565 return Matched; 11566 } 11567 11568 // Resolve and fix an overloaded expression that can be resolved 11569 // because it identifies a single function template specialization. 11570 // 11571 // Last three arguments should only be supplied if Complain = true 11572 // 11573 // Return true if it was logically possible to so resolve the 11574 // expression, regardless of whether or not it succeeded. Always 11575 // returns true if 'complain' is set. 11576 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11577 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11578 bool complain, SourceRange OpRangeForComplaining, 11579 QualType DestTypeForComplaining, 11580 unsigned DiagIDForComplaining) { 11581 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11582 11583 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11584 11585 DeclAccessPair found; 11586 ExprResult SingleFunctionExpression; 11587 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11588 ovl.Expression, /*complain*/ false, &found)) { 11589 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11590 SrcExpr = ExprError(); 11591 return true; 11592 } 11593 11594 // It is only correct to resolve to an instance method if we're 11595 // resolving a form that's permitted to be a pointer to member. 11596 // Otherwise we'll end up making a bound member expression, which 11597 // is illegal in all the contexts we resolve like this. 11598 if (!ovl.HasFormOfMemberPointer && 11599 isa<CXXMethodDecl>(fn) && 11600 cast<CXXMethodDecl>(fn)->isInstance()) { 11601 if (!complain) return false; 11602 11603 Diag(ovl.Expression->getExprLoc(), 11604 diag::err_bound_member_function) 11605 << 0 << ovl.Expression->getSourceRange(); 11606 11607 // TODO: I believe we only end up here if there's a mix of 11608 // static and non-static candidates (otherwise the expression 11609 // would have 'bound member' type, not 'overload' type). 11610 // Ideally we would note which candidate was chosen and why 11611 // the static candidates were rejected. 11612 SrcExpr = ExprError(); 11613 return true; 11614 } 11615 11616 // Fix the expression to refer to 'fn'. 11617 SingleFunctionExpression = 11618 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11619 11620 // If desired, do function-to-pointer decay. 11621 if (doFunctionPointerConverion) { 11622 SingleFunctionExpression = 11623 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11624 if (SingleFunctionExpression.isInvalid()) { 11625 SrcExpr = ExprError(); 11626 return true; 11627 } 11628 } 11629 } 11630 11631 if (!SingleFunctionExpression.isUsable()) { 11632 if (complain) { 11633 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11634 << ovl.Expression->getName() 11635 << DestTypeForComplaining 11636 << OpRangeForComplaining 11637 << ovl.Expression->getQualifierLoc().getSourceRange(); 11638 NoteAllOverloadCandidates(SrcExpr.get()); 11639 11640 SrcExpr = ExprError(); 11641 return true; 11642 } 11643 11644 return false; 11645 } 11646 11647 SrcExpr = SingleFunctionExpression; 11648 return true; 11649 } 11650 11651 /// Add a single candidate to the overload set. 11652 static void AddOverloadedCallCandidate(Sema &S, 11653 DeclAccessPair FoundDecl, 11654 TemplateArgumentListInfo *ExplicitTemplateArgs, 11655 ArrayRef<Expr *> Args, 11656 OverloadCandidateSet &CandidateSet, 11657 bool PartialOverloading, 11658 bool KnownValid) { 11659 NamedDecl *Callee = FoundDecl.getDecl(); 11660 if (isa<UsingShadowDecl>(Callee)) 11661 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11662 11663 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11664 if (ExplicitTemplateArgs) { 11665 assert(!KnownValid && "Explicit template arguments?"); 11666 return; 11667 } 11668 // Prevent ill-formed function decls to be added as overload candidates. 11669 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11670 return; 11671 11672 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11673 /*SuppressUsedConversions=*/false, 11674 PartialOverloading); 11675 return; 11676 } 11677 11678 if (FunctionTemplateDecl *FuncTemplate 11679 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11680 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11681 ExplicitTemplateArgs, Args, CandidateSet, 11682 /*SuppressUsedConversions=*/false, 11683 PartialOverloading); 11684 return; 11685 } 11686 11687 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11688 } 11689 11690 /// Add the overload candidates named by callee and/or found by argument 11691 /// dependent lookup to the given overload set. 11692 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11693 ArrayRef<Expr *> Args, 11694 OverloadCandidateSet &CandidateSet, 11695 bool PartialOverloading) { 11696 11697 #ifndef NDEBUG 11698 // Verify that ArgumentDependentLookup is consistent with the rules 11699 // in C++0x [basic.lookup.argdep]p3: 11700 // 11701 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11702 // and let Y be the lookup set produced by argument dependent 11703 // lookup (defined as follows). If X contains 11704 // 11705 // -- a declaration of a class member, or 11706 // 11707 // -- a block-scope function declaration that is not a 11708 // using-declaration, or 11709 // 11710 // -- a declaration that is neither a function or a function 11711 // template 11712 // 11713 // then Y is empty. 11714 11715 if (ULE->requiresADL()) { 11716 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11717 E = ULE->decls_end(); I != E; ++I) { 11718 assert(!(*I)->getDeclContext()->isRecord()); 11719 assert(isa<UsingShadowDecl>(*I) || 11720 !(*I)->getDeclContext()->isFunctionOrMethod()); 11721 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11722 } 11723 } 11724 #endif 11725 11726 // It would be nice to avoid this copy. 11727 TemplateArgumentListInfo TABuffer; 11728 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11729 if (ULE->hasExplicitTemplateArgs()) { 11730 ULE->copyTemplateArgumentsInto(TABuffer); 11731 ExplicitTemplateArgs = &TABuffer; 11732 } 11733 11734 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11735 E = ULE->decls_end(); I != E; ++I) 11736 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11737 CandidateSet, PartialOverloading, 11738 /*KnownValid*/ true); 11739 11740 if (ULE->requiresADL()) 11741 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11742 Args, ExplicitTemplateArgs, 11743 CandidateSet, PartialOverloading); 11744 } 11745 11746 /// Determine whether a declaration with the specified name could be moved into 11747 /// a different namespace. 11748 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11749 switch (Name.getCXXOverloadedOperator()) { 11750 case OO_New: case OO_Array_New: 11751 case OO_Delete: case OO_Array_Delete: 11752 return false; 11753 11754 default: 11755 return true; 11756 } 11757 } 11758 11759 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11760 /// template, where the non-dependent name was declared after the template 11761 /// was defined. This is common in code written for a compilers which do not 11762 /// correctly implement two-stage name lookup. 11763 /// 11764 /// Returns true if a viable candidate was found and a diagnostic was issued. 11765 static bool 11766 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11767 const CXXScopeSpec &SS, LookupResult &R, 11768 OverloadCandidateSet::CandidateSetKind CSK, 11769 TemplateArgumentListInfo *ExplicitTemplateArgs, 11770 ArrayRef<Expr *> Args, 11771 bool *DoDiagnoseEmptyLookup = nullptr) { 11772 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11773 return false; 11774 11775 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11776 if (DC->isTransparentContext()) 11777 continue; 11778 11779 SemaRef.LookupQualifiedName(R, DC); 11780 11781 if (!R.empty()) { 11782 R.suppressDiagnostics(); 11783 11784 if (isa<CXXRecordDecl>(DC)) { 11785 // Don't diagnose names we find in classes; we get much better 11786 // diagnostics for these from DiagnoseEmptyLookup. 11787 R.clear(); 11788 if (DoDiagnoseEmptyLookup) 11789 *DoDiagnoseEmptyLookup = true; 11790 return false; 11791 } 11792 11793 OverloadCandidateSet Candidates(FnLoc, CSK); 11794 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11795 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11796 ExplicitTemplateArgs, Args, 11797 Candidates, false, /*KnownValid*/ false); 11798 11799 OverloadCandidateSet::iterator Best; 11800 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11801 // No viable functions. Don't bother the user with notes for functions 11802 // which don't work and shouldn't be found anyway. 11803 R.clear(); 11804 return false; 11805 } 11806 11807 // Find the namespaces where ADL would have looked, and suggest 11808 // declaring the function there instead. 11809 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11810 Sema::AssociatedClassSet AssociatedClasses; 11811 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11812 AssociatedNamespaces, 11813 AssociatedClasses); 11814 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11815 if (canBeDeclaredInNamespace(R.getLookupName())) { 11816 DeclContext *Std = SemaRef.getStdNamespace(); 11817 for (Sema::AssociatedNamespaceSet::iterator 11818 it = AssociatedNamespaces.begin(), 11819 end = AssociatedNamespaces.end(); it != end; ++it) { 11820 // Never suggest declaring a function within namespace 'std'. 11821 if (Std && Std->Encloses(*it)) 11822 continue; 11823 11824 // Never suggest declaring a function within a namespace with a 11825 // reserved name, like __gnu_cxx. 11826 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11827 if (NS && 11828 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11829 continue; 11830 11831 SuggestedNamespaces.insert(*it); 11832 } 11833 } 11834 11835 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11836 << R.getLookupName(); 11837 if (SuggestedNamespaces.empty()) { 11838 SemaRef.Diag(Best->Function->getLocation(), 11839 diag::note_not_found_by_two_phase_lookup) 11840 << R.getLookupName() << 0; 11841 } else if (SuggestedNamespaces.size() == 1) { 11842 SemaRef.Diag(Best->Function->getLocation(), 11843 diag::note_not_found_by_two_phase_lookup) 11844 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11845 } else { 11846 // FIXME: It would be useful to list the associated namespaces here, 11847 // but the diagnostics infrastructure doesn't provide a way to produce 11848 // a localized representation of a list of items. 11849 SemaRef.Diag(Best->Function->getLocation(), 11850 diag::note_not_found_by_two_phase_lookup) 11851 << R.getLookupName() << 2; 11852 } 11853 11854 // Try to recover by calling this function. 11855 return true; 11856 } 11857 11858 R.clear(); 11859 } 11860 11861 return false; 11862 } 11863 11864 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11865 /// template, where the non-dependent operator was declared after the template 11866 /// was defined. 11867 /// 11868 /// Returns true if a viable candidate was found and a diagnostic was issued. 11869 static bool 11870 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11871 SourceLocation OpLoc, 11872 ArrayRef<Expr *> Args) { 11873 DeclarationName OpName = 11874 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11875 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11876 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11877 OverloadCandidateSet::CSK_Operator, 11878 /*ExplicitTemplateArgs=*/nullptr, Args); 11879 } 11880 11881 namespace { 11882 class BuildRecoveryCallExprRAII { 11883 Sema &SemaRef; 11884 public: 11885 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11886 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11887 SemaRef.IsBuildingRecoveryCallExpr = true; 11888 } 11889 11890 ~BuildRecoveryCallExprRAII() { 11891 SemaRef.IsBuildingRecoveryCallExpr = false; 11892 } 11893 }; 11894 11895 } 11896 11897 static std::unique_ptr<CorrectionCandidateCallback> 11898 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11899 bool HasTemplateArgs, bool AllowTypoCorrection) { 11900 if (!AllowTypoCorrection) 11901 return llvm::make_unique<NoTypoCorrectionCCC>(); 11902 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11903 HasTemplateArgs, ME); 11904 } 11905 11906 /// Attempts to recover from a call where no functions were found. 11907 /// 11908 /// Returns true if new candidates were found. 11909 static ExprResult 11910 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11911 UnresolvedLookupExpr *ULE, 11912 SourceLocation LParenLoc, 11913 MutableArrayRef<Expr *> Args, 11914 SourceLocation RParenLoc, 11915 bool EmptyLookup, bool AllowTypoCorrection) { 11916 // Do not try to recover if it is already building a recovery call. 11917 // This stops infinite loops for template instantiations like 11918 // 11919 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11920 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11921 // 11922 if (SemaRef.IsBuildingRecoveryCallExpr) 11923 return ExprError(); 11924 BuildRecoveryCallExprRAII RCE(SemaRef); 11925 11926 CXXScopeSpec SS; 11927 SS.Adopt(ULE->getQualifierLoc()); 11928 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11929 11930 TemplateArgumentListInfo TABuffer; 11931 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11932 if (ULE->hasExplicitTemplateArgs()) { 11933 ULE->copyTemplateArgumentsInto(TABuffer); 11934 ExplicitTemplateArgs = &TABuffer; 11935 } 11936 11937 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11938 Sema::LookupOrdinaryName); 11939 bool DoDiagnoseEmptyLookup = EmptyLookup; 11940 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11941 OverloadCandidateSet::CSK_Normal, 11942 ExplicitTemplateArgs, Args, 11943 &DoDiagnoseEmptyLookup) && 11944 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11945 S, SS, R, 11946 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11947 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11948 ExplicitTemplateArgs, Args))) 11949 return ExprError(); 11950 11951 assert(!R.empty() && "lookup results empty despite recovery"); 11952 11953 // If recovery created an ambiguity, just bail out. 11954 if (R.isAmbiguous()) { 11955 R.suppressDiagnostics(); 11956 return ExprError(); 11957 } 11958 11959 // Build an implicit member call if appropriate. Just drop the 11960 // casts and such from the call, we don't really care. 11961 ExprResult NewFn = ExprError(); 11962 if ((*R.begin())->isCXXClassMember()) 11963 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11964 ExplicitTemplateArgs, S); 11965 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11966 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11967 ExplicitTemplateArgs); 11968 else 11969 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11970 11971 if (NewFn.isInvalid()) 11972 return ExprError(); 11973 11974 // This shouldn't cause an infinite loop because we're giving it 11975 // an expression with viable lookup results, which should never 11976 // end up here. 11977 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11978 MultiExprArg(Args.data(), Args.size()), 11979 RParenLoc); 11980 } 11981 11982 /// Constructs and populates an OverloadedCandidateSet from 11983 /// the given function. 11984 /// \returns true when an the ExprResult output parameter has been set. 11985 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11986 UnresolvedLookupExpr *ULE, 11987 MultiExprArg Args, 11988 SourceLocation RParenLoc, 11989 OverloadCandidateSet *CandidateSet, 11990 ExprResult *Result) { 11991 #ifndef NDEBUG 11992 if (ULE->requiresADL()) { 11993 // To do ADL, we must have found an unqualified name. 11994 assert(!ULE->getQualifier() && "qualified name with ADL"); 11995 11996 // We don't perform ADL for implicit declarations of builtins. 11997 // Verify that this was correctly set up. 11998 FunctionDecl *F; 11999 if (ULE->decls_begin() + 1 == ULE->decls_end() && 12000 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12001 F->getBuiltinID() && F->isImplicit()) 12002 llvm_unreachable("performing ADL for builtin"); 12003 12004 // We don't perform ADL in C. 12005 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12006 } 12007 #endif 12008 12009 UnbridgedCastsSet UnbridgedCasts; 12010 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12011 *Result = ExprError(); 12012 return true; 12013 } 12014 12015 // Add the functions denoted by the callee to the set of candidate 12016 // functions, including those from argument-dependent lookup. 12017 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12018 12019 if (getLangOpts().MSVCCompat && 12020 CurContext->isDependentContext() && !isSFINAEContext() && 12021 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12022 12023 OverloadCandidateSet::iterator Best; 12024 if (CandidateSet->empty() || 12025 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12026 OR_No_Viable_Function) { 12027 // In Microsoft mode, if we are inside a template class member function 12028 // then create a type dependent CallExpr. The goal is to postpone name 12029 // lookup to instantiation time to be able to search into type dependent 12030 // base classes. 12031 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12032 VK_RValue, RParenLoc); 12033 CE->setTypeDependent(true); 12034 CE->setValueDependent(true); 12035 CE->setInstantiationDependent(true); 12036 *Result = CE; 12037 return true; 12038 } 12039 } 12040 12041 if (CandidateSet->empty()) 12042 return false; 12043 12044 UnbridgedCasts.restore(); 12045 return false; 12046 } 12047 12048 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12049 /// the completed call expression. If overload resolution fails, emits 12050 /// diagnostics and returns ExprError() 12051 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12052 UnresolvedLookupExpr *ULE, 12053 SourceLocation LParenLoc, 12054 MultiExprArg Args, 12055 SourceLocation RParenLoc, 12056 Expr *ExecConfig, 12057 OverloadCandidateSet *CandidateSet, 12058 OverloadCandidateSet::iterator *Best, 12059 OverloadingResult OverloadResult, 12060 bool AllowTypoCorrection) { 12061 if (CandidateSet->empty()) 12062 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12063 RParenLoc, /*EmptyLookup=*/true, 12064 AllowTypoCorrection); 12065 12066 switch (OverloadResult) { 12067 case OR_Success: { 12068 FunctionDecl *FDecl = (*Best)->Function; 12069 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12070 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12071 return ExprError(); 12072 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12073 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12074 ExecConfig, /*IsExecConfig=*/false, 12075 (*Best)->IsADLCandidate); 12076 } 12077 12078 case OR_No_Viable_Function: { 12079 // Try to recover by looking for viable functions which the user might 12080 // have meant to call. 12081 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12082 Args, RParenLoc, 12083 /*EmptyLookup=*/false, 12084 AllowTypoCorrection); 12085 if (!Recovery.isInvalid()) 12086 return Recovery; 12087 12088 // If the user passes in a function that we can't take the address of, we 12089 // generally end up emitting really bad error messages. Here, we attempt to 12090 // emit better ones. 12091 for (const Expr *Arg : Args) { 12092 if (!Arg->getType()->isFunctionType()) 12093 continue; 12094 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12095 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12096 if (FD && 12097 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12098 Arg->getExprLoc())) 12099 return ExprError(); 12100 } 12101 } 12102 12103 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call) 12104 << ULE->getName() << Fn->getSourceRange(); 12105 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12106 break; 12107 } 12108 12109 case OR_Ambiguous: 12110 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call) 12111 << ULE->getName() << Fn->getSourceRange(); 12112 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12113 break; 12114 12115 case OR_Deleted: { 12116 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call) 12117 << (*Best)->Function->isDeleted() << ULE->getName() 12118 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12119 << Fn->getSourceRange(); 12120 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12121 12122 // We emitted an error for the unavailable/deleted function call but keep 12123 // the call in the AST. 12124 FunctionDecl *FDecl = (*Best)->Function; 12125 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12126 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12127 ExecConfig, /*IsExecConfig=*/false, 12128 (*Best)->IsADLCandidate); 12129 } 12130 } 12131 12132 // Overload resolution failed. 12133 return ExprError(); 12134 } 12135 12136 static void markUnaddressableCandidatesUnviable(Sema &S, 12137 OverloadCandidateSet &CS) { 12138 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12139 if (I->Viable && 12140 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12141 I->Viable = false; 12142 I->FailureKind = ovl_fail_addr_not_available; 12143 } 12144 } 12145 } 12146 12147 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12148 /// (which eventually refers to the declaration Func) and the call 12149 /// arguments Args/NumArgs, attempt to resolve the function call down 12150 /// to a specific function. If overload resolution succeeds, returns 12151 /// the call expression produced by overload resolution. 12152 /// Otherwise, emits diagnostics and returns ExprError. 12153 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12154 UnresolvedLookupExpr *ULE, 12155 SourceLocation LParenLoc, 12156 MultiExprArg Args, 12157 SourceLocation RParenLoc, 12158 Expr *ExecConfig, 12159 bool AllowTypoCorrection, 12160 bool CalleesAddressIsTaken) { 12161 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12162 OverloadCandidateSet::CSK_Normal); 12163 ExprResult result; 12164 12165 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12166 &result)) 12167 return result; 12168 12169 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12170 // functions that aren't addressible are considered unviable. 12171 if (CalleesAddressIsTaken) 12172 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12173 12174 OverloadCandidateSet::iterator Best; 12175 OverloadingResult OverloadResult = 12176 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12177 12178 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12179 RParenLoc, ExecConfig, &CandidateSet, 12180 &Best, OverloadResult, 12181 AllowTypoCorrection); 12182 } 12183 12184 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12185 return Functions.size() > 1 || 12186 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12187 } 12188 12189 /// Create a unary operation that may resolve to an overloaded 12190 /// operator. 12191 /// 12192 /// \param OpLoc The location of the operator itself (e.g., '*'). 12193 /// 12194 /// \param Opc The UnaryOperatorKind that describes this operator. 12195 /// 12196 /// \param Fns The set of non-member functions that will be 12197 /// considered by overload resolution. The caller needs to build this 12198 /// set based on the context using, e.g., 12199 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12200 /// set should not contain any member functions; those will be added 12201 /// by CreateOverloadedUnaryOp(). 12202 /// 12203 /// \param Input The input argument. 12204 ExprResult 12205 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12206 const UnresolvedSetImpl &Fns, 12207 Expr *Input, bool PerformADL) { 12208 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12209 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12210 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12211 // TODO: provide better source location info. 12212 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12213 12214 if (checkPlaceholderForOverload(*this, Input)) 12215 return ExprError(); 12216 12217 Expr *Args[2] = { Input, nullptr }; 12218 unsigned NumArgs = 1; 12219 12220 // For post-increment and post-decrement, add the implicit '0' as 12221 // the second argument, so that we know this is a post-increment or 12222 // post-decrement. 12223 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12224 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12225 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12226 SourceLocation()); 12227 NumArgs = 2; 12228 } 12229 12230 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12231 12232 if (Input->isTypeDependent()) { 12233 if (Fns.empty()) 12234 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12235 VK_RValue, OK_Ordinary, OpLoc, false); 12236 12237 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12238 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12239 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12240 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12241 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12242 Context.DependentTy, VK_RValue, OpLoc, 12243 FPOptions()); 12244 } 12245 12246 // Build an empty overload set. 12247 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12248 12249 // Add the candidates from the given function set. 12250 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12251 12252 // Add operator candidates that are member functions. 12253 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12254 12255 // Add candidates from ADL. 12256 if (PerformADL) { 12257 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12258 /*ExplicitTemplateArgs*/nullptr, 12259 CandidateSet); 12260 } 12261 12262 // Add builtin operator candidates. 12263 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12264 12265 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12266 12267 // Perform overload resolution. 12268 OverloadCandidateSet::iterator Best; 12269 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12270 case OR_Success: { 12271 // We found a built-in operator or an overloaded operator. 12272 FunctionDecl *FnDecl = Best->Function; 12273 12274 if (FnDecl) { 12275 Expr *Base = nullptr; 12276 // We matched an overloaded operator. Build a call to that 12277 // operator. 12278 12279 // Convert the arguments. 12280 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12281 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12282 12283 ExprResult InputRes = 12284 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12285 Best->FoundDecl, Method); 12286 if (InputRes.isInvalid()) 12287 return ExprError(); 12288 Base = Input = InputRes.get(); 12289 } else { 12290 // Convert the arguments. 12291 ExprResult InputInit 12292 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12293 Context, 12294 FnDecl->getParamDecl(0)), 12295 SourceLocation(), 12296 Input); 12297 if (InputInit.isInvalid()) 12298 return ExprError(); 12299 Input = InputInit.get(); 12300 } 12301 12302 // Build the actual expression node. 12303 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12304 Base, HadMultipleCandidates, 12305 OpLoc); 12306 if (FnExpr.isInvalid()) 12307 return ExprError(); 12308 12309 // Determine the result type. 12310 QualType ResultTy = FnDecl->getReturnType(); 12311 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12312 ResultTy = ResultTy.getNonLValueExprType(Context); 12313 12314 Args[0] = Input; 12315 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12316 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12317 FPOptions(), Best->IsADLCandidate); 12318 12319 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12320 return ExprError(); 12321 12322 if (CheckFunctionCall(FnDecl, TheCall, 12323 FnDecl->getType()->castAs<FunctionProtoType>())) 12324 return ExprError(); 12325 12326 return MaybeBindToTemporary(TheCall); 12327 } else { 12328 // We matched a built-in operator. Convert the arguments, then 12329 // break out so that we will build the appropriate built-in 12330 // operator node. 12331 ExprResult InputRes = PerformImplicitConversion( 12332 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12333 CCK_ForBuiltinOverloadedOp); 12334 if (InputRes.isInvalid()) 12335 return ExprError(); 12336 Input = InputRes.get(); 12337 break; 12338 } 12339 } 12340 12341 case OR_No_Viable_Function: 12342 // This is an erroneous use of an operator which can be overloaded by 12343 // a non-member function. Check for non-member operators which were 12344 // defined too late to be candidates. 12345 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12346 // FIXME: Recover by calling the found function. 12347 return ExprError(); 12348 12349 // No viable function; fall through to handling this as a 12350 // built-in operator, which will produce an error message for us. 12351 break; 12352 12353 case OR_Ambiguous: 12354 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12355 << UnaryOperator::getOpcodeStr(Opc) 12356 << Input->getType() 12357 << Input->getSourceRange(); 12358 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12359 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12360 return ExprError(); 12361 12362 case OR_Deleted: 12363 Diag(OpLoc, diag::err_ovl_deleted_oper) 12364 << Best->Function->isDeleted() 12365 << UnaryOperator::getOpcodeStr(Opc) 12366 << getDeletedOrUnavailableSuffix(Best->Function) 12367 << Input->getSourceRange(); 12368 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12369 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12370 return ExprError(); 12371 } 12372 12373 // Either we found no viable overloaded operator or we matched a 12374 // built-in operator. In either case, fall through to trying to 12375 // build a built-in operation. 12376 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12377 } 12378 12379 /// Create a binary operation that may resolve to an overloaded 12380 /// operator. 12381 /// 12382 /// \param OpLoc The location of the operator itself (e.g., '+'). 12383 /// 12384 /// \param Opc The BinaryOperatorKind that describes this operator. 12385 /// 12386 /// \param Fns The set of non-member functions that will be 12387 /// considered by overload resolution. The caller needs to build this 12388 /// set based on the context using, e.g., 12389 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12390 /// set should not contain any member functions; those will be added 12391 /// by CreateOverloadedBinOp(). 12392 /// 12393 /// \param LHS Left-hand argument. 12394 /// \param RHS Right-hand argument. 12395 ExprResult 12396 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12397 BinaryOperatorKind Opc, 12398 const UnresolvedSetImpl &Fns, 12399 Expr *LHS, Expr *RHS, bool PerformADL) { 12400 Expr *Args[2] = { LHS, RHS }; 12401 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12402 12403 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12404 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12405 12406 // If either side is type-dependent, create an appropriate dependent 12407 // expression. 12408 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12409 if (Fns.empty()) { 12410 // If there are no functions to store, just build a dependent 12411 // BinaryOperator or CompoundAssignment. 12412 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12413 return new (Context) BinaryOperator( 12414 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12415 OpLoc, FPFeatures); 12416 12417 return new (Context) CompoundAssignOperator( 12418 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12419 Context.DependentTy, Context.DependentTy, OpLoc, 12420 FPFeatures); 12421 } 12422 12423 // FIXME: save results of ADL from here? 12424 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12425 // TODO: provide better source location info in DNLoc component. 12426 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12427 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12428 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12429 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12430 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12431 Context.DependentTy, VK_RValue, OpLoc, 12432 FPFeatures); 12433 } 12434 12435 // Always do placeholder-like conversions on the RHS. 12436 if (checkPlaceholderForOverload(*this, Args[1])) 12437 return ExprError(); 12438 12439 // Do placeholder-like conversion on the LHS; note that we should 12440 // not get here with a PseudoObject LHS. 12441 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12442 if (checkPlaceholderForOverload(*this, Args[0])) 12443 return ExprError(); 12444 12445 // If this is the assignment operator, we only perform overload resolution 12446 // if the left-hand side is a class or enumeration type. This is actually 12447 // a hack. The standard requires that we do overload resolution between the 12448 // various built-in candidates, but as DR507 points out, this can lead to 12449 // problems. So we do it this way, which pretty much follows what GCC does. 12450 // Note that we go the traditional code path for compound assignment forms. 12451 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12452 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12453 12454 // If this is the .* operator, which is not overloadable, just 12455 // create a built-in binary operator. 12456 if (Opc == BO_PtrMemD) 12457 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12458 12459 // Build an empty overload set. 12460 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12461 12462 // Add the candidates from the given function set. 12463 AddFunctionCandidates(Fns, Args, CandidateSet); 12464 12465 // Add operator candidates that are member functions. 12466 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12467 12468 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12469 // performed for an assignment operator (nor for operator[] nor operator->, 12470 // which don't get here). 12471 if (Opc != BO_Assign && PerformADL) 12472 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12473 /*ExplicitTemplateArgs*/ nullptr, 12474 CandidateSet); 12475 12476 // Add builtin operator candidates. 12477 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12478 12479 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12480 12481 // Perform overload resolution. 12482 OverloadCandidateSet::iterator Best; 12483 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12484 case OR_Success: { 12485 // We found a built-in operator or an overloaded operator. 12486 FunctionDecl *FnDecl = Best->Function; 12487 12488 if (FnDecl) { 12489 Expr *Base = nullptr; 12490 // We matched an overloaded operator. Build a call to that 12491 // operator. 12492 12493 // Convert the arguments. 12494 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12495 // Best->Access is only meaningful for class members. 12496 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12497 12498 ExprResult Arg1 = 12499 PerformCopyInitialization( 12500 InitializedEntity::InitializeParameter(Context, 12501 FnDecl->getParamDecl(0)), 12502 SourceLocation(), Args[1]); 12503 if (Arg1.isInvalid()) 12504 return ExprError(); 12505 12506 ExprResult Arg0 = 12507 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12508 Best->FoundDecl, Method); 12509 if (Arg0.isInvalid()) 12510 return ExprError(); 12511 Base = Args[0] = Arg0.getAs<Expr>(); 12512 Args[1] = RHS = Arg1.getAs<Expr>(); 12513 } else { 12514 // Convert the arguments. 12515 ExprResult Arg0 = PerformCopyInitialization( 12516 InitializedEntity::InitializeParameter(Context, 12517 FnDecl->getParamDecl(0)), 12518 SourceLocation(), Args[0]); 12519 if (Arg0.isInvalid()) 12520 return ExprError(); 12521 12522 ExprResult Arg1 = 12523 PerformCopyInitialization( 12524 InitializedEntity::InitializeParameter(Context, 12525 FnDecl->getParamDecl(1)), 12526 SourceLocation(), Args[1]); 12527 if (Arg1.isInvalid()) 12528 return ExprError(); 12529 Args[0] = LHS = Arg0.getAs<Expr>(); 12530 Args[1] = RHS = Arg1.getAs<Expr>(); 12531 } 12532 12533 // Build the actual expression node. 12534 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12535 Best->FoundDecl, Base, 12536 HadMultipleCandidates, OpLoc); 12537 if (FnExpr.isInvalid()) 12538 return ExprError(); 12539 12540 // Determine the result type. 12541 QualType ResultTy = FnDecl->getReturnType(); 12542 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12543 ResultTy = ResultTy.getNonLValueExprType(Context); 12544 12545 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12546 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12547 Best->IsADLCandidate); 12548 12549 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12550 FnDecl)) 12551 return ExprError(); 12552 12553 ArrayRef<const Expr *> ArgsArray(Args, 2); 12554 const Expr *ImplicitThis = nullptr; 12555 // Cut off the implicit 'this'. 12556 if (isa<CXXMethodDecl>(FnDecl)) { 12557 ImplicitThis = ArgsArray[0]; 12558 ArgsArray = ArgsArray.slice(1); 12559 } 12560 12561 // Check for a self move. 12562 if (Op == OO_Equal) 12563 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12564 12565 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12566 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12567 VariadicDoesNotApply); 12568 12569 return MaybeBindToTemporary(TheCall); 12570 } else { 12571 // We matched a built-in operator. Convert the arguments, then 12572 // break out so that we will build the appropriate built-in 12573 // operator node. 12574 ExprResult ArgsRes0 = PerformImplicitConversion( 12575 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12576 AA_Passing, CCK_ForBuiltinOverloadedOp); 12577 if (ArgsRes0.isInvalid()) 12578 return ExprError(); 12579 Args[0] = ArgsRes0.get(); 12580 12581 ExprResult ArgsRes1 = PerformImplicitConversion( 12582 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12583 AA_Passing, CCK_ForBuiltinOverloadedOp); 12584 if (ArgsRes1.isInvalid()) 12585 return ExprError(); 12586 Args[1] = ArgsRes1.get(); 12587 break; 12588 } 12589 } 12590 12591 case OR_No_Viable_Function: { 12592 // C++ [over.match.oper]p9: 12593 // If the operator is the operator , [...] and there are no 12594 // viable functions, then the operator is assumed to be the 12595 // built-in operator and interpreted according to clause 5. 12596 if (Opc == BO_Comma) 12597 break; 12598 12599 // For class as left operand for assignment or compound assignment 12600 // operator do not fall through to handling in built-in, but report that 12601 // no overloaded assignment operator found 12602 ExprResult Result = ExprError(); 12603 if (Args[0]->getType()->isRecordType() && 12604 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12605 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12606 << BinaryOperator::getOpcodeStr(Opc) 12607 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12608 if (Args[0]->getType()->isIncompleteType()) { 12609 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12610 << Args[0]->getType() 12611 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12612 } 12613 } else { 12614 // This is an erroneous use of an operator which can be overloaded by 12615 // a non-member function. Check for non-member operators which were 12616 // defined too late to be candidates. 12617 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12618 // FIXME: Recover by calling the found function. 12619 return ExprError(); 12620 12621 // No viable function; try to create a built-in operation, which will 12622 // produce an error. Then, show the non-viable candidates. 12623 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12624 } 12625 assert(Result.isInvalid() && 12626 "C++ binary operator overloading is missing candidates!"); 12627 if (Result.isInvalid()) 12628 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12629 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12630 return Result; 12631 } 12632 12633 case OR_Ambiguous: 12634 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12635 << BinaryOperator::getOpcodeStr(Opc) 12636 << Args[0]->getType() << Args[1]->getType() 12637 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12638 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12639 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12640 return ExprError(); 12641 12642 case OR_Deleted: 12643 if (isImplicitlyDeleted(Best->Function)) { 12644 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12645 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12646 << Context.getRecordType(Method->getParent()) 12647 << getSpecialMember(Method); 12648 12649 // The user probably meant to call this special member. Just 12650 // explain why it's deleted. 12651 NoteDeletedFunction(Method); 12652 return ExprError(); 12653 } else { 12654 Diag(OpLoc, diag::err_ovl_deleted_oper) 12655 << Best->Function->isDeleted() 12656 << BinaryOperator::getOpcodeStr(Opc) 12657 << getDeletedOrUnavailableSuffix(Best->Function) 12658 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12659 } 12660 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12661 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12662 return ExprError(); 12663 } 12664 12665 // We matched a built-in operator; build it. 12666 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12667 } 12668 12669 ExprResult 12670 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12671 SourceLocation RLoc, 12672 Expr *Base, Expr *Idx) { 12673 Expr *Args[2] = { Base, Idx }; 12674 DeclarationName OpName = 12675 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12676 12677 // If either side is type-dependent, create an appropriate dependent 12678 // expression. 12679 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12680 12681 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12682 // CHECKME: no 'operator' keyword? 12683 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12684 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12685 UnresolvedLookupExpr *Fn 12686 = UnresolvedLookupExpr::Create(Context, NamingClass, 12687 NestedNameSpecifierLoc(), OpNameInfo, 12688 /*ADL*/ true, /*Overloaded*/ false, 12689 UnresolvedSetIterator(), 12690 UnresolvedSetIterator()); 12691 // Can't add any actual overloads yet 12692 12693 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12694 Context.DependentTy, VK_RValue, RLoc, 12695 FPOptions()); 12696 } 12697 12698 // Handle placeholders on both operands. 12699 if (checkPlaceholderForOverload(*this, Args[0])) 12700 return ExprError(); 12701 if (checkPlaceholderForOverload(*this, Args[1])) 12702 return ExprError(); 12703 12704 // Build an empty overload set. 12705 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12706 12707 // Subscript can only be overloaded as a member function. 12708 12709 // Add operator candidates that are member functions. 12710 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12711 12712 // Add builtin operator candidates. 12713 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12714 12715 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12716 12717 // Perform overload resolution. 12718 OverloadCandidateSet::iterator Best; 12719 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12720 case OR_Success: { 12721 // We found a built-in operator or an overloaded operator. 12722 FunctionDecl *FnDecl = Best->Function; 12723 12724 if (FnDecl) { 12725 // We matched an overloaded operator. Build a call to that 12726 // operator. 12727 12728 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12729 12730 // Convert the arguments. 12731 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12732 ExprResult Arg0 = 12733 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12734 Best->FoundDecl, Method); 12735 if (Arg0.isInvalid()) 12736 return ExprError(); 12737 Args[0] = Arg0.get(); 12738 12739 // Convert the arguments. 12740 ExprResult InputInit 12741 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12742 Context, 12743 FnDecl->getParamDecl(0)), 12744 SourceLocation(), 12745 Args[1]); 12746 if (InputInit.isInvalid()) 12747 return ExprError(); 12748 12749 Args[1] = InputInit.getAs<Expr>(); 12750 12751 // Build the actual expression node. 12752 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12753 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12754 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12755 Best->FoundDecl, 12756 Base, 12757 HadMultipleCandidates, 12758 OpLocInfo.getLoc(), 12759 OpLocInfo.getInfo()); 12760 if (FnExpr.isInvalid()) 12761 return ExprError(); 12762 12763 // Determine the result type 12764 QualType ResultTy = FnDecl->getReturnType(); 12765 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12766 ResultTy = ResultTy.getNonLValueExprType(Context); 12767 12768 CXXOperatorCallExpr *TheCall = 12769 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12770 Args, ResultTy, VK, RLoc, FPOptions()); 12771 12772 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12773 return ExprError(); 12774 12775 if (CheckFunctionCall(Method, TheCall, 12776 Method->getType()->castAs<FunctionProtoType>())) 12777 return ExprError(); 12778 12779 return MaybeBindToTemporary(TheCall); 12780 } else { 12781 // We matched a built-in operator. Convert the arguments, then 12782 // break out so that we will build the appropriate built-in 12783 // operator node. 12784 ExprResult ArgsRes0 = PerformImplicitConversion( 12785 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12786 AA_Passing, CCK_ForBuiltinOverloadedOp); 12787 if (ArgsRes0.isInvalid()) 12788 return ExprError(); 12789 Args[0] = ArgsRes0.get(); 12790 12791 ExprResult ArgsRes1 = PerformImplicitConversion( 12792 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12793 AA_Passing, CCK_ForBuiltinOverloadedOp); 12794 if (ArgsRes1.isInvalid()) 12795 return ExprError(); 12796 Args[1] = ArgsRes1.get(); 12797 12798 break; 12799 } 12800 } 12801 12802 case OR_No_Viable_Function: { 12803 if (CandidateSet.empty()) 12804 Diag(LLoc, diag::err_ovl_no_oper) 12805 << Args[0]->getType() << /*subscript*/ 0 12806 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12807 else 12808 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12809 << Args[0]->getType() 12810 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12811 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12812 "[]", LLoc); 12813 return ExprError(); 12814 } 12815 12816 case OR_Ambiguous: 12817 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12818 << "[]" 12819 << Args[0]->getType() << Args[1]->getType() 12820 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12821 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12822 "[]", LLoc); 12823 return ExprError(); 12824 12825 case OR_Deleted: 12826 Diag(LLoc, diag::err_ovl_deleted_oper) 12827 << Best->Function->isDeleted() << "[]" 12828 << getDeletedOrUnavailableSuffix(Best->Function) 12829 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12830 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12831 "[]", LLoc); 12832 return ExprError(); 12833 } 12834 12835 // We matched a built-in operator; build it. 12836 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12837 } 12838 12839 /// BuildCallToMemberFunction - Build a call to a member 12840 /// function. MemExpr is the expression that refers to the member 12841 /// function (and includes the object parameter), Args/NumArgs are the 12842 /// arguments to the function call (not including the object 12843 /// parameter). The caller needs to validate that the member 12844 /// expression refers to a non-static member function or an overloaded 12845 /// member function. 12846 ExprResult 12847 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12848 SourceLocation LParenLoc, 12849 MultiExprArg Args, 12850 SourceLocation RParenLoc) { 12851 assert(MemExprE->getType() == Context.BoundMemberTy || 12852 MemExprE->getType() == Context.OverloadTy); 12853 12854 // Dig out the member expression. This holds both the object 12855 // argument and the member function we're referring to. 12856 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12857 12858 // Determine whether this is a call to a pointer-to-member function. 12859 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12860 assert(op->getType() == Context.BoundMemberTy); 12861 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12862 12863 QualType fnType = 12864 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12865 12866 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12867 QualType resultType = proto->getCallResultType(Context); 12868 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12869 12870 // Check that the object type isn't more qualified than the 12871 // member function we're calling. 12872 Qualifiers funcQuals = proto->getTypeQuals(); 12873 12874 QualType objectType = op->getLHS()->getType(); 12875 if (op->getOpcode() == BO_PtrMemI) 12876 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12877 Qualifiers objectQuals = objectType.getQualifiers(); 12878 12879 Qualifiers difference = objectQuals - funcQuals; 12880 difference.removeObjCGCAttr(); 12881 difference.removeAddressSpace(); 12882 if (difference) { 12883 std::string qualsString = difference.getAsString(); 12884 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12885 << fnType.getUnqualifiedType() 12886 << qualsString 12887 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12888 } 12889 12890 CXXMemberCallExpr *call = 12891 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 12892 valueKind, RParenLoc, proto->getNumParams()); 12893 12894 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12895 call, nullptr)) 12896 return ExprError(); 12897 12898 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12899 return ExprError(); 12900 12901 if (CheckOtherCall(call, proto)) 12902 return ExprError(); 12903 12904 return MaybeBindToTemporary(call); 12905 } 12906 12907 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12908 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 12909 RParenLoc); 12910 12911 UnbridgedCastsSet UnbridgedCasts; 12912 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12913 return ExprError(); 12914 12915 MemberExpr *MemExpr; 12916 CXXMethodDecl *Method = nullptr; 12917 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12918 NestedNameSpecifier *Qualifier = nullptr; 12919 if (isa<MemberExpr>(NakedMemExpr)) { 12920 MemExpr = cast<MemberExpr>(NakedMemExpr); 12921 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12922 FoundDecl = MemExpr->getFoundDecl(); 12923 Qualifier = MemExpr->getQualifier(); 12924 UnbridgedCasts.restore(); 12925 } else { 12926 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12927 Qualifier = UnresExpr->getQualifier(); 12928 12929 QualType ObjectType = UnresExpr->getBaseType(); 12930 Expr::Classification ObjectClassification 12931 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12932 : UnresExpr->getBase()->Classify(Context); 12933 12934 // Add overload candidates 12935 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12936 OverloadCandidateSet::CSK_Normal); 12937 12938 // FIXME: avoid copy. 12939 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12940 if (UnresExpr->hasExplicitTemplateArgs()) { 12941 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12942 TemplateArgs = &TemplateArgsBuffer; 12943 } 12944 12945 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12946 E = UnresExpr->decls_end(); I != E; ++I) { 12947 12948 NamedDecl *Func = *I; 12949 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12950 if (isa<UsingShadowDecl>(Func)) 12951 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12952 12953 12954 // Microsoft supports direct constructor calls. 12955 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12956 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12957 Args, CandidateSet); 12958 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12959 // If explicit template arguments were provided, we can't call a 12960 // non-template member function. 12961 if (TemplateArgs) 12962 continue; 12963 12964 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12965 ObjectClassification, Args, CandidateSet, 12966 /*SuppressUserConversions=*/false); 12967 } else { 12968 AddMethodTemplateCandidate( 12969 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12970 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12971 /*SuppressUsedConversions=*/false); 12972 } 12973 } 12974 12975 DeclarationName DeclName = UnresExpr->getMemberName(); 12976 12977 UnbridgedCasts.restore(); 12978 12979 OverloadCandidateSet::iterator Best; 12980 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 12981 Best)) { 12982 case OR_Success: 12983 Method = cast<CXXMethodDecl>(Best->Function); 12984 FoundDecl = Best->FoundDecl; 12985 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12986 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12987 return ExprError(); 12988 // If FoundDecl is different from Method (such as if one is a template 12989 // and the other a specialization), make sure DiagnoseUseOfDecl is 12990 // called on both. 12991 // FIXME: This would be more comprehensively addressed by modifying 12992 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12993 // being used. 12994 if (Method != FoundDecl.getDecl() && 12995 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12996 return ExprError(); 12997 break; 12998 12999 case OR_No_Viable_Function: 13000 Diag(UnresExpr->getMemberLoc(), 13001 diag::err_ovl_no_viable_member_function_in_call) 13002 << DeclName << MemExprE->getSourceRange(); 13003 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13004 // FIXME: Leaking incoming expressions! 13005 return ExprError(); 13006 13007 case OR_Ambiguous: 13008 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 13009 << DeclName << MemExprE->getSourceRange(); 13010 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13011 // FIXME: Leaking incoming expressions! 13012 return ExprError(); 13013 13014 case OR_Deleted: 13015 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 13016 << Best->Function->isDeleted() 13017 << DeclName 13018 << getDeletedOrUnavailableSuffix(Best->Function) 13019 << MemExprE->getSourceRange(); 13020 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13021 // FIXME: Leaking incoming expressions! 13022 return ExprError(); 13023 } 13024 13025 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13026 13027 // If overload resolution picked a static member, build a 13028 // non-member call based on that function. 13029 if (Method->isStatic()) { 13030 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13031 RParenLoc); 13032 } 13033 13034 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13035 } 13036 13037 QualType ResultType = Method->getReturnType(); 13038 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13039 ResultType = ResultType.getNonLValueExprType(Context); 13040 13041 assert(Method && "Member call to something that isn't a method?"); 13042 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13043 CXXMemberCallExpr *TheCall = 13044 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13045 RParenLoc, Proto->getNumParams()); 13046 13047 // Check for a valid return type. 13048 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13049 TheCall, Method)) 13050 return ExprError(); 13051 13052 // Convert the object argument (for a non-static member function call). 13053 // We only need to do this if there was actually an overload; otherwise 13054 // it was done at lookup. 13055 if (!Method->isStatic()) { 13056 ExprResult ObjectArg = 13057 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13058 FoundDecl, Method); 13059 if (ObjectArg.isInvalid()) 13060 return ExprError(); 13061 MemExpr->setBase(ObjectArg.get()); 13062 } 13063 13064 // Convert the rest of the arguments 13065 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13066 RParenLoc)) 13067 return ExprError(); 13068 13069 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13070 13071 if (CheckFunctionCall(Method, TheCall, Proto)) 13072 return ExprError(); 13073 13074 // In the case the method to call was not selected by the overloading 13075 // resolution process, we still need to handle the enable_if attribute. Do 13076 // that here, so it will not hide previous -- and more relevant -- errors. 13077 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13078 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13079 Diag(MemE->getMemberLoc(), 13080 diag::err_ovl_no_viable_member_function_in_call) 13081 << Method << Method->getSourceRange(); 13082 Diag(Method->getLocation(), 13083 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13084 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13085 return ExprError(); 13086 } 13087 } 13088 13089 if ((isa<CXXConstructorDecl>(CurContext) || 13090 isa<CXXDestructorDecl>(CurContext)) && 13091 TheCall->getMethodDecl()->isPure()) { 13092 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13093 13094 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13095 MemExpr->performsVirtualDispatch(getLangOpts())) { 13096 Diag(MemExpr->getBeginLoc(), 13097 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13098 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13099 << MD->getParent()->getDeclName(); 13100 13101 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13102 if (getLangOpts().AppleKext) 13103 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13104 << MD->getParent()->getDeclName() << MD->getDeclName(); 13105 } 13106 } 13107 13108 if (CXXDestructorDecl *DD = 13109 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13110 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13111 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13112 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13113 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13114 MemExpr->getMemberLoc()); 13115 } 13116 13117 return MaybeBindToTemporary(TheCall); 13118 } 13119 13120 /// BuildCallToObjectOfClassType - Build a call to an object of class 13121 /// type (C++ [over.call.object]), which can end up invoking an 13122 /// overloaded function call operator (@c operator()) or performing a 13123 /// user-defined conversion on the object argument. 13124 ExprResult 13125 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13126 SourceLocation LParenLoc, 13127 MultiExprArg Args, 13128 SourceLocation RParenLoc) { 13129 if (checkPlaceholderForOverload(*this, Obj)) 13130 return ExprError(); 13131 ExprResult Object = Obj; 13132 13133 UnbridgedCastsSet UnbridgedCasts; 13134 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13135 return ExprError(); 13136 13137 assert(Object.get()->getType()->isRecordType() && 13138 "Requires object type argument"); 13139 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13140 13141 // C++ [over.call.object]p1: 13142 // If the primary-expression E in the function call syntax 13143 // evaluates to a class object of type "cv T", then the set of 13144 // candidate functions includes at least the function call 13145 // operators of T. The function call operators of T are obtained by 13146 // ordinary lookup of the name operator() in the context of 13147 // (E).operator(). 13148 OverloadCandidateSet CandidateSet(LParenLoc, 13149 OverloadCandidateSet::CSK_Operator); 13150 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13151 13152 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13153 diag::err_incomplete_object_call, Object.get())) 13154 return true; 13155 13156 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13157 LookupQualifiedName(R, Record->getDecl()); 13158 R.suppressDiagnostics(); 13159 13160 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13161 Oper != OperEnd; ++Oper) { 13162 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13163 Object.get()->Classify(Context), Args, CandidateSet, 13164 /*SuppressUserConversions=*/false); 13165 } 13166 13167 // C++ [over.call.object]p2: 13168 // In addition, for each (non-explicit in C++0x) conversion function 13169 // declared in T of the form 13170 // 13171 // operator conversion-type-id () cv-qualifier; 13172 // 13173 // where cv-qualifier is the same cv-qualification as, or a 13174 // greater cv-qualification than, cv, and where conversion-type-id 13175 // denotes the type "pointer to function of (P1,...,Pn) returning 13176 // R", or the type "reference to pointer to function of 13177 // (P1,...,Pn) returning R", or the type "reference to function 13178 // of (P1,...,Pn) returning R", a surrogate call function [...] 13179 // is also considered as a candidate function. Similarly, 13180 // surrogate call functions are added to the set of candidate 13181 // functions for each conversion function declared in an 13182 // accessible base class provided the function is not hidden 13183 // within T by another intervening declaration. 13184 const auto &Conversions = 13185 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13186 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13187 NamedDecl *D = *I; 13188 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13189 if (isa<UsingShadowDecl>(D)) 13190 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13191 13192 // Skip over templated conversion functions; they aren't 13193 // surrogates. 13194 if (isa<FunctionTemplateDecl>(D)) 13195 continue; 13196 13197 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13198 if (!Conv->isExplicit()) { 13199 // Strip the reference type (if any) and then the pointer type (if 13200 // any) to get down to what might be a function type. 13201 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13202 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13203 ConvType = ConvPtrType->getPointeeType(); 13204 13205 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13206 { 13207 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13208 Object.get(), Args, CandidateSet); 13209 } 13210 } 13211 } 13212 13213 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13214 13215 // Perform overload resolution. 13216 OverloadCandidateSet::iterator Best; 13217 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13218 Best)) { 13219 case OR_Success: 13220 // Overload resolution succeeded; we'll build the appropriate call 13221 // below. 13222 break; 13223 13224 case OR_No_Viable_Function: 13225 if (CandidateSet.empty()) 13226 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper) 13227 << Object.get()->getType() << /*call*/ 1 13228 << Object.get()->getSourceRange(); 13229 else 13230 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call) 13231 << Object.get()->getType() << Object.get()->getSourceRange(); 13232 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13233 break; 13234 13235 case OR_Ambiguous: 13236 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call) 13237 << Object.get()->getType() << Object.get()->getSourceRange(); 13238 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13239 break; 13240 13241 case OR_Deleted: 13242 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call) 13243 << Best->Function->isDeleted() << Object.get()->getType() 13244 << getDeletedOrUnavailableSuffix(Best->Function) 13245 << Object.get()->getSourceRange(); 13246 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13247 break; 13248 } 13249 13250 if (Best == CandidateSet.end()) 13251 return true; 13252 13253 UnbridgedCasts.restore(); 13254 13255 if (Best->Function == nullptr) { 13256 // Since there is no function declaration, this is one of the 13257 // surrogate candidates. Dig out the conversion function. 13258 CXXConversionDecl *Conv 13259 = cast<CXXConversionDecl>( 13260 Best->Conversions[0].UserDefined.ConversionFunction); 13261 13262 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13263 Best->FoundDecl); 13264 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13265 return ExprError(); 13266 assert(Conv == Best->FoundDecl.getDecl() && 13267 "Found Decl & conversion-to-functionptr should be same, right?!"); 13268 // We selected one of the surrogate functions that converts the 13269 // object parameter to a function pointer. Perform the conversion 13270 // on the object argument, then let ActOnCallExpr finish the job. 13271 13272 // Create an implicit member expr to refer to the conversion operator. 13273 // and then call it. 13274 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13275 Conv, HadMultipleCandidates); 13276 if (Call.isInvalid()) 13277 return ExprError(); 13278 // Record usage of conversion in an implicit cast. 13279 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13280 CK_UserDefinedConversion, Call.get(), 13281 nullptr, VK_RValue); 13282 13283 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13284 } 13285 13286 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13287 13288 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13289 // that calls this method, using Object for the implicit object 13290 // parameter and passing along the remaining arguments. 13291 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13292 13293 // An error diagnostic has already been printed when parsing the declaration. 13294 if (Method->isInvalidDecl()) 13295 return ExprError(); 13296 13297 const FunctionProtoType *Proto = 13298 Method->getType()->getAs<FunctionProtoType>(); 13299 13300 unsigned NumParams = Proto->getNumParams(); 13301 13302 DeclarationNameInfo OpLocInfo( 13303 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13304 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13305 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13306 Obj, HadMultipleCandidates, 13307 OpLocInfo.getLoc(), 13308 OpLocInfo.getInfo()); 13309 if (NewFn.isInvalid()) 13310 return true; 13311 13312 // The number of argument slots to allocate in the call. If we have default 13313 // arguments we need to allocate space for them as well. We additionally 13314 // need one more slot for the object parameter. 13315 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13316 13317 // Build the full argument list for the method call (the implicit object 13318 // parameter is placed at the beginning of the list). 13319 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13320 13321 bool IsError = false; 13322 13323 // Initialize the implicit object parameter. 13324 ExprResult ObjRes = 13325 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13326 Best->FoundDecl, Method); 13327 if (ObjRes.isInvalid()) 13328 IsError = true; 13329 else 13330 Object = ObjRes; 13331 MethodArgs[0] = Object.get(); 13332 13333 // Check the argument types. 13334 for (unsigned i = 0; i != NumParams; i++) { 13335 Expr *Arg; 13336 if (i < Args.size()) { 13337 Arg = Args[i]; 13338 13339 // Pass the argument. 13340 13341 ExprResult InputInit 13342 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13343 Context, 13344 Method->getParamDecl(i)), 13345 SourceLocation(), Arg); 13346 13347 IsError |= InputInit.isInvalid(); 13348 Arg = InputInit.getAs<Expr>(); 13349 } else { 13350 ExprResult DefArg 13351 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13352 if (DefArg.isInvalid()) { 13353 IsError = true; 13354 break; 13355 } 13356 13357 Arg = DefArg.getAs<Expr>(); 13358 } 13359 13360 MethodArgs[i + 1] = Arg; 13361 } 13362 13363 // If this is a variadic call, handle args passed through "...". 13364 if (Proto->isVariadic()) { 13365 // Promote the arguments (C99 6.5.2.2p7). 13366 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13367 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13368 nullptr); 13369 IsError |= Arg.isInvalid(); 13370 MethodArgs[i + 1] = Arg.get(); 13371 } 13372 } 13373 13374 if (IsError) 13375 return true; 13376 13377 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13378 13379 // Once we've built TheCall, all of the expressions are properly owned. 13380 QualType ResultTy = Method->getReturnType(); 13381 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13382 ResultTy = ResultTy.getNonLValueExprType(Context); 13383 13384 CXXOperatorCallExpr *TheCall = 13385 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13386 ResultTy, VK, RParenLoc, FPOptions()); 13387 13388 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13389 return true; 13390 13391 if (CheckFunctionCall(Method, TheCall, Proto)) 13392 return true; 13393 13394 return MaybeBindToTemporary(TheCall); 13395 } 13396 13397 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13398 /// (if one exists), where @c Base is an expression of class type and 13399 /// @c Member is the name of the member we're trying to find. 13400 ExprResult 13401 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13402 bool *NoArrowOperatorFound) { 13403 assert(Base->getType()->isRecordType() && 13404 "left-hand side must have class type"); 13405 13406 if (checkPlaceholderForOverload(*this, Base)) 13407 return ExprError(); 13408 13409 SourceLocation Loc = Base->getExprLoc(); 13410 13411 // C++ [over.ref]p1: 13412 // 13413 // [...] An expression x->m is interpreted as (x.operator->())->m 13414 // for a class object x of type T if T::operator->() exists and if 13415 // the operator is selected as the best match function by the 13416 // overload resolution mechanism (13.3). 13417 DeclarationName OpName = 13418 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13419 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13420 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13421 13422 if (RequireCompleteType(Loc, Base->getType(), 13423 diag::err_typecheck_incomplete_tag, Base)) 13424 return ExprError(); 13425 13426 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13427 LookupQualifiedName(R, BaseRecord->getDecl()); 13428 R.suppressDiagnostics(); 13429 13430 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13431 Oper != OperEnd; ++Oper) { 13432 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13433 None, CandidateSet, /*SuppressUserConversions=*/false); 13434 } 13435 13436 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13437 13438 // Perform overload resolution. 13439 OverloadCandidateSet::iterator Best; 13440 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13441 case OR_Success: 13442 // Overload resolution succeeded; we'll build the call below. 13443 break; 13444 13445 case OR_No_Viable_Function: 13446 if (CandidateSet.empty()) { 13447 QualType BaseType = Base->getType(); 13448 if (NoArrowOperatorFound) { 13449 // Report this specific error to the caller instead of emitting a 13450 // diagnostic, as requested. 13451 *NoArrowOperatorFound = true; 13452 return ExprError(); 13453 } 13454 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13455 << BaseType << Base->getSourceRange(); 13456 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13457 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13458 << FixItHint::CreateReplacement(OpLoc, "."); 13459 } 13460 } else 13461 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13462 << "operator->" << Base->getSourceRange(); 13463 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13464 return ExprError(); 13465 13466 case OR_Ambiguous: 13467 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13468 << "->" << Base->getType() << Base->getSourceRange(); 13469 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13470 return ExprError(); 13471 13472 case OR_Deleted: 13473 Diag(OpLoc, diag::err_ovl_deleted_oper) 13474 << Best->Function->isDeleted() 13475 << "->" 13476 << getDeletedOrUnavailableSuffix(Best->Function) 13477 << Base->getSourceRange(); 13478 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13479 return ExprError(); 13480 } 13481 13482 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13483 13484 // Convert the object parameter. 13485 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13486 ExprResult BaseResult = 13487 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13488 Best->FoundDecl, Method); 13489 if (BaseResult.isInvalid()) 13490 return ExprError(); 13491 Base = BaseResult.get(); 13492 13493 // Build the operator call. 13494 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13495 Base, HadMultipleCandidates, OpLoc); 13496 if (FnExpr.isInvalid()) 13497 return ExprError(); 13498 13499 QualType ResultTy = Method->getReturnType(); 13500 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13501 ResultTy = ResultTy.getNonLValueExprType(Context); 13502 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13503 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13504 13505 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13506 return ExprError(); 13507 13508 if (CheckFunctionCall(Method, TheCall, 13509 Method->getType()->castAs<FunctionProtoType>())) 13510 return ExprError(); 13511 13512 return MaybeBindToTemporary(TheCall); 13513 } 13514 13515 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13516 /// a literal operator described by the provided lookup results. 13517 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13518 DeclarationNameInfo &SuffixInfo, 13519 ArrayRef<Expr*> Args, 13520 SourceLocation LitEndLoc, 13521 TemplateArgumentListInfo *TemplateArgs) { 13522 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13523 13524 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13525 OverloadCandidateSet::CSK_Normal); 13526 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13527 /*SuppressUserConversions=*/true); 13528 13529 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13530 13531 // Perform overload resolution. This will usually be trivial, but might need 13532 // to perform substitutions for a literal operator template. 13533 OverloadCandidateSet::iterator Best; 13534 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13535 case OR_Success: 13536 case OR_Deleted: 13537 break; 13538 13539 case OR_No_Viable_Function: 13540 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13541 << R.getLookupName(); 13542 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13543 return ExprError(); 13544 13545 case OR_Ambiguous: 13546 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13547 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13548 return ExprError(); 13549 } 13550 13551 FunctionDecl *FD = Best->Function; 13552 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13553 nullptr, HadMultipleCandidates, 13554 SuffixInfo.getLoc(), 13555 SuffixInfo.getInfo()); 13556 if (Fn.isInvalid()) 13557 return true; 13558 13559 // Check the argument types. This should almost always be a no-op, except 13560 // that array-to-pointer decay is applied to string literals. 13561 Expr *ConvArgs[2]; 13562 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13563 ExprResult InputInit = PerformCopyInitialization( 13564 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13565 SourceLocation(), Args[ArgIdx]); 13566 if (InputInit.isInvalid()) 13567 return true; 13568 ConvArgs[ArgIdx] = InputInit.get(); 13569 } 13570 13571 QualType ResultTy = FD->getReturnType(); 13572 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13573 ResultTy = ResultTy.getNonLValueExprType(Context); 13574 13575 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13576 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13577 VK, LitEndLoc, UDSuffixLoc); 13578 13579 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13580 return ExprError(); 13581 13582 if (CheckFunctionCall(FD, UDL, nullptr)) 13583 return ExprError(); 13584 13585 return MaybeBindToTemporary(UDL); 13586 } 13587 13588 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13589 /// given LookupResult is non-empty, it is assumed to describe a member which 13590 /// will be invoked. Otherwise, the function will be found via argument 13591 /// dependent lookup. 13592 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13593 /// otherwise CallExpr is set to ExprError() and some non-success value 13594 /// is returned. 13595 Sema::ForRangeStatus 13596 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13597 SourceLocation RangeLoc, 13598 const DeclarationNameInfo &NameInfo, 13599 LookupResult &MemberLookup, 13600 OverloadCandidateSet *CandidateSet, 13601 Expr *Range, ExprResult *CallExpr) { 13602 Scope *S = nullptr; 13603 13604 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13605 if (!MemberLookup.empty()) { 13606 ExprResult MemberRef = 13607 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13608 /*IsPtr=*/false, CXXScopeSpec(), 13609 /*TemplateKWLoc=*/SourceLocation(), 13610 /*FirstQualifierInScope=*/nullptr, 13611 MemberLookup, 13612 /*TemplateArgs=*/nullptr, S); 13613 if (MemberRef.isInvalid()) { 13614 *CallExpr = ExprError(); 13615 return FRS_DiagnosticIssued; 13616 } 13617 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13618 if (CallExpr->isInvalid()) { 13619 *CallExpr = ExprError(); 13620 return FRS_DiagnosticIssued; 13621 } 13622 } else { 13623 UnresolvedSet<0> FoundNames; 13624 UnresolvedLookupExpr *Fn = 13625 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13626 NestedNameSpecifierLoc(), NameInfo, 13627 /*NeedsADL=*/true, /*Overloaded=*/false, 13628 FoundNames.begin(), FoundNames.end()); 13629 13630 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13631 CandidateSet, CallExpr); 13632 if (CandidateSet->empty() || CandidateSetError) { 13633 *CallExpr = ExprError(); 13634 return FRS_NoViableFunction; 13635 } 13636 OverloadCandidateSet::iterator Best; 13637 OverloadingResult OverloadResult = 13638 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13639 13640 if (OverloadResult == OR_No_Viable_Function) { 13641 *CallExpr = ExprError(); 13642 return FRS_NoViableFunction; 13643 } 13644 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13645 Loc, nullptr, CandidateSet, &Best, 13646 OverloadResult, 13647 /*AllowTypoCorrection=*/false); 13648 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13649 *CallExpr = ExprError(); 13650 return FRS_DiagnosticIssued; 13651 } 13652 } 13653 return FRS_Success; 13654 } 13655 13656 13657 /// FixOverloadedFunctionReference - E is an expression that refers to 13658 /// a C++ overloaded function (possibly with some parentheses and 13659 /// perhaps a '&' around it). We have resolved the overloaded function 13660 /// to the function declaration Fn, so patch up the expression E to 13661 /// refer (possibly indirectly) to Fn. Returns the new expr. 13662 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13663 FunctionDecl *Fn) { 13664 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13665 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13666 Found, Fn); 13667 if (SubExpr == PE->getSubExpr()) 13668 return PE; 13669 13670 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13671 } 13672 13673 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13674 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13675 Found, Fn); 13676 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13677 SubExpr->getType()) && 13678 "Implicit cast type cannot be determined from overload"); 13679 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13680 if (SubExpr == ICE->getSubExpr()) 13681 return ICE; 13682 13683 return ImplicitCastExpr::Create(Context, ICE->getType(), 13684 ICE->getCastKind(), 13685 SubExpr, nullptr, 13686 ICE->getValueKind()); 13687 } 13688 13689 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13690 if (!GSE->isResultDependent()) { 13691 Expr *SubExpr = 13692 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13693 if (SubExpr == GSE->getResultExpr()) 13694 return GSE; 13695 13696 // Replace the resulting type information before rebuilding the generic 13697 // selection expression. 13698 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13699 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13700 unsigned ResultIdx = GSE->getResultIndex(); 13701 AssocExprs[ResultIdx] = SubExpr; 13702 13703 return new (Context) GenericSelectionExpr( 13704 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13705 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13706 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13707 ResultIdx); 13708 } 13709 // Rather than fall through to the unreachable, return the original generic 13710 // selection expression. 13711 return GSE; 13712 } 13713 13714 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13715 assert(UnOp->getOpcode() == UO_AddrOf && 13716 "Can only take the address of an overloaded function"); 13717 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13718 if (Method->isStatic()) { 13719 // Do nothing: static member functions aren't any different 13720 // from non-member functions. 13721 } else { 13722 // Fix the subexpression, which really has to be an 13723 // UnresolvedLookupExpr holding an overloaded member function 13724 // or template. 13725 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13726 Found, Fn); 13727 if (SubExpr == UnOp->getSubExpr()) 13728 return UnOp; 13729 13730 assert(isa<DeclRefExpr>(SubExpr) 13731 && "fixed to something other than a decl ref"); 13732 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13733 && "fixed to a member ref with no nested name qualifier"); 13734 13735 // We have taken the address of a pointer to member 13736 // function. Perform the computation here so that we get the 13737 // appropriate pointer to member type. 13738 QualType ClassType 13739 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13740 QualType MemPtrType 13741 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13742 // Under the MS ABI, lock down the inheritance model now. 13743 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13744 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13745 13746 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13747 VK_RValue, OK_Ordinary, 13748 UnOp->getOperatorLoc(), false); 13749 } 13750 } 13751 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13752 Found, Fn); 13753 if (SubExpr == UnOp->getSubExpr()) 13754 return UnOp; 13755 13756 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13757 Context.getPointerType(SubExpr->getType()), 13758 VK_RValue, OK_Ordinary, 13759 UnOp->getOperatorLoc(), false); 13760 } 13761 13762 // C++ [except.spec]p17: 13763 // An exception-specification is considered to be needed when: 13764 // - in an expression the function is the unique lookup result or the 13765 // selected member of a set of overloaded functions 13766 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13767 ResolveExceptionSpec(E->getExprLoc(), FPT); 13768 13769 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13770 // FIXME: avoid copy. 13771 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13772 if (ULE->hasExplicitTemplateArgs()) { 13773 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13774 TemplateArgs = &TemplateArgsBuffer; 13775 } 13776 13777 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13778 ULE->getQualifierLoc(), 13779 ULE->getTemplateKeywordLoc(), 13780 Fn, 13781 /*enclosing*/ false, // FIXME? 13782 ULE->getNameLoc(), 13783 Fn->getType(), 13784 VK_LValue, 13785 Found.getDecl(), 13786 TemplateArgs); 13787 MarkDeclRefReferenced(DRE); 13788 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13789 return DRE; 13790 } 13791 13792 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13793 // FIXME: avoid copy. 13794 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13795 if (MemExpr->hasExplicitTemplateArgs()) { 13796 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13797 TemplateArgs = &TemplateArgsBuffer; 13798 } 13799 13800 Expr *Base; 13801 13802 // If we're filling in a static method where we used to have an 13803 // implicit member access, rewrite to a simple decl ref. 13804 if (MemExpr->isImplicitAccess()) { 13805 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13806 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13807 MemExpr->getQualifierLoc(), 13808 MemExpr->getTemplateKeywordLoc(), 13809 Fn, 13810 /*enclosing*/ false, 13811 MemExpr->getMemberLoc(), 13812 Fn->getType(), 13813 VK_LValue, 13814 Found.getDecl(), 13815 TemplateArgs); 13816 MarkDeclRefReferenced(DRE); 13817 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13818 return DRE; 13819 } else { 13820 SourceLocation Loc = MemExpr->getMemberLoc(); 13821 if (MemExpr->getQualifier()) 13822 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13823 CheckCXXThisCapture(Loc); 13824 Base = new (Context) CXXThisExpr(Loc, 13825 MemExpr->getBaseType(), 13826 /*isImplicit=*/true); 13827 } 13828 } else 13829 Base = MemExpr->getBase(); 13830 13831 ExprValueKind valueKind; 13832 QualType type; 13833 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13834 valueKind = VK_LValue; 13835 type = Fn->getType(); 13836 } else { 13837 valueKind = VK_RValue; 13838 type = Context.BoundMemberTy; 13839 } 13840 13841 MemberExpr *ME = MemberExpr::Create( 13842 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13843 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13844 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13845 OK_Ordinary); 13846 ME->setHadMultipleCandidates(true); 13847 MarkMemberReferenced(ME); 13848 return ME; 13849 } 13850 13851 llvm_unreachable("Invalid reference to overloaded function"); 13852 } 13853 13854 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13855 DeclAccessPair Found, 13856 FunctionDecl *Fn) { 13857 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13858 } 13859