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) DeclRefExpr(Fn, false, Fn->getType(), 67 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 return Ovl_Overload; 1045 } 1046 1047 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1048 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1049 // C++ [basic.start.main]p2: This function shall not be overloaded. 1050 if (New->isMain()) 1051 return false; 1052 1053 // MSVCRT user defined entry points cannot be overloaded. 1054 if (New->isMSVCRTEntryPoint()) 1055 return false; 1056 1057 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1058 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1059 1060 // C++ [temp.fct]p2: 1061 // A function template can be overloaded with other function templates 1062 // and with normal (non-template) functions. 1063 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1064 return true; 1065 1066 // Is the function New an overload of the function Old? 1067 QualType OldQType = Context.getCanonicalType(Old->getType()); 1068 QualType NewQType = Context.getCanonicalType(New->getType()); 1069 1070 // Compare the signatures (C++ 1.3.10) of the two functions to 1071 // determine whether they are overloads. If we find any mismatch 1072 // in the signature, they are overloads. 1073 1074 // If either of these functions is a K&R-style function (no 1075 // prototype), then we consider them to have matching signatures. 1076 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1077 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1078 return false; 1079 1080 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1081 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1082 1083 // The signature of a function includes the types of its 1084 // parameters (C++ 1.3.10), which includes the presence or absence 1085 // of the ellipsis; see C++ DR 357). 1086 if (OldQType != NewQType && 1087 (OldType->getNumParams() != NewType->getNumParams() || 1088 OldType->isVariadic() != NewType->isVariadic() || 1089 !FunctionParamTypesAreEqual(OldType, NewType))) 1090 return true; 1091 1092 // C++ [temp.over.link]p4: 1093 // The signature of a function template consists of its function 1094 // signature, its return type and its template parameter list. The names 1095 // of the template parameters are significant only for establishing the 1096 // relationship between the template parameters and the rest of the 1097 // signature. 1098 // 1099 // We check the return type and template parameter lists for function 1100 // templates first; the remaining checks follow. 1101 // 1102 // However, we don't consider either of these when deciding whether 1103 // a member introduced by a shadow declaration is hidden. 1104 if (!UseMemberUsingDeclRules && NewTemplate && 1105 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1106 OldTemplate->getTemplateParameters(), 1107 false, TPL_TemplateMatch) || 1108 !Context.hasSameType(Old->getDeclaredReturnType(), 1109 New->getDeclaredReturnType()))) 1110 return true; 1111 1112 // If the function is a class member, its signature includes the 1113 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1114 // 1115 // As part of this, also check whether one of the member functions 1116 // is static, in which case they are not overloads (C++ 1117 // 13.1p2). While not part of the definition of the signature, 1118 // this check is important to determine whether these functions 1119 // can be overloaded. 1120 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1121 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1122 if (OldMethod && NewMethod && 1123 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1124 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1125 if (!UseMemberUsingDeclRules && 1126 (OldMethod->getRefQualifier() == RQ_None || 1127 NewMethod->getRefQualifier() == RQ_None)) { 1128 // C++0x [over.load]p2: 1129 // - Member function declarations with the same name and the same 1130 // parameter-type-list as well as member function template 1131 // declarations with the same name, the same parameter-type-list, and 1132 // the same template parameter lists cannot be overloaded if any of 1133 // them, but not all, have a ref-qualifier (8.3.5). 1134 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1135 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1136 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1137 } 1138 return true; 1139 } 1140 1141 // We may not have applied the implicit const for a constexpr member 1142 // function yet (because we haven't yet resolved whether this is a static 1143 // or non-static member function). Add it now, on the assumption that this 1144 // is a redeclaration of OldMethod. 1145 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1146 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1147 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1148 !isa<CXXConstructorDecl>(NewMethod)) 1149 NewQuals |= Qualifiers::Const; 1150 1151 // We do not allow overloading based off of '__restrict'. 1152 OldQuals &= ~Qualifiers::Restrict; 1153 NewQuals &= ~Qualifiers::Restrict; 1154 if (OldQuals != NewQuals) 1155 return true; 1156 } 1157 1158 // Though pass_object_size is placed on parameters and takes an argument, we 1159 // consider it to be a function-level modifier for the sake of function 1160 // identity. Either the function has one or more parameters with 1161 // pass_object_size or it doesn't. 1162 if (functionHasPassObjectSizeParams(New) != 1163 functionHasPassObjectSizeParams(Old)) 1164 return true; 1165 1166 // enable_if attributes are an order-sensitive part of the signature. 1167 for (specific_attr_iterator<EnableIfAttr> 1168 NewI = New->specific_attr_begin<EnableIfAttr>(), 1169 NewE = New->specific_attr_end<EnableIfAttr>(), 1170 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1171 OldE = Old->specific_attr_end<EnableIfAttr>(); 1172 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1173 if (NewI == NewE || OldI == OldE) 1174 return true; 1175 llvm::FoldingSetNodeID NewID, OldID; 1176 NewI->getCond()->Profile(NewID, Context, true); 1177 OldI->getCond()->Profile(OldID, Context, true); 1178 if (NewID != OldID) 1179 return true; 1180 } 1181 1182 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1183 // Don't allow overloading of destructors. (In theory we could, but it 1184 // would be a giant change to clang.) 1185 if (isa<CXXDestructorDecl>(New)) 1186 return false; 1187 1188 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1189 OldTarget = IdentifyCUDATarget(Old); 1190 if (NewTarget == CFT_InvalidTarget) 1191 return false; 1192 1193 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1194 1195 // Allow overloading of functions with same signature and different CUDA 1196 // target attributes. 1197 return NewTarget != OldTarget; 1198 } 1199 1200 // The signatures match; this is not an overload. 1201 return false; 1202 } 1203 1204 /// Checks availability of the function depending on the current 1205 /// function context. Inside an unavailable function, unavailability is ignored. 1206 /// 1207 /// \returns true if \arg FD is unavailable and current context is inside 1208 /// an available function, false otherwise. 1209 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1210 if (!FD->isUnavailable()) 1211 return false; 1212 1213 // Walk up the context of the caller. 1214 Decl *C = cast<Decl>(CurContext); 1215 do { 1216 if (C->isUnavailable()) 1217 return false; 1218 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1219 return true; 1220 } 1221 1222 /// Tries a user-defined conversion from From to ToType. 1223 /// 1224 /// Produces an implicit conversion sequence for when a standard conversion 1225 /// is not an option. See TryImplicitConversion for more information. 1226 static ImplicitConversionSequence 1227 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1228 bool SuppressUserConversions, 1229 bool AllowExplicit, 1230 bool InOverloadResolution, 1231 bool CStyle, 1232 bool AllowObjCWritebackConversion, 1233 bool AllowObjCConversionOnExplicit) { 1234 ImplicitConversionSequence ICS; 1235 1236 if (SuppressUserConversions) { 1237 // We're not in the case above, so there is no conversion that 1238 // we can perform. 1239 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1240 return ICS; 1241 } 1242 1243 // Attempt user-defined conversion. 1244 OverloadCandidateSet Conversions(From->getExprLoc(), 1245 OverloadCandidateSet::CSK_Normal); 1246 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1247 Conversions, AllowExplicit, 1248 AllowObjCConversionOnExplicit)) { 1249 case OR_Success: 1250 case OR_Deleted: 1251 ICS.setUserDefined(); 1252 // C++ [over.ics.user]p4: 1253 // A conversion of an expression of class type to the same class 1254 // type is given Exact Match rank, and a conversion of an 1255 // expression of class type to a base class of that type is 1256 // given Conversion rank, in spite of the fact that a copy 1257 // constructor (i.e., a user-defined conversion function) is 1258 // called for those cases. 1259 if (CXXConstructorDecl *Constructor 1260 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1261 QualType FromCanon 1262 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1263 QualType ToCanon 1264 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1265 if (Constructor->isCopyConstructor() && 1266 (FromCanon == ToCanon || 1267 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1268 // Turn this into a "standard" conversion sequence, so that it 1269 // gets ranked with standard conversion sequences. 1270 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1271 ICS.setStandard(); 1272 ICS.Standard.setAsIdentityConversion(); 1273 ICS.Standard.setFromType(From->getType()); 1274 ICS.Standard.setAllToTypes(ToType); 1275 ICS.Standard.CopyConstructor = Constructor; 1276 ICS.Standard.FoundCopyConstructor = Found; 1277 if (ToCanon != FromCanon) 1278 ICS.Standard.Second = ICK_Derived_To_Base; 1279 } 1280 } 1281 break; 1282 1283 case OR_Ambiguous: 1284 ICS.setAmbiguous(); 1285 ICS.Ambiguous.setFromType(From->getType()); 1286 ICS.Ambiguous.setToType(ToType); 1287 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1288 Cand != Conversions.end(); ++Cand) 1289 if (Cand->Viable) 1290 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1291 break; 1292 1293 // Fall through. 1294 case OR_No_Viable_Function: 1295 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1296 break; 1297 } 1298 1299 return ICS; 1300 } 1301 1302 /// TryImplicitConversion - Attempt to perform an implicit conversion 1303 /// from the given expression (Expr) to the given type (ToType). This 1304 /// function returns an implicit conversion sequence that can be used 1305 /// to perform the initialization. Given 1306 /// 1307 /// void f(float f); 1308 /// void g(int i) { f(i); } 1309 /// 1310 /// this routine would produce an implicit conversion sequence to 1311 /// describe the initialization of f from i, which will be a standard 1312 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1313 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1314 // 1315 /// Note that this routine only determines how the conversion can be 1316 /// performed; it does not actually perform the conversion. As such, 1317 /// it will not produce any diagnostics if no conversion is available, 1318 /// but will instead return an implicit conversion sequence of kind 1319 /// "BadConversion". 1320 /// 1321 /// If @p SuppressUserConversions, then user-defined conversions are 1322 /// not permitted. 1323 /// If @p AllowExplicit, then explicit user-defined conversions are 1324 /// permitted. 1325 /// 1326 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1327 /// writeback conversion, which allows __autoreleasing id* parameters to 1328 /// be initialized with __strong id* or __weak id* arguments. 1329 static ImplicitConversionSequence 1330 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1331 bool SuppressUserConversions, 1332 bool AllowExplicit, 1333 bool InOverloadResolution, 1334 bool CStyle, 1335 bool AllowObjCWritebackConversion, 1336 bool AllowObjCConversionOnExplicit) { 1337 ImplicitConversionSequence ICS; 1338 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1339 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1340 ICS.setStandard(); 1341 return ICS; 1342 } 1343 1344 if (!S.getLangOpts().CPlusPlus) { 1345 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1346 return ICS; 1347 } 1348 1349 // C++ [over.ics.user]p4: 1350 // A conversion of an expression of class type to the same class 1351 // type is given Exact Match rank, and a conversion of an 1352 // expression of class type to a base class of that type is 1353 // given Conversion rank, in spite of the fact that a copy/move 1354 // constructor (i.e., a user-defined conversion function) is 1355 // called for those cases. 1356 QualType FromType = From->getType(); 1357 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1358 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1359 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1360 ICS.setStandard(); 1361 ICS.Standard.setAsIdentityConversion(); 1362 ICS.Standard.setFromType(FromType); 1363 ICS.Standard.setAllToTypes(ToType); 1364 1365 // We don't actually check at this point whether there is a valid 1366 // copy/move constructor, since overloading just assumes that it 1367 // exists. When we actually perform initialization, we'll find the 1368 // appropriate constructor to copy the returned object, if needed. 1369 ICS.Standard.CopyConstructor = nullptr; 1370 1371 // Determine whether this is considered a derived-to-base conversion. 1372 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1373 ICS.Standard.Second = ICK_Derived_To_Base; 1374 1375 return ICS; 1376 } 1377 1378 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1379 AllowExplicit, InOverloadResolution, CStyle, 1380 AllowObjCWritebackConversion, 1381 AllowObjCConversionOnExplicit); 1382 } 1383 1384 ImplicitConversionSequence 1385 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1386 bool SuppressUserConversions, 1387 bool AllowExplicit, 1388 bool InOverloadResolution, 1389 bool CStyle, 1390 bool AllowObjCWritebackConversion) { 1391 return ::TryImplicitConversion(*this, From, ToType, 1392 SuppressUserConversions, AllowExplicit, 1393 InOverloadResolution, CStyle, 1394 AllowObjCWritebackConversion, 1395 /*AllowObjCConversionOnExplicit=*/false); 1396 } 1397 1398 /// PerformImplicitConversion - Perform an implicit conversion of the 1399 /// expression From to the type ToType. Returns the 1400 /// converted expression. Flavor is the kind of conversion we're 1401 /// performing, used in the error message. If @p AllowExplicit, 1402 /// explicit user-defined conversions are permitted. 1403 ExprResult 1404 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1405 AssignmentAction Action, bool AllowExplicit) { 1406 ImplicitConversionSequence ICS; 1407 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1408 } 1409 1410 ExprResult 1411 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1412 AssignmentAction Action, bool AllowExplicit, 1413 ImplicitConversionSequence& ICS) { 1414 if (checkPlaceholderForOverload(*this, From)) 1415 return ExprError(); 1416 1417 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1418 bool AllowObjCWritebackConversion 1419 = getLangOpts().ObjCAutoRefCount && 1420 (Action == AA_Passing || Action == AA_Sending); 1421 if (getLangOpts().ObjC) 1422 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1423 From->getType(), From); 1424 ICS = ::TryImplicitConversion(*this, From, ToType, 1425 /*SuppressUserConversions=*/false, 1426 AllowExplicit, 1427 /*InOverloadResolution=*/false, 1428 /*CStyle=*/false, 1429 AllowObjCWritebackConversion, 1430 /*AllowObjCConversionOnExplicit=*/false); 1431 return PerformImplicitConversion(From, ToType, ICS, Action); 1432 } 1433 1434 /// Determine whether the conversion from FromType to ToType is a valid 1435 /// conversion that strips "noexcept" or "noreturn" off the nested function 1436 /// type. 1437 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1438 QualType &ResultTy) { 1439 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1440 return false; 1441 1442 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1443 // or F(t noexcept) -> F(t) 1444 // where F adds one of the following at most once: 1445 // - a pointer 1446 // - a member pointer 1447 // - a block pointer 1448 // Changes here need matching changes in FindCompositePointerType. 1449 CanQualType CanTo = Context.getCanonicalType(ToType); 1450 CanQualType CanFrom = Context.getCanonicalType(FromType); 1451 Type::TypeClass TyClass = CanTo->getTypeClass(); 1452 if (TyClass != CanFrom->getTypeClass()) return false; 1453 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1454 if (TyClass == Type::Pointer) { 1455 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1456 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1457 } else if (TyClass == Type::BlockPointer) { 1458 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1459 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1460 } else if (TyClass == Type::MemberPointer) { 1461 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1462 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1463 // A function pointer conversion cannot change the class of the function. 1464 if (ToMPT->getClass() != FromMPT->getClass()) 1465 return false; 1466 CanTo = ToMPT->getPointeeType(); 1467 CanFrom = FromMPT->getPointeeType(); 1468 } else { 1469 return false; 1470 } 1471 1472 TyClass = CanTo->getTypeClass(); 1473 if (TyClass != CanFrom->getTypeClass()) return false; 1474 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1475 return false; 1476 } 1477 1478 const auto *FromFn = cast<FunctionType>(CanFrom); 1479 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1480 1481 const auto *ToFn = cast<FunctionType>(CanTo); 1482 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1483 1484 bool Changed = false; 1485 1486 // Drop 'noreturn' if not present in target type. 1487 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1488 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1489 Changed = true; 1490 } 1491 1492 // Drop 'noexcept' if not present in target type. 1493 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1494 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1495 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1496 FromFn = cast<FunctionType>( 1497 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1498 EST_None) 1499 .getTypePtr()); 1500 Changed = true; 1501 } 1502 1503 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1504 // only if the ExtParameterInfo lists of the two function prototypes can be 1505 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1506 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1507 bool CanUseToFPT, CanUseFromFPT; 1508 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1509 CanUseFromFPT, NewParamInfos) && 1510 CanUseToFPT && !CanUseFromFPT) { 1511 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1512 ExtInfo.ExtParameterInfos = 1513 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1514 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1515 FromFPT->getParamTypes(), ExtInfo); 1516 FromFn = QT->getAs<FunctionType>(); 1517 Changed = true; 1518 } 1519 } 1520 1521 if (!Changed) 1522 return false; 1523 1524 assert(QualType(FromFn, 0).isCanonical()); 1525 if (QualType(FromFn, 0) != CanTo) return false; 1526 1527 ResultTy = ToType; 1528 return true; 1529 } 1530 1531 /// Determine whether the conversion from FromType to ToType is a valid 1532 /// vector conversion. 1533 /// 1534 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1535 /// conversion. 1536 static bool IsVectorConversion(Sema &S, QualType FromType, 1537 QualType ToType, ImplicitConversionKind &ICK) { 1538 // We need at least one of these types to be a vector type to have a vector 1539 // conversion. 1540 if (!ToType->isVectorType() && !FromType->isVectorType()) 1541 return false; 1542 1543 // Identical types require no conversions. 1544 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1545 return false; 1546 1547 // There are no conversions between extended vector types, only identity. 1548 if (ToType->isExtVectorType()) { 1549 // There are no conversions between extended vector types other than the 1550 // identity conversion. 1551 if (FromType->isExtVectorType()) 1552 return false; 1553 1554 // Vector splat from any arithmetic type to a vector. 1555 if (FromType->isArithmeticType()) { 1556 ICK = ICK_Vector_Splat; 1557 return true; 1558 } 1559 } 1560 1561 // We can perform the conversion between vector types in the following cases: 1562 // 1)vector types are equivalent AltiVec and GCC vector types 1563 // 2)lax vector conversions are permitted and the vector types are of the 1564 // same size 1565 if (ToType->isVectorType() && FromType->isVectorType()) { 1566 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1567 S.isLaxVectorConversion(FromType, ToType)) { 1568 ICK = ICK_Vector_Conversion; 1569 return true; 1570 } 1571 } 1572 1573 return false; 1574 } 1575 1576 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1577 bool InOverloadResolution, 1578 StandardConversionSequence &SCS, 1579 bool CStyle); 1580 1581 /// IsStandardConversion - Determines whether there is a standard 1582 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1583 /// expression From to the type ToType. Standard conversion sequences 1584 /// only consider non-class types; for conversions that involve class 1585 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1586 /// contain the standard conversion sequence required to perform this 1587 /// conversion and this routine will return true. Otherwise, this 1588 /// routine will return false and the value of SCS is unspecified. 1589 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1590 bool InOverloadResolution, 1591 StandardConversionSequence &SCS, 1592 bool CStyle, 1593 bool AllowObjCWritebackConversion) { 1594 QualType FromType = From->getType(); 1595 1596 // Standard conversions (C++ [conv]) 1597 SCS.setAsIdentityConversion(); 1598 SCS.IncompatibleObjC = false; 1599 SCS.setFromType(FromType); 1600 SCS.CopyConstructor = nullptr; 1601 1602 // There are no standard conversions for class types in C++, so 1603 // abort early. When overloading in C, however, we do permit them. 1604 if (S.getLangOpts().CPlusPlus && 1605 (FromType->isRecordType() || ToType->isRecordType())) 1606 return false; 1607 1608 // The first conversion can be an lvalue-to-rvalue conversion, 1609 // array-to-pointer conversion, or function-to-pointer conversion 1610 // (C++ 4p1). 1611 1612 if (FromType == S.Context.OverloadTy) { 1613 DeclAccessPair AccessPair; 1614 if (FunctionDecl *Fn 1615 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1616 AccessPair)) { 1617 // We were able to resolve the address of the overloaded function, 1618 // so we can convert to the type of that function. 1619 FromType = Fn->getType(); 1620 SCS.setFromType(FromType); 1621 1622 // we can sometimes resolve &foo<int> regardless of ToType, so check 1623 // if the type matches (identity) or we are converting to bool 1624 if (!S.Context.hasSameUnqualifiedType( 1625 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1626 QualType resultTy; 1627 // if the function type matches except for [[noreturn]], it's ok 1628 if (!S.IsFunctionConversion(FromType, 1629 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1630 // otherwise, only a boolean conversion is standard 1631 if (!ToType->isBooleanType()) 1632 return false; 1633 } 1634 1635 // Check if the "from" expression is taking the address of an overloaded 1636 // function and recompute the FromType accordingly. Take advantage of the 1637 // fact that non-static member functions *must* have such an address-of 1638 // expression. 1639 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1640 if (Method && !Method->isStatic()) { 1641 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1642 "Non-unary operator on non-static member address"); 1643 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1644 == UO_AddrOf && 1645 "Non-address-of operator on non-static member address"); 1646 const Type *ClassType 1647 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1648 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1649 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1650 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1651 UO_AddrOf && 1652 "Non-address-of operator for overloaded function expression"); 1653 FromType = S.Context.getPointerType(FromType); 1654 } 1655 1656 // Check that we've computed the proper type after overload resolution. 1657 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1658 // be calling it from within an NDEBUG block. 1659 assert(S.Context.hasSameType( 1660 FromType, 1661 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1662 } else { 1663 return false; 1664 } 1665 } 1666 // Lvalue-to-rvalue conversion (C++11 4.1): 1667 // A glvalue (3.10) of a non-function, non-array type T can 1668 // be converted to a prvalue. 1669 bool argIsLValue = From->isGLValue(); 1670 if (argIsLValue && 1671 !FromType->isFunctionType() && !FromType->isArrayType() && 1672 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1673 SCS.First = ICK_Lvalue_To_Rvalue; 1674 1675 // C11 6.3.2.1p2: 1676 // ... if the lvalue has atomic type, the value has the non-atomic version 1677 // of the type of the lvalue ... 1678 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1679 FromType = Atomic->getValueType(); 1680 1681 // If T is a non-class type, the type of the rvalue is the 1682 // cv-unqualified version of T. Otherwise, the type of the rvalue 1683 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1684 // just strip the qualifiers because they don't matter. 1685 FromType = FromType.getUnqualifiedType(); 1686 } else if (FromType->isArrayType()) { 1687 // Array-to-pointer conversion (C++ 4.2) 1688 SCS.First = ICK_Array_To_Pointer; 1689 1690 // An lvalue or rvalue of type "array of N T" or "array of unknown 1691 // bound of T" can be converted to an rvalue of type "pointer to 1692 // T" (C++ 4.2p1). 1693 FromType = S.Context.getArrayDecayedType(FromType); 1694 1695 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1696 // This conversion is deprecated in C++03 (D.4) 1697 SCS.DeprecatedStringLiteralToCharPtr = true; 1698 1699 // For the purpose of ranking in overload resolution 1700 // (13.3.3.1.1), this conversion is considered an 1701 // array-to-pointer conversion followed by a qualification 1702 // conversion (4.4). (C++ 4.2p2) 1703 SCS.Second = ICK_Identity; 1704 SCS.Third = ICK_Qualification; 1705 SCS.QualificationIncludesObjCLifetime = false; 1706 SCS.setAllToTypes(FromType); 1707 return true; 1708 } 1709 } else if (FromType->isFunctionType() && argIsLValue) { 1710 // Function-to-pointer conversion (C++ 4.3). 1711 SCS.First = ICK_Function_To_Pointer; 1712 1713 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1714 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1715 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1716 return false; 1717 1718 // An lvalue of function type T can be converted to an rvalue of 1719 // type "pointer to T." The result is a pointer to the 1720 // function. (C++ 4.3p1). 1721 FromType = S.Context.getPointerType(FromType); 1722 } else { 1723 // We don't require any conversions for the first step. 1724 SCS.First = ICK_Identity; 1725 } 1726 SCS.setToType(0, FromType); 1727 1728 // The second conversion can be an integral promotion, floating 1729 // point promotion, integral conversion, floating point conversion, 1730 // floating-integral conversion, pointer conversion, 1731 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1732 // For overloading in C, this can also be a "compatible-type" 1733 // conversion. 1734 bool IncompatibleObjC = false; 1735 ImplicitConversionKind SecondICK = ICK_Identity; 1736 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1737 // The unqualified versions of the types are the same: there's no 1738 // conversion to do. 1739 SCS.Second = ICK_Identity; 1740 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1741 // Integral promotion (C++ 4.5). 1742 SCS.Second = ICK_Integral_Promotion; 1743 FromType = ToType.getUnqualifiedType(); 1744 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1745 // Floating point promotion (C++ 4.6). 1746 SCS.Second = ICK_Floating_Promotion; 1747 FromType = ToType.getUnqualifiedType(); 1748 } else if (S.IsComplexPromotion(FromType, ToType)) { 1749 // Complex promotion (Clang extension) 1750 SCS.Second = ICK_Complex_Promotion; 1751 FromType = ToType.getUnqualifiedType(); 1752 } else if (ToType->isBooleanType() && 1753 (FromType->isArithmeticType() || 1754 FromType->isAnyPointerType() || 1755 FromType->isBlockPointerType() || 1756 FromType->isMemberPointerType() || 1757 FromType->isNullPtrType())) { 1758 // Boolean conversions (C++ 4.12). 1759 SCS.Second = ICK_Boolean_Conversion; 1760 FromType = S.Context.BoolTy; 1761 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1762 ToType->isIntegralType(S.Context)) { 1763 // Integral conversions (C++ 4.7). 1764 SCS.Second = ICK_Integral_Conversion; 1765 FromType = ToType.getUnqualifiedType(); 1766 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1767 // Complex conversions (C99 6.3.1.6) 1768 SCS.Second = ICK_Complex_Conversion; 1769 FromType = ToType.getUnqualifiedType(); 1770 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1771 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1772 // Complex-real conversions (C99 6.3.1.7) 1773 SCS.Second = ICK_Complex_Real; 1774 FromType = ToType.getUnqualifiedType(); 1775 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1776 // FIXME: disable conversions between long double and __float128 if 1777 // their representation is different until there is back end support 1778 // We of course allow this conversion if long double is really double. 1779 if (&S.Context.getFloatTypeSemantics(FromType) != 1780 &S.Context.getFloatTypeSemantics(ToType)) { 1781 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1782 ToType == S.Context.LongDoubleTy) || 1783 (FromType == S.Context.LongDoubleTy && 1784 ToType == S.Context.Float128Ty)); 1785 if (Float128AndLongDouble && 1786 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1787 &llvm::APFloat::PPCDoubleDouble())) 1788 return false; 1789 } 1790 // Floating point conversions (C++ 4.8). 1791 SCS.Second = ICK_Floating_Conversion; 1792 FromType = ToType.getUnqualifiedType(); 1793 } else if ((FromType->isRealFloatingType() && 1794 ToType->isIntegralType(S.Context)) || 1795 (FromType->isIntegralOrUnscopedEnumerationType() && 1796 ToType->isRealFloatingType())) { 1797 // Floating-integral conversions (C++ 4.9). 1798 SCS.Second = ICK_Floating_Integral; 1799 FromType = ToType.getUnqualifiedType(); 1800 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1801 SCS.Second = ICK_Block_Pointer_Conversion; 1802 } else if (AllowObjCWritebackConversion && 1803 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1804 SCS.Second = ICK_Writeback_Conversion; 1805 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1806 FromType, IncompatibleObjC)) { 1807 // Pointer conversions (C++ 4.10). 1808 SCS.Second = ICK_Pointer_Conversion; 1809 SCS.IncompatibleObjC = IncompatibleObjC; 1810 FromType = FromType.getUnqualifiedType(); 1811 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1812 InOverloadResolution, FromType)) { 1813 // Pointer to member conversions (4.11). 1814 SCS.Second = ICK_Pointer_Member; 1815 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1816 SCS.Second = SecondICK; 1817 FromType = ToType.getUnqualifiedType(); 1818 } else if (!S.getLangOpts().CPlusPlus && 1819 S.Context.typesAreCompatible(ToType, FromType)) { 1820 // Compatible conversions (Clang extension for C function overloading) 1821 SCS.Second = ICK_Compatible_Conversion; 1822 FromType = ToType.getUnqualifiedType(); 1823 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1824 InOverloadResolution, 1825 SCS, CStyle)) { 1826 SCS.Second = ICK_TransparentUnionConversion; 1827 FromType = ToType; 1828 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1829 CStyle)) { 1830 // tryAtomicConversion has updated the standard conversion sequence 1831 // appropriately. 1832 return true; 1833 } else if (ToType->isEventT() && 1834 From->isIntegerConstantExpr(S.getASTContext()) && 1835 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1836 SCS.Second = ICK_Zero_Event_Conversion; 1837 FromType = ToType; 1838 } else if (ToType->isQueueT() && 1839 From->isIntegerConstantExpr(S.getASTContext()) && 1840 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1841 SCS.Second = ICK_Zero_Queue_Conversion; 1842 FromType = ToType; 1843 } else { 1844 // No second conversion required. 1845 SCS.Second = ICK_Identity; 1846 } 1847 SCS.setToType(1, FromType); 1848 1849 // The third conversion can be a function pointer conversion or a 1850 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1851 bool ObjCLifetimeConversion; 1852 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1853 // Function pointer conversions (removing 'noexcept') including removal of 1854 // 'noreturn' (Clang extension). 1855 SCS.Third = ICK_Function_Conversion; 1856 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1857 ObjCLifetimeConversion)) { 1858 SCS.Third = ICK_Qualification; 1859 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1860 FromType = ToType; 1861 } else { 1862 // No conversion required 1863 SCS.Third = ICK_Identity; 1864 } 1865 1866 // C++ [over.best.ics]p6: 1867 // [...] Any difference in top-level cv-qualification is 1868 // subsumed by the initialization itself and does not constitute 1869 // a conversion. [...] 1870 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1871 QualType CanonTo = S.Context.getCanonicalType(ToType); 1872 if (CanonFrom.getLocalUnqualifiedType() 1873 == CanonTo.getLocalUnqualifiedType() && 1874 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1875 FromType = ToType; 1876 CanonFrom = CanonTo; 1877 } 1878 1879 SCS.setToType(2, FromType); 1880 1881 if (CanonFrom == CanonTo) 1882 return true; 1883 1884 // If we have not converted the argument type to the parameter type, 1885 // this is a bad conversion sequence, unless we're resolving an overload in C. 1886 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1887 return false; 1888 1889 ExprResult ER = ExprResult{From}; 1890 Sema::AssignConvertType Conv = 1891 S.CheckSingleAssignmentConstraints(ToType, ER, 1892 /*Diagnose=*/false, 1893 /*DiagnoseCFAudited=*/false, 1894 /*ConvertRHS=*/false); 1895 ImplicitConversionKind SecondConv; 1896 switch (Conv) { 1897 case Sema::Compatible: 1898 SecondConv = ICK_C_Only_Conversion; 1899 break; 1900 // For our purposes, discarding qualifiers is just as bad as using an 1901 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1902 // qualifiers, as well. 1903 case Sema::CompatiblePointerDiscardsQualifiers: 1904 case Sema::IncompatiblePointer: 1905 case Sema::IncompatiblePointerSign: 1906 SecondConv = ICK_Incompatible_Pointer_Conversion; 1907 break; 1908 default: 1909 return false; 1910 } 1911 1912 // First can only be an lvalue conversion, so we pretend that this was the 1913 // second conversion. First should already be valid from earlier in the 1914 // function. 1915 SCS.Second = SecondConv; 1916 SCS.setToType(1, ToType); 1917 1918 // Third is Identity, because Second should rank us worse than any other 1919 // conversion. This could also be ICK_Qualification, but it's simpler to just 1920 // lump everything in with the second conversion, and we don't gain anything 1921 // from making this ICK_Qualification. 1922 SCS.Third = ICK_Identity; 1923 SCS.setToType(2, ToType); 1924 return true; 1925 } 1926 1927 static bool 1928 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1929 QualType &ToType, 1930 bool InOverloadResolution, 1931 StandardConversionSequence &SCS, 1932 bool CStyle) { 1933 1934 const RecordType *UT = ToType->getAsUnionType(); 1935 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1936 return false; 1937 // The field to initialize within the transparent union. 1938 RecordDecl *UD = UT->getDecl(); 1939 // It's compatible if the expression matches any of the fields. 1940 for (const auto *it : UD->fields()) { 1941 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1942 CStyle, /*ObjCWritebackConversion=*/false)) { 1943 ToType = it->getType(); 1944 return true; 1945 } 1946 } 1947 return false; 1948 } 1949 1950 /// IsIntegralPromotion - Determines whether the conversion from the 1951 /// expression From (whose potentially-adjusted type is FromType) to 1952 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1953 /// sets PromotedType to the promoted type. 1954 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1955 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1956 // All integers are built-in. 1957 if (!To) { 1958 return false; 1959 } 1960 1961 // An rvalue of type char, signed char, unsigned char, short int, or 1962 // unsigned short int can be converted to an rvalue of type int if 1963 // int can represent all the values of the source type; otherwise, 1964 // the source rvalue can be converted to an rvalue of type unsigned 1965 // int (C++ 4.5p1). 1966 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1967 !FromType->isEnumeralType()) { 1968 if (// We can promote any signed, promotable integer type to an int 1969 (FromType->isSignedIntegerType() || 1970 // We can promote any unsigned integer type whose size is 1971 // less than int to an int. 1972 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1973 return To->getKind() == BuiltinType::Int; 1974 } 1975 1976 return To->getKind() == BuiltinType::UInt; 1977 } 1978 1979 // C++11 [conv.prom]p3: 1980 // A prvalue of an unscoped enumeration type whose underlying type is not 1981 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1982 // following types that can represent all the values of the enumeration 1983 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1984 // unsigned int, long int, unsigned long int, long long int, or unsigned 1985 // long long int. If none of the types in that list can represent all the 1986 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1987 // type can be converted to an rvalue a prvalue of the extended integer type 1988 // with lowest integer conversion rank (4.13) greater than the rank of long 1989 // long in which all the values of the enumeration can be represented. If 1990 // there are two such extended types, the signed one is chosen. 1991 // C++11 [conv.prom]p4: 1992 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1993 // can be converted to a prvalue of its underlying type. Moreover, if 1994 // integral promotion can be applied to its underlying type, a prvalue of an 1995 // unscoped enumeration type whose underlying type is fixed can also be 1996 // converted to a prvalue of the promoted underlying type. 1997 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1998 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1999 // provided for a scoped enumeration. 2000 if (FromEnumType->getDecl()->isScoped()) 2001 return false; 2002 2003 // We can perform an integral promotion to the underlying type of the enum, 2004 // even if that's not the promoted type. Note that the check for promoting 2005 // the underlying type is based on the type alone, and does not consider 2006 // the bitfield-ness of the actual source expression. 2007 if (FromEnumType->getDecl()->isFixed()) { 2008 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2009 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2010 IsIntegralPromotion(nullptr, Underlying, ToType); 2011 } 2012 2013 // We have already pre-calculated the promotion type, so this is trivial. 2014 if (ToType->isIntegerType() && 2015 isCompleteType(From->getBeginLoc(), FromType)) 2016 return Context.hasSameUnqualifiedType( 2017 ToType, FromEnumType->getDecl()->getPromotionType()); 2018 2019 // C++ [conv.prom]p5: 2020 // If the bit-field has an enumerated type, it is treated as any other 2021 // value of that type for promotion purposes. 2022 // 2023 // ... so do not fall through into the bit-field checks below in C++. 2024 if (getLangOpts().CPlusPlus) 2025 return false; 2026 } 2027 2028 // C++0x [conv.prom]p2: 2029 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2030 // to an rvalue a prvalue of the first of the following types that can 2031 // represent all the values of its underlying type: int, unsigned int, 2032 // long int, unsigned long int, long long int, or unsigned long long int. 2033 // If none of the types in that list can represent all the values of its 2034 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2035 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2036 // type. 2037 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2038 ToType->isIntegerType()) { 2039 // Determine whether the type we're converting from is signed or 2040 // unsigned. 2041 bool FromIsSigned = FromType->isSignedIntegerType(); 2042 uint64_t FromSize = Context.getTypeSize(FromType); 2043 2044 // The types we'll try to promote to, in the appropriate 2045 // order. Try each of these types. 2046 QualType PromoteTypes[6] = { 2047 Context.IntTy, Context.UnsignedIntTy, 2048 Context.LongTy, Context.UnsignedLongTy , 2049 Context.LongLongTy, Context.UnsignedLongLongTy 2050 }; 2051 for (int Idx = 0; Idx < 6; ++Idx) { 2052 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2053 if (FromSize < ToSize || 2054 (FromSize == ToSize && 2055 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2056 // We found the type that we can promote to. If this is the 2057 // type we wanted, we have a promotion. Otherwise, no 2058 // promotion. 2059 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2060 } 2061 } 2062 } 2063 2064 // An rvalue for an integral bit-field (9.6) can be converted to an 2065 // rvalue of type int if int can represent all the values of the 2066 // bit-field; otherwise, it can be converted to unsigned int if 2067 // unsigned int can represent all the values of the bit-field. If 2068 // the bit-field is larger yet, no integral promotion applies to 2069 // it. If the bit-field has an enumerated type, it is treated as any 2070 // other value of that type for promotion purposes (C++ 4.5p3). 2071 // FIXME: We should delay checking of bit-fields until we actually perform the 2072 // conversion. 2073 // 2074 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2075 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2076 // bit-fields and those whose underlying type is larger than int) for GCC 2077 // compatibility. 2078 if (From) { 2079 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2080 llvm::APSInt BitWidth; 2081 if (FromType->isIntegralType(Context) && 2082 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2083 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2084 ToSize = Context.getTypeSize(ToType); 2085 2086 // Are we promoting to an int from a bitfield that fits in an int? 2087 if (BitWidth < ToSize || 2088 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2089 return To->getKind() == BuiltinType::Int; 2090 } 2091 2092 // Are we promoting to an unsigned int from an unsigned bitfield 2093 // that fits into an unsigned int? 2094 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2095 return To->getKind() == BuiltinType::UInt; 2096 } 2097 2098 return false; 2099 } 2100 } 2101 } 2102 2103 // An rvalue of type bool can be converted to an rvalue of type int, 2104 // with false becoming zero and true becoming one (C++ 4.5p4). 2105 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2106 return true; 2107 } 2108 2109 return false; 2110 } 2111 2112 /// IsFloatingPointPromotion - Determines whether the conversion from 2113 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2114 /// returns true and sets PromotedType to the promoted type. 2115 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2116 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2117 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2118 /// An rvalue of type float can be converted to an rvalue of type 2119 /// double. (C++ 4.6p1). 2120 if (FromBuiltin->getKind() == BuiltinType::Float && 2121 ToBuiltin->getKind() == BuiltinType::Double) 2122 return true; 2123 2124 // C99 6.3.1.5p1: 2125 // When a float is promoted to double or long double, or a 2126 // double is promoted to long double [...]. 2127 if (!getLangOpts().CPlusPlus && 2128 (FromBuiltin->getKind() == BuiltinType::Float || 2129 FromBuiltin->getKind() == BuiltinType::Double) && 2130 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2131 ToBuiltin->getKind() == BuiltinType::Float128)) 2132 return true; 2133 2134 // Half can be promoted to float. 2135 if (!getLangOpts().NativeHalfType && 2136 FromBuiltin->getKind() == BuiltinType::Half && 2137 ToBuiltin->getKind() == BuiltinType::Float) 2138 return true; 2139 } 2140 2141 return false; 2142 } 2143 2144 /// Determine if a conversion is a complex promotion. 2145 /// 2146 /// A complex promotion is defined as a complex -> complex conversion 2147 /// where the conversion between the underlying real types is a 2148 /// floating-point or integral promotion. 2149 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2150 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2151 if (!FromComplex) 2152 return false; 2153 2154 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2155 if (!ToComplex) 2156 return false; 2157 2158 return IsFloatingPointPromotion(FromComplex->getElementType(), 2159 ToComplex->getElementType()) || 2160 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2161 ToComplex->getElementType()); 2162 } 2163 2164 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2165 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2166 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2167 /// if non-empty, will be a pointer to ToType that may or may not have 2168 /// the right set of qualifiers on its pointee. 2169 /// 2170 static QualType 2171 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2172 QualType ToPointee, QualType ToType, 2173 ASTContext &Context, 2174 bool StripObjCLifetime = false) { 2175 assert((FromPtr->getTypeClass() == Type::Pointer || 2176 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2177 "Invalid similarly-qualified pointer type"); 2178 2179 /// Conversions to 'id' subsume cv-qualifier conversions. 2180 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2181 return ToType.getUnqualifiedType(); 2182 2183 QualType CanonFromPointee 2184 = Context.getCanonicalType(FromPtr->getPointeeType()); 2185 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2186 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2187 2188 if (StripObjCLifetime) 2189 Quals.removeObjCLifetime(); 2190 2191 // Exact qualifier match -> return the pointer type we're converting to. 2192 if (CanonToPointee.getLocalQualifiers() == Quals) { 2193 // ToType is exactly what we need. Return it. 2194 if (!ToType.isNull()) 2195 return ToType.getUnqualifiedType(); 2196 2197 // Build a pointer to ToPointee. It has the right qualifiers 2198 // already. 2199 if (isa<ObjCObjectPointerType>(ToType)) 2200 return Context.getObjCObjectPointerType(ToPointee); 2201 return Context.getPointerType(ToPointee); 2202 } 2203 2204 // Just build a canonical type that has the right qualifiers. 2205 QualType QualifiedCanonToPointee 2206 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2207 2208 if (isa<ObjCObjectPointerType>(ToType)) 2209 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2210 return Context.getPointerType(QualifiedCanonToPointee); 2211 } 2212 2213 static bool isNullPointerConstantForConversion(Expr *Expr, 2214 bool InOverloadResolution, 2215 ASTContext &Context) { 2216 // Handle value-dependent integral null pointer constants correctly. 2217 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2218 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2219 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2220 return !InOverloadResolution; 2221 2222 return Expr->isNullPointerConstant(Context, 2223 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2224 : Expr::NPC_ValueDependentIsNull); 2225 } 2226 2227 /// IsPointerConversion - Determines whether the conversion of the 2228 /// expression From, which has the (possibly adjusted) type FromType, 2229 /// can be converted to the type ToType via a pointer conversion (C++ 2230 /// 4.10). If so, returns true and places the converted type (that 2231 /// might differ from ToType in its cv-qualifiers at some level) into 2232 /// ConvertedType. 2233 /// 2234 /// This routine also supports conversions to and from block pointers 2235 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2236 /// pointers to interfaces. FIXME: Once we've determined the 2237 /// appropriate overloading rules for Objective-C, we may want to 2238 /// split the Objective-C checks into a different routine; however, 2239 /// GCC seems to consider all of these conversions to be pointer 2240 /// conversions, so for now they live here. IncompatibleObjC will be 2241 /// set if the conversion is an allowed Objective-C conversion that 2242 /// should result in a warning. 2243 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2244 bool InOverloadResolution, 2245 QualType& ConvertedType, 2246 bool &IncompatibleObjC) { 2247 IncompatibleObjC = false; 2248 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2249 IncompatibleObjC)) 2250 return true; 2251 2252 // Conversion from a null pointer constant to any Objective-C pointer type. 2253 if (ToType->isObjCObjectPointerType() && 2254 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2255 ConvertedType = ToType; 2256 return true; 2257 } 2258 2259 // Blocks: Block pointers can be converted to void*. 2260 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2261 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2262 ConvertedType = ToType; 2263 return true; 2264 } 2265 // Blocks: A null pointer constant can be converted to a block 2266 // pointer type. 2267 if (ToType->isBlockPointerType() && 2268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2269 ConvertedType = ToType; 2270 return true; 2271 } 2272 2273 // If the left-hand-side is nullptr_t, the right side can be a null 2274 // pointer constant. 2275 if (ToType->isNullPtrType() && 2276 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2277 ConvertedType = ToType; 2278 return true; 2279 } 2280 2281 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2282 if (!ToTypePtr) 2283 return false; 2284 2285 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2286 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2287 ConvertedType = ToType; 2288 return true; 2289 } 2290 2291 // Beyond this point, both types need to be pointers 2292 // , including objective-c pointers. 2293 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2294 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2295 !getLangOpts().ObjCAutoRefCount) { 2296 ConvertedType = BuildSimilarlyQualifiedPointerType( 2297 FromType->getAs<ObjCObjectPointerType>(), 2298 ToPointeeType, 2299 ToType, Context); 2300 return true; 2301 } 2302 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2303 if (!FromTypePtr) 2304 return false; 2305 2306 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2307 2308 // If the unqualified pointee types are the same, this can't be a 2309 // pointer conversion, so don't do all of the work below. 2310 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2311 return false; 2312 2313 // An rvalue of type "pointer to cv T," where T is an object type, 2314 // can be converted to an rvalue of type "pointer to cv void" (C++ 2315 // 4.10p2). 2316 if (FromPointeeType->isIncompleteOrObjectType() && 2317 ToPointeeType->isVoidType()) { 2318 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2319 ToPointeeType, 2320 ToType, Context, 2321 /*StripObjCLifetime=*/true); 2322 return true; 2323 } 2324 2325 // MSVC allows implicit function to void* type conversion. 2326 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2327 ToPointeeType->isVoidType()) { 2328 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2329 ToPointeeType, 2330 ToType, Context); 2331 return true; 2332 } 2333 2334 // When we're overloading in C, we allow a special kind of pointer 2335 // conversion for compatible-but-not-identical pointee types. 2336 if (!getLangOpts().CPlusPlus && 2337 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2338 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2339 ToPointeeType, 2340 ToType, Context); 2341 return true; 2342 } 2343 2344 // C++ [conv.ptr]p3: 2345 // 2346 // An rvalue of type "pointer to cv D," where D is a class type, 2347 // can be converted to an rvalue of type "pointer to cv B," where 2348 // B is a base class (clause 10) of D. If B is an inaccessible 2349 // (clause 11) or ambiguous (10.2) base class of D, a program that 2350 // necessitates this conversion is ill-formed. The result of the 2351 // conversion is a pointer to the base class sub-object of the 2352 // derived class object. The null pointer value is converted to 2353 // the null pointer value of the destination type. 2354 // 2355 // Note that we do not check for ambiguity or inaccessibility 2356 // here. That is handled by CheckPointerConversion. 2357 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2358 ToPointeeType->isRecordType() && 2359 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2360 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2361 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2362 ToPointeeType, 2363 ToType, Context); 2364 return true; 2365 } 2366 2367 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2368 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2369 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2370 ToPointeeType, 2371 ToType, Context); 2372 return true; 2373 } 2374 2375 return false; 2376 } 2377 2378 /// Adopt the given qualifiers for the given type. 2379 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2380 Qualifiers TQs = T.getQualifiers(); 2381 2382 // Check whether qualifiers already match. 2383 if (TQs == Qs) 2384 return T; 2385 2386 if (Qs.compatiblyIncludes(TQs)) 2387 return Context.getQualifiedType(T, Qs); 2388 2389 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2390 } 2391 2392 /// isObjCPointerConversion - Determines whether this is an 2393 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2394 /// with the same arguments and return values. 2395 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2396 QualType& ConvertedType, 2397 bool &IncompatibleObjC) { 2398 if (!getLangOpts().ObjC) 2399 return false; 2400 2401 // The set of qualifiers on the type we're converting from. 2402 Qualifiers FromQualifiers = FromType.getQualifiers(); 2403 2404 // First, we handle all conversions on ObjC object pointer types. 2405 const ObjCObjectPointerType* ToObjCPtr = 2406 ToType->getAs<ObjCObjectPointerType>(); 2407 const ObjCObjectPointerType *FromObjCPtr = 2408 FromType->getAs<ObjCObjectPointerType>(); 2409 2410 if (ToObjCPtr && FromObjCPtr) { 2411 // If the pointee types are the same (ignoring qualifications), 2412 // then this is not a pointer conversion. 2413 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2414 FromObjCPtr->getPointeeType())) 2415 return false; 2416 2417 // Conversion between Objective-C pointers. 2418 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2419 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2420 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2421 if (getLangOpts().CPlusPlus && LHS && RHS && 2422 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2423 FromObjCPtr->getPointeeType())) 2424 return false; 2425 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2426 ToObjCPtr->getPointeeType(), 2427 ToType, Context); 2428 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2429 return true; 2430 } 2431 2432 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2433 // Okay: this is some kind of implicit downcast of Objective-C 2434 // interfaces, which is permitted. However, we're going to 2435 // complain about it. 2436 IncompatibleObjC = true; 2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2438 ToObjCPtr->getPointeeType(), 2439 ToType, Context); 2440 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2441 return true; 2442 } 2443 } 2444 // Beyond this point, both types need to be C pointers or block pointers. 2445 QualType ToPointeeType; 2446 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2447 ToPointeeType = ToCPtr->getPointeeType(); 2448 else if (const BlockPointerType *ToBlockPtr = 2449 ToType->getAs<BlockPointerType>()) { 2450 // Objective C++: We're able to convert from a pointer to any object 2451 // to a block pointer type. 2452 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2453 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2454 return true; 2455 } 2456 ToPointeeType = ToBlockPtr->getPointeeType(); 2457 } 2458 else if (FromType->getAs<BlockPointerType>() && 2459 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2460 // Objective C++: We're able to convert from a block pointer type to a 2461 // pointer to any object. 2462 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2463 return true; 2464 } 2465 else 2466 return false; 2467 2468 QualType FromPointeeType; 2469 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2470 FromPointeeType = FromCPtr->getPointeeType(); 2471 else if (const BlockPointerType *FromBlockPtr = 2472 FromType->getAs<BlockPointerType>()) 2473 FromPointeeType = FromBlockPtr->getPointeeType(); 2474 else 2475 return false; 2476 2477 // If we have pointers to pointers, recursively check whether this 2478 // is an Objective-C conversion. 2479 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2480 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2481 IncompatibleObjC)) { 2482 // We always complain about this conversion. 2483 IncompatibleObjC = true; 2484 ConvertedType = Context.getPointerType(ConvertedType); 2485 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2486 return true; 2487 } 2488 // Allow conversion of pointee being objective-c pointer to another one; 2489 // as in I* to id. 2490 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2491 ToPointeeType->getAs<ObjCObjectPointerType>() && 2492 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2493 IncompatibleObjC)) { 2494 2495 ConvertedType = Context.getPointerType(ConvertedType); 2496 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2497 return true; 2498 } 2499 2500 // If we have pointers to functions or blocks, check whether the only 2501 // differences in the argument and result types are in Objective-C 2502 // pointer conversions. If so, we permit the conversion (but 2503 // complain about it). 2504 const FunctionProtoType *FromFunctionType 2505 = FromPointeeType->getAs<FunctionProtoType>(); 2506 const FunctionProtoType *ToFunctionType 2507 = ToPointeeType->getAs<FunctionProtoType>(); 2508 if (FromFunctionType && ToFunctionType) { 2509 // If the function types are exactly the same, this isn't an 2510 // Objective-C pointer conversion. 2511 if (Context.getCanonicalType(FromPointeeType) 2512 == Context.getCanonicalType(ToPointeeType)) 2513 return false; 2514 2515 // Perform the quick checks that will tell us whether these 2516 // function types are obviously different. 2517 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2518 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2519 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2520 return false; 2521 2522 bool HasObjCConversion = false; 2523 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2524 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2525 // Okay, the types match exactly. Nothing to do. 2526 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2527 ToFunctionType->getReturnType(), 2528 ConvertedType, IncompatibleObjC)) { 2529 // Okay, we have an Objective-C pointer conversion. 2530 HasObjCConversion = true; 2531 } else { 2532 // Function types are too different. Abort. 2533 return false; 2534 } 2535 2536 // Check argument types. 2537 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2538 ArgIdx != NumArgs; ++ArgIdx) { 2539 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2540 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2541 if (Context.getCanonicalType(FromArgType) 2542 == Context.getCanonicalType(ToArgType)) { 2543 // Okay, the types match exactly. Nothing to do. 2544 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2545 ConvertedType, IncompatibleObjC)) { 2546 // Okay, we have an Objective-C pointer conversion. 2547 HasObjCConversion = true; 2548 } else { 2549 // Argument types are too different. Abort. 2550 return false; 2551 } 2552 } 2553 2554 if (HasObjCConversion) { 2555 // We had an Objective-C conversion. Allow this pointer 2556 // conversion, but complain about it. 2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2558 IncompatibleObjC = true; 2559 return true; 2560 } 2561 } 2562 2563 return false; 2564 } 2565 2566 /// Determine whether this is an Objective-C writeback conversion, 2567 /// used for parameter passing when performing automatic reference counting. 2568 /// 2569 /// \param FromType The type we're converting form. 2570 /// 2571 /// \param ToType The type we're converting to. 2572 /// 2573 /// \param ConvertedType The type that will be produced after applying 2574 /// this conversion. 2575 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2576 QualType &ConvertedType) { 2577 if (!getLangOpts().ObjCAutoRefCount || 2578 Context.hasSameUnqualifiedType(FromType, ToType)) 2579 return false; 2580 2581 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2582 QualType ToPointee; 2583 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2584 ToPointee = ToPointer->getPointeeType(); 2585 else 2586 return false; 2587 2588 Qualifiers ToQuals = ToPointee.getQualifiers(); 2589 if (!ToPointee->isObjCLifetimeType() || 2590 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2591 !ToQuals.withoutObjCLifetime().empty()) 2592 return false; 2593 2594 // Argument must be a pointer to __strong to __weak. 2595 QualType FromPointee; 2596 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2597 FromPointee = FromPointer->getPointeeType(); 2598 else 2599 return false; 2600 2601 Qualifiers FromQuals = FromPointee.getQualifiers(); 2602 if (!FromPointee->isObjCLifetimeType() || 2603 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2604 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2605 return false; 2606 2607 // Make sure that we have compatible qualifiers. 2608 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2609 if (!ToQuals.compatiblyIncludes(FromQuals)) 2610 return false; 2611 2612 // Remove qualifiers from the pointee type we're converting from; they 2613 // aren't used in the compatibility check belong, and we'll be adding back 2614 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2615 FromPointee = FromPointee.getUnqualifiedType(); 2616 2617 // The unqualified form of the pointee types must be compatible. 2618 ToPointee = ToPointee.getUnqualifiedType(); 2619 bool IncompatibleObjC; 2620 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2621 FromPointee = ToPointee; 2622 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2623 IncompatibleObjC)) 2624 return false; 2625 2626 /// Construct the type we're converting to, which is a pointer to 2627 /// __autoreleasing pointee. 2628 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2629 ConvertedType = Context.getPointerType(FromPointee); 2630 return true; 2631 } 2632 2633 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2634 QualType& ConvertedType) { 2635 QualType ToPointeeType; 2636 if (const BlockPointerType *ToBlockPtr = 2637 ToType->getAs<BlockPointerType>()) 2638 ToPointeeType = ToBlockPtr->getPointeeType(); 2639 else 2640 return false; 2641 2642 QualType FromPointeeType; 2643 if (const BlockPointerType *FromBlockPtr = 2644 FromType->getAs<BlockPointerType>()) 2645 FromPointeeType = FromBlockPtr->getPointeeType(); 2646 else 2647 return false; 2648 // We have pointer to blocks, check whether the only 2649 // differences in the argument and result types are in Objective-C 2650 // pointer conversions. If so, we permit the conversion. 2651 2652 const FunctionProtoType *FromFunctionType 2653 = FromPointeeType->getAs<FunctionProtoType>(); 2654 const FunctionProtoType *ToFunctionType 2655 = ToPointeeType->getAs<FunctionProtoType>(); 2656 2657 if (!FromFunctionType || !ToFunctionType) 2658 return false; 2659 2660 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2661 return true; 2662 2663 // Perform the quick checks that will tell us whether these 2664 // function types are obviously different. 2665 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2666 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2667 return false; 2668 2669 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2670 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2671 if (FromEInfo != ToEInfo) 2672 return false; 2673 2674 bool IncompatibleObjC = false; 2675 if (Context.hasSameType(FromFunctionType->getReturnType(), 2676 ToFunctionType->getReturnType())) { 2677 // Okay, the types match exactly. Nothing to do. 2678 } else { 2679 QualType RHS = FromFunctionType->getReturnType(); 2680 QualType LHS = ToFunctionType->getReturnType(); 2681 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2682 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2683 LHS = LHS.getUnqualifiedType(); 2684 2685 if (Context.hasSameType(RHS,LHS)) { 2686 // OK exact match. 2687 } else if (isObjCPointerConversion(RHS, LHS, 2688 ConvertedType, IncompatibleObjC)) { 2689 if (IncompatibleObjC) 2690 return false; 2691 // Okay, we have an Objective-C pointer conversion. 2692 } 2693 else 2694 return false; 2695 } 2696 2697 // Check argument types. 2698 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2699 ArgIdx != NumArgs; ++ArgIdx) { 2700 IncompatibleObjC = false; 2701 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2702 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2703 if (Context.hasSameType(FromArgType, ToArgType)) { 2704 // Okay, the types match exactly. Nothing to do. 2705 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2706 ConvertedType, IncompatibleObjC)) { 2707 if (IncompatibleObjC) 2708 return false; 2709 // Okay, we have an Objective-C pointer conversion. 2710 } else 2711 // Argument types are too different. Abort. 2712 return false; 2713 } 2714 2715 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2716 bool CanUseToFPT, CanUseFromFPT; 2717 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2718 CanUseToFPT, CanUseFromFPT, 2719 NewParamInfos)) 2720 return false; 2721 2722 ConvertedType = ToType; 2723 return true; 2724 } 2725 2726 enum { 2727 ft_default, 2728 ft_different_class, 2729 ft_parameter_arity, 2730 ft_parameter_mismatch, 2731 ft_return_type, 2732 ft_qualifer_mismatch, 2733 ft_noexcept 2734 }; 2735 2736 /// Attempts to get the FunctionProtoType from a Type. Handles 2737 /// MemberFunctionPointers properly. 2738 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2739 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2740 return FPT; 2741 2742 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2743 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2744 2745 return nullptr; 2746 } 2747 2748 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2749 /// function types. Catches different number of parameter, mismatch in 2750 /// parameter types, and different return types. 2751 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2752 QualType FromType, QualType ToType) { 2753 // If either type is not valid, include no extra info. 2754 if (FromType.isNull() || ToType.isNull()) { 2755 PDiag << ft_default; 2756 return; 2757 } 2758 2759 // Get the function type from the pointers. 2760 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2761 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2762 *ToMember = ToType->getAs<MemberPointerType>(); 2763 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2764 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2765 << QualType(FromMember->getClass(), 0); 2766 return; 2767 } 2768 FromType = FromMember->getPointeeType(); 2769 ToType = ToMember->getPointeeType(); 2770 } 2771 2772 if (FromType->isPointerType()) 2773 FromType = FromType->getPointeeType(); 2774 if (ToType->isPointerType()) 2775 ToType = ToType->getPointeeType(); 2776 2777 // Remove references. 2778 FromType = FromType.getNonReferenceType(); 2779 ToType = ToType.getNonReferenceType(); 2780 2781 // Don't print extra info for non-specialized template functions. 2782 if (FromType->isInstantiationDependentType() && 2783 !FromType->getAs<TemplateSpecializationType>()) { 2784 PDiag << ft_default; 2785 return; 2786 } 2787 2788 // No extra info for same types. 2789 if (Context.hasSameType(FromType, ToType)) { 2790 PDiag << ft_default; 2791 return; 2792 } 2793 2794 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2795 *ToFunction = tryGetFunctionProtoType(ToType); 2796 2797 // Both types need to be function types. 2798 if (!FromFunction || !ToFunction) { 2799 PDiag << ft_default; 2800 return; 2801 } 2802 2803 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2804 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2805 << FromFunction->getNumParams(); 2806 return; 2807 } 2808 2809 // Handle different parameter types. 2810 unsigned ArgPos; 2811 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2812 PDiag << ft_parameter_mismatch << ArgPos + 1 2813 << ToFunction->getParamType(ArgPos) 2814 << FromFunction->getParamType(ArgPos); 2815 return; 2816 } 2817 2818 // Handle different return type. 2819 if (!Context.hasSameType(FromFunction->getReturnType(), 2820 ToFunction->getReturnType())) { 2821 PDiag << ft_return_type << ToFunction->getReturnType() 2822 << FromFunction->getReturnType(); 2823 return; 2824 } 2825 2826 unsigned FromQuals = FromFunction->getTypeQuals(), 2827 ToQuals = ToFunction->getTypeQuals(); 2828 if (FromQuals != ToQuals) { 2829 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2830 return; 2831 } 2832 2833 // Handle exception specification differences on canonical type (in C++17 2834 // onwards). 2835 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2836 ->isNothrow() != 2837 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2838 ->isNothrow()) { 2839 PDiag << ft_noexcept; 2840 return; 2841 } 2842 2843 // Unable to find a difference, so add no extra info. 2844 PDiag << ft_default; 2845 } 2846 2847 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2848 /// for equality of their argument types. Caller has already checked that 2849 /// they have same number of arguments. If the parameters are different, 2850 /// ArgPos will have the parameter index of the first different parameter. 2851 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2852 const FunctionProtoType *NewType, 2853 unsigned *ArgPos) { 2854 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2855 N = NewType->param_type_begin(), 2856 E = OldType->param_type_end(); 2857 O && (O != E); ++O, ++N) { 2858 if (!Context.hasSameType(O->getUnqualifiedType(), 2859 N->getUnqualifiedType())) { 2860 if (ArgPos) 2861 *ArgPos = O - OldType->param_type_begin(); 2862 return false; 2863 } 2864 } 2865 return true; 2866 } 2867 2868 /// CheckPointerConversion - Check the pointer conversion from the 2869 /// expression From to the type ToType. This routine checks for 2870 /// ambiguous or inaccessible derived-to-base pointer 2871 /// conversions for which IsPointerConversion has already returned 2872 /// true. It returns true and produces a diagnostic if there was an 2873 /// error, or returns false otherwise. 2874 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2875 CastKind &Kind, 2876 CXXCastPath& BasePath, 2877 bool IgnoreBaseAccess, 2878 bool Diagnose) { 2879 QualType FromType = From->getType(); 2880 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2881 2882 Kind = CK_BitCast; 2883 2884 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2885 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2886 Expr::NPCK_ZeroExpression) { 2887 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2888 DiagRuntimeBehavior(From->getExprLoc(), From, 2889 PDiag(diag::warn_impcast_bool_to_null_pointer) 2890 << ToType << From->getSourceRange()); 2891 else if (!isUnevaluatedContext()) 2892 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2893 << ToType << From->getSourceRange(); 2894 } 2895 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2896 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2897 QualType FromPointeeType = FromPtrType->getPointeeType(), 2898 ToPointeeType = ToPtrType->getPointeeType(); 2899 2900 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2901 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2902 // We must have a derived-to-base conversion. Check an 2903 // ambiguous or inaccessible conversion. 2904 unsigned InaccessibleID = 0; 2905 unsigned AmbigiousID = 0; 2906 if (Diagnose) { 2907 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2908 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2909 } 2910 if (CheckDerivedToBaseConversion( 2911 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2912 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2913 &BasePath, IgnoreBaseAccess)) 2914 return true; 2915 2916 // The conversion was successful. 2917 Kind = CK_DerivedToBase; 2918 } 2919 2920 if (Diagnose && !IsCStyleOrFunctionalCast && 2921 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2922 assert(getLangOpts().MSVCCompat && 2923 "this should only be possible with MSVCCompat!"); 2924 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2925 << From->getSourceRange(); 2926 } 2927 } 2928 } else if (const ObjCObjectPointerType *ToPtrType = 2929 ToType->getAs<ObjCObjectPointerType>()) { 2930 if (const ObjCObjectPointerType *FromPtrType = 2931 FromType->getAs<ObjCObjectPointerType>()) { 2932 // Objective-C++ conversions are always okay. 2933 // FIXME: We should have a different class of conversions for the 2934 // Objective-C++ implicit conversions. 2935 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2936 return false; 2937 } else if (FromType->isBlockPointerType()) { 2938 Kind = CK_BlockPointerToObjCPointerCast; 2939 } else { 2940 Kind = CK_CPointerToObjCPointerCast; 2941 } 2942 } else if (ToType->isBlockPointerType()) { 2943 if (!FromType->isBlockPointerType()) 2944 Kind = CK_AnyPointerToBlockPointerCast; 2945 } 2946 2947 // We shouldn't fall into this case unless it's valid for other 2948 // reasons. 2949 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2950 Kind = CK_NullToPointer; 2951 2952 return false; 2953 } 2954 2955 /// IsMemberPointerConversion - Determines whether the conversion of the 2956 /// expression From, which has the (possibly adjusted) type FromType, can be 2957 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2958 /// If so, returns true and places the converted type (that might differ from 2959 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2960 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2961 QualType ToType, 2962 bool InOverloadResolution, 2963 QualType &ConvertedType) { 2964 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2965 if (!ToTypePtr) 2966 return false; 2967 2968 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2969 if (From->isNullPointerConstant(Context, 2970 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2971 : Expr::NPC_ValueDependentIsNull)) { 2972 ConvertedType = ToType; 2973 return true; 2974 } 2975 2976 // Otherwise, both types have to be member pointers. 2977 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2978 if (!FromTypePtr) 2979 return false; 2980 2981 // A pointer to member of B can be converted to a pointer to member of D, 2982 // where D is derived from B (C++ 4.11p2). 2983 QualType FromClass(FromTypePtr->getClass(), 0); 2984 QualType ToClass(ToTypePtr->getClass(), 0); 2985 2986 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2987 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 2988 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2989 ToClass.getTypePtr()); 2990 return true; 2991 } 2992 2993 return false; 2994 } 2995 2996 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2997 /// expression From to the type ToType. This routine checks for ambiguous or 2998 /// virtual or inaccessible base-to-derived member pointer conversions 2999 /// for which IsMemberPointerConversion has already returned true. It returns 3000 /// true and produces a diagnostic if there was an error, or returns false 3001 /// otherwise. 3002 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3003 CastKind &Kind, 3004 CXXCastPath &BasePath, 3005 bool IgnoreBaseAccess) { 3006 QualType FromType = From->getType(); 3007 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3008 if (!FromPtrType) { 3009 // This must be a null pointer to member pointer conversion 3010 assert(From->isNullPointerConstant(Context, 3011 Expr::NPC_ValueDependentIsNull) && 3012 "Expr must be null pointer constant!"); 3013 Kind = CK_NullToMemberPointer; 3014 return false; 3015 } 3016 3017 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3018 assert(ToPtrType && "No member pointer cast has a target type " 3019 "that is not a member pointer."); 3020 3021 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3022 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3023 3024 // FIXME: What about dependent types? 3025 assert(FromClass->isRecordType() && "Pointer into non-class."); 3026 assert(ToClass->isRecordType() && "Pointer into non-class."); 3027 3028 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3029 /*DetectVirtual=*/true); 3030 bool DerivationOkay = 3031 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3032 assert(DerivationOkay && 3033 "Should not have been called if derivation isn't OK."); 3034 (void)DerivationOkay; 3035 3036 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3037 getUnqualifiedType())) { 3038 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3039 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3040 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3041 return true; 3042 } 3043 3044 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3045 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3046 << FromClass << ToClass << QualType(VBase, 0) 3047 << From->getSourceRange(); 3048 return true; 3049 } 3050 3051 if (!IgnoreBaseAccess) 3052 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3053 Paths.front(), 3054 diag::err_downcast_from_inaccessible_base); 3055 3056 // Must be a base to derived member conversion. 3057 BuildBasePathArray(Paths, BasePath); 3058 Kind = CK_BaseToDerivedMemberPointer; 3059 return false; 3060 } 3061 3062 /// Determine whether the lifetime conversion between the two given 3063 /// qualifiers sets is nontrivial. 3064 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3065 Qualifiers ToQuals) { 3066 // Converting anything to const __unsafe_unretained is trivial. 3067 if (ToQuals.hasConst() && 3068 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3069 return false; 3070 3071 return true; 3072 } 3073 3074 /// IsQualificationConversion - Determines whether the conversion from 3075 /// an rvalue of type FromType to ToType is a qualification conversion 3076 /// (C++ 4.4). 3077 /// 3078 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3079 /// when the qualification conversion involves a change in the Objective-C 3080 /// object lifetime. 3081 bool 3082 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3083 bool CStyle, bool &ObjCLifetimeConversion) { 3084 FromType = Context.getCanonicalType(FromType); 3085 ToType = Context.getCanonicalType(ToType); 3086 ObjCLifetimeConversion = false; 3087 3088 // If FromType and ToType are the same type, this is not a 3089 // qualification conversion. 3090 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3091 return false; 3092 3093 // (C++ 4.4p4): 3094 // A conversion can add cv-qualifiers at levels other than the first 3095 // in multi-level pointers, subject to the following rules: [...] 3096 bool PreviousToQualsIncludeConst = true; 3097 bool UnwrappedAnyPointer = false; 3098 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3099 // Within each iteration of the loop, we check the qualifiers to 3100 // determine if this still looks like a qualification 3101 // conversion. Then, if all is well, we unwrap one more level of 3102 // pointers or pointers-to-members and do it all again 3103 // until there are no more pointers or pointers-to-members left to 3104 // unwrap. 3105 UnwrappedAnyPointer = true; 3106 3107 Qualifiers FromQuals = FromType.getQualifiers(); 3108 Qualifiers ToQuals = ToType.getQualifiers(); 3109 3110 // Ignore __unaligned qualifier if this type is void. 3111 if (ToType.getUnqualifiedType()->isVoidType()) 3112 FromQuals.removeUnaligned(); 3113 3114 // Objective-C ARC: 3115 // Check Objective-C lifetime conversions. 3116 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3117 UnwrappedAnyPointer) { 3118 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3119 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3120 ObjCLifetimeConversion = true; 3121 FromQuals.removeObjCLifetime(); 3122 ToQuals.removeObjCLifetime(); 3123 } else { 3124 // Qualification conversions cannot cast between different 3125 // Objective-C lifetime qualifiers. 3126 return false; 3127 } 3128 } 3129 3130 // Allow addition/removal of GC attributes but not changing GC attributes. 3131 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3132 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3133 FromQuals.removeObjCGCAttr(); 3134 ToQuals.removeObjCGCAttr(); 3135 } 3136 3137 // -- for every j > 0, if const is in cv 1,j then const is in cv 3138 // 2,j, and similarly for volatile. 3139 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3140 return false; 3141 3142 // -- if the cv 1,j and cv 2,j are different, then const is in 3143 // every cv for 0 < k < j. 3144 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3145 && !PreviousToQualsIncludeConst) 3146 return false; 3147 3148 // Keep track of whether all prior cv-qualifiers in the "to" type 3149 // include const. 3150 PreviousToQualsIncludeConst 3151 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3152 } 3153 3154 // Allows address space promotion by language rules implemented in 3155 // Type::Qualifiers::isAddressSpaceSupersetOf. 3156 Qualifiers FromQuals = FromType.getQualifiers(); 3157 Qualifiers ToQuals = ToType.getQualifiers(); 3158 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3159 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3160 return false; 3161 } 3162 3163 // We are left with FromType and ToType being the pointee types 3164 // after unwrapping the original FromType and ToType the same number 3165 // of types. If we unwrapped any pointers, and if FromType and 3166 // ToType have the same unqualified type (since we checked 3167 // qualifiers above), then this is a qualification conversion. 3168 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3169 } 3170 3171 /// - Determine whether this is a conversion from a scalar type to an 3172 /// atomic type. 3173 /// 3174 /// If successful, updates \c SCS's second and third steps in the conversion 3175 /// sequence to finish the conversion. 3176 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3177 bool InOverloadResolution, 3178 StandardConversionSequence &SCS, 3179 bool CStyle) { 3180 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3181 if (!ToAtomic) 3182 return false; 3183 3184 StandardConversionSequence InnerSCS; 3185 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3186 InOverloadResolution, InnerSCS, 3187 CStyle, /*AllowObjCWritebackConversion=*/false)) 3188 return false; 3189 3190 SCS.Second = InnerSCS.Second; 3191 SCS.setToType(1, InnerSCS.getToType(1)); 3192 SCS.Third = InnerSCS.Third; 3193 SCS.QualificationIncludesObjCLifetime 3194 = InnerSCS.QualificationIncludesObjCLifetime; 3195 SCS.setToType(2, InnerSCS.getToType(2)); 3196 return true; 3197 } 3198 3199 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3200 CXXConstructorDecl *Constructor, 3201 QualType Type) { 3202 const FunctionProtoType *CtorType = 3203 Constructor->getType()->getAs<FunctionProtoType>(); 3204 if (CtorType->getNumParams() > 0) { 3205 QualType FirstArg = CtorType->getParamType(0); 3206 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3207 return true; 3208 } 3209 return false; 3210 } 3211 3212 static OverloadingResult 3213 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3214 CXXRecordDecl *To, 3215 UserDefinedConversionSequence &User, 3216 OverloadCandidateSet &CandidateSet, 3217 bool AllowExplicit) { 3218 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3219 for (auto *D : S.LookupConstructors(To)) { 3220 auto Info = getConstructorInfo(D); 3221 if (!Info) 3222 continue; 3223 3224 bool Usable = !Info.Constructor->isInvalidDecl() && 3225 S.isInitListConstructor(Info.Constructor) && 3226 (AllowExplicit || !Info.Constructor->isExplicit()); 3227 if (Usable) { 3228 // If the first argument is (a reference to) the target type, 3229 // suppress conversions. 3230 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3231 S.Context, Info.Constructor, ToType); 3232 if (Info.ConstructorTmpl) 3233 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3234 /*ExplicitArgs*/ nullptr, From, 3235 CandidateSet, SuppressUserConversions); 3236 else 3237 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3238 CandidateSet, SuppressUserConversions); 3239 } 3240 } 3241 3242 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3243 3244 OverloadCandidateSet::iterator Best; 3245 switch (auto Result = 3246 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3247 case OR_Deleted: 3248 case OR_Success: { 3249 // Record the standard conversion we used and the conversion function. 3250 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3251 QualType ThisType = Constructor->getThisType(S.Context); 3252 // Initializer lists don't have conversions as such. 3253 User.Before.setAsIdentityConversion(); 3254 User.HadMultipleCandidates = HadMultipleCandidates; 3255 User.ConversionFunction = Constructor; 3256 User.FoundConversionFunction = Best->FoundDecl; 3257 User.After.setAsIdentityConversion(); 3258 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3259 User.After.setAllToTypes(ToType); 3260 return Result; 3261 } 3262 3263 case OR_No_Viable_Function: 3264 return OR_No_Viable_Function; 3265 case OR_Ambiguous: 3266 return OR_Ambiguous; 3267 } 3268 3269 llvm_unreachable("Invalid OverloadResult!"); 3270 } 3271 3272 /// Determines whether there is a user-defined conversion sequence 3273 /// (C++ [over.ics.user]) that converts expression From to the type 3274 /// ToType. If such a conversion exists, User will contain the 3275 /// user-defined conversion sequence that performs such a conversion 3276 /// and this routine will return true. Otherwise, this routine returns 3277 /// false and User is unspecified. 3278 /// 3279 /// \param AllowExplicit true if the conversion should consider C++0x 3280 /// "explicit" conversion functions as well as non-explicit conversion 3281 /// functions (C++0x [class.conv.fct]p2). 3282 /// 3283 /// \param AllowObjCConversionOnExplicit true if the conversion should 3284 /// allow an extra Objective-C pointer conversion on uses of explicit 3285 /// constructors. Requires \c AllowExplicit to also be set. 3286 static OverloadingResult 3287 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3288 UserDefinedConversionSequence &User, 3289 OverloadCandidateSet &CandidateSet, 3290 bool AllowExplicit, 3291 bool AllowObjCConversionOnExplicit) { 3292 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3293 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3294 3295 // Whether we will only visit constructors. 3296 bool ConstructorsOnly = false; 3297 3298 // If the type we are conversion to is a class type, enumerate its 3299 // constructors. 3300 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3301 // C++ [over.match.ctor]p1: 3302 // When objects of class type are direct-initialized (8.5), or 3303 // copy-initialized from an expression of the same or a 3304 // derived class type (8.5), overload resolution selects the 3305 // constructor. [...] For copy-initialization, the candidate 3306 // functions are all the converting constructors (12.3.1) of 3307 // that class. The argument list is the expression-list within 3308 // the parentheses of the initializer. 3309 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3310 (From->getType()->getAs<RecordType>() && 3311 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3312 ConstructorsOnly = true; 3313 3314 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3315 // We're not going to find any constructors. 3316 } else if (CXXRecordDecl *ToRecordDecl 3317 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3318 3319 Expr **Args = &From; 3320 unsigned NumArgs = 1; 3321 bool ListInitializing = false; 3322 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3323 // But first, see if there is an init-list-constructor that will work. 3324 OverloadingResult Result = IsInitializerListConstructorConversion( 3325 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3326 if (Result != OR_No_Viable_Function) 3327 return Result; 3328 // Never mind. 3329 CandidateSet.clear( 3330 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3331 3332 // If we're list-initializing, we pass the individual elements as 3333 // arguments, not the entire list. 3334 Args = InitList->getInits(); 3335 NumArgs = InitList->getNumInits(); 3336 ListInitializing = true; 3337 } 3338 3339 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3340 auto Info = getConstructorInfo(D); 3341 if (!Info) 3342 continue; 3343 3344 bool Usable = !Info.Constructor->isInvalidDecl(); 3345 if (ListInitializing) 3346 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3347 else 3348 Usable = Usable && 3349 Info.Constructor->isConvertingConstructor(AllowExplicit); 3350 if (Usable) { 3351 bool SuppressUserConversions = !ConstructorsOnly; 3352 if (SuppressUserConversions && ListInitializing) { 3353 SuppressUserConversions = false; 3354 if (NumArgs == 1) { 3355 // If the first argument is (a reference to) the target type, 3356 // suppress conversions. 3357 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3358 S.Context, Info.Constructor, ToType); 3359 } 3360 } 3361 if (Info.ConstructorTmpl) 3362 S.AddTemplateOverloadCandidate( 3363 Info.ConstructorTmpl, Info.FoundDecl, 3364 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3365 CandidateSet, SuppressUserConversions); 3366 else 3367 // Allow one user-defined conversion when user specifies a 3368 // From->ToType conversion via an static cast (c-style, etc). 3369 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3370 llvm::makeArrayRef(Args, NumArgs), 3371 CandidateSet, SuppressUserConversions); 3372 } 3373 } 3374 } 3375 } 3376 3377 // Enumerate conversion functions, if we're allowed to. 3378 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3379 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3380 // No conversion functions from incomplete types. 3381 } else if (const RecordType *FromRecordType = 3382 From->getType()->getAs<RecordType>()) { 3383 if (CXXRecordDecl *FromRecordDecl 3384 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3385 // Add all of the conversion functions as candidates. 3386 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3387 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3388 DeclAccessPair FoundDecl = I.getPair(); 3389 NamedDecl *D = FoundDecl.getDecl(); 3390 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3391 if (isa<UsingShadowDecl>(D)) 3392 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3393 3394 CXXConversionDecl *Conv; 3395 FunctionTemplateDecl *ConvTemplate; 3396 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3397 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3398 else 3399 Conv = cast<CXXConversionDecl>(D); 3400 3401 if (AllowExplicit || !Conv->isExplicit()) { 3402 if (ConvTemplate) 3403 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3404 ActingContext, From, ToType, 3405 CandidateSet, 3406 AllowObjCConversionOnExplicit); 3407 else 3408 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3409 From, ToType, CandidateSet, 3410 AllowObjCConversionOnExplicit); 3411 } 3412 } 3413 } 3414 } 3415 3416 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3417 3418 OverloadCandidateSet::iterator Best; 3419 switch (auto Result = 3420 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3421 case OR_Success: 3422 case OR_Deleted: 3423 // Record the standard conversion we used and the conversion function. 3424 if (CXXConstructorDecl *Constructor 3425 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3426 // C++ [over.ics.user]p1: 3427 // If the user-defined conversion is specified by a 3428 // constructor (12.3.1), the initial standard conversion 3429 // sequence converts the source type to the type required by 3430 // the argument of the constructor. 3431 // 3432 QualType ThisType = Constructor->getThisType(S.Context); 3433 if (isa<InitListExpr>(From)) { 3434 // Initializer lists don't have conversions as such. 3435 User.Before.setAsIdentityConversion(); 3436 } else { 3437 if (Best->Conversions[0].isEllipsis()) 3438 User.EllipsisConversion = true; 3439 else { 3440 User.Before = Best->Conversions[0].Standard; 3441 User.EllipsisConversion = false; 3442 } 3443 } 3444 User.HadMultipleCandidates = HadMultipleCandidates; 3445 User.ConversionFunction = Constructor; 3446 User.FoundConversionFunction = Best->FoundDecl; 3447 User.After.setAsIdentityConversion(); 3448 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3449 User.After.setAllToTypes(ToType); 3450 return Result; 3451 } 3452 if (CXXConversionDecl *Conversion 3453 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3454 // C++ [over.ics.user]p1: 3455 // 3456 // [...] If the user-defined conversion is specified by a 3457 // conversion function (12.3.2), the initial standard 3458 // conversion sequence converts the source type to the 3459 // implicit object parameter of the conversion function. 3460 User.Before = Best->Conversions[0].Standard; 3461 User.HadMultipleCandidates = HadMultipleCandidates; 3462 User.ConversionFunction = Conversion; 3463 User.FoundConversionFunction = Best->FoundDecl; 3464 User.EllipsisConversion = false; 3465 3466 // C++ [over.ics.user]p2: 3467 // The second standard conversion sequence converts the 3468 // result of the user-defined conversion to the target type 3469 // for the sequence. Since an implicit conversion sequence 3470 // is an initialization, the special rules for 3471 // initialization by user-defined conversion apply when 3472 // selecting the best user-defined conversion for a 3473 // user-defined conversion sequence (see 13.3.3 and 3474 // 13.3.3.1). 3475 User.After = Best->FinalConversion; 3476 return Result; 3477 } 3478 llvm_unreachable("Not a constructor or conversion function?"); 3479 3480 case OR_No_Viable_Function: 3481 return OR_No_Viable_Function; 3482 3483 case OR_Ambiguous: 3484 return OR_Ambiguous; 3485 } 3486 3487 llvm_unreachable("Invalid OverloadResult!"); 3488 } 3489 3490 bool 3491 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3492 ImplicitConversionSequence ICS; 3493 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3494 OverloadCandidateSet::CSK_Normal); 3495 OverloadingResult OvResult = 3496 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3497 CandidateSet, false, false); 3498 if (OvResult == OR_Ambiguous) 3499 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3500 << From->getType() << ToType << From->getSourceRange(); 3501 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3502 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3503 diag::err_typecheck_nonviable_condition_incomplete, 3504 From->getType(), From->getSourceRange())) 3505 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3506 << false << From->getType() << From->getSourceRange() << ToType; 3507 } else 3508 return false; 3509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3510 return true; 3511 } 3512 3513 /// Compare the user-defined conversion functions or constructors 3514 /// of two user-defined conversion sequences to determine whether any ordering 3515 /// is possible. 3516 static ImplicitConversionSequence::CompareKind 3517 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3518 FunctionDecl *Function2) { 3519 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3520 return ImplicitConversionSequence::Indistinguishable; 3521 3522 // Objective-C++: 3523 // If both conversion functions are implicitly-declared conversions from 3524 // a lambda closure type to a function pointer and a block pointer, 3525 // respectively, always prefer the conversion to a function pointer, 3526 // because the function pointer is more lightweight and is more likely 3527 // to keep code working. 3528 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3529 if (!Conv1) 3530 return ImplicitConversionSequence::Indistinguishable; 3531 3532 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3533 if (!Conv2) 3534 return ImplicitConversionSequence::Indistinguishable; 3535 3536 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3537 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3538 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3539 if (Block1 != Block2) 3540 return Block1 ? ImplicitConversionSequence::Worse 3541 : ImplicitConversionSequence::Better; 3542 } 3543 3544 return ImplicitConversionSequence::Indistinguishable; 3545 } 3546 3547 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3548 const ImplicitConversionSequence &ICS) { 3549 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3550 (ICS.isUserDefined() && 3551 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3552 } 3553 3554 /// CompareImplicitConversionSequences - Compare two implicit 3555 /// conversion sequences to determine whether one is better than the 3556 /// other or if they are indistinguishable (C++ 13.3.3.2). 3557 static ImplicitConversionSequence::CompareKind 3558 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3559 const ImplicitConversionSequence& ICS1, 3560 const ImplicitConversionSequence& ICS2) 3561 { 3562 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3563 // conversion sequences (as defined in 13.3.3.1) 3564 // -- a standard conversion sequence (13.3.3.1.1) is a better 3565 // conversion sequence than a user-defined conversion sequence or 3566 // an ellipsis conversion sequence, and 3567 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3568 // conversion sequence than an ellipsis conversion sequence 3569 // (13.3.3.1.3). 3570 // 3571 // C++0x [over.best.ics]p10: 3572 // For the purpose of ranking implicit conversion sequences as 3573 // described in 13.3.3.2, the ambiguous conversion sequence is 3574 // treated as a user-defined sequence that is indistinguishable 3575 // from any other user-defined conversion sequence. 3576 3577 // String literal to 'char *' conversion has been deprecated in C++03. It has 3578 // been removed from C++11. We still accept this conversion, if it happens at 3579 // the best viable function. Otherwise, this conversion is considered worse 3580 // than ellipsis conversion. Consider this as an extension; this is not in the 3581 // standard. For example: 3582 // 3583 // int &f(...); // #1 3584 // void f(char*); // #2 3585 // void g() { int &r = f("foo"); } 3586 // 3587 // In C++03, we pick #2 as the best viable function. 3588 // In C++11, we pick #1 as the best viable function, because ellipsis 3589 // conversion is better than string-literal to char* conversion (since there 3590 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3591 // convert arguments, #2 would be the best viable function in C++11. 3592 // If the best viable function has this conversion, a warning will be issued 3593 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3594 3595 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3596 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3597 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3598 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3599 ? ImplicitConversionSequence::Worse 3600 : ImplicitConversionSequence::Better; 3601 3602 if (ICS1.getKindRank() < ICS2.getKindRank()) 3603 return ImplicitConversionSequence::Better; 3604 if (ICS2.getKindRank() < ICS1.getKindRank()) 3605 return ImplicitConversionSequence::Worse; 3606 3607 // The following checks require both conversion sequences to be of 3608 // the same kind. 3609 if (ICS1.getKind() != ICS2.getKind()) 3610 return ImplicitConversionSequence::Indistinguishable; 3611 3612 ImplicitConversionSequence::CompareKind Result = 3613 ImplicitConversionSequence::Indistinguishable; 3614 3615 // Two implicit conversion sequences of the same form are 3616 // indistinguishable conversion sequences unless one of the 3617 // following rules apply: (C++ 13.3.3.2p3): 3618 3619 // List-initialization sequence L1 is a better conversion sequence than 3620 // list-initialization sequence L2 if: 3621 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3622 // if not that, 3623 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3624 // and N1 is smaller than N2., 3625 // even if one of the other rules in this paragraph would otherwise apply. 3626 if (!ICS1.isBad()) { 3627 if (ICS1.isStdInitializerListElement() && 3628 !ICS2.isStdInitializerListElement()) 3629 return ImplicitConversionSequence::Better; 3630 if (!ICS1.isStdInitializerListElement() && 3631 ICS2.isStdInitializerListElement()) 3632 return ImplicitConversionSequence::Worse; 3633 } 3634 3635 if (ICS1.isStandard()) 3636 // Standard conversion sequence S1 is a better conversion sequence than 3637 // standard conversion sequence S2 if [...] 3638 Result = CompareStandardConversionSequences(S, Loc, 3639 ICS1.Standard, ICS2.Standard); 3640 else if (ICS1.isUserDefined()) { 3641 // User-defined conversion sequence U1 is a better conversion 3642 // sequence than another user-defined conversion sequence U2 if 3643 // they contain the same user-defined conversion function or 3644 // constructor and if the second standard conversion sequence of 3645 // U1 is better than the second standard conversion sequence of 3646 // U2 (C++ 13.3.3.2p3). 3647 if (ICS1.UserDefined.ConversionFunction == 3648 ICS2.UserDefined.ConversionFunction) 3649 Result = CompareStandardConversionSequences(S, Loc, 3650 ICS1.UserDefined.After, 3651 ICS2.UserDefined.After); 3652 else 3653 Result = compareConversionFunctions(S, 3654 ICS1.UserDefined.ConversionFunction, 3655 ICS2.UserDefined.ConversionFunction); 3656 } 3657 3658 return Result; 3659 } 3660 3661 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3662 // determine if one is a proper subset of the other. 3663 static ImplicitConversionSequence::CompareKind 3664 compareStandardConversionSubsets(ASTContext &Context, 3665 const StandardConversionSequence& SCS1, 3666 const StandardConversionSequence& SCS2) { 3667 ImplicitConversionSequence::CompareKind Result 3668 = ImplicitConversionSequence::Indistinguishable; 3669 3670 // the identity conversion sequence is considered to be a subsequence of 3671 // any non-identity conversion sequence 3672 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3673 return ImplicitConversionSequence::Better; 3674 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3675 return ImplicitConversionSequence::Worse; 3676 3677 if (SCS1.Second != SCS2.Second) { 3678 if (SCS1.Second == ICK_Identity) 3679 Result = ImplicitConversionSequence::Better; 3680 else if (SCS2.Second == ICK_Identity) 3681 Result = ImplicitConversionSequence::Worse; 3682 else 3683 return ImplicitConversionSequence::Indistinguishable; 3684 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3685 return ImplicitConversionSequence::Indistinguishable; 3686 3687 if (SCS1.Third == SCS2.Third) { 3688 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3689 : ImplicitConversionSequence::Indistinguishable; 3690 } 3691 3692 if (SCS1.Third == ICK_Identity) 3693 return Result == ImplicitConversionSequence::Worse 3694 ? ImplicitConversionSequence::Indistinguishable 3695 : ImplicitConversionSequence::Better; 3696 3697 if (SCS2.Third == ICK_Identity) 3698 return Result == ImplicitConversionSequence::Better 3699 ? ImplicitConversionSequence::Indistinguishable 3700 : ImplicitConversionSequence::Worse; 3701 3702 return ImplicitConversionSequence::Indistinguishable; 3703 } 3704 3705 /// Determine whether one of the given reference bindings is better 3706 /// than the other based on what kind of bindings they are. 3707 static bool 3708 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3709 const StandardConversionSequence &SCS2) { 3710 // C++0x [over.ics.rank]p3b4: 3711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3712 // implicit object parameter of a non-static member function declared 3713 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3715 // lvalue reference to a function lvalue and S2 binds an rvalue 3716 // reference*. 3717 // 3718 // FIXME: Rvalue references. We're going rogue with the above edits, 3719 // because the semantics in the current C++0x working paper (N3225 at the 3720 // time of this writing) break the standard definition of std::forward 3721 // and std::reference_wrapper when dealing with references to functions. 3722 // Proposed wording changes submitted to CWG for consideration. 3723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3725 return false; 3726 3727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3728 SCS2.IsLvalueReference) || 3729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3730 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3731 } 3732 3733 /// CompareStandardConversionSequences - Compare two standard 3734 /// conversion sequences to determine whether one is better than the 3735 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3736 static ImplicitConversionSequence::CompareKind 3737 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3738 const StandardConversionSequence& SCS1, 3739 const StandardConversionSequence& SCS2) 3740 { 3741 // Standard conversion sequence S1 is a better conversion sequence 3742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3743 3744 // -- S1 is a proper subsequence of S2 (comparing the conversion 3745 // sequences in the canonical form defined by 13.3.3.1.1, 3746 // excluding any Lvalue Transformation; the identity conversion 3747 // sequence is considered to be a subsequence of any 3748 // non-identity conversion sequence) or, if not that, 3749 if (ImplicitConversionSequence::CompareKind CK 3750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3751 return CK; 3752 3753 // -- the rank of S1 is better than the rank of S2 (by the rules 3754 // defined below), or, if not that, 3755 ImplicitConversionRank Rank1 = SCS1.getRank(); 3756 ImplicitConversionRank Rank2 = SCS2.getRank(); 3757 if (Rank1 < Rank2) 3758 return ImplicitConversionSequence::Better; 3759 else if (Rank2 < Rank1) 3760 return ImplicitConversionSequence::Worse; 3761 3762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3763 // are indistinguishable unless one of the following rules 3764 // applies: 3765 3766 // A conversion that is not a conversion of a pointer, or 3767 // pointer to member, to bool is better than another conversion 3768 // that is such a conversion. 3769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3770 return SCS2.isPointerConversionToBool() 3771 ? ImplicitConversionSequence::Better 3772 : ImplicitConversionSequence::Worse; 3773 3774 // C++ [over.ics.rank]p4b2: 3775 // 3776 // If class B is derived directly or indirectly from class A, 3777 // conversion of B* to A* is better than conversion of B* to 3778 // void*, and conversion of A* to void* is better than conversion 3779 // of B* to void*. 3780 bool SCS1ConvertsToVoid 3781 = SCS1.isPointerConversionToVoidPointer(S.Context); 3782 bool SCS2ConvertsToVoid 3783 = SCS2.isPointerConversionToVoidPointer(S.Context); 3784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3785 // Exactly one of the conversion sequences is a conversion to 3786 // a void pointer; it's the worse conversion. 3787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3788 : ImplicitConversionSequence::Worse; 3789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3790 // Neither conversion sequence converts to a void pointer; compare 3791 // their derived-to-base conversions. 3792 if (ImplicitConversionSequence::CompareKind DerivedCK 3793 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3794 return DerivedCK; 3795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3797 // Both conversion sequences are conversions to void 3798 // pointers. Compare the source types to determine if there's an 3799 // inheritance relationship in their sources. 3800 QualType FromType1 = SCS1.getFromType(); 3801 QualType FromType2 = SCS2.getFromType(); 3802 3803 // Adjust the types we're converting from via the array-to-pointer 3804 // conversion, if we need to. 3805 if (SCS1.First == ICK_Array_To_Pointer) 3806 FromType1 = S.Context.getArrayDecayedType(FromType1); 3807 if (SCS2.First == ICK_Array_To_Pointer) 3808 FromType2 = S.Context.getArrayDecayedType(FromType2); 3809 3810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3812 3813 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3814 return ImplicitConversionSequence::Better; 3815 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3816 return ImplicitConversionSequence::Worse; 3817 3818 // Objective-C++: If one interface is more specific than the 3819 // other, it is the better one. 3820 const ObjCObjectPointerType* FromObjCPtr1 3821 = FromType1->getAs<ObjCObjectPointerType>(); 3822 const ObjCObjectPointerType* FromObjCPtr2 3823 = FromType2->getAs<ObjCObjectPointerType>(); 3824 if (FromObjCPtr1 && FromObjCPtr2) { 3825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3826 FromObjCPtr2); 3827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3828 FromObjCPtr1); 3829 if (AssignLeft != AssignRight) { 3830 return AssignLeft? ImplicitConversionSequence::Better 3831 : ImplicitConversionSequence::Worse; 3832 } 3833 } 3834 } 3835 3836 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3837 // bullet 3). 3838 if (ImplicitConversionSequence::CompareKind QualCK 3839 = CompareQualificationConversions(S, SCS1, SCS2)) 3840 return QualCK; 3841 3842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3843 // Check for a better reference binding based on the kind of bindings. 3844 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3845 return ImplicitConversionSequence::Better; 3846 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3847 return ImplicitConversionSequence::Worse; 3848 3849 // C++ [over.ics.rank]p3b4: 3850 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3851 // which the references refer are the same type except for 3852 // top-level cv-qualifiers, and the type to which the reference 3853 // initialized by S2 refers is more cv-qualified than the type 3854 // to which the reference initialized by S1 refers. 3855 QualType T1 = SCS1.getToType(2); 3856 QualType T2 = SCS2.getToType(2); 3857 T1 = S.Context.getCanonicalType(T1); 3858 T2 = S.Context.getCanonicalType(T2); 3859 Qualifiers T1Quals, T2Quals; 3860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3862 if (UnqualT1 == UnqualT2) { 3863 // Objective-C++ ARC: If the references refer to objects with different 3864 // lifetimes, prefer bindings that don't change lifetime. 3865 if (SCS1.ObjCLifetimeConversionBinding != 3866 SCS2.ObjCLifetimeConversionBinding) { 3867 return SCS1.ObjCLifetimeConversionBinding 3868 ? ImplicitConversionSequence::Worse 3869 : ImplicitConversionSequence::Better; 3870 } 3871 3872 // If the type is an array type, promote the element qualifiers to the 3873 // type for comparison. 3874 if (isa<ArrayType>(T1) && T1Quals) 3875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3876 if (isa<ArrayType>(T2) && T2Quals) 3877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3878 if (T2.isMoreQualifiedThan(T1)) 3879 return ImplicitConversionSequence::Better; 3880 else if (T1.isMoreQualifiedThan(T2)) 3881 return ImplicitConversionSequence::Worse; 3882 } 3883 } 3884 3885 // In Microsoft mode, prefer an integral conversion to a 3886 // floating-to-integral conversion if the integral conversion 3887 // is between types of the same size. 3888 // For example: 3889 // void f(float); 3890 // void f(int); 3891 // int main { 3892 // long a; 3893 // f(a); 3894 // } 3895 // Here, MSVC will call f(int) instead of generating a compile error 3896 // as clang will do in standard mode. 3897 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3898 SCS2.Second == ICK_Floating_Integral && 3899 S.Context.getTypeSize(SCS1.getFromType()) == 3900 S.Context.getTypeSize(SCS1.getToType(2))) 3901 return ImplicitConversionSequence::Better; 3902 3903 // Prefer a compatible vector conversion over a lax vector conversion 3904 // For example: 3905 // 3906 // typedef float __v4sf __attribute__((__vector_size__(16))); 3907 // void f(vector float); 3908 // void f(vector signed int); 3909 // int main() { 3910 // __v4sf a; 3911 // f(a); 3912 // } 3913 // Here, we'd like to choose f(vector float) and not 3914 // report an ambiguous call error 3915 if (SCS1.Second == ICK_Vector_Conversion && 3916 SCS2.Second == ICK_Vector_Conversion) { 3917 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3918 SCS1.getFromType(), SCS1.getToType(2)); 3919 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3920 SCS2.getFromType(), SCS2.getToType(2)); 3921 3922 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3923 return SCS1IsCompatibleVectorConversion 3924 ? ImplicitConversionSequence::Better 3925 : ImplicitConversionSequence::Worse; 3926 } 3927 3928 return ImplicitConversionSequence::Indistinguishable; 3929 } 3930 3931 /// CompareQualificationConversions - Compares two standard conversion 3932 /// sequences to determine whether they can be ranked based on their 3933 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3934 static ImplicitConversionSequence::CompareKind 3935 CompareQualificationConversions(Sema &S, 3936 const StandardConversionSequence& SCS1, 3937 const StandardConversionSequence& SCS2) { 3938 // C++ 13.3.3.2p3: 3939 // -- S1 and S2 differ only in their qualification conversion and 3940 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3941 // cv-qualification signature of type T1 is a proper subset of 3942 // the cv-qualification signature of type T2, and S1 is not the 3943 // deprecated string literal array-to-pointer conversion (4.2). 3944 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3945 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3946 return ImplicitConversionSequence::Indistinguishable; 3947 3948 // FIXME: the example in the standard doesn't use a qualification 3949 // conversion (!) 3950 QualType T1 = SCS1.getToType(2); 3951 QualType T2 = SCS2.getToType(2); 3952 T1 = S.Context.getCanonicalType(T1); 3953 T2 = S.Context.getCanonicalType(T2); 3954 Qualifiers T1Quals, T2Quals; 3955 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3956 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3957 3958 // If the types are the same, we won't learn anything by unwrapped 3959 // them. 3960 if (UnqualT1 == UnqualT2) 3961 return ImplicitConversionSequence::Indistinguishable; 3962 3963 // If the type is an array type, promote the element qualifiers to the type 3964 // for comparison. 3965 if (isa<ArrayType>(T1) && T1Quals) 3966 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3967 if (isa<ArrayType>(T2) && T2Quals) 3968 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3969 3970 ImplicitConversionSequence::CompareKind Result 3971 = ImplicitConversionSequence::Indistinguishable; 3972 3973 // Objective-C++ ARC: 3974 // Prefer qualification conversions not involving a change in lifetime 3975 // to qualification conversions that do not change lifetime. 3976 if (SCS1.QualificationIncludesObjCLifetime != 3977 SCS2.QualificationIncludesObjCLifetime) { 3978 Result = SCS1.QualificationIncludesObjCLifetime 3979 ? ImplicitConversionSequence::Worse 3980 : ImplicitConversionSequence::Better; 3981 } 3982 3983 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 3984 // Within each iteration of the loop, we check the qualifiers to 3985 // determine if this still looks like a qualification 3986 // conversion. Then, if all is well, we unwrap one more level of 3987 // pointers or pointers-to-members and do it all again 3988 // until there are no more pointers or pointers-to-members left 3989 // to unwrap. This essentially mimics what 3990 // IsQualificationConversion does, but here we're checking for a 3991 // strict subset of qualifiers. 3992 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3993 // The qualifiers are the same, so this doesn't tell us anything 3994 // about how the sequences rank. 3995 ; 3996 else if (T2.isMoreQualifiedThan(T1)) { 3997 // T1 has fewer qualifiers, so it could be the better sequence. 3998 if (Result == ImplicitConversionSequence::Worse) 3999 // Neither has qualifiers that are a subset of the other's 4000 // qualifiers. 4001 return ImplicitConversionSequence::Indistinguishable; 4002 4003 Result = ImplicitConversionSequence::Better; 4004 } else if (T1.isMoreQualifiedThan(T2)) { 4005 // T2 has fewer qualifiers, so it could be the better sequence. 4006 if (Result == ImplicitConversionSequence::Better) 4007 // Neither has qualifiers that are a subset of the other's 4008 // qualifiers. 4009 return ImplicitConversionSequence::Indistinguishable; 4010 4011 Result = ImplicitConversionSequence::Worse; 4012 } else { 4013 // Qualifiers are disjoint. 4014 return ImplicitConversionSequence::Indistinguishable; 4015 } 4016 4017 // If the types after this point are equivalent, we're done. 4018 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4019 break; 4020 } 4021 4022 // Check that the winning standard conversion sequence isn't using 4023 // the deprecated string literal array to pointer conversion. 4024 switch (Result) { 4025 case ImplicitConversionSequence::Better: 4026 if (SCS1.DeprecatedStringLiteralToCharPtr) 4027 Result = ImplicitConversionSequence::Indistinguishable; 4028 break; 4029 4030 case ImplicitConversionSequence::Indistinguishable: 4031 break; 4032 4033 case ImplicitConversionSequence::Worse: 4034 if (SCS2.DeprecatedStringLiteralToCharPtr) 4035 Result = ImplicitConversionSequence::Indistinguishable; 4036 break; 4037 } 4038 4039 return Result; 4040 } 4041 4042 /// CompareDerivedToBaseConversions - Compares two standard conversion 4043 /// sequences to determine whether they can be ranked based on their 4044 /// various kinds of derived-to-base conversions (C++ 4045 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4046 /// conversions between Objective-C interface types. 4047 static ImplicitConversionSequence::CompareKind 4048 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4049 const StandardConversionSequence& SCS1, 4050 const StandardConversionSequence& SCS2) { 4051 QualType FromType1 = SCS1.getFromType(); 4052 QualType ToType1 = SCS1.getToType(1); 4053 QualType FromType2 = SCS2.getFromType(); 4054 QualType ToType2 = SCS2.getToType(1); 4055 4056 // Adjust the types we're converting from via the array-to-pointer 4057 // conversion, if we need to. 4058 if (SCS1.First == ICK_Array_To_Pointer) 4059 FromType1 = S.Context.getArrayDecayedType(FromType1); 4060 if (SCS2.First == ICK_Array_To_Pointer) 4061 FromType2 = S.Context.getArrayDecayedType(FromType2); 4062 4063 // Canonicalize all of the types. 4064 FromType1 = S.Context.getCanonicalType(FromType1); 4065 ToType1 = S.Context.getCanonicalType(ToType1); 4066 FromType2 = S.Context.getCanonicalType(FromType2); 4067 ToType2 = S.Context.getCanonicalType(ToType2); 4068 4069 // C++ [over.ics.rank]p4b3: 4070 // 4071 // If class B is derived directly or indirectly from class A and 4072 // class C is derived directly or indirectly from B, 4073 // 4074 // Compare based on pointer conversions. 4075 if (SCS1.Second == ICK_Pointer_Conversion && 4076 SCS2.Second == ICK_Pointer_Conversion && 4077 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4078 FromType1->isPointerType() && FromType2->isPointerType() && 4079 ToType1->isPointerType() && ToType2->isPointerType()) { 4080 QualType FromPointee1 4081 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4082 QualType ToPointee1 4083 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4084 QualType FromPointee2 4085 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4086 QualType ToPointee2 4087 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4088 4089 // -- conversion of C* to B* is better than conversion of C* to A*, 4090 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4091 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4092 return ImplicitConversionSequence::Better; 4093 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4094 return ImplicitConversionSequence::Worse; 4095 } 4096 4097 // -- conversion of B* to A* is better than conversion of C* to A*, 4098 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4099 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4100 return ImplicitConversionSequence::Better; 4101 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4102 return ImplicitConversionSequence::Worse; 4103 } 4104 } else if (SCS1.Second == ICK_Pointer_Conversion && 4105 SCS2.Second == ICK_Pointer_Conversion) { 4106 const ObjCObjectPointerType *FromPtr1 4107 = FromType1->getAs<ObjCObjectPointerType>(); 4108 const ObjCObjectPointerType *FromPtr2 4109 = FromType2->getAs<ObjCObjectPointerType>(); 4110 const ObjCObjectPointerType *ToPtr1 4111 = ToType1->getAs<ObjCObjectPointerType>(); 4112 const ObjCObjectPointerType *ToPtr2 4113 = ToType2->getAs<ObjCObjectPointerType>(); 4114 4115 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4116 // Apply the same conversion ranking rules for Objective-C pointer types 4117 // that we do for C++ pointers to class types. However, we employ the 4118 // Objective-C pseudo-subtyping relationship used for assignment of 4119 // Objective-C pointer types. 4120 bool FromAssignLeft 4121 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4122 bool FromAssignRight 4123 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4124 bool ToAssignLeft 4125 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4126 bool ToAssignRight 4127 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4128 4129 // A conversion to an a non-id object pointer type or qualified 'id' 4130 // type is better than a conversion to 'id'. 4131 if (ToPtr1->isObjCIdType() && 4132 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4133 return ImplicitConversionSequence::Worse; 4134 if (ToPtr2->isObjCIdType() && 4135 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4136 return ImplicitConversionSequence::Better; 4137 4138 // A conversion to a non-id object pointer type is better than a 4139 // conversion to a qualified 'id' type 4140 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4141 return ImplicitConversionSequence::Worse; 4142 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4143 return ImplicitConversionSequence::Better; 4144 4145 // A conversion to an a non-Class object pointer type or qualified 'Class' 4146 // type is better than a conversion to 'Class'. 4147 if (ToPtr1->isObjCClassType() && 4148 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4149 return ImplicitConversionSequence::Worse; 4150 if (ToPtr2->isObjCClassType() && 4151 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4152 return ImplicitConversionSequence::Better; 4153 4154 // A conversion to a non-Class object pointer type is better than a 4155 // conversion to a qualified 'Class' type. 4156 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4157 return ImplicitConversionSequence::Worse; 4158 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4159 return ImplicitConversionSequence::Better; 4160 4161 // -- "conversion of C* to B* is better than conversion of C* to A*," 4162 if (S.Context.hasSameType(FromType1, FromType2) && 4163 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4164 (ToAssignLeft != ToAssignRight)) { 4165 if (FromPtr1->isSpecialized()) { 4166 // "conversion of B<A> * to B * is better than conversion of B * to 4167 // C *. 4168 bool IsFirstSame = 4169 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4170 bool IsSecondSame = 4171 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4172 if (IsFirstSame) { 4173 if (!IsSecondSame) 4174 return ImplicitConversionSequence::Better; 4175 } else if (IsSecondSame) 4176 return ImplicitConversionSequence::Worse; 4177 } 4178 return ToAssignLeft? ImplicitConversionSequence::Worse 4179 : ImplicitConversionSequence::Better; 4180 } 4181 4182 // -- "conversion of B* to A* is better than conversion of C* to A*," 4183 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4184 (FromAssignLeft != FromAssignRight)) 4185 return FromAssignLeft? ImplicitConversionSequence::Better 4186 : ImplicitConversionSequence::Worse; 4187 } 4188 } 4189 4190 // Ranking of member-pointer types. 4191 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4192 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4193 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4194 const MemberPointerType * FromMemPointer1 = 4195 FromType1->getAs<MemberPointerType>(); 4196 const MemberPointerType * ToMemPointer1 = 4197 ToType1->getAs<MemberPointerType>(); 4198 const MemberPointerType * FromMemPointer2 = 4199 FromType2->getAs<MemberPointerType>(); 4200 const MemberPointerType * ToMemPointer2 = 4201 ToType2->getAs<MemberPointerType>(); 4202 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4203 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4204 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4205 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4206 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4207 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4208 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4209 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4210 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4211 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4212 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4213 return ImplicitConversionSequence::Worse; 4214 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4215 return ImplicitConversionSequence::Better; 4216 } 4217 // conversion of B::* to C::* is better than conversion of A::* to C::* 4218 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4219 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4220 return ImplicitConversionSequence::Better; 4221 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4222 return ImplicitConversionSequence::Worse; 4223 } 4224 } 4225 4226 if (SCS1.Second == ICK_Derived_To_Base) { 4227 // -- conversion of C to B is better than conversion of C to A, 4228 // -- binding of an expression of type C to a reference of type 4229 // B& is better than binding an expression of type C to a 4230 // reference of type A&, 4231 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4232 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4233 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4234 return ImplicitConversionSequence::Better; 4235 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4236 return ImplicitConversionSequence::Worse; 4237 } 4238 4239 // -- conversion of B to A is better than conversion of C to A. 4240 // -- binding of an expression of type B to a reference of type 4241 // A& is better than binding an expression of type C to a 4242 // reference of type A&, 4243 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4244 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4245 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4246 return ImplicitConversionSequence::Better; 4247 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4248 return ImplicitConversionSequence::Worse; 4249 } 4250 } 4251 4252 return ImplicitConversionSequence::Indistinguishable; 4253 } 4254 4255 /// Determine whether the given type is valid, e.g., it is not an invalid 4256 /// C++ class. 4257 static bool isTypeValid(QualType T) { 4258 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4259 return !Record->isInvalidDecl(); 4260 4261 return true; 4262 } 4263 4264 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4265 /// determine whether they are reference-related, 4266 /// reference-compatible, reference-compatible with added 4267 /// qualification, or incompatible, for use in C++ initialization by 4268 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4269 /// type, and the first type (T1) is the pointee type of the reference 4270 /// type being initialized. 4271 Sema::ReferenceCompareResult 4272 Sema::CompareReferenceRelationship(SourceLocation Loc, 4273 QualType OrigT1, QualType OrigT2, 4274 bool &DerivedToBase, 4275 bool &ObjCConversion, 4276 bool &ObjCLifetimeConversion) { 4277 assert(!OrigT1->isReferenceType() && 4278 "T1 must be the pointee type of the reference type"); 4279 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4280 4281 QualType T1 = Context.getCanonicalType(OrigT1); 4282 QualType T2 = Context.getCanonicalType(OrigT2); 4283 Qualifiers T1Quals, T2Quals; 4284 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4285 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4286 4287 // C++ [dcl.init.ref]p4: 4288 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4289 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4290 // T1 is a base class of T2. 4291 DerivedToBase = false; 4292 ObjCConversion = false; 4293 ObjCLifetimeConversion = false; 4294 QualType ConvertedT2; 4295 if (UnqualT1 == UnqualT2) { 4296 // Nothing to do. 4297 } else if (isCompleteType(Loc, OrigT2) && 4298 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4299 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4300 DerivedToBase = true; 4301 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4302 UnqualT2->isObjCObjectOrInterfaceType() && 4303 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4304 ObjCConversion = true; 4305 else if (UnqualT2->isFunctionType() && 4306 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4307 // C++1z [dcl.init.ref]p4: 4308 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4309 // function" and T1 is "function" 4310 // 4311 // We extend this to also apply to 'noreturn', so allow any function 4312 // conversion between function types. 4313 return Ref_Compatible; 4314 else 4315 return Ref_Incompatible; 4316 4317 // At this point, we know that T1 and T2 are reference-related (at 4318 // least). 4319 4320 // If the type is an array type, promote the element qualifiers to the type 4321 // for comparison. 4322 if (isa<ArrayType>(T1) && T1Quals) 4323 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4324 if (isa<ArrayType>(T2) && T2Quals) 4325 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4326 4327 // C++ [dcl.init.ref]p4: 4328 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4329 // reference-related to T2 and cv1 is the same cv-qualification 4330 // as, or greater cv-qualification than, cv2. For purposes of 4331 // overload resolution, cases for which cv1 is greater 4332 // cv-qualification than cv2 are identified as 4333 // reference-compatible with added qualification (see 13.3.3.2). 4334 // 4335 // Note that we also require equivalence of Objective-C GC and address-space 4336 // qualifiers when performing these computations, so that e.g., an int in 4337 // address space 1 is not reference-compatible with an int in address 4338 // space 2. 4339 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4340 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4341 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4342 ObjCLifetimeConversion = true; 4343 4344 T1Quals.removeObjCLifetime(); 4345 T2Quals.removeObjCLifetime(); 4346 } 4347 4348 // MS compiler ignores __unaligned qualifier for references; do the same. 4349 T1Quals.removeUnaligned(); 4350 T2Quals.removeUnaligned(); 4351 4352 if (T1Quals.compatiblyIncludes(T2Quals)) 4353 return Ref_Compatible; 4354 else 4355 return Ref_Related; 4356 } 4357 4358 /// Look for a user-defined conversion to a value reference-compatible 4359 /// with DeclType. Return true if something definite is found. 4360 static bool 4361 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4362 QualType DeclType, SourceLocation DeclLoc, 4363 Expr *Init, QualType T2, bool AllowRvalues, 4364 bool AllowExplicit) { 4365 assert(T2->isRecordType() && "Can only find conversions of record types."); 4366 CXXRecordDecl *T2RecordDecl 4367 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4368 4369 OverloadCandidateSet CandidateSet( 4370 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4371 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4372 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4373 NamedDecl *D = *I; 4374 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4375 if (isa<UsingShadowDecl>(D)) 4376 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4377 4378 FunctionTemplateDecl *ConvTemplate 4379 = dyn_cast<FunctionTemplateDecl>(D); 4380 CXXConversionDecl *Conv; 4381 if (ConvTemplate) 4382 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4383 else 4384 Conv = cast<CXXConversionDecl>(D); 4385 4386 // If this is an explicit conversion, and we're not allowed to consider 4387 // explicit conversions, skip it. 4388 if (!AllowExplicit && Conv->isExplicit()) 4389 continue; 4390 4391 if (AllowRvalues) { 4392 bool DerivedToBase = false; 4393 bool ObjCConversion = false; 4394 bool ObjCLifetimeConversion = false; 4395 4396 // If we are initializing an rvalue reference, don't permit conversion 4397 // functions that return lvalues. 4398 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4399 const ReferenceType *RefType 4400 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4401 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4402 continue; 4403 } 4404 4405 if (!ConvTemplate && 4406 S.CompareReferenceRelationship( 4407 DeclLoc, 4408 Conv->getConversionType().getNonReferenceType() 4409 .getUnqualifiedType(), 4410 DeclType.getNonReferenceType().getUnqualifiedType(), 4411 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4412 Sema::Ref_Incompatible) 4413 continue; 4414 } else { 4415 // If the conversion function doesn't return a reference type, 4416 // it can't be considered for this conversion. An rvalue reference 4417 // is only acceptable if its referencee is a function type. 4418 4419 const ReferenceType *RefType = 4420 Conv->getConversionType()->getAs<ReferenceType>(); 4421 if (!RefType || 4422 (!RefType->isLValueReferenceType() && 4423 !RefType->getPointeeType()->isFunctionType())) 4424 continue; 4425 } 4426 4427 if (ConvTemplate) 4428 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4429 Init, DeclType, CandidateSet, 4430 /*AllowObjCConversionOnExplicit=*/false); 4431 else 4432 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4433 DeclType, CandidateSet, 4434 /*AllowObjCConversionOnExplicit=*/false); 4435 } 4436 4437 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4438 4439 OverloadCandidateSet::iterator Best; 4440 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4441 case OR_Success: 4442 // C++ [over.ics.ref]p1: 4443 // 4444 // [...] If the parameter binds directly to the result of 4445 // applying a conversion function to the argument 4446 // expression, the implicit conversion sequence is a 4447 // user-defined conversion sequence (13.3.3.1.2), with the 4448 // second standard conversion sequence either an identity 4449 // conversion or, if the conversion function returns an 4450 // entity of a type that is a derived class of the parameter 4451 // type, a derived-to-base Conversion. 4452 if (!Best->FinalConversion.DirectBinding) 4453 return false; 4454 4455 ICS.setUserDefined(); 4456 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4457 ICS.UserDefined.After = Best->FinalConversion; 4458 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4459 ICS.UserDefined.ConversionFunction = Best->Function; 4460 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4461 ICS.UserDefined.EllipsisConversion = false; 4462 assert(ICS.UserDefined.After.ReferenceBinding && 4463 ICS.UserDefined.After.DirectBinding && 4464 "Expected a direct reference binding!"); 4465 return true; 4466 4467 case OR_Ambiguous: 4468 ICS.setAmbiguous(); 4469 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4470 Cand != CandidateSet.end(); ++Cand) 4471 if (Cand->Viable) 4472 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4473 return true; 4474 4475 case OR_No_Viable_Function: 4476 case OR_Deleted: 4477 // There was no suitable conversion, or we found a deleted 4478 // conversion; continue with other checks. 4479 return false; 4480 } 4481 4482 llvm_unreachable("Invalid OverloadResult!"); 4483 } 4484 4485 /// Compute an implicit conversion sequence for reference 4486 /// initialization. 4487 static ImplicitConversionSequence 4488 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4489 SourceLocation DeclLoc, 4490 bool SuppressUserConversions, 4491 bool AllowExplicit) { 4492 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4493 4494 // Most paths end in a failed conversion. 4495 ImplicitConversionSequence ICS; 4496 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4497 4498 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4499 QualType T2 = Init->getType(); 4500 4501 // If the initializer is the address of an overloaded function, try 4502 // to resolve the overloaded function. If all goes well, T2 is the 4503 // type of the resulting function. 4504 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4505 DeclAccessPair Found; 4506 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4507 false, Found)) 4508 T2 = Fn->getType(); 4509 } 4510 4511 // Compute some basic properties of the types and the initializer. 4512 bool isRValRef = DeclType->isRValueReferenceType(); 4513 bool DerivedToBase = false; 4514 bool ObjCConversion = false; 4515 bool ObjCLifetimeConversion = false; 4516 Expr::Classification InitCategory = Init->Classify(S.Context); 4517 Sema::ReferenceCompareResult RefRelationship 4518 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4519 ObjCConversion, ObjCLifetimeConversion); 4520 4521 4522 // C++0x [dcl.init.ref]p5: 4523 // A reference to type "cv1 T1" is initialized by an expression 4524 // of type "cv2 T2" as follows: 4525 4526 // -- If reference is an lvalue reference and the initializer expression 4527 if (!isRValRef) { 4528 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4529 // reference-compatible with "cv2 T2," or 4530 // 4531 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4532 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4533 // C++ [over.ics.ref]p1: 4534 // When a parameter of reference type binds directly (8.5.3) 4535 // to an argument expression, the implicit conversion sequence 4536 // is the identity conversion, unless the argument expression 4537 // has a type that is a derived class of the parameter type, 4538 // in which case the implicit conversion sequence is a 4539 // derived-to-base Conversion (13.3.3.1). 4540 ICS.setStandard(); 4541 ICS.Standard.First = ICK_Identity; 4542 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4543 : ObjCConversion? ICK_Compatible_Conversion 4544 : ICK_Identity; 4545 ICS.Standard.Third = ICK_Identity; 4546 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4547 ICS.Standard.setToType(0, T2); 4548 ICS.Standard.setToType(1, T1); 4549 ICS.Standard.setToType(2, T1); 4550 ICS.Standard.ReferenceBinding = true; 4551 ICS.Standard.DirectBinding = true; 4552 ICS.Standard.IsLvalueReference = !isRValRef; 4553 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4554 ICS.Standard.BindsToRvalue = false; 4555 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4556 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4557 ICS.Standard.CopyConstructor = nullptr; 4558 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4559 4560 // Nothing more to do: the inaccessibility/ambiguity check for 4561 // derived-to-base conversions is suppressed when we're 4562 // computing the implicit conversion sequence (C++ 4563 // [over.best.ics]p2). 4564 return ICS; 4565 } 4566 4567 // -- has a class type (i.e., T2 is a class type), where T1 is 4568 // not reference-related to T2, and can be implicitly 4569 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4570 // is reference-compatible with "cv3 T3" 92) (this 4571 // conversion is selected by enumerating the applicable 4572 // conversion functions (13.3.1.6) and choosing the best 4573 // one through overload resolution (13.3)), 4574 if (!SuppressUserConversions && T2->isRecordType() && 4575 S.isCompleteType(DeclLoc, T2) && 4576 RefRelationship == Sema::Ref_Incompatible) { 4577 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4578 Init, T2, /*AllowRvalues=*/false, 4579 AllowExplicit)) 4580 return ICS; 4581 } 4582 } 4583 4584 // -- Otherwise, the reference shall be an lvalue reference to a 4585 // non-volatile const type (i.e., cv1 shall be const), or the reference 4586 // shall be an rvalue reference. 4587 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4588 return ICS; 4589 4590 // -- If the initializer expression 4591 // 4592 // -- is an xvalue, class prvalue, array prvalue or function 4593 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4594 if (RefRelationship == Sema::Ref_Compatible && 4595 (InitCategory.isXValue() || 4596 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4597 (InitCategory.isLValue() && T2->isFunctionType()))) { 4598 ICS.setStandard(); 4599 ICS.Standard.First = ICK_Identity; 4600 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4601 : ObjCConversion? ICK_Compatible_Conversion 4602 : ICK_Identity; 4603 ICS.Standard.Third = ICK_Identity; 4604 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4605 ICS.Standard.setToType(0, T2); 4606 ICS.Standard.setToType(1, T1); 4607 ICS.Standard.setToType(2, T1); 4608 ICS.Standard.ReferenceBinding = true; 4609 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4610 // binding unless we're binding to a class prvalue. 4611 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4612 // allow the use of rvalue references in C++98/03 for the benefit of 4613 // standard library implementors; therefore, we need the xvalue check here. 4614 ICS.Standard.DirectBinding = 4615 S.getLangOpts().CPlusPlus11 || 4616 !(InitCategory.isPRValue() || T2->isRecordType()); 4617 ICS.Standard.IsLvalueReference = !isRValRef; 4618 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4619 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4620 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4621 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4622 ICS.Standard.CopyConstructor = nullptr; 4623 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4624 return ICS; 4625 } 4626 4627 // -- has a class type (i.e., T2 is a class type), where T1 is not 4628 // reference-related to T2, and can be implicitly converted to 4629 // an xvalue, class prvalue, or function lvalue of type 4630 // "cv3 T3", where "cv1 T1" is reference-compatible with 4631 // "cv3 T3", 4632 // 4633 // then the reference is bound to the value of the initializer 4634 // expression in the first case and to the result of the conversion 4635 // in the second case (or, in either case, to an appropriate base 4636 // class subobject). 4637 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4638 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4639 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4640 Init, T2, /*AllowRvalues=*/true, 4641 AllowExplicit)) { 4642 // In the second case, if the reference is an rvalue reference 4643 // and the second standard conversion sequence of the 4644 // user-defined conversion sequence includes an lvalue-to-rvalue 4645 // conversion, the program is ill-formed. 4646 if (ICS.isUserDefined() && isRValRef && 4647 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4648 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4649 4650 return ICS; 4651 } 4652 4653 // A temporary of function type cannot be created; don't even try. 4654 if (T1->isFunctionType()) 4655 return ICS; 4656 4657 // -- Otherwise, a temporary of type "cv1 T1" is created and 4658 // initialized from the initializer expression using the 4659 // rules for a non-reference copy initialization (8.5). The 4660 // reference is then bound to the temporary. If T1 is 4661 // reference-related to T2, cv1 must be the same 4662 // cv-qualification as, or greater cv-qualification than, 4663 // cv2; otherwise, the program is ill-formed. 4664 if (RefRelationship == Sema::Ref_Related) { 4665 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4666 // we would be reference-compatible or reference-compatible with 4667 // added qualification. But that wasn't the case, so the reference 4668 // initialization fails. 4669 // 4670 // Note that we only want to check address spaces and cvr-qualifiers here. 4671 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4672 Qualifiers T1Quals = T1.getQualifiers(); 4673 Qualifiers T2Quals = T2.getQualifiers(); 4674 T1Quals.removeObjCGCAttr(); 4675 T1Quals.removeObjCLifetime(); 4676 T2Quals.removeObjCGCAttr(); 4677 T2Quals.removeObjCLifetime(); 4678 // MS compiler ignores __unaligned qualifier for references; do the same. 4679 T1Quals.removeUnaligned(); 4680 T2Quals.removeUnaligned(); 4681 if (!T1Quals.compatiblyIncludes(T2Quals)) 4682 return ICS; 4683 } 4684 4685 // If at least one of the types is a class type, the types are not 4686 // related, and we aren't allowed any user conversions, the 4687 // reference binding fails. This case is important for breaking 4688 // recursion, since TryImplicitConversion below will attempt to 4689 // create a temporary through the use of a copy constructor. 4690 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4691 (T1->isRecordType() || T2->isRecordType())) 4692 return ICS; 4693 4694 // If T1 is reference-related to T2 and the reference is an rvalue 4695 // reference, the initializer expression shall not be an lvalue. 4696 if (RefRelationship >= Sema::Ref_Related && 4697 isRValRef && Init->Classify(S.Context).isLValue()) 4698 return ICS; 4699 4700 // C++ [over.ics.ref]p2: 4701 // When a parameter of reference type is not bound directly to 4702 // an argument expression, the conversion sequence is the one 4703 // required to convert the argument expression to the 4704 // underlying type of the reference according to 4705 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4706 // to copy-initializing a temporary of the underlying type with 4707 // the argument expression. Any difference in top-level 4708 // cv-qualification is subsumed by the initialization itself 4709 // and does not constitute a conversion. 4710 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4711 /*AllowExplicit=*/false, 4712 /*InOverloadResolution=*/false, 4713 /*CStyle=*/false, 4714 /*AllowObjCWritebackConversion=*/false, 4715 /*AllowObjCConversionOnExplicit=*/false); 4716 4717 // Of course, that's still a reference binding. 4718 if (ICS.isStandard()) { 4719 ICS.Standard.ReferenceBinding = true; 4720 ICS.Standard.IsLvalueReference = !isRValRef; 4721 ICS.Standard.BindsToFunctionLvalue = false; 4722 ICS.Standard.BindsToRvalue = true; 4723 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4724 ICS.Standard.ObjCLifetimeConversionBinding = false; 4725 } else if (ICS.isUserDefined()) { 4726 const ReferenceType *LValRefType = 4727 ICS.UserDefined.ConversionFunction->getReturnType() 4728 ->getAs<LValueReferenceType>(); 4729 4730 // C++ [over.ics.ref]p3: 4731 // Except for an implicit object parameter, for which see 13.3.1, a 4732 // standard conversion sequence cannot be formed if it requires [...] 4733 // binding an rvalue reference to an lvalue other than a function 4734 // lvalue. 4735 // Note that the function case is not possible here. 4736 if (DeclType->isRValueReferenceType() && LValRefType) { 4737 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4738 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4739 // reference to an rvalue! 4740 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4741 return ICS; 4742 } 4743 4744 ICS.UserDefined.After.ReferenceBinding = true; 4745 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4746 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4747 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4748 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4749 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4750 } 4751 4752 return ICS; 4753 } 4754 4755 static ImplicitConversionSequence 4756 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4757 bool SuppressUserConversions, 4758 bool InOverloadResolution, 4759 bool AllowObjCWritebackConversion, 4760 bool AllowExplicit = false); 4761 4762 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4763 /// initializer list From. 4764 static ImplicitConversionSequence 4765 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4766 bool SuppressUserConversions, 4767 bool InOverloadResolution, 4768 bool AllowObjCWritebackConversion) { 4769 // C++11 [over.ics.list]p1: 4770 // When an argument is an initializer list, it is not an expression and 4771 // special rules apply for converting it to a parameter type. 4772 4773 ImplicitConversionSequence Result; 4774 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4775 4776 // We need a complete type for what follows. Incomplete types can never be 4777 // initialized from init lists. 4778 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4779 return Result; 4780 4781 // Per DR1467: 4782 // If the parameter type is a class X and the initializer list has a single 4783 // element of type cv U, where U is X or a class derived from X, the 4784 // implicit conversion sequence is the one required to convert the element 4785 // to the parameter type. 4786 // 4787 // Otherwise, if the parameter type is a character array [... ] 4788 // and the initializer list has a single element that is an 4789 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4790 // implicit conversion sequence is the identity conversion. 4791 if (From->getNumInits() == 1) { 4792 if (ToType->isRecordType()) { 4793 QualType InitType = From->getInit(0)->getType(); 4794 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4795 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4796 return TryCopyInitialization(S, From->getInit(0), ToType, 4797 SuppressUserConversions, 4798 InOverloadResolution, 4799 AllowObjCWritebackConversion); 4800 } 4801 // FIXME: Check the other conditions here: array of character type, 4802 // initializer is a string literal. 4803 if (ToType->isArrayType()) { 4804 InitializedEntity Entity = 4805 InitializedEntity::InitializeParameter(S.Context, ToType, 4806 /*Consumed=*/false); 4807 if (S.CanPerformCopyInitialization(Entity, From)) { 4808 Result.setStandard(); 4809 Result.Standard.setAsIdentityConversion(); 4810 Result.Standard.setFromType(ToType); 4811 Result.Standard.setAllToTypes(ToType); 4812 return Result; 4813 } 4814 } 4815 } 4816 4817 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4818 // C++11 [over.ics.list]p2: 4819 // If the parameter type is std::initializer_list<X> or "array of X" and 4820 // all the elements can be implicitly converted to X, the implicit 4821 // conversion sequence is the worst conversion necessary to convert an 4822 // element of the list to X. 4823 // 4824 // C++14 [over.ics.list]p3: 4825 // Otherwise, if the parameter type is "array of N X", if the initializer 4826 // list has exactly N elements or if it has fewer than N elements and X is 4827 // default-constructible, and if all the elements of the initializer list 4828 // can be implicitly converted to X, the implicit conversion sequence is 4829 // the worst conversion necessary to convert an element of the list to X. 4830 // 4831 // FIXME: We're missing a lot of these checks. 4832 bool toStdInitializerList = false; 4833 QualType X; 4834 if (ToType->isArrayType()) 4835 X = S.Context.getAsArrayType(ToType)->getElementType(); 4836 else 4837 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4838 if (!X.isNull()) { 4839 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4840 Expr *Init = From->getInit(i); 4841 ImplicitConversionSequence ICS = 4842 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4843 InOverloadResolution, 4844 AllowObjCWritebackConversion); 4845 // If a single element isn't convertible, fail. 4846 if (ICS.isBad()) { 4847 Result = ICS; 4848 break; 4849 } 4850 // Otherwise, look for the worst conversion. 4851 if (Result.isBad() || CompareImplicitConversionSequences( 4852 S, From->getBeginLoc(), ICS, Result) == 4853 ImplicitConversionSequence::Worse) 4854 Result = ICS; 4855 } 4856 4857 // For an empty list, we won't have computed any conversion sequence. 4858 // Introduce the identity conversion sequence. 4859 if (From->getNumInits() == 0) { 4860 Result.setStandard(); 4861 Result.Standard.setAsIdentityConversion(); 4862 Result.Standard.setFromType(ToType); 4863 Result.Standard.setAllToTypes(ToType); 4864 } 4865 4866 Result.setStdInitializerListElement(toStdInitializerList); 4867 return Result; 4868 } 4869 4870 // C++14 [over.ics.list]p4: 4871 // C++11 [over.ics.list]p3: 4872 // Otherwise, if the parameter is a non-aggregate class X and overload 4873 // resolution chooses a single best constructor [...] the implicit 4874 // conversion sequence is a user-defined conversion sequence. If multiple 4875 // constructors are viable but none is better than the others, the 4876 // implicit conversion sequence is a user-defined conversion sequence. 4877 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4878 // This function can deal with initializer lists. 4879 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4880 /*AllowExplicit=*/false, 4881 InOverloadResolution, /*CStyle=*/false, 4882 AllowObjCWritebackConversion, 4883 /*AllowObjCConversionOnExplicit=*/false); 4884 } 4885 4886 // C++14 [over.ics.list]p5: 4887 // C++11 [over.ics.list]p4: 4888 // Otherwise, if the parameter has an aggregate type which can be 4889 // initialized from the initializer list [...] the implicit conversion 4890 // sequence is a user-defined conversion sequence. 4891 if (ToType->isAggregateType()) { 4892 // Type is an aggregate, argument is an init list. At this point it comes 4893 // down to checking whether the initialization works. 4894 // FIXME: Find out whether this parameter is consumed or not. 4895 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4896 // need to call into the initialization code here; overload resolution 4897 // should not be doing that. 4898 InitializedEntity Entity = 4899 InitializedEntity::InitializeParameter(S.Context, ToType, 4900 /*Consumed=*/false); 4901 if (S.CanPerformCopyInitialization(Entity, From)) { 4902 Result.setUserDefined(); 4903 Result.UserDefined.Before.setAsIdentityConversion(); 4904 // Initializer lists don't have a type. 4905 Result.UserDefined.Before.setFromType(QualType()); 4906 Result.UserDefined.Before.setAllToTypes(QualType()); 4907 4908 Result.UserDefined.After.setAsIdentityConversion(); 4909 Result.UserDefined.After.setFromType(ToType); 4910 Result.UserDefined.After.setAllToTypes(ToType); 4911 Result.UserDefined.ConversionFunction = nullptr; 4912 } 4913 return Result; 4914 } 4915 4916 // C++14 [over.ics.list]p6: 4917 // C++11 [over.ics.list]p5: 4918 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4919 if (ToType->isReferenceType()) { 4920 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4921 // mention initializer lists in any way. So we go by what list- 4922 // initialization would do and try to extrapolate from that. 4923 4924 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4925 4926 // If the initializer list has a single element that is reference-related 4927 // to the parameter type, we initialize the reference from that. 4928 if (From->getNumInits() == 1) { 4929 Expr *Init = From->getInit(0); 4930 4931 QualType T2 = Init->getType(); 4932 4933 // If the initializer is the address of an overloaded function, try 4934 // to resolve the overloaded function. If all goes well, T2 is the 4935 // type of the resulting function. 4936 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4937 DeclAccessPair Found; 4938 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4939 Init, ToType, false, Found)) 4940 T2 = Fn->getType(); 4941 } 4942 4943 // Compute some basic properties of the types and the initializer. 4944 bool dummy1 = false; 4945 bool dummy2 = false; 4946 bool dummy3 = false; 4947 Sema::ReferenceCompareResult RefRelationship = 4948 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4949 dummy2, dummy3); 4950 4951 if (RefRelationship >= Sema::Ref_Related) { 4952 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4953 SuppressUserConversions, 4954 /*AllowExplicit=*/false); 4955 } 4956 } 4957 4958 // Otherwise, we bind the reference to a temporary created from the 4959 // initializer list. 4960 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4961 InOverloadResolution, 4962 AllowObjCWritebackConversion); 4963 if (Result.isFailure()) 4964 return Result; 4965 assert(!Result.isEllipsis() && 4966 "Sub-initialization cannot result in ellipsis conversion."); 4967 4968 // Can we even bind to a temporary? 4969 if (ToType->isRValueReferenceType() || 4970 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4971 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4972 Result.UserDefined.After; 4973 SCS.ReferenceBinding = true; 4974 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4975 SCS.BindsToRvalue = true; 4976 SCS.BindsToFunctionLvalue = false; 4977 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4978 SCS.ObjCLifetimeConversionBinding = false; 4979 } else 4980 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4981 From, ToType); 4982 return Result; 4983 } 4984 4985 // C++14 [over.ics.list]p7: 4986 // C++11 [over.ics.list]p6: 4987 // Otherwise, if the parameter type is not a class: 4988 if (!ToType->isRecordType()) { 4989 // - if the initializer list has one element that is not itself an 4990 // initializer list, the implicit conversion sequence is the one 4991 // required to convert the element to the parameter type. 4992 unsigned NumInits = From->getNumInits(); 4993 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4994 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4995 SuppressUserConversions, 4996 InOverloadResolution, 4997 AllowObjCWritebackConversion); 4998 // - if the initializer list has no elements, the implicit conversion 4999 // sequence is the identity conversion. 5000 else if (NumInits == 0) { 5001 Result.setStandard(); 5002 Result.Standard.setAsIdentityConversion(); 5003 Result.Standard.setFromType(ToType); 5004 Result.Standard.setAllToTypes(ToType); 5005 } 5006 return Result; 5007 } 5008 5009 // C++14 [over.ics.list]p8: 5010 // C++11 [over.ics.list]p7: 5011 // In all cases other than those enumerated above, no conversion is possible 5012 return Result; 5013 } 5014 5015 /// TryCopyInitialization - Try to copy-initialize a value of type 5016 /// ToType from the expression From. Return the implicit conversion 5017 /// sequence required to pass this argument, which may be a bad 5018 /// conversion sequence (meaning that the argument cannot be passed to 5019 /// a parameter of this type). If @p SuppressUserConversions, then we 5020 /// do not permit any user-defined conversion sequences. 5021 static ImplicitConversionSequence 5022 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5023 bool SuppressUserConversions, 5024 bool InOverloadResolution, 5025 bool AllowObjCWritebackConversion, 5026 bool AllowExplicit) { 5027 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5028 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5029 InOverloadResolution,AllowObjCWritebackConversion); 5030 5031 if (ToType->isReferenceType()) 5032 return TryReferenceInit(S, From, ToType, 5033 /*FIXME:*/ From->getBeginLoc(), 5034 SuppressUserConversions, AllowExplicit); 5035 5036 return TryImplicitConversion(S, From, ToType, 5037 SuppressUserConversions, 5038 /*AllowExplicit=*/false, 5039 InOverloadResolution, 5040 /*CStyle=*/false, 5041 AllowObjCWritebackConversion, 5042 /*AllowObjCConversionOnExplicit=*/false); 5043 } 5044 5045 static bool TryCopyInitialization(const CanQualType FromQTy, 5046 const CanQualType ToQTy, 5047 Sema &S, 5048 SourceLocation Loc, 5049 ExprValueKind FromVK) { 5050 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5051 ImplicitConversionSequence ICS = 5052 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5053 5054 return !ICS.isBad(); 5055 } 5056 5057 /// TryObjectArgumentInitialization - Try to initialize the object 5058 /// parameter of the given member function (@c Method) from the 5059 /// expression @p From. 5060 static ImplicitConversionSequence 5061 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5062 Expr::Classification FromClassification, 5063 CXXMethodDecl *Method, 5064 CXXRecordDecl *ActingContext) { 5065 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5066 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5067 // const volatile object. 5068 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 5069 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 5070 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 5071 5072 // Set up the conversion sequence as a "bad" conversion, to allow us 5073 // to exit early. 5074 ImplicitConversionSequence ICS; 5075 5076 // We need to have an object of class type. 5077 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5078 FromType = PT->getPointeeType(); 5079 5080 // When we had a pointer, it's implicitly dereferenced, so we 5081 // better have an lvalue. 5082 assert(FromClassification.isLValue()); 5083 } 5084 5085 assert(FromType->isRecordType()); 5086 5087 // C++0x [over.match.funcs]p4: 5088 // For non-static member functions, the type of the implicit object 5089 // parameter is 5090 // 5091 // - "lvalue reference to cv X" for functions declared without a 5092 // ref-qualifier or with the & ref-qualifier 5093 // - "rvalue reference to cv X" for functions declared with the && 5094 // ref-qualifier 5095 // 5096 // where X is the class of which the function is a member and cv is the 5097 // cv-qualification on the member function declaration. 5098 // 5099 // However, when finding an implicit conversion sequence for the argument, we 5100 // are not allowed to perform user-defined conversions 5101 // (C++ [over.match.funcs]p5). We perform a simplified version of 5102 // reference binding here, that allows class rvalues to bind to 5103 // non-constant references. 5104 5105 // First check the qualifiers. 5106 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5107 if (ImplicitParamType.getCVRQualifiers() 5108 != FromTypeCanon.getLocalCVRQualifiers() && 5109 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5110 ICS.setBad(BadConversionSequence::bad_qualifiers, 5111 FromType, ImplicitParamType); 5112 return ICS; 5113 } 5114 5115 // Check that we have either the same type or a derived type. It 5116 // affects the conversion rank. 5117 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5118 ImplicitConversionKind SecondKind; 5119 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5120 SecondKind = ICK_Identity; 5121 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5122 SecondKind = ICK_Derived_To_Base; 5123 else { 5124 ICS.setBad(BadConversionSequence::unrelated_class, 5125 FromType, ImplicitParamType); 5126 return ICS; 5127 } 5128 5129 // Check the ref-qualifier. 5130 switch (Method->getRefQualifier()) { 5131 case RQ_None: 5132 // Do nothing; we don't care about lvalueness or rvalueness. 5133 break; 5134 5135 case RQ_LValue: 5136 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5137 // non-const lvalue reference cannot bind to an rvalue 5138 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5139 ImplicitParamType); 5140 return ICS; 5141 } 5142 break; 5143 5144 case RQ_RValue: 5145 if (!FromClassification.isRValue()) { 5146 // rvalue reference cannot bind to an lvalue 5147 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5148 ImplicitParamType); 5149 return ICS; 5150 } 5151 break; 5152 } 5153 5154 // Success. Mark this as a reference binding. 5155 ICS.setStandard(); 5156 ICS.Standard.setAsIdentityConversion(); 5157 ICS.Standard.Second = SecondKind; 5158 ICS.Standard.setFromType(FromType); 5159 ICS.Standard.setAllToTypes(ImplicitParamType); 5160 ICS.Standard.ReferenceBinding = true; 5161 ICS.Standard.DirectBinding = true; 5162 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5163 ICS.Standard.BindsToFunctionLvalue = false; 5164 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5165 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5166 = (Method->getRefQualifier() == RQ_None); 5167 return ICS; 5168 } 5169 5170 /// PerformObjectArgumentInitialization - Perform initialization of 5171 /// the implicit object parameter for the given Method with the given 5172 /// expression. 5173 ExprResult 5174 Sema::PerformObjectArgumentInitialization(Expr *From, 5175 NestedNameSpecifier *Qualifier, 5176 NamedDecl *FoundDecl, 5177 CXXMethodDecl *Method) { 5178 QualType FromRecordType, DestType; 5179 QualType ImplicitParamRecordType = 5180 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5181 5182 Expr::Classification FromClassification; 5183 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5184 FromRecordType = PT->getPointeeType(); 5185 DestType = Method->getThisType(Context); 5186 FromClassification = Expr::Classification::makeSimpleLValue(); 5187 } else { 5188 FromRecordType = From->getType(); 5189 DestType = ImplicitParamRecordType; 5190 FromClassification = From->Classify(Context); 5191 5192 // When performing member access on an rvalue, materialize a temporary. 5193 if (From->isRValue()) { 5194 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5195 Method->getRefQualifier() != 5196 RefQualifierKind::RQ_RValue); 5197 } 5198 } 5199 5200 // Note that we always use the true parent context when performing 5201 // the actual argument initialization. 5202 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5203 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5204 Method->getParent()); 5205 if (ICS.isBad()) { 5206 switch (ICS.Bad.Kind) { 5207 case BadConversionSequence::bad_qualifiers: { 5208 Qualifiers FromQs = FromRecordType.getQualifiers(); 5209 Qualifiers ToQs = DestType.getQualifiers(); 5210 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5211 if (CVR) { 5212 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5213 << Method->getDeclName() << FromRecordType << (CVR - 1) 5214 << From->getSourceRange(); 5215 Diag(Method->getLocation(), diag::note_previous_decl) 5216 << Method->getDeclName(); 5217 return ExprError(); 5218 } 5219 break; 5220 } 5221 5222 case BadConversionSequence::lvalue_ref_to_rvalue: 5223 case BadConversionSequence::rvalue_ref_to_lvalue: { 5224 bool IsRValueQualified = 5225 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5226 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5227 << Method->getDeclName() << FromClassification.isRValue() 5228 << IsRValueQualified; 5229 Diag(Method->getLocation(), diag::note_previous_decl) 5230 << Method->getDeclName(); 5231 return ExprError(); 5232 } 5233 5234 case BadConversionSequence::no_conversion: 5235 case BadConversionSequence::unrelated_class: 5236 break; 5237 } 5238 5239 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5240 << ImplicitParamRecordType << FromRecordType 5241 << From->getSourceRange(); 5242 } 5243 5244 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5245 ExprResult FromRes = 5246 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5247 if (FromRes.isInvalid()) 5248 return ExprError(); 5249 From = FromRes.get(); 5250 } 5251 5252 if (!Context.hasSameType(From->getType(), DestType)) 5253 From = ImpCastExprToType(From, DestType, CK_NoOp, 5254 From->getValueKind()).get(); 5255 return From; 5256 } 5257 5258 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5259 /// expression From to bool (C++0x [conv]p3). 5260 static ImplicitConversionSequence 5261 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5262 return TryImplicitConversion(S, From, S.Context.BoolTy, 5263 /*SuppressUserConversions=*/false, 5264 /*AllowExplicit=*/true, 5265 /*InOverloadResolution=*/false, 5266 /*CStyle=*/false, 5267 /*AllowObjCWritebackConversion=*/false, 5268 /*AllowObjCConversionOnExplicit=*/false); 5269 } 5270 5271 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5272 /// of the expression From to bool (C++0x [conv]p3). 5273 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5274 if (checkPlaceholderForOverload(*this, From)) 5275 return ExprError(); 5276 5277 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5278 if (!ICS.isBad()) 5279 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5280 5281 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5282 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5283 << From->getType() << From->getSourceRange(); 5284 return ExprError(); 5285 } 5286 5287 /// Check that the specified conversion is permitted in a converted constant 5288 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5289 /// is acceptable. 5290 static bool CheckConvertedConstantConversions(Sema &S, 5291 StandardConversionSequence &SCS) { 5292 // Since we know that the target type is an integral or unscoped enumeration 5293 // type, most conversion kinds are impossible. All possible First and Third 5294 // conversions are fine. 5295 switch (SCS.Second) { 5296 case ICK_Identity: 5297 case ICK_Function_Conversion: 5298 case ICK_Integral_Promotion: 5299 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5300 case ICK_Zero_Queue_Conversion: 5301 return true; 5302 5303 case ICK_Boolean_Conversion: 5304 // Conversion from an integral or unscoped enumeration type to bool is 5305 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5306 // conversion, so we allow it in a converted constant expression. 5307 // 5308 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5309 // a lot of popular code. We should at least add a warning for this 5310 // (non-conforming) extension. 5311 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5312 SCS.getToType(2)->isBooleanType(); 5313 5314 case ICK_Pointer_Conversion: 5315 case ICK_Pointer_Member: 5316 // C++1z: null pointer conversions and null member pointer conversions are 5317 // only permitted if the source type is std::nullptr_t. 5318 return SCS.getFromType()->isNullPtrType(); 5319 5320 case ICK_Floating_Promotion: 5321 case ICK_Complex_Promotion: 5322 case ICK_Floating_Conversion: 5323 case ICK_Complex_Conversion: 5324 case ICK_Floating_Integral: 5325 case ICK_Compatible_Conversion: 5326 case ICK_Derived_To_Base: 5327 case ICK_Vector_Conversion: 5328 case ICK_Vector_Splat: 5329 case ICK_Complex_Real: 5330 case ICK_Block_Pointer_Conversion: 5331 case ICK_TransparentUnionConversion: 5332 case ICK_Writeback_Conversion: 5333 case ICK_Zero_Event_Conversion: 5334 case ICK_C_Only_Conversion: 5335 case ICK_Incompatible_Pointer_Conversion: 5336 return false; 5337 5338 case ICK_Lvalue_To_Rvalue: 5339 case ICK_Array_To_Pointer: 5340 case ICK_Function_To_Pointer: 5341 llvm_unreachable("found a first conversion kind in Second"); 5342 5343 case ICK_Qualification: 5344 llvm_unreachable("found a third conversion kind in Second"); 5345 5346 case ICK_Num_Conversion_Kinds: 5347 break; 5348 } 5349 5350 llvm_unreachable("unknown conversion kind"); 5351 } 5352 5353 /// CheckConvertedConstantExpression - Check that the expression From is a 5354 /// converted constant expression of type T, perform the conversion and produce 5355 /// the converted expression, per C++11 [expr.const]p3. 5356 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5357 QualType T, APValue &Value, 5358 Sema::CCEKind CCE, 5359 bool RequireInt) { 5360 assert(S.getLangOpts().CPlusPlus11 && 5361 "converted constant expression outside C++11"); 5362 5363 if (checkPlaceholderForOverload(S, From)) 5364 return ExprError(); 5365 5366 // C++1z [expr.const]p3: 5367 // A converted constant expression of type T is an expression, 5368 // implicitly converted to type T, where the converted 5369 // expression is a constant expression and the implicit conversion 5370 // sequence contains only [... list of conversions ...]. 5371 // C++1z [stmt.if]p2: 5372 // If the if statement is of the form if constexpr, the value of the 5373 // condition shall be a contextually converted constant expression of type 5374 // bool. 5375 ImplicitConversionSequence ICS = 5376 CCE == Sema::CCEK_ConstexprIf 5377 ? TryContextuallyConvertToBool(S, From) 5378 : TryCopyInitialization(S, From, T, 5379 /*SuppressUserConversions=*/false, 5380 /*InOverloadResolution=*/false, 5381 /*AllowObjcWritebackConversion=*/false, 5382 /*AllowExplicit=*/false); 5383 StandardConversionSequence *SCS = nullptr; 5384 switch (ICS.getKind()) { 5385 case ImplicitConversionSequence::StandardConversion: 5386 SCS = &ICS.Standard; 5387 break; 5388 case ImplicitConversionSequence::UserDefinedConversion: 5389 // We are converting to a non-class type, so the Before sequence 5390 // must be trivial. 5391 SCS = &ICS.UserDefined.After; 5392 break; 5393 case ImplicitConversionSequence::AmbiguousConversion: 5394 case ImplicitConversionSequence::BadConversion: 5395 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5396 return S.Diag(From->getBeginLoc(), 5397 diag::err_typecheck_converted_constant_expression) 5398 << From->getType() << From->getSourceRange() << T; 5399 return ExprError(); 5400 5401 case ImplicitConversionSequence::EllipsisConversion: 5402 llvm_unreachable("ellipsis conversion in converted constant expression"); 5403 } 5404 5405 // Check that we would only use permitted conversions. 5406 if (!CheckConvertedConstantConversions(S, *SCS)) { 5407 return S.Diag(From->getBeginLoc(), 5408 diag::err_typecheck_converted_constant_expression_disallowed) 5409 << From->getType() << From->getSourceRange() << T; 5410 } 5411 // [...] and where the reference binding (if any) binds directly. 5412 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5413 return S.Diag(From->getBeginLoc(), 5414 diag::err_typecheck_converted_constant_expression_indirect) 5415 << From->getType() << From->getSourceRange() << T; 5416 } 5417 5418 ExprResult Result = 5419 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5420 if (Result.isInvalid()) 5421 return Result; 5422 5423 // Check for a narrowing implicit conversion. 5424 APValue PreNarrowingValue; 5425 QualType PreNarrowingType; 5426 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5427 PreNarrowingType)) { 5428 case NK_Dependent_Narrowing: 5429 // Implicit conversion to a narrower type, but the expression is 5430 // value-dependent so we can't tell whether it's actually narrowing. 5431 case NK_Variable_Narrowing: 5432 // Implicit conversion to a narrower type, and the value is not a constant 5433 // expression. We'll diagnose this in a moment. 5434 case NK_Not_Narrowing: 5435 break; 5436 5437 case NK_Constant_Narrowing: 5438 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5439 << CCE << /*Constant*/ 1 5440 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5441 break; 5442 5443 case NK_Type_Narrowing: 5444 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5445 << CCE << /*Constant*/ 0 << From->getType() << T; 5446 break; 5447 } 5448 5449 if (Result.get()->isValueDependent()) { 5450 Value = APValue(); 5451 return Result; 5452 } 5453 5454 // Check the expression is a constant expression. 5455 SmallVector<PartialDiagnosticAt, 8> Notes; 5456 Expr::EvalResult Eval; 5457 Eval.Diag = &Notes; 5458 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5459 ? Expr::EvaluateForMangling 5460 : Expr::EvaluateForCodeGen; 5461 5462 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5463 (RequireInt && !Eval.Val.isInt())) { 5464 // The expression can't be folded, so we can't keep it at this position in 5465 // the AST. 5466 Result = ExprError(); 5467 } else { 5468 Value = Eval.Val; 5469 5470 if (Notes.empty()) { 5471 // It's a constant expression. 5472 return ConstantExpr::Create(S.Context, Result.get()); 5473 } 5474 } 5475 5476 // It's not a constant expression. Produce an appropriate diagnostic. 5477 if (Notes.size() == 1 && 5478 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5479 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5480 else { 5481 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5482 << CCE << From->getSourceRange(); 5483 for (unsigned I = 0; I < Notes.size(); ++I) 5484 S.Diag(Notes[I].first, Notes[I].second); 5485 } 5486 return ExprError(); 5487 } 5488 5489 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5490 APValue &Value, CCEKind CCE) { 5491 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5492 } 5493 5494 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5495 llvm::APSInt &Value, 5496 CCEKind CCE) { 5497 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5498 5499 APValue V; 5500 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5501 if (!R.isInvalid() && !R.get()->isValueDependent()) 5502 Value = V.getInt(); 5503 return R; 5504 } 5505 5506 5507 /// dropPointerConversions - If the given standard conversion sequence 5508 /// involves any pointer conversions, remove them. This may change 5509 /// the result type of the conversion sequence. 5510 static void dropPointerConversion(StandardConversionSequence &SCS) { 5511 if (SCS.Second == ICK_Pointer_Conversion) { 5512 SCS.Second = ICK_Identity; 5513 SCS.Third = ICK_Identity; 5514 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5515 } 5516 } 5517 5518 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5519 /// convert the expression From to an Objective-C pointer type. 5520 static ImplicitConversionSequence 5521 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5522 // Do an implicit conversion to 'id'. 5523 QualType Ty = S.Context.getObjCIdType(); 5524 ImplicitConversionSequence ICS 5525 = TryImplicitConversion(S, From, Ty, 5526 // FIXME: Are these flags correct? 5527 /*SuppressUserConversions=*/false, 5528 /*AllowExplicit=*/true, 5529 /*InOverloadResolution=*/false, 5530 /*CStyle=*/false, 5531 /*AllowObjCWritebackConversion=*/false, 5532 /*AllowObjCConversionOnExplicit=*/true); 5533 5534 // Strip off any final conversions to 'id'. 5535 switch (ICS.getKind()) { 5536 case ImplicitConversionSequence::BadConversion: 5537 case ImplicitConversionSequence::AmbiguousConversion: 5538 case ImplicitConversionSequence::EllipsisConversion: 5539 break; 5540 5541 case ImplicitConversionSequence::UserDefinedConversion: 5542 dropPointerConversion(ICS.UserDefined.After); 5543 break; 5544 5545 case ImplicitConversionSequence::StandardConversion: 5546 dropPointerConversion(ICS.Standard); 5547 break; 5548 } 5549 5550 return ICS; 5551 } 5552 5553 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5554 /// conversion of the expression From to an Objective-C pointer type. 5555 /// Returns a valid but null ExprResult if no conversion sequence exists. 5556 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5557 if (checkPlaceholderForOverload(*this, From)) 5558 return ExprError(); 5559 5560 QualType Ty = Context.getObjCIdType(); 5561 ImplicitConversionSequence ICS = 5562 TryContextuallyConvertToObjCPointer(*this, From); 5563 if (!ICS.isBad()) 5564 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5565 return ExprResult(); 5566 } 5567 5568 /// Determine whether the provided type is an integral type, or an enumeration 5569 /// type of a permitted flavor. 5570 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5571 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5572 : T->isIntegralOrUnscopedEnumerationType(); 5573 } 5574 5575 static ExprResult 5576 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5577 Sema::ContextualImplicitConverter &Converter, 5578 QualType T, UnresolvedSetImpl &ViableConversions) { 5579 5580 if (Converter.Suppress) 5581 return ExprError(); 5582 5583 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5584 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5585 CXXConversionDecl *Conv = 5586 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5587 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5588 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5589 } 5590 return From; 5591 } 5592 5593 static bool 5594 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5595 Sema::ContextualImplicitConverter &Converter, 5596 QualType T, bool HadMultipleCandidates, 5597 UnresolvedSetImpl &ExplicitConversions) { 5598 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5599 DeclAccessPair Found = ExplicitConversions[0]; 5600 CXXConversionDecl *Conversion = 5601 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5602 5603 // The user probably meant to invoke the given explicit 5604 // conversion; use it. 5605 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5606 std::string TypeStr; 5607 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5608 5609 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5610 << FixItHint::CreateInsertion(From->getBeginLoc(), 5611 "static_cast<" + TypeStr + ">(") 5612 << FixItHint::CreateInsertion( 5613 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5614 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5615 5616 // If we aren't in a SFINAE context, build a call to the 5617 // explicit conversion function. 5618 if (SemaRef.isSFINAEContext()) 5619 return true; 5620 5621 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5622 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5623 HadMultipleCandidates); 5624 if (Result.isInvalid()) 5625 return true; 5626 // Record usage of conversion in an implicit cast. 5627 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5628 CK_UserDefinedConversion, Result.get(), 5629 nullptr, Result.get()->getValueKind()); 5630 } 5631 return false; 5632 } 5633 5634 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5635 Sema::ContextualImplicitConverter &Converter, 5636 QualType T, bool HadMultipleCandidates, 5637 DeclAccessPair &Found) { 5638 CXXConversionDecl *Conversion = 5639 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5640 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5641 5642 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5643 if (!Converter.SuppressConversion) { 5644 if (SemaRef.isSFINAEContext()) 5645 return true; 5646 5647 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5648 << From->getSourceRange(); 5649 } 5650 5651 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5652 HadMultipleCandidates); 5653 if (Result.isInvalid()) 5654 return true; 5655 // Record usage of conversion in an implicit cast. 5656 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5657 CK_UserDefinedConversion, Result.get(), 5658 nullptr, Result.get()->getValueKind()); 5659 return false; 5660 } 5661 5662 static ExprResult finishContextualImplicitConversion( 5663 Sema &SemaRef, SourceLocation Loc, Expr *From, 5664 Sema::ContextualImplicitConverter &Converter) { 5665 if (!Converter.match(From->getType()) && !Converter.Suppress) 5666 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5667 << From->getSourceRange(); 5668 5669 return SemaRef.DefaultLvalueConversion(From); 5670 } 5671 5672 static void 5673 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5674 UnresolvedSetImpl &ViableConversions, 5675 OverloadCandidateSet &CandidateSet) { 5676 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5677 DeclAccessPair FoundDecl = ViableConversions[I]; 5678 NamedDecl *D = FoundDecl.getDecl(); 5679 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5680 if (isa<UsingShadowDecl>(D)) 5681 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5682 5683 CXXConversionDecl *Conv; 5684 FunctionTemplateDecl *ConvTemplate; 5685 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5686 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5687 else 5688 Conv = cast<CXXConversionDecl>(D); 5689 5690 if (ConvTemplate) 5691 SemaRef.AddTemplateConversionCandidate( 5692 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5693 /*AllowObjCConversionOnExplicit=*/false); 5694 else 5695 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5696 ToType, CandidateSet, 5697 /*AllowObjCConversionOnExplicit=*/false); 5698 } 5699 } 5700 5701 /// Attempt to convert the given expression to a type which is accepted 5702 /// by the given converter. 5703 /// 5704 /// This routine will attempt to convert an expression of class type to a 5705 /// type accepted by the specified converter. In C++11 and before, the class 5706 /// must have a single non-explicit conversion function converting to a matching 5707 /// type. In C++1y, there can be multiple such conversion functions, but only 5708 /// one target type. 5709 /// 5710 /// \param Loc The source location of the construct that requires the 5711 /// conversion. 5712 /// 5713 /// \param From The expression we're converting from. 5714 /// 5715 /// \param Converter Used to control and diagnose the conversion process. 5716 /// 5717 /// \returns The expression, converted to an integral or enumeration type if 5718 /// successful. 5719 ExprResult Sema::PerformContextualImplicitConversion( 5720 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5721 // We can't perform any more checking for type-dependent expressions. 5722 if (From->isTypeDependent()) 5723 return From; 5724 5725 // Process placeholders immediately. 5726 if (From->hasPlaceholderType()) { 5727 ExprResult result = CheckPlaceholderExpr(From); 5728 if (result.isInvalid()) 5729 return result; 5730 From = result.get(); 5731 } 5732 5733 // If the expression already has a matching type, we're golden. 5734 QualType T = From->getType(); 5735 if (Converter.match(T)) 5736 return DefaultLvalueConversion(From); 5737 5738 // FIXME: Check for missing '()' if T is a function type? 5739 5740 // We can only perform contextual implicit conversions on objects of class 5741 // type. 5742 const RecordType *RecordTy = T->getAs<RecordType>(); 5743 if (!RecordTy || !getLangOpts().CPlusPlus) { 5744 if (!Converter.Suppress) 5745 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5746 return From; 5747 } 5748 5749 // We must have a complete class type. 5750 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5751 ContextualImplicitConverter &Converter; 5752 Expr *From; 5753 5754 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5755 : Converter(Converter), From(From) {} 5756 5757 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5758 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5759 } 5760 } IncompleteDiagnoser(Converter, From); 5761 5762 if (Converter.Suppress ? !isCompleteType(Loc, T) 5763 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5764 return From; 5765 5766 // Look for a conversion to an integral or enumeration type. 5767 UnresolvedSet<4> 5768 ViableConversions; // These are *potentially* viable in C++1y. 5769 UnresolvedSet<4> ExplicitConversions; 5770 const auto &Conversions = 5771 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5772 5773 bool HadMultipleCandidates = 5774 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5775 5776 // To check that there is only one target type, in C++1y: 5777 QualType ToType; 5778 bool HasUniqueTargetType = true; 5779 5780 // Collect explicit or viable (potentially in C++1y) conversions. 5781 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5782 NamedDecl *D = (*I)->getUnderlyingDecl(); 5783 CXXConversionDecl *Conversion; 5784 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5785 if (ConvTemplate) { 5786 if (getLangOpts().CPlusPlus14) 5787 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5788 else 5789 continue; // C++11 does not consider conversion operator templates(?). 5790 } else 5791 Conversion = cast<CXXConversionDecl>(D); 5792 5793 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5794 "Conversion operator templates are considered potentially " 5795 "viable in C++1y"); 5796 5797 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5798 if (Converter.match(CurToType) || ConvTemplate) { 5799 5800 if (Conversion->isExplicit()) { 5801 // FIXME: For C++1y, do we need this restriction? 5802 // cf. diagnoseNoViableConversion() 5803 if (!ConvTemplate) 5804 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5805 } else { 5806 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5807 if (ToType.isNull()) 5808 ToType = CurToType.getUnqualifiedType(); 5809 else if (HasUniqueTargetType && 5810 (CurToType.getUnqualifiedType() != ToType)) 5811 HasUniqueTargetType = false; 5812 } 5813 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5814 } 5815 } 5816 } 5817 5818 if (getLangOpts().CPlusPlus14) { 5819 // C++1y [conv]p6: 5820 // ... An expression e of class type E appearing in such a context 5821 // is said to be contextually implicitly converted to a specified 5822 // type T and is well-formed if and only if e can be implicitly 5823 // converted to a type T that is determined as follows: E is searched 5824 // for conversion functions whose return type is cv T or reference to 5825 // cv T such that T is allowed by the context. There shall be 5826 // exactly one such T. 5827 5828 // If no unique T is found: 5829 if (ToType.isNull()) { 5830 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5831 HadMultipleCandidates, 5832 ExplicitConversions)) 5833 return ExprError(); 5834 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5835 } 5836 5837 // If more than one unique Ts are found: 5838 if (!HasUniqueTargetType) 5839 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5840 ViableConversions); 5841 5842 // If one unique T is found: 5843 // First, build a candidate set from the previously recorded 5844 // potentially viable conversions. 5845 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5846 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5847 CandidateSet); 5848 5849 // Then, perform overload resolution over the candidate set. 5850 OverloadCandidateSet::iterator Best; 5851 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5852 case OR_Success: { 5853 // Apply this conversion. 5854 DeclAccessPair Found = 5855 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5856 if (recordConversion(*this, Loc, From, Converter, T, 5857 HadMultipleCandidates, Found)) 5858 return ExprError(); 5859 break; 5860 } 5861 case OR_Ambiguous: 5862 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5863 ViableConversions); 5864 case OR_No_Viable_Function: 5865 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5866 HadMultipleCandidates, 5867 ExplicitConversions)) 5868 return ExprError(); 5869 LLVM_FALLTHROUGH; 5870 case OR_Deleted: 5871 // We'll complain below about a non-integral condition type. 5872 break; 5873 } 5874 } else { 5875 switch (ViableConversions.size()) { 5876 case 0: { 5877 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5878 HadMultipleCandidates, 5879 ExplicitConversions)) 5880 return ExprError(); 5881 5882 // We'll complain below about a non-integral condition type. 5883 break; 5884 } 5885 case 1: { 5886 // Apply this conversion. 5887 DeclAccessPair Found = ViableConversions[0]; 5888 if (recordConversion(*this, Loc, From, Converter, T, 5889 HadMultipleCandidates, Found)) 5890 return ExprError(); 5891 break; 5892 } 5893 default: 5894 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5895 ViableConversions); 5896 } 5897 } 5898 5899 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5900 } 5901 5902 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5903 /// an acceptable non-member overloaded operator for a call whose 5904 /// arguments have types T1 (and, if non-empty, T2). This routine 5905 /// implements the check in C++ [over.match.oper]p3b2 concerning 5906 /// enumeration types. 5907 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5908 FunctionDecl *Fn, 5909 ArrayRef<Expr *> Args) { 5910 QualType T1 = Args[0]->getType(); 5911 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5912 5913 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5914 return true; 5915 5916 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5917 return true; 5918 5919 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5920 if (Proto->getNumParams() < 1) 5921 return false; 5922 5923 if (T1->isEnumeralType()) { 5924 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5925 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5926 return true; 5927 } 5928 5929 if (Proto->getNumParams() < 2) 5930 return false; 5931 5932 if (!T2.isNull() && T2->isEnumeralType()) { 5933 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5934 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5935 return true; 5936 } 5937 5938 return false; 5939 } 5940 5941 /// AddOverloadCandidate - Adds the given function to the set of 5942 /// candidate functions, using the given function call arguments. If 5943 /// @p SuppressUserConversions, then don't allow user-defined 5944 /// conversions via constructors or conversion operators. 5945 /// 5946 /// \param PartialOverloading true if we are performing "partial" overloading 5947 /// based on an incomplete set of function arguments. This feature is used by 5948 /// code completion. 5949 void 5950 Sema::AddOverloadCandidate(FunctionDecl *Function, 5951 DeclAccessPair FoundDecl, 5952 ArrayRef<Expr *> Args, 5953 OverloadCandidateSet &CandidateSet, 5954 bool SuppressUserConversions, 5955 bool PartialOverloading, 5956 bool AllowExplicit, 5957 ConversionSequenceList EarlyConversions) { 5958 const FunctionProtoType *Proto 5959 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5960 assert(Proto && "Functions without a prototype cannot be overloaded"); 5961 assert(!Function->getDescribedFunctionTemplate() && 5962 "Use AddTemplateOverloadCandidate for function templates"); 5963 5964 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5965 if (!isa<CXXConstructorDecl>(Method)) { 5966 // If we get here, it's because we're calling a member function 5967 // that is named without a member access expression (e.g., 5968 // "this->f") that was either written explicitly or created 5969 // implicitly. This can happen with a qualified call to a member 5970 // function, e.g., X::f(). We use an empty type for the implied 5971 // object argument (C++ [over.call.func]p3), and the acting context 5972 // is irrelevant. 5973 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 5974 Expr::Classification::makeSimpleLValue(), Args, 5975 CandidateSet, SuppressUserConversions, 5976 PartialOverloading, EarlyConversions); 5977 return; 5978 } 5979 // We treat a constructor like a non-member function, since its object 5980 // argument doesn't participate in overload resolution. 5981 } 5982 5983 if (!CandidateSet.isNewCandidate(Function)) 5984 return; 5985 5986 // C++ [over.match.oper]p3: 5987 // if no operand has a class type, only those non-member functions in the 5988 // lookup set that have a first parameter of type T1 or "reference to 5989 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5990 // is a right operand) a second parameter of type T2 or "reference to 5991 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5992 // candidate functions. 5993 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5994 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5995 return; 5996 5997 // C++11 [class.copy]p11: [DR1402] 5998 // A defaulted move constructor that is defined as deleted is ignored by 5999 // overload resolution. 6000 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6001 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6002 Constructor->isMoveConstructor()) 6003 return; 6004 6005 // Overload resolution is always an unevaluated context. 6006 EnterExpressionEvaluationContext Unevaluated( 6007 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6008 6009 // Add this candidate 6010 OverloadCandidate &Candidate = 6011 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6012 Candidate.FoundDecl = FoundDecl; 6013 Candidate.Function = Function; 6014 Candidate.Viable = true; 6015 Candidate.IsSurrogate = false; 6016 Candidate.IgnoreObjectArgument = false; 6017 Candidate.ExplicitCallArguments = Args.size(); 6018 6019 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6020 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6021 Candidate.Viable = false; 6022 Candidate.FailureKind = ovl_non_default_multiversion_function; 6023 return; 6024 } 6025 6026 if (Constructor) { 6027 // C++ [class.copy]p3: 6028 // A member function template is never instantiated to perform the copy 6029 // of a class object to an object of its class type. 6030 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6031 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6032 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6033 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6034 ClassType))) { 6035 Candidate.Viable = false; 6036 Candidate.FailureKind = ovl_fail_illegal_constructor; 6037 return; 6038 } 6039 6040 // C++ [over.match.funcs]p8: (proposed DR resolution) 6041 // A constructor inherited from class type C that has a first parameter 6042 // of type "reference to P" (including such a constructor instantiated 6043 // from a template) is excluded from the set of candidate functions when 6044 // constructing an object of type cv D if the argument list has exactly 6045 // one argument and D is reference-related to P and P is reference-related 6046 // to C. 6047 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6048 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6049 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6050 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6051 QualType C = Context.getRecordType(Constructor->getParent()); 6052 QualType D = Context.getRecordType(Shadow->getParent()); 6053 SourceLocation Loc = Args.front()->getExprLoc(); 6054 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6055 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6056 Candidate.Viable = false; 6057 Candidate.FailureKind = ovl_fail_inhctor_slice; 6058 return; 6059 } 6060 } 6061 } 6062 6063 unsigned NumParams = Proto->getNumParams(); 6064 6065 // (C++ 13.3.2p2): A candidate function having fewer than m 6066 // parameters is viable only if it has an ellipsis in its parameter 6067 // list (8.3.5). 6068 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6069 !Proto->isVariadic()) { 6070 Candidate.Viable = false; 6071 Candidate.FailureKind = ovl_fail_too_many_arguments; 6072 return; 6073 } 6074 6075 // (C++ 13.3.2p2): A candidate function having more than m parameters 6076 // is viable only if the (m+1)st parameter has a default argument 6077 // (8.3.6). For the purposes of overload resolution, the 6078 // parameter list is truncated on the right, so that there are 6079 // exactly m parameters. 6080 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6081 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6082 // Not enough arguments. 6083 Candidate.Viable = false; 6084 Candidate.FailureKind = ovl_fail_too_few_arguments; 6085 return; 6086 } 6087 6088 // (CUDA B.1): Check for invalid calls between targets. 6089 if (getLangOpts().CUDA) 6090 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6091 // Skip the check for callers that are implicit members, because in this 6092 // case we may not yet know what the member's target is; the target is 6093 // inferred for the member automatically, based on the bases and fields of 6094 // the class. 6095 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6096 Candidate.Viable = false; 6097 Candidate.FailureKind = ovl_fail_bad_target; 6098 return; 6099 } 6100 6101 // Determine the implicit conversion sequences for each of the 6102 // arguments. 6103 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6104 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6105 // We already formed a conversion sequence for this parameter during 6106 // template argument deduction. 6107 } else if (ArgIdx < NumParams) { 6108 // (C++ 13.3.2p3): for F to be a viable function, there shall 6109 // exist for each argument an implicit conversion sequence 6110 // (13.3.3.1) that converts that argument to the corresponding 6111 // parameter of F. 6112 QualType ParamType = Proto->getParamType(ArgIdx); 6113 Candidate.Conversions[ArgIdx] 6114 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6115 SuppressUserConversions, 6116 /*InOverloadResolution=*/true, 6117 /*AllowObjCWritebackConversion=*/ 6118 getLangOpts().ObjCAutoRefCount, 6119 AllowExplicit); 6120 if (Candidate.Conversions[ArgIdx].isBad()) { 6121 Candidate.Viable = false; 6122 Candidate.FailureKind = ovl_fail_bad_conversion; 6123 return; 6124 } 6125 } else { 6126 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6127 // argument for which there is no corresponding parameter is 6128 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6129 Candidate.Conversions[ArgIdx].setEllipsis(); 6130 } 6131 } 6132 6133 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6134 Candidate.Viable = false; 6135 Candidate.FailureKind = ovl_fail_enable_if; 6136 Candidate.DeductionFailure.Data = FailedAttr; 6137 return; 6138 } 6139 6140 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6141 Candidate.Viable = false; 6142 Candidate.FailureKind = ovl_fail_ext_disabled; 6143 return; 6144 } 6145 } 6146 6147 ObjCMethodDecl * 6148 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6149 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6150 if (Methods.size() <= 1) 6151 return nullptr; 6152 6153 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6154 bool Match = true; 6155 ObjCMethodDecl *Method = Methods[b]; 6156 unsigned NumNamedArgs = Sel.getNumArgs(); 6157 // Method might have more arguments than selector indicates. This is due 6158 // to addition of c-style arguments in method. 6159 if (Method->param_size() > NumNamedArgs) 6160 NumNamedArgs = Method->param_size(); 6161 if (Args.size() < NumNamedArgs) 6162 continue; 6163 6164 for (unsigned i = 0; i < NumNamedArgs; i++) { 6165 // We can't do any type-checking on a type-dependent argument. 6166 if (Args[i]->isTypeDependent()) { 6167 Match = false; 6168 break; 6169 } 6170 6171 ParmVarDecl *param = Method->parameters()[i]; 6172 Expr *argExpr = Args[i]; 6173 assert(argExpr && "SelectBestMethod(): missing expression"); 6174 6175 // Strip the unbridged-cast placeholder expression off unless it's 6176 // a consumed argument. 6177 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6178 !param->hasAttr<CFConsumedAttr>()) 6179 argExpr = stripARCUnbridgedCast(argExpr); 6180 6181 // If the parameter is __unknown_anytype, move on to the next method. 6182 if (param->getType() == Context.UnknownAnyTy) { 6183 Match = false; 6184 break; 6185 } 6186 6187 ImplicitConversionSequence ConversionState 6188 = TryCopyInitialization(*this, argExpr, param->getType(), 6189 /*SuppressUserConversions*/false, 6190 /*InOverloadResolution=*/true, 6191 /*AllowObjCWritebackConversion=*/ 6192 getLangOpts().ObjCAutoRefCount, 6193 /*AllowExplicit*/false); 6194 // This function looks for a reasonably-exact match, so we consider 6195 // incompatible pointer conversions to be a failure here. 6196 if (ConversionState.isBad() || 6197 (ConversionState.isStandard() && 6198 ConversionState.Standard.Second == 6199 ICK_Incompatible_Pointer_Conversion)) { 6200 Match = false; 6201 break; 6202 } 6203 } 6204 // Promote additional arguments to variadic methods. 6205 if (Match && Method->isVariadic()) { 6206 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6207 if (Args[i]->isTypeDependent()) { 6208 Match = false; 6209 break; 6210 } 6211 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6212 nullptr); 6213 if (Arg.isInvalid()) { 6214 Match = false; 6215 break; 6216 } 6217 } 6218 } else { 6219 // Check for extra arguments to non-variadic methods. 6220 if (Args.size() != NumNamedArgs) 6221 Match = false; 6222 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6223 // Special case when selectors have no argument. In this case, select 6224 // one with the most general result type of 'id'. 6225 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6226 QualType ReturnT = Methods[b]->getReturnType(); 6227 if (ReturnT->isObjCIdType()) 6228 return Methods[b]; 6229 } 6230 } 6231 } 6232 6233 if (Match) 6234 return Method; 6235 } 6236 return nullptr; 6237 } 6238 6239 static bool 6240 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6241 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6242 bool MissingImplicitThis, Expr *&ConvertedThis, 6243 SmallVectorImpl<Expr *> &ConvertedArgs) { 6244 if (ThisArg) { 6245 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6246 assert(!isa<CXXConstructorDecl>(Method) && 6247 "Shouldn't have `this` for ctors!"); 6248 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6249 ExprResult R = S.PerformObjectArgumentInitialization( 6250 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6251 if (R.isInvalid()) 6252 return false; 6253 ConvertedThis = R.get(); 6254 } else { 6255 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6256 (void)MD; 6257 assert((MissingImplicitThis || MD->isStatic() || 6258 isa<CXXConstructorDecl>(MD)) && 6259 "Expected `this` for non-ctor instance methods"); 6260 } 6261 ConvertedThis = nullptr; 6262 } 6263 6264 // Ignore any variadic arguments. Converting them is pointless, since the 6265 // user can't refer to them in the function condition. 6266 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6267 6268 // Convert the arguments. 6269 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6270 ExprResult R; 6271 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6272 S.Context, Function->getParamDecl(I)), 6273 SourceLocation(), Args[I]); 6274 6275 if (R.isInvalid()) 6276 return false; 6277 6278 ConvertedArgs.push_back(R.get()); 6279 } 6280 6281 if (Trap.hasErrorOccurred()) 6282 return false; 6283 6284 // Push default arguments if needed. 6285 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6286 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6287 ParmVarDecl *P = Function->getParamDecl(i); 6288 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6289 ? P->getUninstantiatedDefaultArg() 6290 : P->getDefaultArg(); 6291 // This can only happen in code completion, i.e. when PartialOverloading 6292 // is true. 6293 if (!DefArg) 6294 return false; 6295 ExprResult R = 6296 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6297 S.Context, Function->getParamDecl(i)), 6298 SourceLocation(), DefArg); 6299 if (R.isInvalid()) 6300 return false; 6301 ConvertedArgs.push_back(R.get()); 6302 } 6303 6304 if (Trap.hasErrorOccurred()) 6305 return false; 6306 } 6307 return true; 6308 } 6309 6310 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6311 bool MissingImplicitThis) { 6312 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6313 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6314 return nullptr; 6315 6316 SFINAETrap Trap(*this); 6317 SmallVector<Expr *, 16> ConvertedArgs; 6318 // FIXME: We should look into making enable_if late-parsed. 6319 Expr *DiscardedThis; 6320 if (!convertArgsForAvailabilityChecks( 6321 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6322 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6323 return *EnableIfAttrs.begin(); 6324 6325 for (auto *EIA : EnableIfAttrs) { 6326 APValue Result; 6327 // FIXME: This doesn't consider value-dependent cases, because doing so is 6328 // very difficult. Ideally, we should handle them more gracefully. 6329 if (!EIA->getCond()->EvaluateWithSubstitution( 6330 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6331 return EIA; 6332 6333 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6334 return EIA; 6335 } 6336 return nullptr; 6337 } 6338 6339 template <typename CheckFn> 6340 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6341 bool ArgDependent, SourceLocation Loc, 6342 CheckFn &&IsSuccessful) { 6343 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6344 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6345 if (ArgDependent == DIA->getArgDependent()) 6346 Attrs.push_back(DIA); 6347 } 6348 6349 // Common case: No diagnose_if attributes, so we can quit early. 6350 if (Attrs.empty()) 6351 return false; 6352 6353 auto WarningBegin = std::stable_partition( 6354 Attrs.begin(), Attrs.end(), 6355 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6356 6357 // Note that diagnose_if attributes are late-parsed, so they appear in the 6358 // correct order (unlike enable_if attributes). 6359 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6360 IsSuccessful); 6361 if (ErrAttr != WarningBegin) { 6362 const DiagnoseIfAttr *DIA = *ErrAttr; 6363 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6364 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6365 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6366 return true; 6367 } 6368 6369 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6370 if (IsSuccessful(DIA)) { 6371 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6372 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6373 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6374 } 6375 6376 return false; 6377 } 6378 6379 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6380 const Expr *ThisArg, 6381 ArrayRef<const Expr *> Args, 6382 SourceLocation Loc) { 6383 return diagnoseDiagnoseIfAttrsWith( 6384 *this, Function, /*ArgDependent=*/true, Loc, 6385 [&](const DiagnoseIfAttr *DIA) { 6386 APValue Result; 6387 // It's sane to use the same Args for any redecl of this function, since 6388 // EvaluateWithSubstitution only cares about the position of each 6389 // argument in the arg list, not the ParmVarDecl* it maps to. 6390 if (!DIA->getCond()->EvaluateWithSubstitution( 6391 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6392 return false; 6393 return Result.isInt() && Result.getInt().getBoolValue(); 6394 }); 6395 } 6396 6397 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6398 SourceLocation Loc) { 6399 return diagnoseDiagnoseIfAttrsWith( 6400 *this, ND, /*ArgDependent=*/false, Loc, 6401 [&](const DiagnoseIfAttr *DIA) { 6402 bool Result; 6403 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6404 Result; 6405 }); 6406 } 6407 6408 /// Add all of the function declarations in the given function set to 6409 /// the overload candidate set. 6410 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6411 ArrayRef<Expr *> Args, 6412 OverloadCandidateSet &CandidateSet, 6413 TemplateArgumentListInfo *ExplicitTemplateArgs, 6414 bool SuppressUserConversions, 6415 bool PartialOverloading, 6416 bool FirstArgumentIsBase) { 6417 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6418 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6419 ArrayRef<Expr *> FunctionArgs = Args; 6420 6421 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6422 FunctionDecl *FD = 6423 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6424 6425 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6426 QualType ObjectType; 6427 Expr::Classification ObjectClassification; 6428 if (Args.size() > 0) { 6429 if (Expr *E = Args[0]) { 6430 // Use the explicit base to restrict the lookup: 6431 ObjectType = E->getType(); 6432 ObjectClassification = E->Classify(Context); 6433 } // .. else there is an implicit base. 6434 FunctionArgs = Args.slice(1); 6435 } 6436 if (FunTmpl) { 6437 AddMethodTemplateCandidate( 6438 FunTmpl, F.getPair(), 6439 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6440 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6441 FunctionArgs, CandidateSet, SuppressUserConversions, 6442 PartialOverloading); 6443 } else { 6444 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6445 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6446 ObjectClassification, FunctionArgs, CandidateSet, 6447 SuppressUserConversions, PartialOverloading); 6448 } 6449 } else { 6450 // This branch handles both standalone functions and static methods. 6451 6452 // Slice the first argument (which is the base) when we access 6453 // static method as non-static. 6454 if (Args.size() > 0 && 6455 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6456 !isa<CXXConstructorDecl>(FD)))) { 6457 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6458 FunctionArgs = Args.slice(1); 6459 } 6460 if (FunTmpl) { 6461 AddTemplateOverloadCandidate( 6462 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6463 CandidateSet, SuppressUserConversions, PartialOverloading); 6464 } else { 6465 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6466 SuppressUserConversions, PartialOverloading); 6467 } 6468 } 6469 } 6470 } 6471 6472 /// AddMethodCandidate - Adds a named decl (which is some kind of 6473 /// method) as a method candidate to the given overload set. 6474 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6475 QualType ObjectType, 6476 Expr::Classification ObjectClassification, 6477 ArrayRef<Expr *> Args, 6478 OverloadCandidateSet& CandidateSet, 6479 bool SuppressUserConversions) { 6480 NamedDecl *Decl = FoundDecl.getDecl(); 6481 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6482 6483 if (isa<UsingShadowDecl>(Decl)) 6484 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6485 6486 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6487 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6488 "Expected a member function template"); 6489 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6490 /*ExplicitArgs*/ nullptr, ObjectType, 6491 ObjectClassification, Args, CandidateSet, 6492 SuppressUserConversions); 6493 } else { 6494 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6495 ObjectType, ObjectClassification, Args, CandidateSet, 6496 SuppressUserConversions); 6497 } 6498 } 6499 6500 /// AddMethodCandidate - Adds the given C++ member function to the set 6501 /// of candidate functions, using the given function call arguments 6502 /// and the object argument (@c Object). For example, in a call 6503 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6504 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6505 /// allow user-defined conversions via constructors or conversion 6506 /// operators. 6507 void 6508 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6509 CXXRecordDecl *ActingContext, QualType ObjectType, 6510 Expr::Classification ObjectClassification, 6511 ArrayRef<Expr *> Args, 6512 OverloadCandidateSet &CandidateSet, 6513 bool SuppressUserConversions, 6514 bool PartialOverloading, 6515 ConversionSequenceList EarlyConversions) { 6516 const FunctionProtoType *Proto 6517 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6518 assert(Proto && "Methods without a prototype cannot be overloaded"); 6519 assert(!isa<CXXConstructorDecl>(Method) && 6520 "Use AddOverloadCandidate for constructors"); 6521 6522 if (!CandidateSet.isNewCandidate(Method)) 6523 return; 6524 6525 // C++11 [class.copy]p23: [DR1402] 6526 // A defaulted move assignment operator that is defined as deleted is 6527 // ignored by overload resolution. 6528 if (Method->isDefaulted() && Method->isDeleted() && 6529 Method->isMoveAssignmentOperator()) 6530 return; 6531 6532 // Overload resolution is always an unevaluated context. 6533 EnterExpressionEvaluationContext Unevaluated( 6534 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6535 6536 // Add this candidate 6537 OverloadCandidate &Candidate = 6538 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6539 Candidate.FoundDecl = FoundDecl; 6540 Candidate.Function = Method; 6541 Candidate.IsSurrogate = false; 6542 Candidate.IgnoreObjectArgument = false; 6543 Candidate.ExplicitCallArguments = Args.size(); 6544 6545 unsigned NumParams = Proto->getNumParams(); 6546 6547 // (C++ 13.3.2p2): A candidate function having fewer than m 6548 // parameters is viable only if it has an ellipsis in its parameter 6549 // list (8.3.5). 6550 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6551 !Proto->isVariadic()) { 6552 Candidate.Viable = false; 6553 Candidate.FailureKind = ovl_fail_too_many_arguments; 6554 return; 6555 } 6556 6557 // (C++ 13.3.2p2): A candidate function having more than m parameters 6558 // is viable only if the (m+1)st parameter has a default argument 6559 // (8.3.6). For the purposes of overload resolution, the 6560 // parameter list is truncated on the right, so that there are 6561 // exactly m parameters. 6562 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6563 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6564 // Not enough arguments. 6565 Candidate.Viable = false; 6566 Candidate.FailureKind = ovl_fail_too_few_arguments; 6567 return; 6568 } 6569 6570 Candidate.Viable = true; 6571 6572 if (Method->isStatic() || ObjectType.isNull()) 6573 // The implicit object argument is ignored. 6574 Candidate.IgnoreObjectArgument = true; 6575 else { 6576 // Determine the implicit conversion sequence for the object 6577 // parameter. 6578 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6579 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6580 Method, ActingContext); 6581 if (Candidate.Conversions[0].isBad()) { 6582 Candidate.Viable = false; 6583 Candidate.FailureKind = ovl_fail_bad_conversion; 6584 return; 6585 } 6586 } 6587 6588 // (CUDA B.1): Check for invalid calls between targets. 6589 if (getLangOpts().CUDA) 6590 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6591 if (!IsAllowedCUDACall(Caller, Method)) { 6592 Candidate.Viable = false; 6593 Candidate.FailureKind = ovl_fail_bad_target; 6594 return; 6595 } 6596 6597 // Determine the implicit conversion sequences for each of the 6598 // arguments. 6599 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6600 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6601 // We already formed a conversion sequence for this parameter during 6602 // template argument deduction. 6603 } else if (ArgIdx < NumParams) { 6604 // (C++ 13.3.2p3): for F to be a viable function, there shall 6605 // exist for each argument an implicit conversion sequence 6606 // (13.3.3.1) that converts that argument to the corresponding 6607 // parameter of F. 6608 QualType ParamType = Proto->getParamType(ArgIdx); 6609 Candidate.Conversions[ArgIdx + 1] 6610 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6611 SuppressUserConversions, 6612 /*InOverloadResolution=*/true, 6613 /*AllowObjCWritebackConversion=*/ 6614 getLangOpts().ObjCAutoRefCount); 6615 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6616 Candidate.Viable = false; 6617 Candidate.FailureKind = ovl_fail_bad_conversion; 6618 return; 6619 } 6620 } else { 6621 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6622 // argument for which there is no corresponding parameter is 6623 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6624 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6625 } 6626 } 6627 6628 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6629 Candidate.Viable = false; 6630 Candidate.FailureKind = ovl_fail_enable_if; 6631 Candidate.DeductionFailure.Data = FailedAttr; 6632 return; 6633 } 6634 6635 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6636 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6637 Candidate.Viable = false; 6638 Candidate.FailureKind = ovl_non_default_multiversion_function; 6639 } 6640 } 6641 6642 /// Add a C++ member function template as a candidate to the candidate 6643 /// set, using template argument deduction to produce an appropriate member 6644 /// function template specialization. 6645 void 6646 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6647 DeclAccessPair FoundDecl, 6648 CXXRecordDecl *ActingContext, 6649 TemplateArgumentListInfo *ExplicitTemplateArgs, 6650 QualType ObjectType, 6651 Expr::Classification ObjectClassification, 6652 ArrayRef<Expr *> Args, 6653 OverloadCandidateSet& CandidateSet, 6654 bool SuppressUserConversions, 6655 bool PartialOverloading) { 6656 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6657 return; 6658 6659 // C++ [over.match.funcs]p7: 6660 // In each case where a candidate is a function template, candidate 6661 // function template specializations are generated using template argument 6662 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6663 // candidate functions in the usual way.113) A given name can refer to one 6664 // or more function templates and also to a set of overloaded non-template 6665 // functions. In such a case, the candidate functions generated from each 6666 // function template are combined with the set of non-template candidate 6667 // functions. 6668 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6669 FunctionDecl *Specialization = nullptr; 6670 ConversionSequenceList Conversions; 6671 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6672 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6673 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6674 return CheckNonDependentConversions( 6675 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6676 SuppressUserConversions, ActingContext, ObjectType, 6677 ObjectClassification); 6678 })) { 6679 OverloadCandidate &Candidate = 6680 CandidateSet.addCandidate(Conversions.size(), Conversions); 6681 Candidate.FoundDecl = FoundDecl; 6682 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6683 Candidate.Viable = false; 6684 Candidate.IsSurrogate = false; 6685 Candidate.IgnoreObjectArgument = 6686 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6687 ObjectType.isNull(); 6688 Candidate.ExplicitCallArguments = Args.size(); 6689 if (Result == TDK_NonDependentConversionFailure) 6690 Candidate.FailureKind = ovl_fail_bad_conversion; 6691 else { 6692 Candidate.FailureKind = ovl_fail_bad_deduction; 6693 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6694 Info); 6695 } 6696 return; 6697 } 6698 6699 // Add the function template specialization produced by template argument 6700 // deduction as a candidate. 6701 assert(Specialization && "Missing member function template specialization?"); 6702 assert(isa<CXXMethodDecl>(Specialization) && 6703 "Specialization is not a member function?"); 6704 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6705 ActingContext, ObjectType, ObjectClassification, Args, 6706 CandidateSet, SuppressUserConversions, PartialOverloading, 6707 Conversions); 6708 } 6709 6710 /// Add a C++ function template specialization as a candidate 6711 /// in the candidate set, using template argument deduction to produce 6712 /// an appropriate function template specialization. 6713 void 6714 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6715 DeclAccessPair FoundDecl, 6716 TemplateArgumentListInfo *ExplicitTemplateArgs, 6717 ArrayRef<Expr *> Args, 6718 OverloadCandidateSet& CandidateSet, 6719 bool SuppressUserConversions, 6720 bool PartialOverloading) { 6721 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6722 return; 6723 6724 // C++ [over.match.funcs]p7: 6725 // In each case where a candidate is a function template, candidate 6726 // function template specializations are generated using template argument 6727 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6728 // candidate functions in the usual way.113) A given name can refer to one 6729 // or more function templates and also to a set of overloaded non-template 6730 // functions. In such a case, the candidate functions generated from each 6731 // function template are combined with the set of non-template candidate 6732 // functions. 6733 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6734 FunctionDecl *Specialization = nullptr; 6735 ConversionSequenceList Conversions; 6736 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6737 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6738 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6739 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6740 Args, CandidateSet, Conversions, 6741 SuppressUserConversions); 6742 })) { 6743 OverloadCandidate &Candidate = 6744 CandidateSet.addCandidate(Conversions.size(), Conversions); 6745 Candidate.FoundDecl = FoundDecl; 6746 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6747 Candidate.Viable = false; 6748 Candidate.IsSurrogate = false; 6749 // Ignore the object argument if there is one, since we don't have an object 6750 // type. 6751 Candidate.IgnoreObjectArgument = 6752 isa<CXXMethodDecl>(Candidate.Function) && 6753 !isa<CXXConstructorDecl>(Candidate.Function); 6754 Candidate.ExplicitCallArguments = Args.size(); 6755 if (Result == TDK_NonDependentConversionFailure) 6756 Candidate.FailureKind = ovl_fail_bad_conversion; 6757 else { 6758 Candidate.FailureKind = ovl_fail_bad_deduction; 6759 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6760 Info); 6761 } 6762 return; 6763 } 6764 6765 // Add the function template specialization produced by template argument 6766 // deduction as a candidate. 6767 assert(Specialization && "Missing function template specialization?"); 6768 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6769 SuppressUserConversions, PartialOverloading, 6770 /*AllowExplicit*/false, Conversions); 6771 } 6772 6773 /// Check that implicit conversion sequences can be formed for each argument 6774 /// whose corresponding parameter has a non-dependent type, per DR1391's 6775 /// [temp.deduct.call]p10. 6776 bool Sema::CheckNonDependentConversions( 6777 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6778 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6779 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6780 CXXRecordDecl *ActingContext, QualType ObjectType, 6781 Expr::Classification ObjectClassification) { 6782 // FIXME: The cases in which we allow explicit conversions for constructor 6783 // arguments never consider calling a constructor template. It's not clear 6784 // that is correct. 6785 const bool AllowExplicit = false; 6786 6787 auto *FD = FunctionTemplate->getTemplatedDecl(); 6788 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6789 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6790 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6791 6792 Conversions = 6793 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6794 6795 // Overload resolution is always an unevaluated context. 6796 EnterExpressionEvaluationContext Unevaluated( 6797 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6798 6799 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6800 // require that, but this check should never result in a hard error, and 6801 // overload resolution is permitted to sidestep instantiations. 6802 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6803 !ObjectType.isNull()) { 6804 Conversions[0] = TryObjectArgumentInitialization( 6805 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6806 Method, ActingContext); 6807 if (Conversions[0].isBad()) 6808 return true; 6809 } 6810 6811 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6812 ++I) { 6813 QualType ParamType = ParamTypes[I]; 6814 if (!ParamType->isDependentType()) { 6815 Conversions[ThisConversions + I] 6816 = TryCopyInitialization(*this, Args[I], ParamType, 6817 SuppressUserConversions, 6818 /*InOverloadResolution=*/true, 6819 /*AllowObjCWritebackConversion=*/ 6820 getLangOpts().ObjCAutoRefCount, 6821 AllowExplicit); 6822 if (Conversions[ThisConversions + I].isBad()) 6823 return true; 6824 } 6825 } 6826 6827 return false; 6828 } 6829 6830 /// Determine whether this is an allowable conversion from the result 6831 /// of an explicit conversion operator to the expected type, per C++ 6832 /// [over.match.conv]p1 and [over.match.ref]p1. 6833 /// 6834 /// \param ConvType The return type of the conversion function. 6835 /// 6836 /// \param ToType The type we are converting to. 6837 /// 6838 /// \param AllowObjCPointerConversion Allow a conversion from one 6839 /// Objective-C pointer to another. 6840 /// 6841 /// \returns true if the conversion is allowable, false otherwise. 6842 static bool isAllowableExplicitConversion(Sema &S, 6843 QualType ConvType, QualType ToType, 6844 bool AllowObjCPointerConversion) { 6845 QualType ToNonRefType = ToType.getNonReferenceType(); 6846 6847 // Easy case: the types are the same. 6848 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6849 return true; 6850 6851 // Allow qualification conversions. 6852 bool ObjCLifetimeConversion; 6853 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6854 ObjCLifetimeConversion)) 6855 return true; 6856 6857 // If we're not allowed to consider Objective-C pointer conversions, 6858 // we're done. 6859 if (!AllowObjCPointerConversion) 6860 return false; 6861 6862 // Is this an Objective-C pointer conversion? 6863 bool IncompatibleObjC = false; 6864 QualType ConvertedType; 6865 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6866 IncompatibleObjC); 6867 } 6868 6869 /// AddConversionCandidate - Add a C++ conversion function as a 6870 /// candidate in the candidate set (C++ [over.match.conv], 6871 /// C++ [over.match.copy]). From is the expression we're converting from, 6872 /// and ToType is the type that we're eventually trying to convert to 6873 /// (which may or may not be the same type as the type that the 6874 /// conversion function produces). 6875 void 6876 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6877 DeclAccessPair FoundDecl, 6878 CXXRecordDecl *ActingContext, 6879 Expr *From, QualType ToType, 6880 OverloadCandidateSet& CandidateSet, 6881 bool AllowObjCConversionOnExplicit, 6882 bool AllowResultConversion) { 6883 assert(!Conversion->getDescribedFunctionTemplate() && 6884 "Conversion function templates use AddTemplateConversionCandidate"); 6885 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6886 if (!CandidateSet.isNewCandidate(Conversion)) 6887 return; 6888 6889 // If the conversion function has an undeduced return type, trigger its 6890 // deduction now. 6891 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6892 if (DeduceReturnType(Conversion, From->getExprLoc())) 6893 return; 6894 ConvType = Conversion->getConversionType().getNonReferenceType(); 6895 } 6896 6897 // If we don't allow any conversion of the result type, ignore conversion 6898 // functions that don't convert to exactly (possibly cv-qualified) T. 6899 if (!AllowResultConversion && 6900 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6901 return; 6902 6903 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6904 // operator is only a candidate if its return type is the target type or 6905 // can be converted to the target type with a qualification conversion. 6906 if (Conversion->isExplicit() && 6907 !isAllowableExplicitConversion(*this, ConvType, ToType, 6908 AllowObjCConversionOnExplicit)) 6909 return; 6910 6911 // Overload resolution is always an unevaluated context. 6912 EnterExpressionEvaluationContext Unevaluated( 6913 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6914 6915 // Add this candidate 6916 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6917 Candidate.FoundDecl = FoundDecl; 6918 Candidate.Function = Conversion; 6919 Candidate.IsSurrogate = false; 6920 Candidate.IgnoreObjectArgument = false; 6921 Candidate.FinalConversion.setAsIdentityConversion(); 6922 Candidate.FinalConversion.setFromType(ConvType); 6923 Candidate.FinalConversion.setAllToTypes(ToType); 6924 Candidate.Viable = true; 6925 Candidate.ExplicitCallArguments = 1; 6926 6927 // C++ [over.match.funcs]p4: 6928 // For conversion functions, the function is considered to be a member of 6929 // the class of the implicit implied object argument for the purpose of 6930 // defining the type of the implicit object parameter. 6931 // 6932 // Determine the implicit conversion sequence for the implicit 6933 // object parameter. 6934 QualType ImplicitParamType = From->getType(); 6935 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6936 ImplicitParamType = FromPtrType->getPointeeType(); 6937 CXXRecordDecl *ConversionContext 6938 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6939 6940 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6941 *this, CandidateSet.getLocation(), From->getType(), 6942 From->Classify(Context), Conversion, ConversionContext); 6943 6944 if (Candidate.Conversions[0].isBad()) { 6945 Candidate.Viable = false; 6946 Candidate.FailureKind = ovl_fail_bad_conversion; 6947 return; 6948 } 6949 6950 // We won't go through a user-defined type conversion function to convert a 6951 // derived to base as such conversions are given Conversion Rank. They only 6952 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6953 QualType FromCanon 6954 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6955 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6956 if (FromCanon == ToCanon || 6957 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6958 Candidate.Viable = false; 6959 Candidate.FailureKind = ovl_fail_trivial_conversion; 6960 return; 6961 } 6962 6963 // To determine what the conversion from the result of calling the 6964 // conversion function to the type we're eventually trying to 6965 // convert to (ToType), we need to synthesize a call to the 6966 // conversion function and attempt copy initialization from it. This 6967 // makes sure that we get the right semantics with respect to 6968 // lvalues/rvalues and the type. Fortunately, we can allocate this 6969 // call on the stack and we don't need its arguments to be 6970 // well-formed. 6971 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), VK_LValue, 6972 From->getBeginLoc()); 6973 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6974 Context.getPointerType(Conversion->getType()), 6975 CK_FunctionToPointerDecay, 6976 &ConversionRef, VK_RValue); 6977 6978 QualType ConversionType = Conversion->getConversionType(); 6979 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 6980 Candidate.Viable = false; 6981 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6982 return; 6983 } 6984 6985 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6986 6987 // Note that it is safe to allocate CallExpr on the stack here because 6988 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6989 // allocator). 6990 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6991 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6992 From->getBeginLoc()); 6993 ImplicitConversionSequence ICS = 6994 TryCopyInitialization(*this, &Call, ToType, 6995 /*SuppressUserConversions=*/true, 6996 /*InOverloadResolution=*/false, 6997 /*AllowObjCWritebackConversion=*/false); 6998 6999 switch (ICS.getKind()) { 7000 case ImplicitConversionSequence::StandardConversion: 7001 Candidate.FinalConversion = ICS.Standard; 7002 7003 // C++ [over.ics.user]p3: 7004 // If the user-defined conversion is specified by a specialization of a 7005 // conversion function template, the second standard conversion sequence 7006 // shall have exact match rank. 7007 if (Conversion->getPrimaryTemplate() && 7008 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7009 Candidate.Viable = false; 7010 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7011 return; 7012 } 7013 7014 // C++0x [dcl.init.ref]p5: 7015 // In the second case, if the reference is an rvalue reference and 7016 // the second standard conversion sequence of the user-defined 7017 // conversion sequence includes an lvalue-to-rvalue conversion, the 7018 // program is ill-formed. 7019 if (ToType->isRValueReferenceType() && 7020 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7021 Candidate.Viable = false; 7022 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7023 return; 7024 } 7025 break; 7026 7027 case ImplicitConversionSequence::BadConversion: 7028 Candidate.Viable = false; 7029 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7030 return; 7031 7032 default: 7033 llvm_unreachable( 7034 "Can only end up with a standard conversion sequence or failure"); 7035 } 7036 7037 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7038 Candidate.Viable = false; 7039 Candidate.FailureKind = ovl_fail_enable_if; 7040 Candidate.DeductionFailure.Data = FailedAttr; 7041 return; 7042 } 7043 7044 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7045 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7046 Candidate.Viable = false; 7047 Candidate.FailureKind = ovl_non_default_multiversion_function; 7048 } 7049 } 7050 7051 /// Adds a conversion function template specialization 7052 /// candidate to the overload set, using template argument deduction 7053 /// to deduce the template arguments of the conversion function 7054 /// template from the type that we are converting to (C++ 7055 /// [temp.deduct.conv]). 7056 void 7057 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7058 DeclAccessPair FoundDecl, 7059 CXXRecordDecl *ActingDC, 7060 Expr *From, QualType ToType, 7061 OverloadCandidateSet &CandidateSet, 7062 bool AllowObjCConversionOnExplicit, 7063 bool AllowResultConversion) { 7064 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7065 "Only conversion function templates permitted here"); 7066 7067 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7068 return; 7069 7070 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7071 CXXConversionDecl *Specialization = nullptr; 7072 if (TemplateDeductionResult Result 7073 = DeduceTemplateArguments(FunctionTemplate, ToType, 7074 Specialization, Info)) { 7075 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7076 Candidate.FoundDecl = FoundDecl; 7077 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7078 Candidate.Viable = false; 7079 Candidate.FailureKind = ovl_fail_bad_deduction; 7080 Candidate.IsSurrogate = false; 7081 Candidate.IgnoreObjectArgument = false; 7082 Candidate.ExplicitCallArguments = 1; 7083 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7084 Info); 7085 return; 7086 } 7087 7088 // Add the conversion function template specialization produced by 7089 // template argument deduction as a candidate. 7090 assert(Specialization && "Missing function template specialization?"); 7091 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7092 CandidateSet, AllowObjCConversionOnExplicit, 7093 AllowResultConversion); 7094 } 7095 7096 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7097 /// converts the given @c Object to a function pointer via the 7098 /// conversion function @c Conversion, and then attempts to call it 7099 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7100 /// the type of function that we'll eventually be calling. 7101 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7102 DeclAccessPair FoundDecl, 7103 CXXRecordDecl *ActingContext, 7104 const FunctionProtoType *Proto, 7105 Expr *Object, 7106 ArrayRef<Expr *> Args, 7107 OverloadCandidateSet& CandidateSet) { 7108 if (!CandidateSet.isNewCandidate(Conversion)) 7109 return; 7110 7111 // Overload resolution is always an unevaluated context. 7112 EnterExpressionEvaluationContext Unevaluated( 7113 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7114 7115 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7116 Candidate.FoundDecl = FoundDecl; 7117 Candidate.Function = nullptr; 7118 Candidate.Surrogate = Conversion; 7119 Candidate.Viable = true; 7120 Candidate.IsSurrogate = true; 7121 Candidate.IgnoreObjectArgument = false; 7122 Candidate.ExplicitCallArguments = Args.size(); 7123 7124 // Determine the implicit conversion sequence for the implicit 7125 // object parameter. 7126 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7127 *this, CandidateSet.getLocation(), Object->getType(), 7128 Object->Classify(Context), Conversion, ActingContext); 7129 if (ObjectInit.isBad()) { 7130 Candidate.Viable = false; 7131 Candidate.FailureKind = ovl_fail_bad_conversion; 7132 Candidate.Conversions[0] = ObjectInit; 7133 return; 7134 } 7135 7136 // The first conversion is actually a user-defined conversion whose 7137 // first conversion is ObjectInit's standard conversion (which is 7138 // effectively a reference binding). Record it as such. 7139 Candidate.Conversions[0].setUserDefined(); 7140 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7141 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7142 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7143 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7144 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7145 Candidate.Conversions[0].UserDefined.After 7146 = Candidate.Conversions[0].UserDefined.Before; 7147 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7148 7149 // Find the 7150 unsigned NumParams = Proto->getNumParams(); 7151 7152 // (C++ 13.3.2p2): A candidate function having fewer than m 7153 // parameters is viable only if it has an ellipsis in its parameter 7154 // list (8.3.5). 7155 if (Args.size() > NumParams && !Proto->isVariadic()) { 7156 Candidate.Viable = false; 7157 Candidate.FailureKind = ovl_fail_too_many_arguments; 7158 return; 7159 } 7160 7161 // Function types don't have any default arguments, so just check if 7162 // we have enough arguments. 7163 if (Args.size() < NumParams) { 7164 // Not enough arguments. 7165 Candidate.Viable = false; 7166 Candidate.FailureKind = ovl_fail_too_few_arguments; 7167 return; 7168 } 7169 7170 // Determine the implicit conversion sequences for each of the 7171 // arguments. 7172 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7173 if (ArgIdx < NumParams) { 7174 // (C++ 13.3.2p3): for F to be a viable function, there shall 7175 // exist for each argument an implicit conversion sequence 7176 // (13.3.3.1) that converts that argument to the corresponding 7177 // parameter of F. 7178 QualType ParamType = Proto->getParamType(ArgIdx); 7179 Candidate.Conversions[ArgIdx + 1] 7180 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7181 /*SuppressUserConversions=*/false, 7182 /*InOverloadResolution=*/false, 7183 /*AllowObjCWritebackConversion=*/ 7184 getLangOpts().ObjCAutoRefCount); 7185 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7186 Candidate.Viable = false; 7187 Candidate.FailureKind = ovl_fail_bad_conversion; 7188 return; 7189 } 7190 } else { 7191 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7192 // argument for which there is no corresponding parameter is 7193 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7194 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7195 } 7196 } 7197 7198 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7199 Candidate.Viable = false; 7200 Candidate.FailureKind = ovl_fail_enable_if; 7201 Candidate.DeductionFailure.Data = FailedAttr; 7202 return; 7203 } 7204 } 7205 7206 /// Add overload candidates for overloaded operators that are 7207 /// member functions. 7208 /// 7209 /// Add the overloaded operator candidates that are member functions 7210 /// for the operator Op that was used in an operator expression such 7211 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7212 /// CandidateSet will store the added overload candidates. (C++ 7213 /// [over.match.oper]). 7214 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7215 SourceLocation OpLoc, 7216 ArrayRef<Expr *> Args, 7217 OverloadCandidateSet& CandidateSet, 7218 SourceRange OpRange) { 7219 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7220 7221 // C++ [over.match.oper]p3: 7222 // For a unary operator @ with an operand of a type whose 7223 // cv-unqualified version is T1, and for a binary operator @ with 7224 // a left operand of a type whose cv-unqualified version is T1 and 7225 // a right operand of a type whose cv-unqualified version is T2, 7226 // three sets of candidate functions, designated member 7227 // candidates, non-member candidates and built-in candidates, are 7228 // constructed as follows: 7229 QualType T1 = Args[0]->getType(); 7230 7231 // -- If T1 is a complete class type or a class currently being 7232 // defined, the set of member candidates is the result of the 7233 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7234 // the set of member candidates is empty. 7235 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7236 // Complete the type if it can be completed. 7237 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7238 return; 7239 // If the type is neither complete nor being defined, bail out now. 7240 if (!T1Rec->getDecl()->getDefinition()) 7241 return; 7242 7243 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7244 LookupQualifiedName(Operators, T1Rec->getDecl()); 7245 Operators.suppressDiagnostics(); 7246 7247 for (LookupResult::iterator Oper = Operators.begin(), 7248 OperEnd = Operators.end(); 7249 Oper != OperEnd; 7250 ++Oper) 7251 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7252 Args[0]->Classify(Context), Args.slice(1), 7253 CandidateSet, /*SuppressUserConversions=*/false); 7254 } 7255 } 7256 7257 /// AddBuiltinCandidate - Add a candidate for a built-in 7258 /// operator. ResultTy and ParamTys are the result and parameter types 7259 /// of the built-in candidate, respectively. Args and NumArgs are the 7260 /// arguments being passed to the candidate. IsAssignmentOperator 7261 /// should be true when this built-in candidate is an assignment 7262 /// operator. NumContextualBoolArguments is the number of arguments 7263 /// (at the beginning of the argument list) that will be contextually 7264 /// converted to bool. 7265 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7266 OverloadCandidateSet& CandidateSet, 7267 bool IsAssignmentOperator, 7268 unsigned NumContextualBoolArguments) { 7269 // Overload resolution is always an unevaluated context. 7270 EnterExpressionEvaluationContext Unevaluated( 7271 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7272 7273 // Add this candidate 7274 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7275 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7276 Candidate.Function = nullptr; 7277 Candidate.IsSurrogate = false; 7278 Candidate.IgnoreObjectArgument = false; 7279 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7280 7281 // Determine the implicit conversion sequences for each of the 7282 // arguments. 7283 Candidate.Viable = true; 7284 Candidate.ExplicitCallArguments = Args.size(); 7285 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7286 // C++ [over.match.oper]p4: 7287 // For the built-in assignment operators, conversions of the 7288 // left operand are restricted as follows: 7289 // -- no temporaries are introduced to hold the left operand, and 7290 // -- no user-defined conversions are applied to the left 7291 // operand to achieve a type match with the left-most 7292 // parameter of a built-in candidate. 7293 // 7294 // We block these conversions by turning off user-defined 7295 // conversions, since that is the only way that initialization of 7296 // a reference to a non-class type can occur from something that 7297 // is not of the same type. 7298 if (ArgIdx < NumContextualBoolArguments) { 7299 assert(ParamTys[ArgIdx] == Context.BoolTy && 7300 "Contextual conversion to bool requires bool type"); 7301 Candidate.Conversions[ArgIdx] 7302 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7303 } else { 7304 Candidate.Conversions[ArgIdx] 7305 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7306 ArgIdx == 0 && IsAssignmentOperator, 7307 /*InOverloadResolution=*/false, 7308 /*AllowObjCWritebackConversion=*/ 7309 getLangOpts().ObjCAutoRefCount); 7310 } 7311 if (Candidate.Conversions[ArgIdx].isBad()) { 7312 Candidate.Viable = false; 7313 Candidate.FailureKind = ovl_fail_bad_conversion; 7314 break; 7315 } 7316 } 7317 } 7318 7319 namespace { 7320 7321 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7322 /// candidate operator functions for built-in operators (C++ 7323 /// [over.built]). The types are separated into pointer types and 7324 /// enumeration types. 7325 class BuiltinCandidateTypeSet { 7326 /// TypeSet - A set of types. 7327 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7328 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7329 7330 /// PointerTypes - The set of pointer types that will be used in the 7331 /// built-in candidates. 7332 TypeSet PointerTypes; 7333 7334 /// MemberPointerTypes - The set of member pointer types that will be 7335 /// used in the built-in candidates. 7336 TypeSet MemberPointerTypes; 7337 7338 /// EnumerationTypes - The set of enumeration types that will be 7339 /// used in the built-in candidates. 7340 TypeSet EnumerationTypes; 7341 7342 /// The set of vector types that will be used in the built-in 7343 /// candidates. 7344 TypeSet VectorTypes; 7345 7346 /// A flag indicating non-record types are viable candidates 7347 bool HasNonRecordTypes; 7348 7349 /// A flag indicating whether either arithmetic or enumeration types 7350 /// were present in the candidate set. 7351 bool HasArithmeticOrEnumeralTypes; 7352 7353 /// A flag indicating whether the nullptr type was present in the 7354 /// candidate set. 7355 bool HasNullPtrType; 7356 7357 /// Sema - The semantic analysis instance where we are building the 7358 /// candidate type set. 7359 Sema &SemaRef; 7360 7361 /// Context - The AST context in which we will build the type sets. 7362 ASTContext &Context; 7363 7364 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7365 const Qualifiers &VisibleQuals); 7366 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7367 7368 public: 7369 /// iterator - Iterates through the types that are part of the set. 7370 typedef TypeSet::iterator iterator; 7371 7372 BuiltinCandidateTypeSet(Sema &SemaRef) 7373 : HasNonRecordTypes(false), 7374 HasArithmeticOrEnumeralTypes(false), 7375 HasNullPtrType(false), 7376 SemaRef(SemaRef), 7377 Context(SemaRef.Context) { } 7378 7379 void AddTypesConvertedFrom(QualType Ty, 7380 SourceLocation Loc, 7381 bool AllowUserConversions, 7382 bool AllowExplicitConversions, 7383 const Qualifiers &VisibleTypeConversionsQuals); 7384 7385 /// pointer_begin - First pointer type found; 7386 iterator pointer_begin() { return PointerTypes.begin(); } 7387 7388 /// pointer_end - Past the last pointer type found; 7389 iterator pointer_end() { return PointerTypes.end(); } 7390 7391 /// member_pointer_begin - First member pointer type found; 7392 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7393 7394 /// member_pointer_end - Past the last member pointer type found; 7395 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7396 7397 /// enumeration_begin - First enumeration type found; 7398 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7399 7400 /// enumeration_end - Past the last enumeration type found; 7401 iterator enumeration_end() { return EnumerationTypes.end(); } 7402 7403 iterator vector_begin() { return VectorTypes.begin(); } 7404 iterator vector_end() { return VectorTypes.end(); } 7405 7406 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7407 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7408 bool hasNullPtrType() const { return HasNullPtrType; } 7409 }; 7410 7411 } // end anonymous namespace 7412 7413 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7414 /// the set of pointer types along with any more-qualified variants of 7415 /// that type. For example, if @p Ty is "int const *", this routine 7416 /// will add "int const *", "int const volatile *", "int const 7417 /// restrict *", and "int const volatile restrict *" to the set of 7418 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7419 /// false otherwise. 7420 /// 7421 /// FIXME: what to do about extended qualifiers? 7422 bool 7423 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7424 const Qualifiers &VisibleQuals) { 7425 7426 // Insert this type. 7427 if (!PointerTypes.insert(Ty)) 7428 return false; 7429 7430 QualType PointeeTy; 7431 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7432 bool buildObjCPtr = false; 7433 if (!PointerTy) { 7434 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7435 PointeeTy = PTy->getPointeeType(); 7436 buildObjCPtr = true; 7437 } else { 7438 PointeeTy = PointerTy->getPointeeType(); 7439 } 7440 7441 // Don't add qualified variants of arrays. For one, they're not allowed 7442 // (the qualifier would sink to the element type), and for another, the 7443 // only overload situation where it matters is subscript or pointer +- int, 7444 // and those shouldn't have qualifier variants anyway. 7445 if (PointeeTy->isArrayType()) 7446 return true; 7447 7448 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7449 bool hasVolatile = VisibleQuals.hasVolatile(); 7450 bool hasRestrict = VisibleQuals.hasRestrict(); 7451 7452 // Iterate through all strict supersets of BaseCVR. 7453 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7454 if ((CVR | BaseCVR) != CVR) continue; 7455 // Skip over volatile if no volatile found anywhere in the types. 7456 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7457 7458 // Skip over restrict if no restrict found anywhere in the types, or if 7459 // the type cannot be restrict-qualified. 7460 if ((CVR & Qualifiers::Restrict) && 7461 (!hasRestrict || 7462 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7463 continue; 7464 7465 // Build qualified pointee type. 7466 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7467 7468 // Build qualified pointer type. 7469 QualType QPointerTy; 7470 if (!buildObjCPtr) 7471 QPointerTy = Context.getPointerType(QPointeeTy); 7472 else 7473 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7474 7475 // Insert qualified pointer type. 7476 PointerTypes.insert(QPointerTy); 7477 } 7478 7479 return true; 7480 } 7481 7482 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7483 /// to the set of pointer types along with any more-qualified variants of 7484 /// that type. For example, if @p Ty is "int const *", this routine 7485 /// will add "int const *", "int const volatile *", "int const 7486 /// restrict *", and "int const volatile restrict *" to the set of 7487 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7488 /// false otherwise. 7489 /// 7490 /// FIXME: what to do about extended qualifiers? 7491 bool 7492 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7493 QualType Ty) { 7494 // Insert this type. 7495 if (!MemberPointerTypes.insert(Ty)) 7496 return false; 7497 7498 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7499 assert(PointerTy && "type was not a member pointer type!"); 7500 7501 QualType PointeeTy = PointerTy->getPointeeType(); 7502 // Don't add qualified variants of arrays. For one, they're not allowed 7503 // (the qualifier would sink to the element type), and for another, the 7504 // only overload situation where it matters is subscript or pointer +- int, 7505 // and those shouldn't have qualifier variants anyway. 7506 if (PointeeTy->isArrayType()) 7507 return true; 7508 const Type *ClassTy = PointerTy->getClass(); 7509 7510 // Iterate through all strict supersets of the pointee type's CVR 7511 // qualifiers. 7512 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7513 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7514 if ((CVR | BaseCVR) != CVR) continue; 7515 7516 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7517 MemberPointerTypes.insert( 7518 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7519 } 7520 7521 return true; 7522 } 7523 7524 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7525 /// Ty can be implicit converted to the given set of @p Types. We're 7526 /// primarily interested in pointer types and enumeration types. We also 7527 /// take member pointer types, for the conditional operator. 7528 /// AllowUserConversions is true if we should look at the conversion 7529 /// functions of a class type, and AllowExplicitConversions if we 7530 /// should also include the explicit conversion functions of a class 7531 /// type. 7532 void 7533 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7534 SourceLocation Loc, 7535 bool AllowUserConversions, 7536 bool AllowExplicitConversions, 7537 const Qualifiers &VisibleQuals) { 7538 // Only deal with canonical types. 7539 Ty = Context.getCanonicalType(Ty); 7540 7541 // Look through reference types; they aren't part of the type of an 7542 // expression for the purposes of conversions. 7543 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7544 Ty = RefTy->getPointeeType(); 7545 7546 // If we're dealing with an array type, decay to the pointer. 7547 if (Ty->isArrayType()) 7548 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7549 7550 // Otherwise, we don't care about qualifiers on the type. 7551 Ty = Ty.getLocalUnqualifiedType(); 7552 7553 // Flag if we ever add a non-record type. 7554 const RecordType *TyRec = Ty->getAs<RecordType>(); 7555 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7556 7557 // Flag if we encounter an arithmetic type. 7558 HasArithmeticOrEnumeralTypes = 7559 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7560 7561 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7562 PointerTypes.insert(Ty); 7563 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7564 // Insert our type, and its more-qualified variants, into the set 7565 // of types. 7566 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7567 return; 7568 } else if (Ty->isMemberPointerType()) { 7569 // Member pointers are far easier, since the pointee can't be converted. 7570 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7571 return; 7572 } else if (Ty->isEnumeralType()) { 7573 HasArithmeticOrEnumeralTypes = true; 7574 EnumerationTypes.insert(Ty); 7575 } else if (Ty->isVectorType()) { 7576 // We treat vector types as arithmetic types in many contexts as an 7577 // extension. 7578 HasArithmeticOrEnumeralTypes = true; 7579 VectorTypes.insert(Ty); 7580 } else if (Ty->isNullPtrType()) { 7581 HasNullPtrType = true; 7582 } else if (AllowUserConversions && TyRec) { 7583 // No conversion functions in incomplete types. 7584 if (!SemaRef.isCompleteType(Loc, Ty)) 7585 return; 7586 7587 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7588 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7589 if (isa<UsingShadowDecl>(D)) 7590 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7591 7592 // Skip conversion function templates; they don't tell us anything 7593 // about which builtin types we can convert to. 7594 if (isa<FunctionTemplateDecl>(D)) 7595 continue; 7596 7597 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7598 if (AllowExplicitConversions || !Conv->isExplicit()) { 7599 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7600 VisibleQuals); 7601 } 7602 } 7603 } 7604 } 7605 7606 /// Helper function for AddBuiltinOperatorCandidates() that adds 7607 /// the volatile- and non-volatile-qualified assignment operators for the 7608 /// given type to the candidate set. 7609 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7610 QualType T, 7611 ArrayRef<Expr *> Args, 7612 OverloadCandidateSet &CandidateSet) { 7613 QualType ParamTypes[2]; 7614 7615 // T& operator=(T&, T) 7616 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7617 ParamTypes[1] = T; 7618 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7619 /*IsAssignmentOperator=*/true); 7620 7621 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7622 // volatile T& operator=(volatile T&, T) 7623 ParamTypes[0] 7624 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7625 ParamTypes[1] = T; 7626 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7627 /*IsAssignmentOperator=*/true); 7628 } 7629 } 7630 7631 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7632 /// if any, found in visible type conversion functions found in ArgExpr's type. 7633 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7634 Qualifiers VRQuals; 7635 const RecordType *TyRec; 7636 if (const MemberPointerType *RHSMPType = 7637 ArgExpr->getType()->getAs<MemberPointerType>()) 7638 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7639 else 7640 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7641 if (!TyRec) { 7642 // Just to be safe, assume the worst case. 7643 VRQuals.addVolatile(); 7644 VRQuals.addRestrict(); 7645 return VRQuals; 7646 } 7647 7648 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7649 if (!ClassDecl->hasDefinition()) 7650 return VRQuals; 7651 7652 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7653 if (isa<UsingShadowDecl>(D)) 7654 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7655 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7656 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7657 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7658 CanTy = ResTypeRef->getPointeeType(); 7659 // Need to go down the pointer/mempointer chain and add qualifiers 7660 // as see them. 7661 bool done = false; 7662 while (!done) { 7663 if (CanTy.isRestrictQualified()) 7664 VRQuals.addRestrict(); 7665 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7666 CanTy = ResTypePtr->getPointeeType(); 7667 else if (const MemberPointerType *ResTypeMPtr = 7668 CanTy->getAs<MemberPointerType>()) 7669 CanTy = ResTypeMPtr->getPointeeType(); 7670 else 7671 done = true; 7672 if (CanTy.isVolatileQualified()) 7673 VRQuals.addVolatile(); 7674 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7675 return VRQuals; 7676 } 7677 } 7678 } 7679 return VRQuals; 7680 } 7681 7682 namespace { 7683 7684 /// Helper class to manage the addition of builtin operator overload 7685 /// candidates. It provides shared state and utility methods used throughout 7686 /// the process, as well as a helper method to add each group of builtin 7687 /// operator overloads from the standard to a candidate set. 7688 class BuiltinOperatorOverloadBuilder { 7689 // Common instance state available to all overload candidate addition methods. 7690 Sema &S; 7691 ArrayRef<Expr *> Args; 7692 Qualifiers VisibleTypeConversionsQuals; 7693 bool HasArithmeticOrEnumeralCandidateType; 7694 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7695 OverloadCandidateSet &CandidateSet; 7696 7697 static constexpr int ArithmeticTypesCap = 24; 7698 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7699 7700 // Define some indices used to iterate over the arithemetic types in 7701 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7702 // types are that preserved by promotion (C++ [over.built]p2). 7703 unsigned FirstIntegralType, 7704 LastIntegralType; 7705 unsigned FirstPromotedIntegralType, 7706 LastPromotedIntegralType; 7707 unsigned FirstPromotedArithmeticType, 7708 LastPromotedArithmeticType; 7709 unsigned NumArithmeticTypes; 7710 7711 void InitArithmeticTypes() { 7712 // Start of promoted types. 7713 FirstPromotedArithmeticType = 0; 7714 ArithmeticTypes.push_back(S.Context.FloatTy); 7715 ArithmeticTypes.push_back(S.Context.DoubleTy); 7716 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7717 if (S.Context.getTargetInfo().hasFloat128Type()) 7718 ArithmeticTypes.push_back(S.Context.Float128Ty); 7719 7720 // Start of integral types. 7721 FirstIntegralType = ArithmeticTypes.size(); 7722 FirstPromotedIntegralType = ArithmeticTypes.size(); 7723 ArithmeticTypes.push_back(S.Context.IntTy); 7724 ArithmeticTypes.push_back(S.Context.LongTy); 7725 ArithmeticTypes.push_back(S.Context.LongLongTy); 7726 if (S.Context.getTargetInfo().hasInt128Type()) 7727 ArithmeticTypes.push_back(S.Context.Int128Ty); 7728 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7729 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7730 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7731 if (S.Context.getTargetInfo().hasInt128Type()) 7732 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7733 LastPromotedIntegralType = ArithmeticTypes.size(); 7734 LastPromotedArithmeticType = ArithmeticTypes.size(); 7735 // End of promoted types. 7736 7737 ArithmeticTypes.push_back(S.Context.BoolTy); 7738 ArithmeticTypes.push_back(S.Context.CharTy); 7739 ArithmeticTypes.push_back(S.Context.WCharTy); 7740 if (S.Context.getLangOpts().Char8) 7741 ArithmeticTypes.push_back(S.Context.Char8Ty); 7742 ArithmeticTypes.push_back(S.Context.Char16Ty); 7743 ArithmeticTypes.push_back(S.Context.Char32Ty); 7744 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7745 ArithmeticTypes.push_back(S.Context.ShortTy); 7746 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7747 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7748 LastIntegralType = ArithmeticTypes.size(); 7749 NumArithmeticTypes = ArithmeticTypes.size(); 7750 // End of integral types. 7751 // FIXME: What about complex? What about half? 7752 7753 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7754 "Enough inline storage for all arithmetic types."); 7755 } 7756 7757 /// Helper method to factor out the common pattern of adding overloads 7758 /// for '++' and '--' builtin operators. 7759 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7760 bool HasVolatile, 7761 bool HasRestrict) { 7762 QualType ParamTypes[2] = { 7763 S.Context.getLValueReferenceType(CandidateTy), 7764 S.Context.IntTy 7765 }; 7766 7767 // Non-volatile version. 7768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7769 7770 // Use a heuristic to reduce number of builtin candidates in the set: 7771 // add volatile version only if there are conversions to a volatile type. 7772 if (HasVolatile) { 7773 ParamTypes[0] = 7774 S.Context.getLValueReferenceType( 7775 S.Context.getVolatileType(CandidateTy)); 7776 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7777 } 7778 7779 // Add restrict version only if there are conversions to a restrict type 7780 // and our candidate type is a non-restrict-qualified pointer. 7781 if (HasRestrict && CandidateTy->isAnyPointerType() && 7782 !CandidateTy.isRestrictQualified()) { 7783 ParamTypes[0] 7784 = S.Context.getLValueReferenceType( 7785 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7786 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7787 7788 if (HasVolatile) { 7789 ParamTypes[0] 7790 = S.Context.getLValueReferenceType( 7791 S.Context.getCVRQualifiedType(CandidateTy, 7792 (Qualifiers::Volatile | 7793 Qualifiers::Restrict))); 7794 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7795 } 7796 } 7797 7798 } 7799 7800 public: 7801 BuiltinOperatorOverloadBuilder( 7802 Sema &S, ArrayRef<Expr *> Args, 7803 Qualifiers VisibleTypeConversionsQuals, 7804 bool HasArithmeticOrEnumeralCandidateType, 7805 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7806 OverloadCandidateSet &CandidateSet) 7807 : S(S), Args(Args), 7808 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7809 HasArithmeticOrEnumeralCandidateType( 7810 HasArithmeticOrEnumeralCandidateType), 7811 CandidateTypes(CandidateTypes), 7812 CandidateSet(CandidateSet) { 7813 7814 InitArithmeticTypes(); 7815 } 7816 7817 // Increment is deprecated for bool since C++17. 7818 // 7819 // C++ [over.built]p3: 7820 // 7821 // For every pair (T, VQ), where T is an arithmetic type other 7822 // than bool, and VQ is either volatile or empty, there exist 7823 // candidate operator functions of the form 7824 // 7825 // VQ T& operator++(VQ T&); 7826 // T operator++(VQ T&, int); 7827 // 7828 // C++ [over.built]p4: 7829 // 7830 // For every pair (T, VQ), where T is an arithmetic type other 7831 // than bool, and VQ is either volatile or empty, there exist 7832 // candidate operator functions of the form 7833 // 7834 // VQ T& operator--(VQ T&); 7835 // T operator--(VQ T&, int); 7836 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7837 if (!HasArithmeticOrEnumeralCandidateType) 7838 return; 7839 7840 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7841 const auto TypeOfT = ArithmeticTypes[Arith]; 7842 if (TypeOfT == S.Context.BoolTy) { 7843 if (Op == OO_MinusMinus) 7844 continue; 7845 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7846 continue; 7847 } 7848 addPlusPlusMinusMinusStyleOverloads( 7849 TypeOfT, 7850 VisibleTypeConversionsQuals.hasVolatile(), 7851 VisibleTypeConversionsQuals.hasRestrict()); 7852 } 7853 } 7854 7855 // C++ [over.built]p5: 7856 // 7857 // For every pair (T, VQ), where T is a cv-qualified or 7858 // cv-unqualified object type, and VQ is either volatile or 7859 // empty, there exist candidate operator functions of the form 7860 // 7861 // T*VQ& operator++(T*VQ&); 7862 // T*VQ& operator--(T*VQ&); 7863 // T* operator++(T*VQ&, int); 7864 // T* operator--(T*VQ&, int); 7865 void addPlusPlusMinusMinusPointerOverloads() { 7866 for (BuiltinCandidateTypeSet::iterator 7867 Ptr = CandidateTypes[0].pointer_begin(), 7868 PtrEnd = CandidateTypes[0].pointer_end(); 7869 Ptr != PtrEnd; ++Ptr) { 7870 // Skip pointer types that aren't pointers to object types. 7871 if (!(*Ptr)->getPointeeType()->isObjectType()) 7872 continue; 7873 7874 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7875 (!(*Ptr).isVolatileQualified() && 7876 VisibleTypeConversionsQuals.hasVolatile()), 7877 (!(*Ptr).isRestrictQualified() && 7878 VisibleTypeConversionsQuals.hasRestrict())); 7879 } 7880 } 7881 7882 // C++ [over.built]p6: 7883 // For every cv-qualified or cv-unqualified object type T, there 7884 // exist candidate operator functions of the form 7885 // 7886 // T& operator*(T*); 7887 // 7888 // C++ [over.built]p7: 7889 // For every function type T that does not have cv-qualifiers or a 7890 // ref-qualifier, there exist candidate operator functions of the form 7891 // T& operator*(T*); 7892 void addUnaryStarPointerOverloads() { 7893 for (BuiltinCandidateTypeSet::iterator 7894 Ptr = CandidateTypes[0].pointer_begin(), 7895 PtrEnd = CandidateTypes[0].pointer_end(); 7896 Ptr != PtrEnd; ++Ptr) { 7897 QualType ParamTy = *Ptr; 7898 QualType PointeeTy = ParamTy->getPointeeType(); 7899 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7900 continue; 7901 7902 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7903 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7904 continue; 7905 7906 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7907 } 7908 } 7909 7910 // C++ [over.built]p9: 7911 // For every promoted arithmetic type T, there exist candidate 7912 // operator functions of the form 7913 // 7914 // T operator+(T); 7915 // T operator-(T); 7916 void addUnaryPlusOrMinusArithmeticOverloads() { 7917 if (!HasArithmeticOrEnumeralCandidateType) 7918 return; 7919 7920 for (unsigned Arith = FirstPromotedArithmeticType; 7921 Arith < LastPromotedArithmeticType; ++Arith) { 7922 QualType ArithTy = ArithmeticTypes[Arith]; 7923 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7924 } 7925 7926 // Extension: We also add these operators for vector types. 7927 for (BuiltinCandidateTypeSet::iterator 7928 Vec = CandidateTypes[0].vector_begin(), 7929 VecEnd = CandidateTypes[0].vector_end(); 7930 Vec != VecEnd; ++Vec) { 7931 QualType VecTy = *Vec; 7932 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7933 } 7934 } 7935 7936 // C++ [over.built]p8: 7937 // For every type T, there exist candidate operator functions of 7938 // the form 7939 // 7940 // T* operator+(T*); 7941 void addUnaryPlusPointerOverloads() { 7942 for (BuiltinCandidateTypeSet::iterator 7943 Ptr = CandidateTypes[0].pointer_begin(), 7944 PtrEnd = CandidateTypes[0].pointer_end(); 7945 Ptr != PtrEnd; ++Ptr) { 7946 QualType ParamTy = *Ptr; 7947 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7948 } 7949 } 7950 7951 // C++ [over.built]p10: 7952 // For every promoted integral type T, there exist candidate 7953 // operator functions of the form 7954 // 7955 // T operator~(T); 7956 void addUnaryTildePromotedIntegralOverloads() { 7957 if (!HasArithmeticOrEnumeralCandidateType) 7958 return; 7959 7960 for (unsigned Int = FirstPromotedIntegralType; 7961 Int < LastPromotedIntegralType; ++Int) { 7962 QualType IntTy = ArithmeticTypes[Int]; 7963 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 7964 } 7965 7966 // Extension: We also add this operator for vector types. 7967 for (BuiltinCandidateTypeSet::iterator 7968 Vec = CandidateTypes[0].vector_begin(), 7969 VecEnd = CandidateTypes[0].vector_end(); 7970 Vec != VecEnd; ++Vec) { 7971 QualType VecTy = *Vec; 7972 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7973 } 7974 } 7975 7976 // C++ [over.match.oper]p16: 7977 // For every pointer to member type T or type std::nullptr_t, there 7978 // exist candidate operator functions of the form 7979 // 7980 // bool operator==(T,T); 7981 // bool operator!=(T,T); 7982 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7983 /// Set of (canonical) types that we've already handled. 7984 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7985 7986 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7987 for (BuiltinCandidateTypeSet::iterator 7988 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7989 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7990 MemPtr != MemPtrEnd; 7991 ++MemPtr) { 7992 // Don't add the same builtin candidate twice. 7993 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7994 continue; 7995 7996 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7997 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7998 } 7999 8000 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8001 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8002 if (AddedTypes.insert(NullPtrTy).second) { 8003 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8004 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8005 } 8006 } 8007 } 8008 } 8009 8010 // C++ [over.built]p15: 8011 // 8012 // For every T, where T is an enumeration type or a pointer type, 8013 // there exist candidate operator functions of the form 8014 // 8015 // bool operator<(T, T); 8016 // bool operator>(T, T); 8017 // bool operator<=(T, T); 8018 // bool operator>=(T, T); 8019 // bool operator==(T, T); 8020 // bool operator!=(T, T); 8021 // R operator<=>(T, T) 8022 void addGenericBinaryPointerOrEnumeralOverloads() { 8023 // C++ [over.match.oper]p3: 8024 // [...]the built-in candidates include all of the candidate operator 8025 // functions defined in 13.6 that, compared to the given operator, [...] 8026 // do not have the same parameter-type-list as any non-template non-member 8027 // candidate. 8028 // 8029 // Note that in practice, this only affects enumeration types because there 8030 // aren't any built-in candidates of record type, and a user-defined operator 8031 // must have an operand of record or enumeration type. Also, the only other 8032 // overloaded operator with enumeration arguments, operator=, 8033 // cannot be overloaded for enumeration types, so this is the only place 8034 // where we must suppress candidates like this. 8035 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8036 UserDefinedBinaryOperators; 8037 8038 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8039 if (CandidateTypes[ArgIdx].enumeration_begin() != 8040 CandidateTypes[ArgIdx].enumeration_end()) { 8041 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8042 CEnd = CandidateSet.end(); 8043 C != CEnd; ++C) { 8044 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8045 continue; 8046 8047 if (C->Function->isFunctionTemplateSpecialization()) 8048 continue; 8049 8050 QualType FirstParamType = 8051 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8052 QualType SecondParamType = 8053 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8054 8055 // Skip if either parameter isn't of enumeral type. 8056 if (!FirstParamType->isEnumeralType() || 8057 !SecondParamType->isEnumeralType()) 8058 continue; 8059 8060 // Add this operator to the set of known user-defined operators. 8061 UserDefinedBinaryOperators.insert( 8062 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8063 S.Context.getCanonicalType(SecondParamType))); 8064 } 8065 } 8066 } 8067 8068 /// Set of (canonical) types that we've already handled. 8069 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8070 8071 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8072 for (BuiltinCandidateTypeSet::iterator 8073 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8074 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8075 Ptr != PtrEnd; ++Ptr) { 8076 // Don't add the same builtin candidate twice. 8077 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8078 continue; 8079 8080 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8082 } 8083 for (BuiltinCandidateTypeSet::iterator 8084 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8085 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8086 Enum != EnumEnd; ++Enum) { 8087 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8088 8089 // Don't add the same builtin candidate twice, or if a user defined 8090 // candidate exists. 8091 if (!AddedTypes.insert(CanonType).second || 8092 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8093 CanonType))) 8094 continue; 8095 QualType ParamTypes[2] = { *Enum, *Enum }; 8096 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8097 } 8098 } 8099 } 8100 8101 // C++ [over.built]p13: 8102 // 8103 // For every cv-qualified or cv-unqualified object type T 8104 // there exist candidate operator functions of the form 8105 // 8106 // T* operator+(T*, ptrdiff_t); 8107 // T& operator[](T*, ptrdiff_t); [BELOW] 8108 // T* operator-(T*, ptrdiff_t); 8109 // T* operator+(ptrdiff_t, T*); 8110 // T& operator[](ptrdiff_t, T*); [BELOW] 8111 // 8112 // C++ [over.built]p14: 8113 // 8114 // For every T, where T is a pointer to object type, there 8115 // exist candidate operator functions of the form 8116 // 8117 // ptrdiff_t operator-(T, T); 8118 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8119 /// Set of (canonical) types that we've already handled. 8120 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8121 8122 for (int Arg = 0; Arg < 2; ++Arg) { 8123 QualType AsymmetricParamTypes[2] = { 8124 S.Context.getPointerDiffType(), 8125 S.Context.getPointerDiffType(), 8126 }; 8127 for (BuiltinCandidateTypeSet::iterator 8128 Ptr = CandidateTypes[Arg].pointer_begin(), 8129 PtrEnd = CandidateTypes[Arg].pointer_end(); 8130 Ptr != PtrEnd; ++Ptr) { 8131 QualType PointeeTy = (*Ptr)->getPointeeType(); 8132 if (!PointeeTy->isObjectType()) 8133 continue; 8134 8135 AsymmetricParamTypes[Arg] = *Ptr; 8136 if (Arg == 0 || Op == OO_Plus) { 8137 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8138 // T* operator+(ptrdiff_t, T*); 8139 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8140 } 8141 if (Op == OO_Minus) { 8142 // ptrdiff_t operator-(T, T); 8143 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8144 continue; 8145 8146 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8148 } 8149 } 8150 } 8151 } 8152 8153 // C++ [over.built]p12: 8154 // 8155 // For every pair of promoted arithmetic types L and R, there 8156 // exist candidate operator functions of the form 8157 // 8158 // LR operator*(L, R); 8159 // LR operator/(L, R); 8160 // LR operator+(L, R); 8161 // LR operator-(L, R); 8162 // bool operator<(L, R); 8163 // bool operator>(L, R); 8164 // bool operator<=(L, R); 8165 // bool operator>=(L, R); 8166 // bool operator==(L, R); 8167 // bool operator!=(L, R); 8168 // 8169 // where LR is the result of the usual arithmetic conversions 8170 // between types L and R. 8171 // 8172 // C++ [over.built]p24: 8173 // 8174 // For every pair of promoted arithmetic types L and R, there exist 8175 // candidate operator functions of the form 8176 // 8177 // LR operator?(bool, L, R); 8178 // 8179 // where LR is the result of the usual arithmetic conversions 8180 // between types L and R. 8181 // Our candidates ignore the first parameter. 8182 void addGenericBinaryArithmeticOverloads() { 8183 if (!HasArithmeticOrEnumeralCandidateType) 8184 return; 8185 8186 for (unsigned Left = FirstPromotedArithmeticType; 8187 Left < LastPromotedArithmeticType; ++Left) { 8188 for (unsigned Right = FirstPromotedArithmeticType; 8189 Right < LastPromotedArithmeticType; ++Right) { 8190 QualType LandR[2] = { ArithmeticTypes[Left], 8191 ArithmeticTypes[Right] }; 8192 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8193 } 8194 } 8195 8196 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8197 // conditional operator for vector types. 8198 for (BuiltinCandidateTypeSet::iterator 8199 Vec1 = CandidateTypes[0].vector_begin(), 8200 Vec1End = CandidateTypes[0].vector_end(); 8201 Vec1 != Vec1End; ++Vec1) { 8202 for (BuiltinCandidateTypeSet::iterator 8203 Vec2 = CandidateTypes[1].vector_begin(), 8204 Vec2End = CandidateTypes[1].vector_end(); 8205 Vec2 != Vec2End; ++Vec2) { 8206 QualType LandR[2] = { *Vec1, *Vec2 }; 8207 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8208 } 8209 } 8210 } 8211 8212 // C++2a [over.built]p14: 8213 // 8214 // For every integral type T there exists a candidate operator function 8215 // of the form 8216 // 8217 // std::strong_ordering operator<=>(T, T) 8218 // 8219 // C++2a [over.built]p15: 8220 // 8221 // For every pair of floating-point types L and R, there exists a candidate 8222 // operator function of the form 8223 // 8224 // std::partial_ordering operator<=>(L, R); 8225 // 8226 // FIXME: The current specification for integral types doesn't play nice with 8227 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8228 // comparisons. Under the current spec this can lead to ambiguity during 8229 // overload resolution. For example: 8230 // 8231 // enum A : int {a}; 8232 // auto x = (a <=> (long)42); 8233 // 8234 // error: call is ambiguous for arguments 'A' and 'long'. 8235 // note: candidate operator<=>(int, int) 8236 // note: candidate operator<=>(long, long) 8237 // 8238 // To avoid this error, this function deviates from the specification and adds 8239 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8240 // arithmetic types (the same as the generic relational overloads). 8241 // 8242 // For now this function acts as a placeholder. 8243 void addThreeWayArithmeticOverloads() { 8244 addGenericBinaryArithmeticOverloads(); 8245 } 8246 8247 // C++ [over.built]p17: 8248 // 8249 // For every pair of promoted integral types L and R, there 8250 // exist candidate operator functions of the form 8251 // 8252 // LR operator%(L, R); 8253 // LR operator&(L, R); 8254 // LR operator^(L, R); 8255 // LR operator|(L, R); 8256 // L operator<<(L, R); 8257 // L operator>>(L, R); 8258 // 8259 // where LR is the result of the usual arithmetic conversions 8260 // between types L and R. 8261 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8262 if (!HasArithmeticOrEnumeralCandidateType) 8263 return; 8264 8265 for (unsigned Left = FirstPromotedIntegralType; 8266 Left < LastPromotedIntegralType; ++Left) { 8267 for (unsigned Right = FirstPromotedIntegralType; 8268 Right < LastPromotedIntegralType; ++Right) { 8269 QualType LandR[2] = { ArithmeticTypes[Left], 8270 ArithmeticTypes[Right] }; 8271 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8272 } 8273 } 8274 } 8275 8276 // C++ [over.built]p20: 8277 // 8278 // For every pair (T, VQ), where T is an enumeration or 8279 // pointer to member type and VQ is either volatile or 8280 // empty, there exist candidate operator functions of the form 8281 // 8282 // VQ T& operator=(VQ T&, T); 8283 void addAssignmentMemberPointerOrEnumeralOverloads() { 8284 /// Set of (canonical) types that we've already handled. 8285 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8286 8287 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8288 for (BuiltinCandidateTypeSet::iterator 8289 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8290 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8291 Enum != EnumEnd; ++Enum) { 8292 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8293 continue; 8294 8295 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8296 } 8297 8298 for (BuiltinCandidateTypeSet::iterator 8299 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8300 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8301 MemPtr != MemPtrEnd; ++MemPtr) { 8302 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8303 continue; 8304 8305 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8306 } 8307 } 8308 } 8309 8310 // C++ [over.built]p19: 8311 // 8312 // For every pair (T, VQ), where T is any type and VQ is either 8313 // volatile or empty, there exist candidate operator functions 8314 // of the form 8315 // 8316 // T*VQ& operator=(T*VQ&, T*); 8317 // 8318 // C++ [over.built]p21: 8319 // 8320 // For every pair (T, VQ), where T is a cv-qualified or 8321 // cv-unqualified object type and VQ is either volatile or 8322 // empty, there exist candidate operator functions of the form 8323 // 8324 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8325 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8326 void addAssignmentPointerOverloads(bool isEqualOp) { 8327 /// Set of (canonical) types that we've already handled. 8328 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8329 8330 for (BuiltinCandidateTypeSet::iterator 8331 Ptr = CandidateTypes[0].pointer_begin(), 8332 PtrEnd = CandidateTypes[0].pointer_end(); 8333 Ptr != PtrEnd; ++Ptr) { 8334 // If this is operator=, keep track of the builtin candidates we added. 8335 if (isEqualOp) 8336 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8337 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8338 continue; 8339 8340 // non-volatile version 8341 QualType ParamTypes[2] = { 8342 S.Context.getLValueReferenceType(*Ptr), 8343 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8344 }; 8345 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8346 /*IsAssigmentOperator=*/ isEqualOp); 8347 8348 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8349 VisibleTypeConversionsQuals.hasVolatile(); 8350 if (NeedVolatile) { 8351 // volatile version 8352 ParamTypes[0] = 8353 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8354 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8355 /*IsAssigmentOperator=*/isEqualOp); 8356 } 8357 8358 if (!(*Ptr).isRestrictQualified() && 8359 VisibleTypeConversionsQuals.hasRestrict()) { 8360 // restrict version 8361 ParamTypes[0] 8362 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8363 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8364 /*IsAssigmentOperator=*/isEqualOp); 8365 8366 if (NeedVolatile) { 8367 // volatile restrict version 8368 ParamTypes[0] 8369 = S.Context.getLValueReferenceType( 8370 S.Context.getCVRQualifiedType(*Ptr, 8371 (Qualifiers::Volatile | 8372 Qualifiers::Restrict))); 8373 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8374 /*IsAssigmentOperator=*/isEqualOp); 8375 } 8376 } 8377 } 8378 8379 if (isEqualOp) { 8380 for (BuiltinCandidateTypeSet::iterator 8381 Ptr = CandidateTypes[1].pointer_begin(), 8382 PtrEnd = CandidateTypes[1].pointer_end(); 8383 Ptr != PtrEnd; ++Ptr) { 8384 // Make sure we don't add the same candidate twice. 8385 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8386 continue; 8387 8388 QualType ParamTypes[2] = { 8389 S.Context.getLValueReferenceType(*Ptr), 8390 *Ptr, 8391 }; 8392 8393 // non-volatile version 8394 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8395 /*IsAssigmentOperator=*/true); 8396 8397 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8398 VisibleTypeConversionsQuals.hasVolatile(); 8399 if (NeedVolatile) { 8400 // volatile version 8401 ParamTypes[0] = 8402 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8403 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8404 /*IsAssigmentOperator=*/true); 8405 } 8406 8407 if (!(*Ptr).isRestrictQualified() && 8408 VisibleTypeConversionsQuals.hasRestrict()) { 8409 // restrict version 8410 ParamTypes[0] 8411 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8412 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8413 /*IsAssigmentOperator=*/true); 8414 8415 if (NeedVolatile) { 8416 // volatile restrict version 8417 ParamTypes[0] 8418 = S.Context.getLValueReferenceType( 8419 S.Context.getCVRQualifiedType(*Ptr, 8420 (Qualifiers::Volatile | 8421 Qualifiers::Restrict))); 8422 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8423 /*IsAssigmentOperator=*/true); 8424 } 8425 } 8426 } 8427 } 8428 } 8429 8430 // C++ [over.built]p18: 8431 // 8432 // For every triple (L, VQ, R), where L is an arithmetic type, 8433 // VQ is either volatile or empty, and R is a promoted 8434 // arithmetic type, there exist candidate operator functions of 8435 // the form 8436 // 8437 // VQ L& operator=(VQ L&, R); 8438 // VQ L& operator*=(VQ L&, R); 8439 // VQ L& operator/=(VQ L&, R); 8440 // VQ L& operator+=(VQ L&, R); 8441 // VQ L& operator-=(VQ L&, R); 8442 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8443 if (!HasArithmeticOrEnumeralCandidateType) 8444 return; 8445 8446 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8447 for (unsigned Right = FirstPromotedArithmeticType; 8448 Right < LastPromotedArithmeticType; ++Right) { 8449 QualType ParamTypes[2]; 8450 ParamTypes[1] = ArithmeticTypes[Right]; 8451 8452 // Add this built-in operator as a candidate (VQ is empty). 8453 ParamTypes[0] = 8454 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8455 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8456 /*IsAssigmentOperator=*/isEqualOp); 8457 8458 // Add this built-in operator as a candidate (VQ is 'volatile'). 8459 if (VisibleTypeConversionsQuals.hasVolatile()) { 8460 ParamTypes[0] = 8461 S.Context.getVolatileType(ArithmeticTypes[Left]); 8462 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8463 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8464 /*IsAssigmentOperator=*/isEqualOp); 8465 } 8466 } 8467 } 8468 8469 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8470 for (BuiltinCandidateTypeSet::iterator 8471 Vec1 = CandidateTypes[0].vector_begin(), 8472 Vec1End = CandidateTypes[0].vector_end(); 8473 Vec1 != Vec1End; ++Vec1) { 8474 for (BuiltinCandidateTypeSet::iterator 8475 Vec2 = CandidateTypes[1].vector_begin(), 8476 Vec2End = CandidateTypes[1].vector_end(); 8477 Vec2 != Vec2End; ++Vec2) { 8478 QualType ParamTypes[2]; 8479 ParamTypes[1] = *Vec2; 8480 // Add this built-in operator as a candidate (VQ is empty). 8481 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8482 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8483 /*IsAssigmentOperator=*/isEqualOp); 8484 8485 // Add this built-in operator as a candidate (VQ is 'volatile'). 8486 if (VisibleTypeConversionsQuals.hasVolatile()) { 8487 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8488 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8489 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8490 /*IsAssigmentOperator=*/isEqualOp); 8491 } 8492 } 8493 } 8494 } 8495 8496 // C++ [over.built]p22: 8497 // 8498 // For every triple (L, VQ, R), where L is an integral type, VQ 8499 // is either volatile or empty, and R is a promoted integral 8500 // type, there exist candidate operator functions of the form 8501 // 8502 // VQ L& operator%=(VQ L&, R); 8503 // VQ L& operator<<=(VQ L&, R); 8504 // VQ L& operator>>=(VQ L&, R); 8505 // VQ L& operator&=(VQ L&, R); 8506 // VQ L& operator^=(VQ L&, R); 8507 // VQ L& operator|=(VQ L&, R); 8508 void addAssignmentIntegralOverloads() { 8509 if (!HasArithmeticOrEnumeralCandidateType) 8510 return; 8511 8512 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8513 for (unsigned Right = FirstPromotedIntegralType; 8514 Right < LastPromotedIntegralType; ++Right) { 8515 QualType ParamTypes[2]; 8516 ParamTypes[1] = ArithmeticTypes[Right]; 8517 8518 // Add this built-in operator as a candidate (VQ is empty). 8519 ParamTypes[0] = 8520 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8521 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8522 if (VisibleTypeConversionsQuals.hasVolatile()) { 8523 // Add this built-in operator as a candidate (VQ is 'volatile'). 8524 ParamTypes[0] = ArithmeticTypes[Left]; 8525 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8526 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8527 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8528 } 8529 } 8530 } 8531 } 8532 8533 // C++ [over.operator]p23: 8534 // 8535 // There also exist candidate operator functions of the form 8536 // 8537 // bool operator!(bool); 8538 // bool operator&&(bool, bool); 8539 // bool operator||(bool, bool); 8540 void addExclaimOverload() { 8541 QualType ParamTy = S.Context.BoolTy; 8542 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8543 /*IsAssignmentOperator=*/false, 8544 /*NumContextualBoolArguments=*/1); 8545 } 8546 void addAmpAmpOrPipePipeOverload() { 8547 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8548 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8549 /*IsAssignmentOperator=*/false, 8550 /*NumContextualBoolArguments=*/2); 8551 } 8552 8553 // C++ [over.built]p13: 8554 // 8555 // For every cv-qualified or cv-unqualified object type T there 8556 // exist candidate operator functions of the form 8557 // 8558 // T* operator+(T*, ptrdiff_t); [ABOVE] 8559 // T& operator[](T*, ptrdiff_t); 8560 // T* operator-(T*, ptrdiff_t); [ABOVE] 8561 // T* operator+(ptrdiff_t, T*); [ABOVE] 8562 // T& operator[](ptrdiff_t, T*); 8563 void addSubscriptOverloads() { 8564 for (BuiltinCandidateTypeSet::iterator 8565 Ptr = CandidateTypes[0].pointer_begin(), 8566 PtrEnd = CandidateTypes[0].pointer_end(); 8567 Ptr != PtrEnd; ++Ptr) { 8568 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8569 QualType PointeeType = (*Ptr)->getPointeeType(); 8570 if (!PointeeType->isObjectType()) 8571 continue; 8572 8573 // T& operator[](T*, ptrdiff_t) 8574 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8575 } 8576 8577 for (BuiltinCandidateTypeSet::iterator 8578 Ptr = CandidateTypes[1].pointer_begin(), 8579 PtrEnd = CandidateTypes[1].pointer_end(); 8580 Ptr != PtrEnd; ++Ptr) { 8581 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8582 QualType PointeeType = (*Ptr)->getPointeeType(); 8583 if (!PointeeType->isObjectType()) 8584 continue; 8585 8586 // T& operator[](ptrdiff_t, T*) 8587 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8588 } 8589 } 8590 8591 // C++ [over.built]p11: 8592 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8593 // C1 is the same type as C2 or is a derived class of C2, T is an object 8594 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8595 // there exist candidate operator functions of the form 8596 // 8597 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8598 // 8599 // where CV12 is the union of CV1 and CV2. 8600 void addArrowStarOverloads() { 8601 for (BuiltinCandidateTypeSet::iterator 8602 Ptr = CandidateTypes[0].pointer_begin(), 8603 PtrEnd = CandidateTypes[0].pointer_end(); 8604 Ptr != PtrEnd; ++Ptr) { 8605 QualType C1Ty = (*Ptr); 8606 QualType C1; 8607 QualifierCollector Q1; 8608 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8609 if (!isa<RecordType>(C1)) 8610 continue; 8611 // heuristic to reduce number of builtin candidates in the set. 8612 // Add volatile/restrict version only if there are conversions to a 8613 // volatile/restrict type. 8614 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8615 continue; 8616 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8617 continue; 8618 for (BuiltinCandidateTypeSet::iterator 8619 MemPtr = CandidateTypes[1].member_pointer_begin(), 8620 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8621 MemPtr != MemPtrEnd; ++MemPtr) { 8622 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8623 QualType C2 = QualType(mptr->getClass(), 0); 8624 C2 = C2.getUnqualifiedType(); 8625 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8626 break; 8627 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8628 // build CV12 T& 8629 QualType T = mptr->getPointeeType(); 8630 if (!VisibleTypeConversionsQuals.hasVolatile() && 8631 T.isVolatileQualified()) 8632 continue; 8633 if (!VisibleTypeConversionsQuals.hasRestrict() && 8634 T.isRestrictQualified()) 8635 continue; 8636 T = Q1.apply(S.Context, T); 8637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8638 } 8639 } 8640 } 8641 8642 // Note that we don't consider the first argument, since it has been 8643 // contextually converted to bool long ago. The candidates below are 8644 // therefore added as binary. 8645 // 8646 // C++ [over.built]p25: 8647 // For every type T, where T is a pointer, pointer-to-member, or scoped 8648 // enumeration type, there exist candidate operator functions of the form 8649 // 8650 // T operator?(bool, T, T); 8651 // 8652 void addConditionalOperatorOverloads() { 8653 /// Set of (canonical) types that we've already handled. 8654 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8655 8656 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8657 for (BuiltinCandidateTypeSet::iterator 8658 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8659 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8660 Ptr != PtrEnd; ++Ptr) { 8661 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8662 continue; 8663 8664 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8665 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8666 } 8667 8668 for (BuiltinCandidateTypeSet::iterator 8669 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8670 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8671 MemPtr != MemPtrEnd; ++MemPtr) { 8672 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8673 continue; 8674 8675 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8676 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8677 } 8678 8679 if (S.getLangOpts().CPlusPlus11) { 8680 for (BuiltinCandidateTypeSet::iterator 8681 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8682 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8683 Enum != EnumEnd; ++Enum) { 8684 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8685 continue; 8686 8687 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8688 continue; 8689 8690 QualType ParamTypes[2] = { *Enum, *Enum }; 8691 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8692 } 8693 } 8694 } 8695 } 8696 }; 8697 8698 } // end anonymous namespace 8699 8700 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8701 /// operator overloads to the candidate set (C++ [over.built]), based 8702 /// on the operator @p Op and the arguments given. For example, if the 8703 /// operator is a binary '+', this routine might add "int 8704 /// operator+(int, int)" to cover integer addition. 8705 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8706 SourceLocation OpLoc, 8707 ArrayRef<Expr *> Args, 8708 OverloadCandidateSet &CandidateSet) { 8709 // Find all of the types that the arguments can convert to, but only 8710 // if the operator we're looking at has built-in operator candidates 8711 // that make use of these types. Also record whether we encounter non-record 8712 // candidate types or either arithmetic or enumeral candidate types. 8713 Qualifiers VisibleTypeConversionsQuals; 8714 VisibleTypeConversionsQuals.addConst(); 8715 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8716 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8717 8718 bool HasNonRecordCandidateType = false; 8719 bool HasArithmeticOrEnumeralCandidateType = false; 8720 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8721 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8722 CandidateTypes.emplace_back(*this); 8723 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8724 OpLoc, 8725 true, 8726 (Op == OO_Exclaim || 8727 Op == OO_AmpAmp || 8728 Op == OO_PipePipe), 8729 VisibleTypeConversionsQuals); 8730 HasNonRecordCandidateType = HasNonRecordCandidateType || 8731 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8732 HasArithmeticOrEnumeralCandidateType = 8733 HasArithmeticOrEnumeralCandidateType || 8734 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8735 } 8736 8737 // Exit early when no non-record types have been added to the candidate set 8738 // for any of the arguments to the operator. 8739 // 8740 // We can't exit early for !, ||, or &&, since there we have always have 8741 // 'bool' overloads. 8742 if (!HasNonRecordCandidateType && 8743 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8744 return; 8745 8746 // Setup an object to manage the common state for building overloads. 8747 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8748 VisibleTypeConversionsQuals, 8749 HasArithmeticOrEnumeralCandidateType, 8750 CandidateTypes, CandidateSet); 8751 8752 // Dispatch over the operation to add in only those overloads which apply. 8753 switch (Op) { 8754 case OO_None: 8755 case NUM_OVERLOADED_OPERATORS: 8756 llvm_unreachable("Expected an overloaded operator"); 8757 8758 case OO_New: 8759 case OO_Delete: 8760 case OO_Array_New: 8761 case OO_Array_Delete: 8762 case OO_Call: 8763 llvm_unreachable( 8764 "Special operators don't use AddBuiltinOperatorCandidates"); 8765 8766 case OO_Comma: 8767 case OO_Arrow: 8768 case OO_Coawait: 8769 // C++ [over.match.oper]p3: 8770 // -- For the operator ',', the unary operator '&', the 8771 // operator '->', or the operator 'co_await', the 8772 // built-in candidates set is empty. 8773 break; 8774 8775 case OO_Plus: // '+' is either unary or binary 8776 if (Args.size() == 1) 8777 OpBuilder.addUnaryPlusPointerOverloads(); 8778 LLVM_FALLTHROUGH; 8779 8780 case OO_Minus: // '-' is either unary or binary 8781 if (Args.size() == 1) { 8782 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8783 } else { 8784 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8785 OpBuilder.addGenericBinaryArithmeticOverloads(); 8786 } 8787 break; 8788 8789 case OO_Star: // '*' is either unary or binary 8790 if (Args.size() == 1) 8791 OpBuilder.addUnaryStarPointerOverloads(); 8792 else 8793 OpBuilder.addGenericBinaryArithmeticOverloads(); 8794 break; 8795 8796 case OO_Slash: 8797 OpBuilder.addGenericBinaryArithmeticOverloads(); 8798 break; 8799 8800 case OO_PlusPlus: 8801 case OO_MinusMinus: 8802 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8803 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8804 break; 8805 8806 case OO_EqualEqual: 8807 case OO_ExclaimEqual: 8808 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8809 LLVM_FALLTHROUGH; 8810 8811 case OO_Less: 8812 case OO_Greater: 8813 case OO_LessEqual: 8814 case OO_GreaterEqual: 8815 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8816 OpBuilder.addGenericBinaryArithmeticOverloads(); 8817 break; 8818 8819 case OO_Spaceship: 8820 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8821 OpBuilder.addThreeWayArithmeticOverloads(); 8822 break; 8823 8824 case OO_Percent: 8825 case OO_Caret: 8826 case OO_Pipe: 8827 case OO_LessLess: 8828 case OO_GreaterGreater: 8829 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8830 break; 8831 8832 case OO_Amp: // '&' is either unary or binary 8833 if (Args.size() == 1) 8834 // C++ [over.match.oper]p3: 8835 // -- For the operator ',', the unary operator '&', or the 8836 // operator '->', the built-in candidates set is empty. 8837 break; 8838 8839 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8840 break; 8841 8842 case OO_Tilde: 8843 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8844 break; 8845 8846 case OO_Equal: 8847 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8848 LLVM_FALLTHROUGH; 8849 8850 case OO_PlusEqual: 8851 case OO_MinusEqual: 8852 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8853 LLVM_FALLTHROUGH; 8854 8855 case OO_StarEqual: 8856 case OO_SlashEqual: 8857 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8858 break; 8859 8860 case OO_PercentEqual: 8861 case OO_LessLessEqual: 8862 case OO_GreaterGreaterEqual: 8863 case OO_AmpEqual: 8864 case OO_CaretEqual: 8865 case OO_PipeEqual: 8866 OpBuilder.addAssignmentIntegralOverloads(); 8867 break; 8868 8869 case OO_Exclaim: 8870 OpBuilder.addExclaimOverload(); 8871 break; 8872 8873 case OO_AmpAmp: 8874 case OO_PipePipe: 8875 OpBuilder.addAmpAmpOrPipePipeOverload(); 8876 break; 8877 8878 case OO_Subscript: 8879 OpBuilder.addSubscriptOverloads(); 8880 break; 8881 8882 case OO_ArrowStar: 8883 OpBuilder.addArrowStarOverloads(); 8884 break; 8885 8886 case OO_Conditional: 8887 OpBuilder.addConditionalOperatorOverloads(); 8888 OpBuilder.addGenericBinaryArithmeticOverloads(); 8889 break; 8890 } 8891 } 8892 8893 /// Add function candidates found via argument-dependent lookup 8894 /// to the set of overloading candidates. 8895 /// 8896 /// This routine performs argument-dependent name lookup based on the 8897 /// given function name (which may also be an operator name) and adds 8898 /// all of the overload candidates found by ADL to the overload 8899 /// candidate set (C++ [basic.lookup.argdep]). 8900 void 8901 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8902 SourceLocation Loc, 8903 ArrayRef<Expr *> Args, 8904 TemplateArgumentListInfo *ExplicitTemplateArgs, 8905 OverloadCandidateSet& CandidateSet, 8906 bool PartialOverloading) { 8907 ADLResult Fns; 8908 8909 // FIXME: This approach for uniquing ADL results (and removing 8910 // redundant candidates from the set) relies on pointer-equality, 8911 // which means we need to key off the canonical decl. However, 8912 // always going back to the canonical decl might not get us the 8913 // right set of default arguments. What default arguments are 8914 // we supposed to consider on ADL candidates, anyway? 8915 8916 // FIXME: Pass in the explicit template arguments? 8917 ArgumentDependentLookup(Name, Loc, Args, Fns); 8918 8919 // Erase all of the candidates we already knew about. 8920 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8921 CandEnd = CandidateSet.end(); 8922 Cand != CandEnd; ++Cand) 8923 if (Cand->Function) { 8924 Fns.erase(Cand->Function); 8925 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8926 Fns.erase(FunTmpl); 8927 } 8928 8929 // For each of the ADL candidates we found, add it to the overload 8930 // set. 8931 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8932 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8933 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8934 if (ExplicitTemplateArgs) 8935 continue; 8936 8937 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8938 PartialOverloading); 8939 } else 8940 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8941 FoundDecl, ExplicitTemplateArgs, 8942 Args, CandidateSet, PartialOverloading); 8943 } 8944 } 8945 8946 namespace { 8947 enum class Comparison { Equal, Better, Worse }; 8948 } 8949 8950 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8951 /// overload resolution. 8952 /// 8953 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8954 /// Cand1's first N enable_if attributes have precisely the same conditions as 8955 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8956 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8957 /// 8958 /// Note that you can have a pair of candidates such that Cand1's enable_if 8959 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8960 /// worse than Cand1's. 8961 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8962 const FunctionDecl *Cand2) { 8963 // Common case: One (or both) decls don't have enable_if attrs. 8964 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8965 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8966 if (!Cand1Attr || !Cand2Attr) { 8967 if (Cand1Attr == Cand2Attr) 8968 return Comparison::Equal; 8969 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8970 } 8971 8972 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 8973 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 8974 8975 auto Cand1I = Cand1Attrs.begin(); 8976 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8977 for (EnableIfAttr *Cand2A : Cand2Attrs) { 8978 Cand1ID.clear(); 8979 Cand2ID.clear(); 8980 8981 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8982 // has fewer enable_if attributes than Cand2. 8983 auto Cand1A = Cand1I++; 8984 if (Cand1A == Cand1Attrs.end()) 8985 return Comparison::Worse; 8986 8987 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8988 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8989 if (Cand1ID != Cand2ID) 8990 return Comparison::Worse; 8991 } 8992 8993 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8994 } 8995 8996 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 8997 const OverloadCandidate &Cand2) { 8998 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 8999 !Cand2.Function->isMultiVersion()) 9000 return false; 9001 9002 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9003 // cpu_dispatch, else arbitrarily based on the identifiers. 9004 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9005 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9006 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9007 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9008 9009 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9010 return false; 9011 9012 if (Cand1CPUDisp && !Cand2CPUDisp) 9013 return true; 9014 if (Cand2CPUDisp && !Cand1CPUDisp) 9015 return false; 9016 9017 if (Cand1CPUSpec && Cand2CPUSpec) { 9018 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9019 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9020 9021 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9022 FirstDiff = std::mismatch( 9023 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9024 Cand2CPUSpec->cpus_begin(), 9025 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9026 return LHS->getName() == RHS->getName(); 9027 }); 9028 9029 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9030 "Two different cpu-specific versions should not have the same " 9031 "identifier list, otherwise they'd be the same decl!"); 9032 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9033 } 9034 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9035 } 9036 9037 /// isBetterOverloadCandidate - Determines whether the first overload 9038 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9039 bool clang::isBetterOverloadCandidate( 9040 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9041 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9042 // Define viable functions to be better candidates than non-viable 9043 // functions. 9044 if (!Cand2.Viable) 9045 return Cand1.Viable; 9046 else if (!Cand1.Viable) 9047 return false; 9048 9049 // C++ [over.match.best]p1: 9050 // 9051 // -- if F is a static member function, ICS1(F) is defined such 9052 // that ICS1(F) is neither better nor worse than ICS1(G) for 9053 // any function G, and, symmetrically, ICS1(G) is neither 9054 // better nor worse than ICS1(F). 9055 unsigned StartArg = 0; 9056 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9057 StartArg = 1; 9058 9059 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9060 // We don't allow incompatible pointer conversions in C++. 9061 if (!S.getLangOpts().CPlusPlus) 9062 return ICS.isStandard() && 9063 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9064 9065 // The only ill-formed conversion we allow in C++ is the string literal to 9066 // char* conversion, which is only considered ill-formed after C++11. 9067 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9068 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9069 }; 9070 9071 // Define functions that don't require ill-formed conversions for a given 9072 // argument to be better candidates than functions that do. 9073 unsigned NumArgs = Cand1.Conversions.size(); 9074 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9075 bool HasBetterConversion = false; 9076 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9077 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9078 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9079 if (Cand1Bad != Cand2Bad) { 9080 if (Cand1Bad) 9081 return false; 9082 HasBetterConversion = true; 9083 } 9084 } 9085 9086 if (HasBetterConversion) 9087 return true; 9088 9089 // C++ [over.match.best]p1: 9090 // A viable function F1 is defined to be a better function than another 9091 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9092 // conversion sequence than ICSi(F2), and then... 9093 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9094 switch (CompareImplicitConversionSequences(S, Loc, 9095 Cand1.Conversions[ArgIdx], 9096 Cand2.Conversions[ArgIdx])) { 9097 case ImplicitConversionSequence::Better: 9098 // Cand1 has a better conversion sequence. 9099 HasBetterConversion = true; 9100 break; 9101 9102 case ImplicitConversionSequence::Worse: 9103 // Cand1 can't be better than Cand2. 9104 return false; 9105 9106 case ImplicitConversionSequence::Indistinguishable: 9107 // Do nothing. 9108 break; 9109 } 9110 } 9111 9112 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9113 // ICSj(F2), or, if not that, 9114 if (HasBetterConversion) 9115 return true; 9116 9117 // -- the context is an initialization by user-defined conversion 9118 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9119 // from the return type of F1 to the destination type (i.e., 9120 // the type of the entity being initialized) is a better 9121 // conversion sequence than the standard conversion sequence 9122 // from the return type of F2 to the destination type. 9123 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9124 Cand1.Function && Cand2.Function && 9125 isa<CXXConversionDecl>(Cand1.Function) && 9126 isa<CXXConversionDecl>(Cand2.Function)) { 9127 // First check whether we prefer one of the conversion functions over the 9128 // other. This only distinguishes the results in non-standard, extension 9129 // cases such as the conversion from a lambda closure type to a function 9130 // pointer or block. 9131 ImplicitConversionSequence::CompareKind Result = 9132 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9133 if (Result == ImplicitConversionSequence::Indistinguishable) 9134 Result = CompareStandardConversionSequences(S, Loc, 9135 Cand1.FinalConversion, 9136 Cand2.FinalConversion); 9137 9138 if (Result != ImplicitConversionSequence::Indistinguishable) 9139 return Result == ImplicitConversionSequence::Better; 9140 9141 // FIXME: Compare kind of reference binding if conversion functions 9142 // convert to a reference type used in direct reference binding, per 9143 // C++14 [over.match.best]p1 section 2 bullet 3. 9144 } 9145 9146 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9147 // as combined with the resolution to CWG issue 243. 9148 // 9149 // When the context is initialization by constructor ([over.match.ctor] or 9150 // either phase of [over.match.list]), a constructor is preferred over 9151 // a conversion function. 9152 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9153 Cand1.Function && Cand2.Function && 9154 isa<CXXConstructorDecl>(Cand1.Function) != 9155 isa<CXXConstructorDecl>(Cand2.Function)) 9156 return isa<CXXConstructorDecl>(Cand1.Function); 9157 9158 // -- F1 is a non-template function and F2 is a function template 9159 // specialization, or, if not that, 9160 bool Cand1IsSpecialization = Cand1.Function && 9161 Cand1.Function->getPrimaryTemplate(); 9162 bool Cand2IsSpecialization = Cand2.Function && 9163 Cand2.Function->getPrimaryTemplate(); 9164 if (Cand1IsSpecialization != Cand2IsSpecialization) 9165 return Cand2IsSpecialization; 9166 9167 // -- F1 and F2 are function template specializations, and the function 9168 // template for F1 is more specialized than the template for F2 9169 // according to the partial ordering rules described in 14.5.5.2, or, 9170 // if not that, 9171 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9172 if (FunctionTemplateDecl *BetterTemplate 9173 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9174 Cand2.Function->getPrimaryTemplate(), 9175 Loc, 9176 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9177 : TPOC_Call, 9178 Cand1.ExplicitCallArguments, 9179 Cand2.ExplicitCallArguments)) 9180 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9181 } 9182 9183 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9184 // A derived-class constructor beats an (inherited) base class constructor. 9185 bool Cand1IsInherited = 9186 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9187 bool Cand2IsInherited = 9188 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9189 if (Cand1IsInherited != Cand2IsInherited) 9190 return Cand2IsInherited; 9191 else if (Cand1IsInherited) { 9192 assert(Cand2IsInherited); 9193 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9194 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9195 if (Cand1Class->isDerivedFrom(Cand2Class)) 9196 return true; 9197 if (Cand2Class->isDerivedFrom(Cand1Class)) 9198 return false; 9199 // Inherited from sibling base classes: still ambiguous. 9200 } 9201 9202 // Check C++17 tie-breakers for deduction guides. 9203 { 9204 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9205 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9206 if (Guide1 && Guide2) { 9207 // -- F1 is generated from a deduction-guide and F2 is not 9208 if (Guide1->isImplicit() != Guide2->isImplicit()) 9209 return Guide2->isImplicit(); 9210 9211 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9212 if (Guide1->isCopyDeductionCandidate()) 9213 return true; 9214 } 9215 } 9216 9217 // Check for enable_if value-based overload resolution. 9218 if (Cand1.Function && Cand2.Function) { 9219 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9220 if (Cmp != Comparison::Equal) 9221 return Cmp == Comparison::Better; 9222 } 9223 9224 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9225 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9226 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9227 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9228 } 9229 9230 bool HasPS1 = Cand1.Function != nullptr && 9231 functionHasPassObjectSizeParams(Cand1.Function); 9232 bool HasPS2 = Cand2.Function != nullptr && 9233 functionHasPassObjectSizeParams(Cand2.Function); 9234 if (HasPS1 != HasPS2 && HasPS1) 9235 return true; 9236 9237 return isBetterMultiversionCandidate(Cand1, Cand2); 9238 } 9239 9240 /// Determine whether two declarations are "equivalent" for the purposes of 9241 /// name lookup and overload resolution. This applies when the same internal/no 9242 /// linkage entity is defined by two modules (probably by textually including 9243 /// the same header). In such a case, we don't consider the declarations to 9244 /// declare the same entity, but we also don't want lookups with both 9245 /// declarations visible to be ambiguous in some cases (this happens when using 9246 /// a modularized libstdc++). 9247 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9248 const NamedDecl *B) { 9249 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9250 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9251 if (!VA || !VB) 9252 return false; 9253 9254 // The declarations must be declaring the same name as an internal linkage 9255 // entity in different modules. 9256 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9257 VB->getDeclContext()->getRedeclContext()) || 9258 getOwningModule(const_cast<ValueDecl *>(VA)) == 9259 getOwningModule(const_cast<ValueDecl *>(VB)) || 9260 VA->isExternallyVisible() || VB->isExternallyVisible()) 9261 return false; 9262 9263 // Check that the declarations appear to be equivalent. 9264 // 9265 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9266 // For constants and functions, we should check the initializer or body is 9267 // the same. For non-constant variables, we shouldn't allow it at all. 9268 if (Context.hasSameType(VA->getType(), VB->getType())) 9269 return true; 9270 9271 // Enum constants within unnamed enumerations will have different types, but 9272 // may still be similar enough to be interchangeable for our purposes. 9273 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9274 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9275 // Only handle anonymous enums. If the enumerations were named and 9276 // equivalent, they would have been merged to the same type. 9277 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9278 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9279 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9280 !Context.hasSameType(EnumA->getIntegerType(), 9281 EnumB->getIntegerType())) 9282 return false; 9283 // Allow this only if the value is the same for both enumerators. 9284 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9285 } 9286 } 9287 9288 // Nothing else is sufficiently similar. 9289 return false; 9290 } 9291 9292 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9293 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9294 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9295 9296 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9297 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9298 << !M << (M ? M->getFullModuleName() : ""); 9299 9300 for (auto *E : Equiv) { 9301 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9302 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9303 << !M << (M ? M->getFullModuleName() : ""); 9304 } 9305 } 9306 9307 /// Computes the best viable function (C++ 13.3.3) 9308 /// within an overload candidate set. 9309 /// 9310 /// \param Loc The location of the function name (or operator symbol) for 9311 /// which overload resolution occurs. 9312 /// 9313 /// \param Best If overload resolution was successful or found a deleted 9314 /// function, \p Best points to the candidate function found. 9315 /// 9316 /// \returns The result of overload resolution. 9317 OverloadingResult 9318 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9319 iterator &Best) { 9320 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9321 std::transform(begin(), end(), std::back_inserter(Candidates), 9322 [](OverloadCandidate &Cand) { return &Cand; }); 9323 9324 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9325 // are accepted by both clang and NVCC. However, during a particular 9326 // compilation mode only one call variant is viable. We need to 9327 // exclude non-viable overload candidates from consideration based 9328 // only on their host/device attributes. Specifically, if one 9329 // candidate call is WrongSide and the other is SameSide, we ignore 9330 // the WrongSide candidate. 9331 if (S.getLangOpts().CUDA) { 9332 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9333 bool ContainsSameSideCandidate = 9334 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9335 return Cand->Function && 9336 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9337 Sema::CFP_SameSide; 9338 }); 9339 if (ContainsSameSideCandidate) { 9340 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9341 return Cand->Function && 9342 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9343 Sema::CFP_WrongSide; 9344 }; 9345 llvm::erase_if(Candidates, IsWrongSideCandidate); 9346 } 9347 } 9348 9349 // Find the best viable function. 9350 Best = end(); 9351 for (auto *Cand : Candidates) 9352 if (Cand->Viable) 9353 if (Best == end() || 9354 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9355 Best = Cand; 9356 9357 // If we didn't find any viable functions, abort. 9358 if (Best == end()) 9359 return OR_No_Viable_Function; 9360 9361 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9362 9363 // Make sure that this function is better than every other viable 9364 // function. If not, we have an ambiguity. 9365 for (auto *Cand : Candidates) { 9366 if (Cand->Viable && Cand != Best && 9367 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9368 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9369 Cand->Function)) { 9370 EquivalentCands.push_back(Cand->Function); 9371 continue; 9372 } 9373 9374 Best = end(); 9375 return OR_Ambiguous; 9376 } 9377 } 9378 9379 // Best is the best viable function. 9380 if (Best->Function && 9381 (Best->Function->isDeleted() || 9382 S.isFunctionConsideredUnavailable(Best->Function))) 9383 return OR_Deleted; 9384 9385 if (!EquivalentCands.empty()) 9386 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9387 EquivalentCands); 9388 9389 return OR_Success; 9390 } 9391 9392 namespace { 9393 9394 enum OverloadCandidateKind { 9395 oc_function, 9396 oc_method, 9397 oc_constructor, 9398 oc_implicit_default_constructor, 9399 oc_implicit_copy_constructor, 9400 oc_implicit_move_constructor, 9401 oc_implicit_copy_assignment, 9402 oc_implicit_move_assignment, 9403 oc_inherited_constructor 9404 }; 9405 9406 enum OverloadCandidateSelect { 9407 ocs_non_template, 9408 ocs_template, 9409 ocs_described_template, 9410 }; 9411 9412 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9413 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9414 std::string &Description) { 9415 9416 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9417 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9418 isTemplate = true; 9419 Description = S.getTemplateArgumentBindingsText( 9420 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9421 } 9422 9423 OverloadCandidateSelect Select = [&]() { 9424 if (!Description.empty()) 9425 return ocs_described_template; 9426 return isTemplate ? ocs_template : ocs_non_template; 9427 }(); 9428 9429 OverloadCandidateKind Kind = [&]() { 9430 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9431 if (!Ctor->isImplicit()) { 9432 if (isa<ConstructorUsingShadowDecl>(Found)) 9433 return oc_inherited_constructor; 9434 else 9435 return oc_constructor; 9436 } 9437 9438 if (Ctor->isDefaultConstructor()) 9439 return oc_implicit_default_constructor; 9440 9441 if (Ctor->isMoveConstructor()) 9442 return oc_implicit_move_constructor; 9443 9444 assert(Ctor->isCopyConstructor() && 9445 "unexpected sort of implicit constructor"); 9446 return oc_implicit_copy_constructor; 9447 } 9448 9449 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9450 // This actually gets spelled 'candidate function' for now, but 9451 // it doesn't hurt to split it out. 9452 if (!Meth->isImplicit()) 9453 return oc_method; 9454 9455 if (Meth->isMoveAssignmentOperator()) 9456 return oc_implicit_move_assignment; 9457 9458 if (Meth->isCopyAssignmentOperator()) 9459 return oc_implicit_copy_assignment; 9460 9461 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9462 return oc_method; 9463 } 9464 9465 return oc_function; 9466 }(); 9467 9468 return std::make_pair(Kind, Select); 9469 } 9470 9471 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9472 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9473 // set. 9474 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9475 S.Diag(FoundDecl->getLocation(), 9476 diag::note_ovl_candidate_inherited_constructor) 9477 << Shadow->getNominatedBaseClass(); 9478 } 9479 9480 } // end anonymous namespace 9481 9482 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9483 const FunctionDecl *FD) { 9484 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9485 bool AlwaysTrue; 9486 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9487 return false; 9488 if (!AlwaysTrue) 9489 return false; 9490 } 9491 return true; 9492 } 9493 9494 /// Returns true if we can take the address of the function. 9495 /// 9496 /// \param Complain - If true, we'll emit a diagnostic 9497 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9498 /// we in overload resolution? 9499 /// \param Loc - The location of the statement we're complaining about. Ignored 9500 /// if we're not complaining, or if we're in overload resolution. 9501 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9502 bool Complain, 9503 bool InOverloadResolution, 9504 SourceLocation Loc) { 9505 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9506 if (Complain) { 9507 if (InOverloadResolution) 9508 S.Diag(FD->getBeginLoc(), 9509 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9510 else 9511 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9512 } 9513 return false; 9514 } 9515 9516 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9517 return P->hasAttr<PassObjectSizeAttr>(); 9518 }); 9519 if (I == FD->param_end()) 9520 return true; 9521 9522 if (Complain) { 9523 // Add one to ParamNo because it's user-facing 9524 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9525 if (InOverloadResolution) 9526 S.Diag(FD->getLocation(), 9527 diag::note_ovl_candidate_has_pass_object_size_params) 9528 << ParamNo; 9529 else 9530 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9531 << FD << ParamNo; 9532 } 9533 return false; 9534 } 9535 9536 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9537 const FunctionDecl *FD) { 9538 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9539 /*InOverloadResolution=*/true, 9540 /*Loc=*/SourceLocation()); 9541 } 9542 9543 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9544 bool Complain, 9545 SourceLocation Loc) { 9546 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9547 /*InOverloadResolution=*/false, 9548 Loc); 9549 } 9550 9551 // Notes the location of an overload candidate. 9552 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9553 QualType DestType, bool TakingAddress) { 9554 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9555 return; 9556 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9557 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9558 return; 9559 9560 std::string FnDesc; 9561 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9562 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9563 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9564 << (unsigned)KSPair.first << (unsigned)KSPair.second 9565 << Fn << FnDesc; 9566 9567 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9568 Diag(Fn->getLocation(), PD); 9569 MaybeEmitInheritedConstructorNote(*this, Found); 9570 } 9571 9572 // Notes the location of all overload candidates designated through 9573 // OverloadedExpr 9574 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9575 bool TakingAddress) { 9576 assert(OverloadedExpr->getType() == Context.OverloadTy); 9577 9578 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9579 OverloadExpr *OvlExpr = Ovl.Expression; 9580 9581 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9582 IEnd = OvlExpr->decls_end(); 9583 I != IEnd; ++I) { 9584 if (FunctionTemplateDecl *FunTmpl = 9585 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9586 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9587 TakingAddress); 9588 } else if (FunctionDecl *Fun 9589 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9590 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9591 } 9592 } 9593 } 9594 9595 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9596 /// "lead" diagnostic; it will be given two arguments, the source and 9597 /// target types of the conversion. 9598 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9599 Sema &S, 9600 SourceLocation CaretLoc, 9601 const PartialDiagnostic &PDiag) const { 9602 S.Diag(CaretLoc, PDiag) 9603 << Ambiguous.getFromType() << Ambiguous.getToType(); 9604 // FIXME: The note limiting machinery is borrowed from 9605 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9606 // refactoring here. 9607 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9608 unsigned CandsShown = 0; 9609 AmbiguousConversionSequence::const_iterator I, E; 9610 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9611 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9612 break; 9613 ++CandsShown; 9614 S.NoteOverloadCandidate(I->first, I->second); 9615 } 9616 if (I != E) 9617 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9618 } 9619 9620 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9621 unsigned I, bool TakingCandidateAddress) { 9622 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9623 assert(Conv.isBad()); 9624 assert(Cand->Function && "for now, candidate must be a function"); 9625 FunctionDecl *Fn = Cand->Function; 9626 9627 // There's a conversion slot for the object argument if this is a 9628 // non-constructor method. Note that 'I' corresponds the 9629 // conversion-slot index. 9630 bool isObjectArgument = false; 9631 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9632 if (I == 0) 9633 isObjectArgument = true; 9634 else 9635 I--; 9636 } 9637 9638 std::string FnDesc; 9639 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9640 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9641 9642 Expr *FromExpr = Conv.Bad.FromExpr; 9643 QualType FromTy = Conv.Bad.getFromType(); 9644 QualType ToTy = Conv.Bad.getToType(); 9645 9646 if (FromTy == S.Context.OverloadTy) { 9647 assert(FromExpr && "overload set argument came from implicit argument?"); 9648 Expr *E = FromExpr->IgnoreParens(); 9649 if (isa<UnaryOperator>(E)) 9650 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9651 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9652 9653 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9654 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9655 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9656 << Name << I + 1; 9657 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9658 return; 9659 } 9660 9661 // Do some hand-waving analysis to see if the non-viability is due 9662 // to a qualifier mismatch. 9663 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9664 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9665 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9666 CToTy = RT->getPointeeType(); 9667 else { 9668 // TODO: detect and diagnose the full richness of const mismatches. 9669 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9670 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9671 CFromTy = FromPT->getPointeeType(); 9672 CToTy = ToPT->getPointeeType(); 9673 } 9674 } 9675 9676 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9677 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9678 Qualifiers FromQs = CFromTy.getQualifiers(); 9679 Qualifiers ToQs = CToTy.getQualifiers(); 9680 9681 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9682 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9683 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9684 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9685 << ToTy << (unsigned)isObjectArgument << I + 1; 9686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9687 return; 9688 } 9689 9690 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9692 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9693 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9694 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9695 << (unsigned)isObjectArgument << I + 1; 9696 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9697 return; 9698 } 9699 9700 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9702 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9704 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9705 << (unsigned)isObjectArgument << I + 1; 9706 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9707 return; 9708 } 9709 9710 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9711 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9712 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9713 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9714 << FromQs.hasUnaligned() << I + 1; 9715 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9716 return; 9717 } 9718 9719 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9720 assert(CVR && "unexpected qualifiers mismatch"); 9721 9722 if (isObjectArgument) { 9723 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9724 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9725 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9726 << (CVR - 1); 9727 } else { 9728 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9729 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9730 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9731 << (CVR - 1) << I + 1; 9732 } 9733 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9734 return; 9735 } 9736 9737 // Special diagnostic for failure to convert an initializer list, since 9738 // telling the user that it has type void is not useful. 9739 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 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 // Diagnose references or pointers to incomplete types differently, 9749 // since it's far from impossible that the incompleteness triggered 9750 // the failure. 9751 QualType TempFromTy = FromTy.getNonReferenceType(); 9752 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9753 TempFromTy = PTy->getPointeeType(); 9754 if (TempFromTy->isIncompleteType()) { 9755 // Emit the generic diagnostic and, optionally, add the hints to it. 9756 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9757 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9758 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9759 << ToTy << (unsigned)isObjectArgument << I + 1 9760 << (unsigned)(Cand->Fix.Kind); 9761 9762 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9763 return; 9764 } 9765 9766 // Diagnose base -> derived pointer conversions. 9767 unsigned BaseToDerivedConversion = 0; 9768 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9769 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9770 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9771 FromPtrTy->getPointeeType()) && 9772 !FromPtrTy->getPointeeType()->isIncompleteType() && 9773 !ToPtrTy->getPointeeType()->isIncompleteType() && 9774 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9775 FromPtrTy->getPointeeType())) 9776 BaseToDerivedConversion = 1; 9777 } 9778 } else if (const ObjCObjectPointerType *FromPtrTy 9779 = FromTy->getAs<ObjCObjectPointerType>()) { 9780 if (const ObjCObjectPointerType *ToPtrTy 9781 = ToTy->getAs<ObjCObjectPointerType>()) 9782 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9783 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9784 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9785 FromPtrTy->getPointeeType()) && 9786 FromIface->isSuperClassOf(ToIface)) 9787 BaseToDerivedConversion = 2; 9788 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9789 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9790 !FromTy->isIncompleteType() && 9791 !ToRefTy->getPointeeType()->isIncompleteType() && 9792 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9793 BaseToDerivedConversion = 3; 9794 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9795 ToTy.getNonReferenceType().getCanonicalType() == 9796 FromTy.getNonReferenceType().getCanonicalType()) { 9797 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9798 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9799 << (unsigned)isObjectArgument << I + 1 9800 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9801 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9802 return; 9803 } 9804 } 9805 9806 if (BaseToDerivedConversion) { 9807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9808 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9809 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9810 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9811 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9812 return; 9813 } 9814 9815 if (isa<ObjCObjectPointerType>(CFromTy) && 9816 isa<PointerType>(CToTy)) { 9817 Qualifiers FromQs = CFromTy.getQualifiers(); 9818 Qualifiers ToQs = CToTy.getQualifiers(); 9819 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9820 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9821 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9822 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9823 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9825 return; 9826 } 9827 } 9828 9829 if (TakingCandidateAddress && 9830 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9831 return; 9832 9833 // Emit the generic diagnostic and, optionally, add the hints to it. 9834 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9835 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9837 << ToTy << (unsigned)isObjectArgument << I + 1 9838 << (unsigned)(Cand->Fix.Kind); 9839 9840 // If we can fix the conversion, suggest the FixIts. 9841 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9842 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9843 FDiag << *HI; 9844 S.Diag(Fn->getLocation(), FDiag); 9845 9846 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9847 } 9848 9849 /// Additional arity mismatch diagnosis specific to a function overload 9850 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9851 /// over a candidate in any candidate set. 9852 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9853 unsigned NumArgs) { 9854 FunctionDecl *Fn = Cand->Function; 9855 unsigned MinParams = Fn->getMinRequiredArguments(); 9856 9857 // With invalid overloaded operators, it's possible that we think we 9858 // have an arity mismatch when in fact it looks like we have the 9859 // right number of arguments, because only overloaded operators have 9860 // the weird behavior of overloading member and non-member functions. 9861 // Just don't report anything. 9862 if (Fn->isInvalidDecl() && 9863 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9864 return true; 9865 9866 if (NumArgs < MinParams) { 9867 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9868 (Cand->FailureKind == ovl_fail_bad_deduction && 9869 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9870 } else { 9871 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9872 (Cand->FailureKind == ovl_fail_bad_deduction && 9873 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9874 } 9875 9876 return false; 9877 } 9878 9879 /// General arity mismatch diagnosis over a candidate in a candidate set. 9880 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9881 unsigned NumFormalArgs) { 9882 assert(isa<FunctionDecl>(D) && 9883 "The templated declaration should at least be a function" 9884 " when diagnosing bad template argument deduction due to too many" 9885 " or too few arguments"); 9886 9887 FunctionDecl *Fn = cast<FunctionDecl>(D); 9888 9889 // TODO: treat calls to a missing default constructor as a special case 9890 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9891 unsigned MinParams = Fn->getMinRequiredArguments(); 9892 9893 // at least / at most / exactly 9894 unsigned mode, modeCount; 9895 if (NumFormalArgs < MinParams) { 9896 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9897 FnTy->isTemplateVariadic()) 9898 mode = 0; // "at least" 9899 else 9900 mode = 2; // "exactly" 9901 modeCount = MinParams; 9902 } else { 9903 if (MinParams != FnTy->getNumParams()) 9904 mode = 1; // "at most" 9905 else 9906 mode = 2; // "exactly" 9907 modeCount = FnTy->getNumParams(); 9908 } 9909 9910 std::string Description; 9911 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9912 ClassifyOverloadCandidate(S, Found, Fn, Description); 9913 9914 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9916 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9917 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9918 else 9919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9920 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9921 << Description << mode << modeCount << NumFormalArgs; 9922 9923 MaybeEmitInheritedConstructorNote(S, Found); 9924 } 9925 9926 /// Arity mismatch diagnosis specific to a function overload candidate. 9927 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9928 unsigned NumFormalArgs) { 9929 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9930 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9931 } 9932 9933 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9934 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9935 return TD; 9936 llvm_unreachable("Unsupported: Getting the described template declaration" 9937 " for bad deduction diagnosis"); 9938 } 9939 9940 /// Diagnose a failed template-argument deduction. 9941 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9942 DeductionFailureInfo &DeductionFailure, 9943 unsigned NumArgs, 9944 bool TakingCandidateAddress) { 9945 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9946 NamedDecl *ParamD; 9947 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9948 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9949 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9950 switch (DeductionFailure.Result) { 9951 case Sema::TDK_Success: 9952 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9953 9954 case Sema::TDK_Incomplete: { 9955 assert(ParamD && "no parameter found for incomplete deduction result"); 9956 S.Diag(Templated->getLocation(), 9957 diag::note_ovl_candidate_incomplete_deduction) 9958 << ParamD->getDeclName(); 9959 MaybeEmitInheritedConstructorNote(S, Found); 9960 return; 9961 } 9962 9963 case Sema::TDK_IncompletePack: { 9964 assert(ParamD && "no parameter found for incomplete deduction result"); 9965 S.Diag(Templated->getLocation(), 9966 diag::note_ovl_candidate_incomplete_deduction_pack) 9967 << ParamD->getDeclName() 9968 << (DeductionFailure.getFirstArg()->pack_size() + 1) 9969 << *DeductionFailure.getFirstArg(); 9970 MaybeEmitInheritedConstructorNote(S, Found); 9971 return; 9972 } 9973 9974 case Sema::TDK_Underqualified: { 9975 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9976 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9977 9978 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9979 9980 // Param will have been canonicalized, but it should just be a 9981 // qualified version of ParamD, so move the qualifiers to that. 9982 QualifierCollector Qs; 9983 Qs.strip(Param); 9984 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9985 assert(S.Context.hasSameType(Param, NonCanonParam)); 9986 9987 // Arg has also been canonicalized, but there's nothing we can do 9988 // about that. It also doesn't matter as much, because it won't 9989 // have any template parameters in it (because deduction isn't 9990 // done on dependent types). 9991 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9992 9993 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9994 << ParamD->getDeclName() << Arg << NonCanonParam; 9995 MaybeEmitInheritedConstructorNote(S, Found); 9996 return; 9997 } 9998 9999 case Sema::TDK_Inconsistent: { 10000 assert(ParamD && "no parameter found for inconsistent deduction result"); 10001 int which = 0; 10002 if (isa<TemplateTypeParmDecl>(ParamD)) 10003 which = 0; 10004 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10005 // Deduction might have failed because we deduced arguments of two 10006 // different types for a non-type template parameter. 10007 // FIXME: Use a different TDK value for this. 10008 QualType T1 = 10009 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10010 QualType T2 = 10011 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10012 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10013 S.Diag(Templated->getLocation(), 10014 diag::note_ovl_candidate_inconsistent_deduction_types) 10015 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10016 << *DeductionFailure.getSecondArg() << T2; 10017 MaybeEmitInheritedConstructorNote(S, Found); 10018 return; 10019 } 10020 10021 which = 1; 10022 } else { 10023 which = 2; 10024 } 10025 10026 S.Diag(Templated->getLocation(), 10027 diag::note_ovl_candidate_inconsistent_deduction) 10028 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10029 << *DeductionFailure.getSecondArg(); 10030 MaybeEmitInheritedConstructorNote(S, Found); 10031 return; 10032 } 10033 10034 case Sema::TDK_InvalidExplicitArguments: 10035 assert(ParamD && "no parameter found for invalid explicit arguments"); 10036 if (ParamD->getDeclName()) 10037 S.Diag(Templated->getLocation(), 10038 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10039 << ParamD->getDeclName(); 10040 else { 10041 int index = 0; 10042 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10043 index = TTP->getIndex(); 10044 else if (NonTypeTemplateParmDecl *NTTP 10045 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10046 index = NTTP->getIndex(); 10047 else 10048 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10049 S.Diag(Templated->getLocation(), 10050 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10051 << (index + 1); 10052 } 10053 MaybeEmitInheritedConstructorNote(S, Found); 10054 return; 10055 10056 case Sema::TDK_TooManyArguments: 10057 case Sema::TDK_TooFewArguments: 10058 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10059 return; 10060 10061 case Sema::TDK_InstantiationDepth: 10062 S.Diag(Templated->getLocation(), 10063 diag::note_ovl_candidate_instantiation_depth); 10064 MaybeEmitInheritedConstructorNote(S, Found); 10065 return; 10066 10067 case Sema::TDK_SubstitutionFailure: { 10068 // Format the template argument list into the argument string. 10069 SmallString<128> TemplateArgString; 10070 if (TemplateArgumentList *Args = 10071 DeductionFailure.getTemplateArgumentList()) { 10072 TemplateArgString = " "; 10073 TemplateArgString += S.getTemplateArgumentBindingsText( 10074 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10075 } 10076 10077 // If this candidate was disabled by enable_if, say so. 10078 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10079 if (PDiag && PDiag->second.getDiagID() == 10080 diag::err_typename_nested_not_found_enable_if) { 10081 // FIXME: Use the source range of the condition, and the fully-qualified 10082 // name of the enable_if template. These are both present in PDiag. 10083 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10084 << "'enable_if'" << TemplateArgString; 10085 return; 10086 } 10087 10088 // We found a specific requirement that disabled the enable_if. 10089 if (PDiag && PDiag->second.getDiagID() == 10090 diag::err_typename_nested_not_found_requirement) { 10091 S.Diag(Templated->getLocation(), 10092 diag::note_ovl_candidate_disabled_by_requirement) 10093 << PDiag->second.getStringArg(0) << TemplateArgString; 10094 return; 10095 } 10096 10097 // Format the SFINAE diagnostic into the argument string. 10098 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10099 // formatted message in another diagnostic. 10100 SmallString<128> SFINAEArgString; 10101 SourceRange R; 10102 if (PDiag) { 10103 SFINAEArgString = ": "; 10104 R = SourceRange(PDiag->first, PDiag->first); 10105 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10106 } 10107 10108 S.Diag(Templated->getLocation(), 10109 diag::note_ovl_candidate_substitution_failure) 10110 << TemplateArgString << SFINAEArgString << R; 10111 MaybeEmitInheritedConstructorNote(S, Found); 10112 return; 10113 } 10114 10115 case Sema::TDK_DeducedMismatch: 10116 case Sema::TDK_DeducedMismatchNested: { 10117 // Format the template argument list into the argument string. 10118 SmallString<128> TemplateArgString; 10119 if (TemplateArgumentList *Args = 10120 DeductionFailure.getTemplateArgumentList()) { 10121 TemplateArgString = " "; 10122 TemplateArgString += S.getTemplateArgumentBindingsText( 10123 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10124 } 10125 10126 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10127 << (*DeductionFailure.getCallArgIndex() + 1) 10128 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10129 << TemplateArgString 10130 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10131 break; 10132 } 10133 10134 case Sema::TDK_NonDeducedMismatch: { 10135 // FIXME: Provide a source location to indicate what we couldn't match. 10136 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10137 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10138 if (FirstTA.getKind() == TemplateArgument::Template && 10139 SecondTA.getKind() == TemplateArgument::Template) { 10140 TemplateName FirstTN = FirstTA.getAsTemplate(); 10141 TemplateName SecondTN = SecondTA.getAsTemplate(); 10142 if (FirstTN.getKind() == TemplateName::Template && 10143 SecondTN.getKind() == TemplateName::Template) { 10144 if (FirstTN.getAsTemplateDecl()->getName() == 10145 SecondTN.getAsTemplateDecl()->getName()) { 10146 // FIXME: This fixes a bad diagnostic where both templates are named 10147 // the same. This particular case is a bit difficult since: 10148 // 1) It is passed as a string to the diagnostic printer. 10149 // 2) The diagnostic printer only attempts to find a better 10150 // name for types, not decls. 10151 // Ideally, this should folded into the diagnostic printer. 10152 S.Diag(Templated->getLocation(), 10153 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10154 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10155 return; 10156 } 10157 } 10158 } 10159 10160 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10161 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10162 return; 10163 10164 // FIXME: For generic lambda parameters, check if the function is a lambda 10165 // call operator, and if so, emit a prettier and more informative 10166 // diagnostic that mentions 'auto' and lambda in addition to 10167 // (or instead of?) the canonical template type parameters. 10168 S.Diag(Templated->getLocation(), 10169 diag::note_ovl_candidate_non_deduced_mismatch) 10170 << FirstTA << SecondTA; 10171 return; 10172 } 10173 // TODO: diagnose these individually, then kill off 10174 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10175 case Sema::TDK_MiscellaneousDeductionFailure: 10176 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10177 MaybeEmitInheritedConstructorNote(S, Found); 10178 return; 10179 case Sema::TDK_CUDATargetMismatch: 10180 S.Diag(Templated->getLocation(), 10181 diag::note_cuda_ovl_candidate_target_mismatch); 10182 return; 10183 } 10184 } 10185 10186 /// Diagnose a failed template-argument deduction, for function calls. 10187 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10188 unsigned NumArgs, 10189 bool TakingCandidateAddress) { 10190 unsigned TDK = Cand->DeductionFailure.Result; 10191 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10192 if (CheckArityMismatch(S, Cand, NumArgs)) 10193 return; 10194 } 10195 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10196 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10197 } 10198 10199 /// CUDA: diagnose an invalid call across targets. 10200 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10201 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10202 FunctionDecl *Callee = Cand->Function; 10203 10204 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10205 CalleeTarget = S.IdentifyCUDATarget(Callee); 10206 10207 std::string FnDesc; 10208 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10209 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10210 10211 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10212 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10213 << FnDesc /* Ignored */ 10214 << CalleeTarget << CallerTarget; 10215 10216 // This could be an implicit constructor for which we could not infer the 10217 // target due to a collsion. Diagnose that case. 10218 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10219 if (Meth != nullptr && Meth->isImplicit()) { 10220 CXXRecordDecl *ParentClass = Meth->getParent(); 10221 Sema::CXXSpecialMember CSM; 10222 10223 switch (FnKindPair.first) { 10224 default: 10225 return; 10226 case oc_implicit_default_constructor: 10227 CSM = Sema::CXXDefaultConstructor; 10228 break; 10229 case oc_implicit_copy_constructor: 10230 CSM = Sema::CXXCopyConstructor; 10231 break; 10232 case oc_implicit_move_constructor: 10233 CSM = Sema::CXXMoveConstructor; 10234 break; 10235 case oc_implicit_copy_assignment: 10236 CSM = Sema::CXXCopyAssignment; 10237 break; 10238 case oc_implicit_move_assignment: 10239 CSM = Sema::CXXMoveAssignment; 10240 break; 10241 }; 10242 10243 bool ConstRHS = false; 10244 if (Meth->getNumParams()) { 10245 if (const ReferenceType *RT = 10246 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10247 ConstRHS = RT->getPointeeType().isConstQualified(); 10248 } 10249 } 10250 10251 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10252 /* ConstRHS */ ConstRHS, 10253 /* Diagnose */ true); 10254 } 10255 } 10256 10257 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10258 FunctionDecl *Callee = Cand->Function; 10259 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10260 10261 S.Diag(Callee->getLocation(), 10262 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10263 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10264 } 10265 10266 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10267 FunctionDecl *Callee = Cand->Function; 10268 10269 S.Diag(Callee->getLocation(), 10270 diag::note_ovl_candidate_disabled_by_extension) 10271 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10272 } 10273 10274 /// Generates a 'note' diagnostic for an overload candidate. We've 10275 /// already generated a primary error at the call site. 10276 /// 10277 /// It really does need to be a single diagnostic with its caret 10278 /// pointed at the candidate declaration. Yes, this creates some 10279 /// major challenges of technical writing. Yes, this makes pointing 10280 /// out problems with specific arguments quite awkward. It's still 10281 /// better than generating twenty screens of text for every failed 10282 /// overload. 10283 /// 10284 /// It would be great to be able to express per-candidate problems 10285 /// more richly for those diagnostic clients that cared, but we'd 10286 /// still have to be just as careful with the default diagnostics. 10287 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10288 unsigned NumArgs, 10289 bool TakingCandidateAddress) { 10290 FunctionDecl *Fn = Cand->Function; 10291 10292 // Note deleted candidates, but only if they're viable. 10293 if (Cand->Viable) { 10294 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10295 std::string FnDesc; 10296 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10297 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10298 10299 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10300 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10301 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10302 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10303 return; 10304 } 10305 10306 // We don't really have anything else to say about viable candidates. 10307 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10308 return; 10309 } 10310 10311 switch (Cand->FailureKind) { 10312 case ovl_fail_too_many_arguments: 10313 case ovl_fail_too_few_arguments: 10314 return DiagnoseArityMismatch(S, Cand, NumArgs); 10315 10316 case ovl_fail_bad_deduction: 10317 return DiagnoseBadDeduction(S, Cand, NumArgs, 10318 TakingCandidateAddress); 10319 10320 case ovl_fail_illegal_constructor: { 10321 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10322 << (Fn->getPrimaryTemplate() ? 1 : 0); 10323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10324 return; 10325 } 10326 10327 case ovl_fail_trivial_conversion: 10328 case ovl_fail_bad_final_conversion: 10329 case ovl_fail_final_conversion_not_exact: 10330 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10331 10332 case ovl_fail_bad_conversion: { 10333 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10334 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10335 if (Cand->Conversions[I].isBad()) 10336 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10337 10338 // FIXME: this currently happens when we're called from SemaInit 10339 // when user-conversion overload fails. Figure out how to handle 10340 // those conditions and diagnose them well. 10341 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10342 } 10343 10344 case ovl_fail_bad_target: 10345 return DiagnoseBadTarget(S, Cand); 10346 10347 case ovl_fail_enable_if: 10348 return DiagnoseFailedEnableIfAttr(S, Cand); 10349 10350 case ovl_fail_ext_disabled: 10351 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10352 10353 case ovl_fail_inhctor_slice: 10354 // It's generally not interesting to note copy/move constructors here. 10355 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10356 return; 10357 S.Diag(Fn->getLocation(), 10358 diag::note_ovl_candidate_inherited_constructor_slice) 10359 << (Fn->getPrimaryTemplate() ? 1 : 0) 10360 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10361 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10362 return; 10363 10364 case ovl_fail_addr_not_available: { 10365 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10366 (void)Available; 10367 assert(!Available); 10368 break; 10369 } 10370 case ovl_non_default_multiversion_function: 10371 // Do nothing, these should simply be ignored. 10372 break; 10373 } 10374 } 10375 10376 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10377 // Desugar the type of the surrogate down to a function type, 10378 // retaining as many typedefs as possible while still showing 10379 // the function type (and, therefore, its parameter types). 10380 QualType FnType = Cand->Surrogate->getConversionType(); 10381 bool isLValueReference = false; 10382 bool isRValueReference = false; 10383 bool isPointer = false; 10384 if (const LValueReferenceType *FnTypeRef = 10385 FnType->getAs<LValueReferenceType>()) { 10386 FnType = FnTypeRef->getPointeeType(); 10387 isLValueReference = true; 10388 } else if (const RValueReferenceType *FnTypeRef = 10389 FnType->getAs<RValueReferenceType>()) { 10390 FnType = FnTypeRef->getPointeeType(); 10391 isRValueReference = true; 10392 } 10393 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10394 FnType = FnTypePtr->getPointeeType(); 10395 isPointer = true; 10396 } 10397 // Desugar down to a function type. 10398 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10399 // Reconstruct the pointer/reference as appropriate. 10400 if (isPointer) FnType = S.Context.getPointerType(FnType); 10401 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10402 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10403 10404 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10405 << FnType; 10406 } 10407 10408 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10409 SourceLocation OpLoc, 10410 OverloadCandidate *Cand) { 10411 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10412 std::string TypeStr("operator"); 10413 TypeStr += Opc; 10414 TypeStr += "("; 10415 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10416 if (Cand->Conversions.size() == 1) { 10417 TypeStr += ")"; 10418 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10419 } else { 10420 TypeStr += ", "; 10421 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10422 TypeStr += ")"; 10423 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10424 } 10425 } 10426 10427 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10428 OverloadCandidate *Cand) { 10429 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10430 if (ICS.isBad()) break; // all meaningless after first invalid 10431 if (!ICS.isAmbiguous()) continue; 10432 10433 ICS.DiagnoseAmbiguousConversion( 10434 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10435 } 10436 } 10437 10438 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10439 if (Cand->Function) 10440 return Cand->Function->getLocation(); 10441 if (Cand->IsSurrogate) 10442 return Cand->Surrogate->getLocation(); 10443 return SourceLocation(); 10444 } 10445 10446 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10447 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10448 case Sema::TDK_Success: 10449 case Sema::TDK_NonDependentConversionFailure: 10450 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10451 10452 case Sema::TDK_Invalid: 10453 case Sema::TDK_Incomplete: 10454 case Sema::TDK_IncompletePack: 10455 return 1; 10456 10457 case Sema::TDK_Underqualified: 10458 case Sema::TDK_Inconsistent: 10459 return 2; 10460 10461 case Sema::TDK_SubstitutionFailure: 10462 case Sema::TDK_DeducedMismatch: 10463 case Sema::TDK_DeducedMismatchNested: 10464 case Sema::TDK_NonDeducedMismatch: 10465 case Sema::TDK_MiscellaneousDeductionFailure: 10466 case Sema::TDK_CUDATargetMismatch: 10467 return 3; 10468 10469 case Sema::TDK_InstantiationDepth: 10470 return 4; 10471 10472 case Sema::TDK_InvalidExplicitArguments: 10473 return 5; 10474 10475 case Sema::TDK_TooManyArguments: 10476 case Sema::TDK_TooFewArguments: 10477 return 6; 10478 } 10479 llvm_unreachable("Unhandled deduction result"); 10480 } 10481 10482 namespace { 10483 struct CompareOverloadCandidatesForDisplay { 10484 Sema &S; 10485 SourceLocation Loc; 10486 size_t NumArgs; 10487 OverloadCandidateSet::CandidateSetKind CSK; 10488 10489 CompareOverloadCandidatesForDisplay( 10490 Sema &S, SourceLocation Loc, size_t NArgs, 10491 OverloadCandidateSet::CandidateSetKind CSK) 10492 : S(S), NumArgs(NArgs), CSK(CSK) {} 10493 10494 bool operator()(const OverloadCandidate *L, 10495 const OverloadCandidate *R) { 10496 // Fast-path this check. 10497 if (L == R) return false; 10498 10499 // Order first by viability. 10500 if (L->Viable) { 10501 if (!R->Viable) return true; 10502 10503 // TODO: introduce a tri-valued comparison for overload 10504 // candidates. Would be more worthwhile if we had a sort 10505 // that could exploit it. 10506 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10507 return true; 10508 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10509 return false; 10510 } else if (R->Viable) 10511 return false; 10512 10513 assert(L->Viable == R->Viable); 10514 10515 // Criteria by which we can sort non-viable candidates: 10516 if (!L->Viable) { 10517 // 1. Arity mismatches come after other candidates. 10518 if (L->FailureKind == ovl_fail_too_many_arguments || 10519 L->FailureKind == ovl_fail_too_few_arguments) { 10520 if (R->FailureKind == ovl_fail_too_many_arguments || 10521 R->FailureKind == ovl_fail_too_few_arguments) { 10522 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10523 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10524 if (LDist == RDist) { 10525 if (L->FailureKind == R->FailureKind) 10526 // Sort non-surrogates before surrogates. 10527 return !L->IsSurrogate && R->IsSurrogate; 10528 // Sort candidates requiring fewer parameters than there were 10529 // arguments given after candidates requiring more parameters 10530 // than there were arguments given. 10531 return L->FailureKind == ovl_fail_too_many_arguments; 10532 } 10533 return LDist < RDist; 10534 } 10535 return false; 10536 } 10537 if (R->FailureKind == ovl_fail_too_many_arguments || 10538 R->FailureKind == ovl_fail_too_few_arguments) 10539 return true; 10540 10541 // 2. Bad conversions come first and are ordered by the number 10542 // of bad conversions and quality of good conversions. 10543 if (L->FailureKind == ovl_fail_bad_conversion) { 10544 if (R->FailureKind != ovl_fail_bad_conversion) 10545 return true; 10546 10547 // The conversion that can be fixed with a smaller number of changes, 10548 // comes first. 10549 unsigned numLFixes = L->Fix.NumConversionsFixed; 10550 unsigned numRFixes = R->Fix.NumConversionsFixed; 10551 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10552 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10553 if (numLFixes != numRFixes) { 10554 return numLFixes < numRFixes; 10555 } 10556 10557 // If there's any ordering between the defined conversions... 10558 // FIXME: this might not be transitive. 10559 assert(L->Conversions.size() == R->Conversions.size()); 10560 10561 int leftBetter = 0; 10562 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10563 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10564 switch (CompareImplicitConversionSequences(S, Loc, 10565 L->Conversions[I], 10566 R->Conversions[I])) { 10567 case ImplicitConversionSequence::Better: 10568 leftBetter++; 10569 break; 10570 10571 case ImplicitConversionSequence::Worse: 10572 leftBetter--; 10573 break; 10574 10575 case ImplicitConversionSequence::Indistinguishable: 10576 break; 10577 } 10578 } 10579 if (leftBetter > 0) return true; 10580 if (leftBetter < 0) return false; 10581 10582 } else if (R->FailureKind == ovl_fail_bad_conversion) 10583 return false; 10584 10585 if (L->FailureKind == ovl_fail_bad_deduction) { 10586 if (R->FailureKind != ovl_fail_bad_deduction) 10587 return true; 10588 10589 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10590 return RankDeductionFailure(L->DeductionFailure) 10591 < RankDeductionFailure(R->DeductionFailure); 10592 } else if (R->FailureKind == ovl_fail_bad_deduction) 10593 return false; 10594 10595 // TODO: others? 10596 } 10597 10598 // Sort everything else by location. 10599 SourceLocation LLoc = GetLocationForCandidate(L); 10600 SourceLocation RLoc = GetLocationForCandidate(R); 10601 10602 // Put candidates without locations (e.g. builtins) at the end. 10603 if (LLoc.isInvalid()) return false; 10604 if (RLoc.isInvalid()) return true; 10605 10606 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10607 } 10608 }; 10609 } 10610 10611 /// CompleteNonViableCandidate - Normally, overload resolution only 10612 /// computes up to the first bad conversion. Produces the FixIt set if 10613 /// possible. 10614 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10615 ArrayRef<Expr *> Args) { 10616 assert(!Cand->Viable); 10617 10618 // Don't do anything on failures other than bad conversion. 10619 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10620 10621 // We only want the FixIts if all the arguments can be corrected. 10622 bool Unfixable = false; 10623 // Use a implicit copy initialization to check conversion fixes. 10624 Cand->Fix.setConversionChecker(TryCopyInitialization); 10625 10626 // Attempt to fix the bad conversion. 10627 unsigned ConvCount = Cand->Conversions.size(); 10628 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10629 ++ConvIdx) { 10630 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10631 if (Cand->Conversions[ConvIdx].isInitialized() && 10632 Cand->Conversions[ConvIdx].isBad()) { 10633 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10634 break; 10635 } 10636 } 10637 10638 // FIXME: this should probably be preserved from the overload 10639 // operation somehow. 10640 bool SuppressUserConversions = false; 10641 10642 unsigned ConvIdx = 0; 10643 ArrayRef<QualType> ParamTypes; 10644 10645 if (Cand->IsSurrogate) { 10646 QualType ConvType 10647 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10648 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10649 ConvType = ConvPtrType->getPointeeType(); 10650 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10651 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10652 ConvIdx = 1; 10653 } else if (Cand->Function) { 10654 ParamTypes = 10655 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10656 if (isa<CXXMethodDecl>(Cand->Function) && 10657 !isa<CXXConstructorDecl>(Cand->Function)) { 10658 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10659 ConvIdx = 1; 10660 } 10661 } else { 10662 // Builtin operator. 10663 assert(ConvCount <= 3); 10664 ParamTypes = Cand->BuiltinParamTypes; 10665 } 10666 10667 // Fill in the rest of the conversions. 10668 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10669 if (Cand->Conversions[ConvIdx].isInitialized()) { 10670 // We've already checked this conversion. 10671 } else if (ArgIdx < ParamTypes.size()) { 10672 if (ParamTypes[ArgIdx]->isDependentType()) 10673 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10674 Args[ArgIdx]->getType()); 10675 else { 10676 Cand->Conversions[ConvIdx] = 10677 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10678 SuppressUserConversions, 10679 /*InOverloadResolution=*/true, 10680 /*AllowObjCWritebackConversion=*/ 10681 S.getLangOpts().ObjCAutoRefCount); 10682 // Store the FixIt in the candidate if it exists. 10683 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10684 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10685 } 10686 } else 10687 Cand->Conversions[ConvIdx].setEllipsis(); 10688 } 10689 } 10690 10691 /// When overload resolution fails, prints diagnostic messages containing the 10692 /// candidates in the candidate set. 10693 void OverloadCandidateSet::NoteCandidates( 10694 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10695 StringRef Opc, SourceLocation OpLoc, 10696 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10697 // Sort the candidates by viability and position. Sorting directly would 10698 // be prohibitive, so we make a set of pointers and sort those. 10699 SmallVector<OverloadCandidate*, 32> Cands; 10700 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10701 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10702 if (!Filter(*Cand)) 10703 continue; 10704 if (Cand->Viable) 10705 Cands.push_back(Cand); 10706 else if (OCD == OCD_AllCandidates) { 10707 CompleteNonViableCandidate(S, Cand, Args); 10708 if (Cand->Function || Cand->IsSurrogate) 10709 Cands.push_back(Cand); 10710 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10711 // want to list every possible builtin candidate. 10712 } 10713 } 10714 10715 std::stable_sort(Cands.begin(), Cands.end(), 10716 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10717 10718 bool ReportedAmbiguousConversions = false; 10719 10720 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10721 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10722 unsigned CandsShown = 0; 10723 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10724 OverloadCandidate *Cand = *I; 10725 10726 // Set an arbitrary limit on the number of candidate functions we'll spam 10727 // the user with. FIXME: This limit should depend on details of the 10728 // candidate list. 10729 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10730 break; 10731 } 10732 ++CandsShown; 10733 10734 if (Cand->Function) 10735 NoteFunctionCandidate(S, Cand, Args.size(), 10736 /*TakingCandidateAddress=*/false); 10737 else if (Cand->IsSurrogate) 10738 NoteSurrogateCandidate(S, Cand); 10739 else { 10740 assert(Cand->Viable && 10741 "Non-viable built-in candidates are not added to Cands."); 10742 // Generally we only see ambiguities including viable builtin 10743 // operators if overload resolution got screwed up by an 10744 // ambiguous user-defined conversion. 10745 // 10746 // FIXME: It's quite possible for different conversions to see 10747 // different ambiguities, though. 10748 if (!ReportedAmbiguousConversions) { 10749 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10750 ReportedAmbiguousConversions = true; 10751 } 10752 10753 // If this is a viable builtin, print it. 10754 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10755 } 10756 } 10757 10758 if (I != E) 10759 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10760 } 10761 10762 static SourceLocation 10763 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10764 return Cand->Specialization ? Cand->Specialization->getLocation() 10765 : SourceLocation(); 10766 } 10767 10768 namespace { 10769 struct CompareTemplateSpecCandidatesForDisplay { 10770 Sema &S; 10771 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10772 10773 bool operator()(const TemplateSpecCandidate *L, 10774 const TemplateSpecCandidate *R) { 10775 // Fast-path this check. 10776 if (L == R) 10777 return false; 10778 10779 // Assuming that both candidates are not matches... 10780 10781 // Sort by the ranking of deduction failures. 10782 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10783 return RankDeductionFailure(L->DeductionFailure) < 10784 RankDeductionFailure(R->DeductionFailure); 10785 10786 // Sort everything else by location. 10787 SourceLocation LLoc = GetLocationForCandidate(L); 10788 SourceLocation RLoc = GetLocationForCandidate(R); 10789 10790 // Put candidates without locations (e.g. builtins) at the end. 10791 if (LLoc.isInvalid()) 10792 return false; 10793 if (RLoc.isInvalid()) 10794 return true; 10795 10796 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10797 } 10798 }; 10799 } 10800 10801 /// Diagnose a template argument deduction failure. 10802 /// We are treating these failures as overload failures due to bad 10803 /// deductions. 10804 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10805 bool ForTakingAddress) { 10806 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10807 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10808 } 10809 10810 void TemplateSpecCandidateSet::destroyCandidates() { 10811 for (iterator i = begin(), e = end(); i != e; ++i) { 10812 i->DeductionFailure.Destroy(); 10813 } 10814 } 10815 10816 void TemplateSpecCandidateSet::clear() { 10817 destroyCandidates(); 10818 Candidates.clear(); 10819 } 10820 10821 /// NoteCandidates - When no template specialization match is found, prints 10822 /// diagnostic messages containing the non-matching specializations that form 10823 /// the candidate set. 10824 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10825 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10826 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10827 // Sort the candidates by position (assuming no candidate is a match). 10828 // Sorting directly would be prohibitive, so we make a set of pointers 10829 // and sort those. 10830 SmallVector<TemplateSpecCandidate *, 32> Cands; 10831 Cands.reserve(size()); 10832 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10833 if (Cand->Specialization) 10834 Cands.push_back(Cand); 10835 // Otherwise, this is a non-matching builtin candidate. We do not, 10836 // in general, want to list every possible builtin candidate. 10837 } 10838 10839 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10840 10841 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10842 // for generalization purposes (?). 10843 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10844 10845 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10846 unsigned CandsShown = 0; 10847 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10848 TemplateSpecCandidate *Cand = *I; 10849 10850 // Set an arbitrary limit on the number of candidates we'll spam 10851 // the user with. FIXME: This limit should depend on details of the 10852 // candidate list. 10853 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10854 break; 10855 ++CandsShown; 10856 10857 assert(Cand->Specialization && 10858 "Non-matching built-in candidates are not added to Cands."); 10859 Cand->NoteDeductionFailure(S, ForTakingAddress); 10860 } 10861 10862 if (I != E) 10863 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10864 } 10865 10866 // [PossiblyAFunctionType] --> [Return] 10867 // NonFunctionType --> NonFunctionType 10868 // R (A) --> R(A) 10869 // R (*)(A) --> R (A) 10870 // R (&)(A) --> R (A) 10871 // R (S::*)(A) --> R (A) 10872 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10873 QualType Ret = PossiblyAFunctionType; 10874 if (const PointerType *ToTypePtr = 10875 PossiblyAFunctionType->getAs<PointerType>()) 10876 Ret = ToTypePtr->getPointeeType(); 10877 else if (const ReferenceType *ToTypeRef = 10878 PossiblyAFunctionType->getAs<ReferenceType>()) 10879 Ret = ToTypeRef->getPointeeType(); 10880 else if (const MemberPointerType *MemTypePtr = 10881 PossiblyAFunctionType->getAs<MemberPointerType>()) 10882 Ret = MemTypePtr->getPointeeType(); 10883 Ret = 10884 Context.getCanonicalType(Ret).getUnqualifiedType(); 10885 return Ret; 10886 } 10887 10888 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10889 bool Complain = true) { 10890 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10891 S.DeduceReturnType(FD, Loc, Complain)) 10892 return true; 10893 10894 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10895 if (S.getLangOpts().CPlusPlus17 && 10896 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10897 !S.ResolveExceptionSpec(Loc, FPT)) 10898 return true; 10899 10900 return false; 10901 } 10902 10903 namespace { 10904 // A helper class to help with address of function resolution 10905 // - allows us to avoid passing around all those ugly parameters 10906 class AddressOfFunctionResolver { 10907 Sema& S; 10908 Expr* SourceExpr; 10909 const QualType& TargetType; 10910 QualType TargetFunctionType; // Extracted function type from target type 10911 10912 bool Complain; 10913 //DeclAccessPair& ResultFunctionAccessPair; 10914 ASTContext& Context; 10915 10916 bool TargetTypeIsNonStaticMemberFunction; 10917 bool FoundNonTemplateFunction; 10918 bool StaticMemberFunctionFromBoundPointer; 10919 bool HasComplained; 10920 10921 OverloadExpr::FindResult OvlExprInfo; 10922 OverloadExpr *OvlExpr; 10923 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10924 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10925 TemplateSpecCandidateSet FailedCandidates; 10926 10927 public: 10928 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10929 const QualType &TargetType, bool Complain) 10930 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10931 Complain(Complain), Context(S.getASTContext()), 10932 TargetTypeIsNonStaticMemberFunction( 10933 !!TargetType->getAs<MemberPointerType>()), 10934 FoundNonTemplateFunction(false), 10935 StaticMemberFunctionFromBoundPointer(false), 10936 HasComplained(false), 10937 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10938 OvlExpr(OvlExprInfo.Expression), 10939 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10940 ExtractUnqualifiedFunctionTypeFromTargetType(); 10941 10942 if (TargetFunctionType->isFunctionType()) { 10943 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10944 if (!UME->isImplicitAccess() && 10945 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10946 StaticMemberFunctionFromBoundPointer = true; 10947 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10948 DeclAccessPair dap; 10949 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10950 OvlExpr, false, &dap)) { 10951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10952 if (!Method->isStatic()) { 10953 // If the target type is a non-function type and the function found 10954 // is a non-static member function, pretend as if that was the 10955 // target, it's the only possible type to end up with. 10956 TargetTypeIsNonStaticMemberFunction = true; 10957 10958 // And skip adding the function if its not in the proper form. 10959 // We'll diagnose this due to an empty set of functions. 10960 if (!OvlExprInfo.HasFormOfMemberPointer) 10961 return; 10962 } 10963 10964 Matches.push_back(std::make_pair(dap, Fn)); 10965 } 10966 return; 10967 } 10968 10969 if (OvlExpr->hasExplicitTemplateArgs()) 10970 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10971 10972 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10973 // C++ [over.over]p4: 10974 // If more than one function is selected, [...] 10975 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10976 if (FoundNonTemplateFunction) 10977 EliminateAllTemplateMatches(); 10978 else 10979 EliminateAllExceptMostSpecializedTemplate(); 10980 } 10981 } 10982 10983 if (S.getLangOpts().CUDA && Matches.size() > 1) 10984 EliminateSuboptimalCudaMatches(); 10985 } 10986 10987 bool hasComplained() const { return HasComplained; } 10988 10989 private: 10990 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10991 QualType Discard; 10992 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10993 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10994 } 10995 10996 /// \return true if A is considered a better overload candidate for the 10997 /// desired type than B. 10998 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10999 // If A doesn't have exactly the correct type, we don't want to classify it 11000 // as "better" than anything else. This way, the user is required to 11001 // disambiguate for us if there are multiple candidates and no exact match. 11002 return candidateHasExactlyCorrectType(A) && 11003 (!candidateHasExactlyCorrectType(B) || 11004 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11005 } 11006 11007 /// \return true if we were able to eliminate all but one overload candidate, 11008 /// false otherwise. 11009 bool eliminiateSuboptimalOverloadCandidates() { 11010 // Same algorithm as overload resolution -- one pass to pick the "best", 11011 // another pass to be sure that nothing is better than the best. 11012 auto Best = Matches.begin(); 11013 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11014 if (isBetterCandidate(I->second, Best->second)) 11015 Best = I; 11016 11017 const FunctionDecl *BestFn = Best->second; 11018 auto IsBestOrInferiorToBest = [this, BestFn]( 11019 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11020 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11021 }; 11022 11023 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11024 // option, so we can potentially give the user a better error 11025 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11026 return false; 11027 Matches[0] = *Best; 11028 Matches.resize(1); 11029 return true; 11030 } 11031 11032 bool isTargetTypeAFunction() const { 11033 return TargetFunctionType->isFunctionType(); 11034 } 11035 11036 // [ToType] [Return] 11037 11038 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11039 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11040 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11041 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11042 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11043 } 11044 11045 // return true if any matching specializations were found 11046 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11047 const DeclAccessPair& CurAccessFunPair) { 11048 if (CXXMethodDecl *Method 11049 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11050 // Skip non-static function templates when converting to pointer, and 11051 // static when converting to member pointer. 11052 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11053 return false; 11054 } 11055 else if (TargetTypeIsNonStaticMemberFunction) 11056 return false; 11057 11058 // C++ [over.over]p2: 11059 // If the name is a function template, template argument deduction is 11060 // done (14.8.2.2), and if the argument deduction succeeds, the 11061 // resulting template argument list is used to generate a single 11062 // function template specialization, which is added to the set of 11063 // overloaded functions considered. 11064 FunctionDecl *Specialization = nullptr; 11065 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11066 if (Sema::TemplateDeductionResult Result 11067 = S.DeduceTemplateArguments(FunctionTemplate, 11068 &OvlExplicitTemplateArgs, 11069 TargetFunctionType, Specialization, 11070 Info, /*IsAddressOfFunction*/true)) { 11071 // Make a note of the failed deduction for diagnostics. 11072 FailedCandidates.addCandidate() 11073 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11074 MakeDeductionFailureInfo(Context, Result, Info)); 11075 return false; 11076 } 11077 11078 // Template argument deduction ensures that we have an exact match or 11079 // compatible pointer-to-function arguments that would be adjusted by ICS. 11080 // This function template specicalization works. 11081 assert(S.isSameOrCompatibleFunctionType( 11082 Context.getCanonicalType(Specialization->getType()), 11083 Context.getCanonicalType(TargetFunctionType))); 11084 11085 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11086 return false; 11087 11088 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11089 return true; 11090 } 11091 11092 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11093 const DeclAccessPair& CurAccessFunPair) { 11094 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11095 // Skip non-static functions when converting to pointer, and static 11096 // when converting to member pointer. 11097 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11098 return false; 11099 } 11100 else if (TargetTypeIsNonStaticMemberFunction) 11101 return false; 11102 11103 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11104 if (S.getLangOpts().CUDA) 11105 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11106 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11107 return false; 11108 if (FunDecl->isMultiVersion()) { 11109 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11110 if (TA && !TA->isDefaultVersion()) 11111 return false; 11112 } 11113 11114 // If any candidate has a placeholder return type, trigger its deduction 11115 // now. 11116 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11117 Complain)) { 11118 HasComplained |= Complain; 11119 return false; 11120 } 11121 11122 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11123 return false; 11124 11125 // If we're in C, we need to support types that aren't exactly identical. 11126 if (!S.getLangOpts().CPlusPlus || 11127 candidateHasExactlyCorrectType(FunDecl)) { 11128 Matches.push_back(std::make_pair( 11129 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11130 FoundNonTemplateFunction = true; 11131 return true; 11132 } 11133 } 11134 11135 return false; 11136 } 11137 11138 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11139 bool Ret = false; 11140 11141 // If the overload expression doesn't have the form of a pointer to 11142 // member, don't try to convert it to a pointer-to-member type. 11143 if (IsInvalidFormOfPointerToMemberFunction()) 11144 return false; 11145 11146 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11147 E = OvlExpr->decls_end(); 11148 I != E; ++I) { 11149 // Look through any using declarations to find the underlying function. 11150 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11151 11152 // C++ [over.over]p3: 11153 // Non-member functions and static member functions match 11154 // targets of type "pointer-to-function" or "reference-to-function." 11155 // Nonstatic member functions match targets of 11156 // type "pointer-to-member-function." 11157 // Note that according to DR 247, the containing class does not matter. 11158 if (FunctionTemplateDecl *FunctionTemplate 11159 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11160 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11161 Ret = true; 11162 } 11163 // If we have explicit template arguments supplied, skip non-templates. 11164 else if (!OvlExpr->hasExplicitTemplateArgs() && 11165 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11166 Ret = true; 11167 } 11168 assert(Ret || Matches.empty()); 11169 return Ret; 11170 } 11171 11172 void EliminateAllExceptMostSpecializedTemplate() { 11173 // [...] and any given function template specialization F1 is 11174 // eliminated if the set contains a second function template 11175 // specialization whose function template is more specialized 11176 // than the function template of F1 according to the partial 11177 // ordering rules of 14.5.5.2. 11178 11179 // The algorithm specified above is quadratic. We instead use a 11180 // two-pass algorithm (similar to the one used to identify the 11181 // best viable function in an overload set) that identifies the 11182 // best function template (if it exists). 11183 11184 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11185 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11186 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11187 11188 // TODO: It looks like FailedCandidates does not serve much purpose 11189 // here, since the no_viable diagnostic has index 0. 11190 UnresolvedSetIterator Result = S.getMostSpecialized( 11191 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11192 SourceExpr->getBeginLoc(), S.PDiag(), 11193 S.PDiag(diag::err_addr_ovl_ambiguous) 11194 << Matches[0].second->getDeclName(), 11195 S.PDiag(diag::note_ovl_candidate) 11196 << (unsigned)oc_function << (unsigned)ocs_described_template, 11197 Complain, TargetFunctionType); 11198 11199 if (Result != MatchesCopy.end()) { 11200 // Make it the first and only element 11201 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11202 Matches[0].second = cast<FunctionDecl>(*Result); 11203 Matches.resize(1); 11204 } else 11205 HasComplained |= Complain; 11206 } 11207 11208 void EliminateAllTemplateMatches() { 11209 // [...] any function template specializations in the set are 11210 // eliminated if the set also contains a non-template function, [...] 11211 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11212 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11213 ++I; 11214 else { 11215 Matches[I] = Matches[--N]; 11216 Matches.resize(N); 11217 } 11218 } 11219 } 11220 11221 void EliminateSuboptimalCudaMatches() { 11222 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11223 } 11224 11225 public: 11226 void ComplainNoMatchesFound() const { 11227 assert(Matches.empty()); 11228 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11229 << OvlExpr->getName() << TargetFunctionType 11230 << OvlExpr->getSourceRange(); 11231 if (FailedCandidates.empty()) 11232 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11233 /*TakingAddress=*/true); 11234 else { 11235 // We have some deduction failure messages. Use them to diagnose 11236 // the function templates, and diagnose the non-template candidates 11237 // normally. 11238 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11239 IEnd = OvlExpr->decls_end(); 11240 I != IEnd; ++I) 11241 if (FunctionDecl *Fun = 11242 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11243 if (!functionHasPassObjectSizeParams(Fun)) 11244 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11245 /*TakingAddress=*/true); 11246 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11247 } 11248 } 11249 11250 bool IsInvalidFormOfPointerToMemberFunction() const { 11251 return TargetTypeIsNonStaticMemberFunction && 11252 !OvlExprInfo.HasFormOfMemberPointer; 11253 } 11254 11255 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11256 // TODO: Should we condition this on whether any functions might 11257 // have matched, or is it more appropriate to do that in callers? 11258 // TODO: a fixit wouldn't hurt. 11259 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11260 << TargetType << OvlExpr->getSourceRange(); 11261 } 11262 11263 bool IsStaticMemberFunctionFromBoundPointer() const { 11264 return StaticMemberFunctionFromBoundPointer; 11265 } 11266 11267 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11268 S.Diag(OvlExpr->getBeginLoc(), 11269 diag::err_invalid_form_pointer_member_function) 11270 << OvlExpr->getSourceRange(); 11271 } 11272 11273 void ComplainOfInvalidConversion() const { 11274 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11275 << OvlExpr->getName() << TargetType; 11276 } 11277 11278 void ComplainMultipleMatchesFound() const { 11279 assert(Matches.size() > 1); 11280 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11281 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11282 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11283 /*TakingAddress=*/true); 11284 } 11285 11286 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11287 11288 int getNumMatches() const { return Matches.size(); } 11289 11290 FunctionDecl* getMatchingFunctionDecl() const { 11291 if (Matches.size() != 1) return nullptr; 11292 return Matches[0].second; 11293 } 11294 11295 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11296 if (Matches.size() != 1) return nullptr; 11297 return &Matches[0].first; 11298 } 11299 }; 11300 } 11301 11302 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11303 /// an overloaded function (C++ [over.over]), where @p From is an 11304 /// expression with overloaded function type and @p ToType is the type 11305 /// we're trying to resolve to. For example: 11306 /// 11307 /// @code 11308 /// int f(double); 11309 /// int f(int); 11310 /// 11311 /// int (*pfd)(double) = f; // selects f(double) 11312 /// @endcode 11313 /// 11314 /// This routine returns the resulting FunctionDecl if it could be 11315 /// resolved, and NULL otherwise. When @p Complain is true, this 11316 /// routine will emit diagnostics if there is an error. 11317 FunctionDecl * 11318 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11319 QualType TargetType, 11320 bool Complain, 11321 DeclAccessPair &FoundResult, 11322 bool *pHadMultipleCandidates) { 11323 assert(AddressOfExpr->getType() == Context.OverloadTy); 11324 11325 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11326 Complain); 11327 int NumMatches = Resolver.getNumMatches(); 11328 FunctionDecl *Fn = nullptr; 11329 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11330 if (NumMatches == 0 && ShouldComplain) { 11331 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11332 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11333 else 11334 Resolver.ComplainNoMatchesFound(); 11335 } 11336 else if (NumMatches > 1 && ShouldComplain) 11337 Resolver.ComplainMultipleMatchesFound(); 11338 else if (NumMatches == 1) { 11339 Fn = Resolver.getMatchingFunctionDecl(); 11340 assert(Fn); 11341 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11342 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11343 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11344 if (Complain) { 11345 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11346 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11347 else 11348 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11349 } 11350 } 11351 11352 if (pHadMultipleCandidates) 11353 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11354 return Fn; 11355 } 11356 11357 /// Given an expression that refers to an overloaded function, try to 11358 /// resolve that function to a single function that can have its address taken. 11359 /// This will modify `Pair` iff it returns non-null. 11360 /// 11361 /// This routine can only realistically succeed if all but one candidates in the 11362 /// overload set for SrcExpr cannot have their addresses taken. 11363 FunctionDecl * 11364 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11365 DeclAccessPair &Pair) { 11366 OverloadExpr::FindResult R = OverloadExpr::find(E); 11367 OverloadExpr *Ovl = R.Expression; 11368 FunctionDecl *Result = nullptr; 11369 DeclAccessPair DAP; 11370 // Don't use the AddressOfResolver because we're specifically looking for 11371 // cases where we have one overload candidate that lacks 11372 // enable_if/pass_object_size/... 11373 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11374 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11375 if (!FD) 11376 return nullptr; 11377 11378 if (!checkAddressOfFunctionIsAvailable(FD)) 11379 continue; 11380 11381 // We have more than one result; quit. 11382 if (Result) 11383 return nullptr; 11384 DAP = I.getPair(); 11385 Result = FD; 11386 } 11387 11388 if (Result) 11389 Pair = DAP; 11390 return Result; 11391 } 11392 11393 /// Given an overloaded function, tries to turn it into a non-overloaded 11394 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11395 /// will perform access checks, diagnose the use of the resultant decl, and, if 11396 /// requested, potentially perform a function-to-pointer decay. 11397 /// 11398 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11399 /// Otherwise, returns true. This may emit diagnostics and return true. 11400 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11401 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11402 Expr *E = SrcExpr.get(); 11403 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11404 11405 DeclAccessPair DAP; 11406 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11407 if (!Found || Found->isCPUDispatchMultiVersion() || 11408 Found->isCPUSpecificMultiVersion()) 11409 return false; 11410 11411 // Emitting multiple diagnostics for a function that is both inaccessible and 11412 // unavailable is consistent with our behavior elsewhere. So, always check 11413 // for both. 11414 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11415 CheckAddressOfMemberAccess(E, DAP); 11416 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11417 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11418 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11419 else 11420 SrcExpr = Fixed; 11421 return true; 11422 } 11423 11424 /// Given an expression that refers to an overloaded function, try to 11425 /// resolve that overloaded function expression down to a single function. 11426 /// 11427 /// This routine can only resolve template-ids that refer to a single function 11428 /// template, where that template-id refers to a single template whose template 11429 /// arguments are either provided by the template-id or have defaults, 11430 /// as described in C++0x [temp.arg.explicit]p3. 11431 /// 11432 /// If no template-ids are found, no diagnostics are emitted and NULL is 11433 /// returned. 11434 FunctionDecl * 11435 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11436 bool Complain, 11437 DeclAccessPair *FoundResult) { 11438 // C++ [over.over]p1: 11439 // [...] [Note: any redundant set of parentheses surrounding the 11440 // overloaded function name is ignored (5.1). ] 11441 // C++ [over.over]p1: 11442 // [...] The overloaded function name can be preceded by the & 11443 // operator. 11444 11445 // If we didn't actually find any template-ids, we're done. 11446 if (!ovl->hasExplicitTemplateArgs()) 11447 return nullptr; 11448 11449 TemplateArgumentListInfo ExplicitTemplateArgs; 11450 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11451 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11452 11453 // Look through all of the overloaded functions, searching for one 11454 // whose type matches exactly. 11455 FunctionDecl *Matched = nullptr; 11456 for (UnresolvedSetIterator I = ovl->decls_begin(), 11457 E = ovl->decls_end(); I != E; ++I) { 11458 // C++0x [temp.arg.explicit]p3: 11459 // [...] In contexts where deduction is done and fails, or in contexts 11460 // where deduction is not done, if a template argument list is 11461 // specified and it, along with any default template arguments, 11462 // identifies a single function template specialization, then the 11463 // template-id is an lvalue for the function template specialization. 11464 FunctionTemplateDecl *FunctionTemplate 11465 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11466 11467 // C++ [over.over]p2: 11468 // If the name is a function template, template argument deduction is 11469 // done (14.8.2.2), and if the argument deduction succeeds, the 11470 // resulting template argument list is used to generate a single 11471 // function template specialization, which is added to the set of 11472 // overloaded functions considered. 11473 FunctionDecl *Specialization = nullptr; 11474 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11475 if (TemplateDeductionResult Result 11476 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11477 Specialization, Info, 11478 /*IsAddressOfFunction*/true)) { 11479 // Make a note of the failed deduction for diagnostics. 11480 // TODO: Actually use the failed-deduction info? 11481 FailedCandidates.addCandidate() 11482 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11483 MakeDeductionFailureInfo(Context, Result, Info)); 11484 continue; 11485 } 11486 11487 assert(Specialization && "no specialization and no error?"); 11488 11489 // Multiple matches; we can't resolve to a single declaration. 11490 if (Matched) { 11491 if (Complain) { 11492 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11493 << ovl->getName(); 11494 NoteAllOverloadCandidates(ovl); 11495 } 11496 return nullptr; 11497 } 11498 11499 Matched = Specialization; 11500 if (FoundResult) *FoundResult = I.getPair(); 11501 } 11502 11503 if (Matched && 11504 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11505 return nullptr; 11506 11507 return Matched; 11508 } 11509 11510 // Resolve and fix an overloaded expression that can be resolved 11511 // because it identifies a single function template specialization. 11512 // 11513 // Last three arguments should only be supplied if Complain = true 11514 // 11515 // Return true if it was logically possible to so resolve the 11516 // expression, regardless of whether or not it succeeded. Always 11517 // returns true if 'complain' is set. 11518 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11519 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11520 bool complain, SourceRange OpRangeForComplaining, 11521 QualType DestTypeForComplaining, 11522 unsigned DiagIDForComplaining) { 11523 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11524 11525 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11526 11527 DeclAccessPair found; 11528 ExprResult SingleFunctionExpression; 11529 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11530 ovl.Expression, /*complain*/ false, &found)) { 11531 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11532 SrcExpr = ExprError(); 11533 return true; 11534 } 11535 11536 // It is only correct to resolve to an instance method if we're 11537 // resolving a form that's permitted to be a pointer to member. 11538 // Otherwise we'll end up making a bound member expression, which 11539 // is illegal in all the contexts we resolve like this. 11540 if (!ovl.HasFormOfMemberPointer && 11541 isa<CXXMethodDecl>(fn) && 11542 cast<CXXMethodDecl>(fn)->isInstance()) { 11543 if (!complain) return false; 11544 11545 Diag(ovl.Expression->getExprLoc(), 11546 diag::err_bound_member_function) 11547 << 0 << ovl.Expression->getSourceRange(); 11548 11549 // TODO: I believe we only end up here if there's a mix of 11550 // static and non-static candidates (otherwise the expression 11551 // would have 'bound member' type, not 'overload' type). 11552 // Ideally we would note which candidate was chosen and why 11553 // the static candidates were rejected. 11554 SrcExpr = ExprError(); 11555 return true; 11556 } 11557 11558 // Fix the expression to refer to 'fn'. 11559 SingleFunctionExpression = 11560 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11561 11562 // If desired, do function-to-pointer decay. 11563 if (doFunctionPointerConverion) { 11564 SingleFunctionExpression = 11565 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11566 if (SingleFunctionExpression.isInvalid()) { 11567 SrcExpr = ExprError(); 11568 return true; 11569 } 11570 } 11571 } 11572 11573 if (!SingleFunctionExpression.isUsable()) { 11574 if (complain) { 11575 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11576 << ovl.Expression->getName() 11577 << DestTypeForComplaining 11578 << OpRangeForComplaining 11579 << ovl.Expression->getQualifierLoc().getSourceRange(); 11580 NoteAllOverloadCandidates(SrcExpr.get()); 11581 11582 SrcExpr = ExprError(); 11583 return true; 11584 } 11585 11586 return false; 11587 } 11588 11589 SrcExpr = SingleFunctionExpression; 11590 return true; 11591 } 11592 11593 /// Add a single candidate to the overload set. 11594 static void AddOverloadedCallCandidate(Sema &S, 11595 DeclAccessPair FoundDecl, 11596 TemplateArgumentListInfo *ExplicitTemplateArgs, 11597 ArrayRef<Expr *> Args, 11598 OverloadCandidateSet &CandidateSet, 11599 bool PartialOverloading, 11600 bool KnownValid) { 11601 NamedDecl *Callee = FoundDecl.getDecl(); 11602 if (isa<UsingShadowDecl>(Callee)) 11603 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11604 11605 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11606 if (ExplicitTemplateArgs) { 11607 assert(!KnownValid && "Explicit template arguments?"); 11608 return; 11609 } 11610 // Prevent ill-formed function decls to be added as overload candidates. 11611 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11612 return; 11613 11614 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11615 /*SuppressUsedConversions=*/false, 11616 PartialOverloading); 11617 return; 11618 } 11619 11620 if (FunctionTemplateDecl *FuncTemplate 11621 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11622 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11623 ExplicitTemplateArgs, Args, CandidateSet, 11624 /*SuppressUsedConversions=*/false, 11625 PartialOverloading); 11626 return; 11627 } 11628 11629 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11630 } 11631 11632 /// Add the overload candidates named by callee and/or found by argument 11633 /// dependent lookup to the given overload set. 11634 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11635 ArrayRef<Expr *> Args, 11636 OverloadCandidateSet &CandidateSet, 11637 bool PartialOverloading) { 11638 11639 #ifndef NDEBUG 11640 // Verify that ArgumentDependentLookup is consistent with the rules 11641 // in C++0x [basic.lookup.argdep]p3: 11642 // 11643 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11644 // and let Y be the lookup set produced by argument dependent 11645 // lookup (defined as follows). If X contains 11646 // 11647 // -- a declaration of a class member, or 11648 // 11649 // -- a block-scope function declaration that is not a 11650 // using-declaration, or 11651 // 11652 // -- a declaration that is neither a function or a function 11653 // template 11654 // 11655 // then Y is empty. 11656 11657 if (ULE->requiresADL()) { 11658 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11659 E = ULE->decls_end(); I != E; ++I) { 11660 assert(!(*I)->getDeclContext()->isRecord()); 11661 assert(isa<UsingShadowDecl>(*I) || 11662 !(*I)->getDeclContext()->isFunctionOrMethod()); 11663 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11664 } 11665 } 11666 #endif 11667 11668 // It would be nice to avoid this copy. 11669 TemplateArgumentListInfo TABuffer; 11670 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11671 if (ULE->hasExplicitTemplateArgs()) { 11672 ULE->copyTemplateArgumentsInto(TABuffer); 11673 ExplicitTemplateArgs = &TABuffer; 11674 } 11675 11676 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11677 E = ULE->decls_end(); I != E; ++I) 11678 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11679 CandidateSet, PartialOverloading, 11680 /*KnownValid*/ true); 11681 11682 if (ULE->requiresADL()) 11683 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11684 Args, ExplicitTemplateArgs, 11685 CandidateSet, PartialOverloading); 11686 } 11687 11688 /// Determine whether a declaration with the specified name could be moved into 11689 /// a different namespace. 11690 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11691 switch (Name.getCXXOverloadedOperator()) { 11692 case OO_New: case OO_Array_New: 11693 case OO_Delete: case OO_Array_Delete: 11694 return false; 11695 11696 default: 11697 return true; 11698 } 11699 } 11700 11701 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11702 /// template, where the non-dependent name was declared after the template 11703 /// was defined. This is common in code written for a compilers which do not 11704 /// correctly implement two-stage name lookup. 11705 /// 11706 /// Returns true if a viable candidate was found and a diagnostic was issued. 11707 static bool 11708 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11709 const CXXScopeSpec &SS, LookupResult &R, 11710 OverloadCandidateSet::CandidateSetKind CSK, 11711 TemplateArgumentListInfo *ExplicitTemplateArgs, 11712 ArrayRef<Expr *> Args, 11713 bool *DoDiagnoseEmptyLookup = nullptr) { 11714 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11715 return false; 11716 11717 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11718 if (DC->isTransparentContext()) 11719 continue; 11720 11721 SemaRef.LookupQualifiedName(R, DC); 11722 11723 if (!R.empty()) { 11724 R.suppressDiagnostics(); 11725 11726 if (isa<CXXRecordDecl>(DC)) { 11727 // Don't diagnose names we find in classes; we get much better 11728 // diagnostics for these from DiagnoseEmptyLookup. 11729 R.clear(); 11730 if (DoDiagnoseEmptyLookup) 11731 *DoDiagnoseEmptyLookup = true; 11732 return false; 11733 } 11734 11735 OverloadCandidateSet Candidates(FnLoc, CSK); 11736 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11737 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11738 ExplicitTemplateArgs, Args, 11739 Candidates, false, /*KnownValid*/ false); 11740 11741 OverloadCandidateSet::iterator Best; 11742 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11743 // No viable functions. Don't bother the user with notes for functions 11744 // which don't work and shouldn't be found anyway. 11745 R.clear(); 11746 return false; 11747 } 11748 11749 // Find the namespaces where ADL would have looked, and suggest 11750 // declaring the function there instead. 11751 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11752 Sema::AssociatedClassSet AssociatedClasses; 11753 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11754 AssociatedNamespaces, 11755 AssociatedClasses); 11756 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11757 if (canBeDeclaredInNamespace(R.getLookupName())) { 11758 DeclContext *Std = SemaRef.getStdNamespace(); 11759 for (Sema::AssociatedNamespaceSet::iterator 11760 it = AssociatedNamespaces.begin(), 11761 end = AssociatedNamespaces.end(); it != end; ++it) { 11762 // Never suggest declaring a function within namespace 'std'. 11763 if (Std && Std->Encloses(*it)) 11764 continue; 11765 11766 // Never suggest declaring a function within a namespace with a 11767 // reserved name, like __gnu_cxx. 11768 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11769 if (NS && 11770 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11771 continue; 11772 11773 SuggestedNamespaces.insert(*it); 11774 } 11775 } 11776 11777 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11778 << R.getLookupName(); 11779 if (SuggestedNamespaces.empty()) { 11780 SemaRef.Diag(Best->Function->getLocation(), 11781 diag::note_not_found_by_two_phase_lookup) 11782 << R.getLookupName() << 0; 11783 } else if (SuggestedNamespaces.size() == 1) { 11784 SemaRef.Diag(Best->Function->getLocation(), 11785 diag::note_not_found_by_two_phase_lookup) 11786 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11787 } else { 11788 // FIXME: It would be useful to list the associated namespaces here, 11789 // but the diagnostics infrastructure doesn't provide a way to produce 11790 // a localized representation of a list of items. 11791 SemaRef.Diag(Best->Function->getLocation(), 11792 diag::note_not_found_by_two_phase_lookup) 11793 << R.getLookupName() << 2; 11794 } 11795 11796 // Try to recover by calling this function. 11797 return true; 11798 } 11799 11800 R.clear(); 11801 } 11802 11803 return false; 11804 } 11805 11806 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11807 /// template, where the non-dependent operator was declared after the template 11808 /// was defined. 11809 /// 11810 /// Returns true if a viable candidate was found and a diagnostic was issued. 11811 static bool 11812 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11813 SourceLocation OpLoc, 11814 ArrayRef<Expr *> Args) { 11815 DeclarationName OpName = 11816 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11817 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11818 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11819 OverloadCandidateSet::CSK_Operator, 11820 /*ExplicitTemplateArgs=*/nullptr, Args); 11821 } 11822 11823 namespace { 11824 class BuildRecoveryCallExprRAII { 11825 Sema &SemaRef; 11826 public: 11827 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11828 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11829 SemaRef.IsBuildingRecoveryCallExpr = true; 11830 } 11831 11832 ~BuildRecoveryCallExprRAII() { 11833 SemaRef.IsBuildingRecoveryCallExpr = false; 11834 } 11835 }; 11836 11837 } 11838 11839 static std::unique_ptr<CorrectionCandidateCallback> 11840 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11841 bool HasTemplateArgs, bool AllowTypoCorrection) { 11842 if (!AllowTypoCorrection) 11843 return llvm::make_unique<NoTypoCorrectionCCC>(); 11844 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11845 HasTemplateArgs, ME); 11846 } 11847 11848 /// Attempts to recover from a call where no functions were found. 11849 /// 11850 /// Returns true if new candidates were found. 11851 static ExprResult 11852 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11853 UnresolvedLookupExpr *ULE, 11854 SourceLocation LParenLoc, 11855 MutableArrayRef<Expr *> Args, 11856 SourceLocation RParenLoc, 11857 bool EmptyLookup, bool AllowTypoCorrection) { 11858 // Do not try to recover if it is already building a recovery call. 11859 // This stops infinite loops for template instantiations like 11860 // 11861 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11862 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11863 // 11864 if (SemaRef.IsBuildingRecoveryCallExpr) 11865 return ExprError(); 11866 BuildRecoveryCallExprRAII RCE(SemaRef); 11867 11868 CXXScopeSpec SS; 11869 SS.Adopt(ULE->getQualifierLoc()); 11870 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11871 11872 TemplateArgumentListInfo TABuffer; 11873 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11874 if (ULE->hasExplicitTemplateArgs()) { 11875 ULE->copyTemplateArgumentsInto(TABuffer); 11876 ExplicitTemplateArgs = &TABuffer; 11877 } 11878 11879 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11880 Sema::LookupOrdinaryName); 11881 bool DoDiagnoseEmptyLookup = EmptyLookup; 11882 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11883 OverloadCandidateSet::CSK_Normal, 11884 ExplicitTemplateArgs, Args, 11885 &DoDiagnoseEmptyLookup) && 11886 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11887 S, SS, R, 11888 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11889 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11890 ExplicitTemplateArgs, Args))) 11891 return ExprError(); 11892 11893 assert(!R.empty() && "lookup results empty despite recovery"); 11894 11895 // If recovery created an ambiguity, just bail out. 11896 if (R.isAmbiguous()) { 11897 R.suppressDiagnostics(); 11898 return ExprError(); 11899 } 11900 11901 // Build an implicit member call if appropriate. Just drop the 11902 // casts and such from the call, we don't really care. 11903 ExprResult NewFn = ExprError(); 11904 if ((*R.begin())->isCXXClassMember()) 11905 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11906 ExplicitTemplateArgs, S); 11907 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11908 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11909 ExplicitTemplateArgs); 11910 else 11911 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11912 11913 if (NewFn.isInvalid()) 11914 return ExprError(); 11915 11916 // This shouldn't cause an infinite loop because we're giving it 11917 // an expression with viable lookup results, which should never 11918 // end up here. 11919 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11920 MultiExprArg(Args.data(), Args.size()), 11921 RParenLoc); 11922 } 11923 11924 /// Constructs and populates an OverloadedCandidateSet from 11925 /// the given function. 11926 /// \returns true when an the ExprResult output parameter has been set. 11927 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11928 UnresolvedLookupExpr *ULE, 11929 MultiExprArg Args, 11930 SourceLocation RParenLoc, 11931 OverloadCandidateSet *CandidateSet, 11932 ExprResult *Result) { 11933 #ifndef NDEBUG 11934 if (ULE->requiresADL()) { 11935 // To do ADL, we must have found an unqualified name. 11936 assert(!ULE->getQualifier() && "qualified name with ADL"); 11937 11938 // We don't perform ADL for implicit declarations of builtins. 11939 // Verify that this was correctly set up. 11940 FunctionDecl *F; 11941 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11942 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11943 F->getBuiltinID() && F->isImplicit()) 11944 llvm_unreachable("performing ADL for builtin"); 11945 11946 // We don't perform ADL in C. 11947 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11948 } 11949 #endif 11950 11951 UnbridgedCastsSet UnbridgedCasts; 11952 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11953 *Result = ExprError(); 11954 return true; 11955 } 11956 11957 // Add the functions denoted by the callee to the set of candidate 11958 // functions, including those from argument-dependent lookup. 11959 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11960 11961 if (getLangOpts().MSVCCompat && 11962 CurContext->isDependentContext() && !isSFINAEContext() && 11963 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11964 11965 OverloadCandidateSet::iterator Best; 11966 if (CandidateSet->empty() || 11967 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 11968 OR_No_Viable_Function) { 11969 // In Microsoft mode, if we are inside a template class member function then 11970 // create a type dependent CallExpr. The goal is to postpone name lookup 11971 // to instantiation time to be able to search into type dependent base 11972 // classes. 11973 CallExpr *CE = new (Context) CallExpr( 11974 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11975 CE->setTypeDependent(true); 11976 CE->setValueDependent(true); 11977 CE->setInstantiationDependent(true); 11978 *Result = CE; 11979 return true; 11980 } 11981 } 11982 11983 if (CandidateSet->empty()) 11984 return false; 11985 11986 UnbridgedCasts.restore(); 11987 return false; 11988 } 11989 11990 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11991 /// the completed call expression. If overload resolution fails, emits 11992 /// diagnostics and returns ExprError() 11993 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11994 UnresolvedLookupExpr *ULE, 11995 SourceLocation LParenLoc, 11996 MultiExprArg Args, 11997 SourceLocation RParenLoc, 11998 Expr *ExecConfig, 11999 OverloadCandidateSet *CandidateSet, 12000 OverloadCandidateSet::iterator *Best, 12001 OverloadingResult OverloadResult, 12002 bool AllowTypoCorrection) { 12003 if (CandidateSet->empty()) 12004 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12005 RParenLoc, /*EmptyLookup=*/true, 12006 AllowTypoCorrection); 12007 12008 switch (OverloadResult) { 12009 case OR_Success: { 12010 FunctionDecl *FDecl = (*Best)->Function; 12011 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12012 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12013 return ExprError(); 12014 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12015 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12016 ExecConfig); 12017 } 12018 12019 case OR_No_Viable_Function: { 12020 // Try to recover by looking for viable functions which the user might 12021 // have meant to call. 12022 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12023 Args, RParenLoc, 12024 /*EmptyLookup=*/false, 12025 AllowTypoCorrection); 12026 if (!Recovery.isInvalid()) 12027 return Recovery; 12028 12029 // If the user passes in a function that we can't take the address of, we 12030 // generally end up emitting really bad error messages. Here, we attempt to 12031 // emit better ones. 12032 for (const Expr *Arg : Args) { 12033 if (!Arg->getType()->isFunctionType()) 12034 continue; 12035 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12036 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12037 if (FD && 12038 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12039 Arg->getExprLoc())) 12040 return ExprError(); 12041 } 12042 } 12043 12044 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call) 12045 << ULE->getName() << Fn->getSourceRange(); 12046 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12047 break; 12048 } 12049 12050 case OR_Ambiguous: 12051 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call) 12052 << ULE->getName() << Fn->getSourceRange(); 12053 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12054 break; 12055 12056 case OR_Deleted: { 12057 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call) 12058 << (*Best)->Function->isDeleted() << ULE->getName() 12059 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12060 << Fn->getSourceRange(); 12061 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12062 12063 // We emitted an error for the unavailable/deleted function call but keep 12064 // the call in the AST. 12065 FunctionDecl *FDecl = (*Best)->Function; 12066 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12067 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12068 ExecConfig); 12069 } 12070 } 12071 12072 // Overload resolution failed. 12073 return ExprError(); 12074 } 12075 12076 static void markUnaddressableCandidatesUnviable(Sema &S, 12077 OverloadCandidateSet &CS) { 12078 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12079 if (I->Viable && 12080 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12081 I->Viable = false; 12082 I->FailureKind = ovl_fail_addr_not_available; 12083 } 12084 } 12085 } 12086 12087 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12088 /// (which eventually refers to the declaration Func) and the call 12089 /// arguments Args/NumArgs, attempt to resolve the function call down 12090 /// to a specific function. If overload resolution succeeds, returns 12091 /// the call expression produced by overload resolution. 12092 /// Otherwise, emits diagnostics and returns ExprError. 12093 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12094 UnresolvedLookupExpr *ULE, 12095 SourceLocation LParenLoc, 12096 MultiExprArg Args, 12097 SourceLocation RParenLoc, 12098 Expr *ExecConfig, 12099 bool AllowTypoCorrection, 12100 bool CalleesAddressIsTaken) { 12101 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12102 OverloadCandidateSet::CSK_Normal); 12103 ExprResult result; 12104 12105 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12106 &result)) 12107 return result; 12108 12109 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12110 // functions that aren't addressible are considered unviable. 12111 if (CalleesAddressIsTaken) 12112 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12113 12114 OverloadCandidateSet::iterator Best; 12115 OverloadingResult OverloadResult = 12116 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12117 12118 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12119 RParenLoc, ExecConfig, &CandidateSet, 12120 &Best, OverloadResult, 12121 AllowTypoCorrection); 12122 } 12123 12124 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12125 return Functions.size() > 1 || 12126 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12127 } 12128 12129 /// Create a unary operation that may resolve to an overloaded 12130 /// operator. 12131 /// 12132 /// \param OpLoc The location of the operator itself (e.g., '*'). 12133 /// 12134 /// \param Opc The UnaryOperatorKind that describes this operator. 12135 /// 12136 /// \param Fns The set of non-member functions that will be 12137 /// considered by overload resolution. The caller needs to build this 12138 /// set based on the context using, e.g., 12139 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12140 /// set should not contain any member functions; those will be added 12141 /// by CreateOverloadedUnaryOp(). 12142 /// 12143 /// \param Input The input argument. 12144 ExprResult 12145 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12146 const UnresolvedSetImpl &Fns, 12147 Expr *Input, bool PerformADL) { 12148 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12149 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12150 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12151 // TODO: provide better source location info. 12152 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12153 12154 if (checkPlaceholderForOverload(*this, Input)) 12155 return ExprError(); 12156 12157 Expr *Args[2] = { Input, nullptr }; 12158 unsigned NumArgs = 1; 12159 12160 // For post-increment and post-decrement, add the implicit '0' as 12161 // the second argument, so that we know this is a post-increment or 12162 // post-decrement. 12163 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12164 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12165 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12166 SourceLocation()); 12167 NumArgs = 2; 12168 } 12169 12170 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12171 12172 if (Input->isTypeDependent()) { 12173 if (Fns.empty()) 12174 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12175 VK_RValue, OK_Ordinary, OpLoc, false); 12176 12177 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12178 UnresolvedLookupExpr *Fn 12179 = UnresolvedLookupExpr::Create(Context, NamingClass, 12180 NestedNameSpecifierLoc(), OpNameInfo, 12181 /*ADL*/ true, IsOverloaded(Fns), 12182 Fns.begin(), Fns.end()); 12183 return new (Context) 12184 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 12185 VK_RValue, OpLoc, FPOptions()); 12186 } 12187 12188 // Build an empty overload set. 12189 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12190 12191 // Add the candidates from the given function set. 12192 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12193 12194 // Add operator candidates that are member functions. 12195 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12196 12197 // Add candidates from ADL. 12198 if (PerformADL) { 12199 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12200 /*ExplicitTemplateArgs*/nullptr, 12201 CandidateSet); 12202 } 12203 12204 // Add builtin operator candidates. 12205 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12206 12207 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12208 12209 // Perform overload resolution. 12210 OverloadCandidateSet::iterator Best; 12211 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12212 case OR_Success: { 12213 // We found a built-in operator or an overloaded operator. 12214 FunctionDecl *FnDecl = Best->Function; 12215 12216 if (FnDecl) { 12217 Expr *Base = nullptr; 12218 // We matched an overloaded operator. Build a call to that 12219 // operator. 12220 12221 // Convert the arguments. 12222 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12223 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12224 12225 ExprResult InputRes = 12226 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12227 Best->FoundDecl, Method); 12228 if (InputRes.isInvalid()) 12229 return ExprError(); 12230 Base = Input = InputRes.get(); 12231 } else { 12232 // Convert the arguments. 12233 ExprResult InputInit 12234 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12235 Context, 12236 FnDecl->getParamDecl(0)), 12237 SourceLocation(), 12238 Input); 12239 if (InputInit.isInvalid()) 12240 return ExprError(); 12241 Input = InputInit.get(); 12242 } 12243 12244 // Build the actual expression node. 12245 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12246 Base, HadMultipleCandidates, 12247 OpLoc); 12248 if (FnExpr.isInvalid()) 12249 return ExprError(); 12250 12251 // Determine the result type. 12252 QualType ResultTy = FnDecl->getReturnType(); 12253 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12254 ResultTy = ResultTy.getNonLValueExprType(Context); 12255 12256 Args[0] = Input; 12257 CallExpr *TheCall = 12258 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 12259 ResultTy, VK, OpLoc, FPOptions()); 12260 12261 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12262 return ExprError(); 12263 12264 if (CheckFunctionCall(FnDecl, TheCall, 12265 FnDecl->getType()->castAs<FunctionProtoType>())) 12266 return ExprError(); 12267 12268 return MaybeBindToTemporary(TheCall); 12269 } else { 12270 // We matched a built-in operator. Convert the arguments, then 12271 // break out so that we will build the appropriate built-in 12272 // operator node. 12273 ExprResult InputRes = PerformImplicitConversion( 12274 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12275 CCK_ForBuiltinOverloadedOp); 12276 if (InputRes.isInvalid()) 12277 return ExprError(); 12278 Input = InputRes.get(); 12279 break; 12280 } 12281 } 12282 12283 case OR_No_Viable_Function: 12284 // This is an erroneous use of an operator which can be overloaded by 12285 // a non-member function. Check for non-member operators which were 12286 // defined too late to be candidates. 12287 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12288 // FIXME: Recover by calling the found function. 12289 return ExprError(); 12290 12291 // No viable function; fall through to handling this as a 12292 // built-in operator, which will produce an error message for us. 12293 break; 12294 12295 case OR_Ambiguous: 12296 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12297 << UnaryOperator::getOpcodeStr(Opc) 12298 << Input->getType() 12299 << Input->getSourceRange(); 12300 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12301 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12302 return ExprError(); 12303 12304 case OR_Deleted: 12305 Diag(OpLoc, diag::err_ovl_deleted_oper) 12306 << Best->Function->isDeleted() 12307 << UnaryOperator::getOpcodeStr(Opc) 12308 << getDeletedOrUnavailableSuffix(Best->Function) 12309 << Input->getSourceRange(); 12310 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12311 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12312 return ExprError(); 12313 } 12314 12315 // Either we found no viable overloaded operator or we matched a 12316 // built-in operator. In either case, fall through to trying to 12317 // build a built-in operation. 12318 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12319 } 12320 12321 /// Create a binary operation that may resolve to an overloaded 12322 /// operator. 12323 /// 12324 /// \param OpLoc The location of the operator itself (e.g., '+'). 12325 /// 12326 /// \param Opc The BinaryOperatorKind that describes this operator. 12327 /// 12328 /// \param Fns The set of non-member functions that will be 12329 /// considered by overload resolution. The caller needs to build this 12330 /// set based on the context using, e.g., 12331 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12332 /// set should not contain any member functions; those will be added 12333 /// by CreateOverloadedBinOp(). 12334 /// 12335 /// \param LHS Left-hand argument. 12336 /// \param RHS Right-hand argument. 12337 ExprResult 12338 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12339 BinaryOperatorKind Opc, 12340 const UnresolvedSetImpl &Fns, 12341 Expr *LHS, Expr *RHS, bool PerformADL) { 12342 Expr *Args[2] = { LHS, RHS }; 12343 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12344 12345 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12346 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12347 12348 // If either side is type-dependent, create an appropriate dependent 12349 // expression. 12350 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12351 if (Fns.empty()) { 12352 // If there are no functions to store, just build a dependent 12353 // BinaryOperator or CompoundAssignment. 12354 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12355 return new (Context) BinaryOperator( 12356 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12357 OpLoc, FPFeatures); 12358 12359 return new (Context) CompoundAssignOperator( 12360 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12361 Context.DependentTy, Context.DependentTy, OpLoc, 12362 FPFeatures); 12363 } 12364 12365 // FIXME: save results of ADL from here? 12366 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12367 // TODO: provide better source location info in DNLoc component. 12368 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12369 UnresolvedLookupExpr *Fn 12370 = UnresolvedLookupExpr::Create(Context, NamingClass, 12371 NestedNameSpecifierLoc(), OpNameInfo, 12372 /*ADL*/PerformADL, IsOverloaded(Fns), 12373 Fns.begin(), Fns.end()); 12374 return new (Context) 12375 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 12376 VK_RValue, OpLoc, FPFeatures); 12377 } 12378 12379 // Always do placeholder-like conversions on the RHS. 12380 if (checkPlaceholderForOverload(*this, Args[1])) 12381 return ExprError(); 12382 12383 // Do placeholder-like conversion on the LHS; note that we should 12384 // not get here with a PseudoObject LHS. 12385 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12386 if (checkPlaceholderForOverload(*this, Args[0])) 12387 return ExprError(); 12388 12389 // If this is the assignment operator, we only perform overload resolution 12390 // if the left-hand side is a class or enumeration type. This is actually 12391 // a hack. The standard requires that we do overload resolution between the 12392 // various built-in candidates, but as DR507 points out, this can lead to 12393 // problems. So we do it this way, which pretty much follows what GCC does. 12394 // Note that we go the traditional code path for compound assignment forms. 12395 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12396 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12397 12398 // If this is the .* operator, which is not overloadable, just 12399 // create a built-in binary operator. 12400 if (Opc == BO_PtrMemD) 12401 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12402 12403 // Build an empty overload set. 12404 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12405 12406 // Add the candidates from the given function set. 12407 AddFunctionCandidates(Fns, Args, CandidateSet); 12408 12409 // Add operator candidates that are member functions. 12410 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12411 12412 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12413 // performed for an assignment operator (nor for operator[] nor operator->, 12414 // which don't get here). 12415 if (Opc != BO_Assign && PerformADL) 12416 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12417 /*ExplicitTemplateArgs*/ nullptr, 12418 CandidateSet); 12419 12420 // Add builtin operator candidates. 12421 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12422 12423 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12424 12425 // Perform overload resolution. 12426 OverloadCandidateSet::iterator Best; 12427 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12428 case OR_Success: { 12429 // We found a built-in operator or an overloaded operator. 12430 FunctionDecl *FnDecl = Best->Function; 12431 12432 if (FnDecl) { 12433 Expr *Base = nullptr; 12434 // We matched an overloaded operator. Build a call to that 12435 // operator. 12436 12437 // Convert the arguments. 12438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12439 // Best->Access is only meaningful for class members. 12440 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12441 12442 ExprResult Arg1 = 12443 PerformCopyInitialization( 12444 InitializedEntity::InitializeParameter(Context, 12445 FnDecl->getParamDecl(0)), 12446 SourceLocation(), Args[1]); 12447 if (Arg1.isInvalid()) 12448 return ExprError(); 12449 12450 ExprResult Arg0 = 12451 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12452 Best->FoundDecl, Method); 12453 if (Arg0.isInvalid()) 12454 return ExprError(); 12455 Base = Args[0] = Arg0.getAs<Expr>(); 12456 Args[1] = RHS = Arg1.getAs<Expr>(); 12457 } else { 12458 // Convert the arguments. 12459 ExprResult Arg0 = PerformCopyInitialization( 12460 InitializedEntity::InitializeParameter(Context, 12461 FnDecl->getParamDecl(0)), 12462 SourceLocation(), Args[0]); 12463 if (Arg0.isInvalid()) 12464 return ExprError(); 12465 12466 ExprResult Arg1 = 12467 PerformCopyInitialization( 12468 InitializedEntity::InitializeParameter(Context, 12469 FnDecl->getParamDecl(1)), 12470 SourceLocation(), Args[1]); 12471 if (Arg1.isInvalid()) 12472 return ExprError(); 12473 Args[0] = LHS = Arg0.getAs<Expr>(); 12474 Args[1] = RHS = Arg1.getAs<Expr>(); 12475 } 12476 12477 // Build the actual expression node. 12478 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12479 Best->FoundDecl, Base, 12480 HadMultipleCandidates, OpLoc); 12481 if (FnExpr.isInvalid()) 12482 return ExprError(); 12483 12484 // Determine the result type. 12485 QualType ResultTy = FnDecl->getReturnType(); 12486 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12487 ResultTy = ResultTy.getNonLValueExprType(Context); 12488 12489 CXXOperatorCallExpr *TheCall = 12490 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12491 Args, ResultTy, VK, OpLoc, 12492 FPFeatures); 12493 12494 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12495 FnDecl)) 12496 return ExprError(); 12497 12498 ArrayRef<const Expr *> ArgsArray(Args, 2); 12499 const Expr *ImplicitThis = nullptr; 12500 // Cut off the implicit 'this'. 12501 if (isa<CXXMethodDecl>(FnDecl)) { 12502 ImplicitThis = ArgsArray[0]; 12503 ArgsArray = ArgsArray.slice(1); 12504 } 12505 12506 // Check for a self move. 12507 if (Op == OO_Equal) 12508 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12509 12510 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12511 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12512 VariadicDoesNotApply); 12513 12514 return MaybeBindToTemporary(TheCall); 12515 } else { 12516 // We matched a built-in operator. Convert the arguments, then 12517 // break out so that we will build the appropriate built-in 12518 // operator node. 12519 ExprResult ArgsRes0 = PerformImplicitConversion( 12520 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12521 AA_Passing, CCK_ForBuiltinOverloadedOp); 12522 if (ArgsRes0.isInvalid()) 12523 return ExprError(); 12524 Args[0] = ArgsRes0.get(); 12525 12526 ExprResult ArgsRes1 = PerformImplicitConversion( 12527 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12528 AA_Passing, CCK_ForBuiltinOverloadedOp); 12529 if (ArgsRes1.isInvalid()) 12530 return ExprError(); 12531 Args[1] = ArgsRes1.get(); 12532 break; 12533 } 12534 } 12535 12536 case OR_No_Viable_Function: { 12537 // C++ [over.match.oper]p9: 12538 // If the operator is the operator , [...] and there are no 12539 // viable functions, then the operator is assumed to be the 12540 // built-in operator and interpreted according to clause 5. 12541 if (Opc == BO_Comma) 12542 break; 12543 12544 // For class as left operand for assignment or compound assignment 12545 // operator do not fall through to handling in built-in, but report that 12546 // no overloaded assignment operator found 12547 ExprResult Result = ExprError(); 12548 if (Args[0]->getType()->isRecordType() && 12549 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12550 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12551 << BinaryOperator::getOpcodeStr(Opc) 12552 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12553 if (Args[0]->getType()->isIncompleteType()) { 12554 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12555 << Args[0]->getType() 12556 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12557 } 12558 } else { 12559 // This is an erroneous use of an operator which can be overloaded by 12560 // a non-member function. Check for non-member operators which were 12561 // defined too late to be candidates. 12562 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12563 // FIXME: Recover by calling the found function. 12564 return ExprError(); 12565 12566 // No viable function; try to create a built-in operation, which will 12567 // produce an error. Then, show the non-viable candidates. 12568 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12569 } 12570 assert(Result.isInvalid() && 12571 "C++ binary operator overloading is missing candidates!"); 12572 if (Result.isInvalid()) 12573 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12574 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12575 return Result; 12576 } 12577 12578 case OR_Ambiguous: 12579 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12580 << BinaryOperator::getOpcodeStr(Opc) 12581 << Args[0]->getType() << Args[1]->getType() 12582 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12583 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12584 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12585 return ExprError(); 12586 12587 case OR_Deleted: 12588 if (isImplicitlyDeleted(Best->Function)) { 12589 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12590 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12591 << Context.getRecordType(Method->getParent()) 12592 << getSpecialMember(Method); 12593 12594 // The user probably meant to call this special member. Just 12595 // explain why it's deleted. 12596 NoteDeletedFunction(Method); 12597 return ExprError(); 12598 } else { 12599 Diag(OpLoc, diag::err_ovl_deleted_oper) 12600 << Best->Function->isDeleted() 12601 << BinaryOperator::getOpcodeStr(Opc) 12602 << getDeletedOrUnavailableSuffix(Best->Function) 12603 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12604 } 12605 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12606 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12607 return ExprError(); 12608 } 12609 12610 // We matched a built-in operator; build it. 12611 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12612 } 12613 12614 ExprResult 12615 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12616 SourceLocation RLoc, 12617 Expr *Base, Expr *Idx) { 12618 Expr *Args[2] = { Base, Idx }; 12619 DeclarationName OpName = 12620 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12621 12622 // If either side is type-dependent, create an appropriate dependent 12623 // expression. 12624 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12625 12626 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12627 // CHECKME: no 'operator' keyword? 12628 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12629 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12630 UnresolvedLookupExpr *Fn 12631 = UnresolvedLookupExpr::Create(Context, NamingClass, 12632 NestedNameSpecifierLoc(), OpNameInfo, 12633 /*ADL*/ true, /*Overloaded*/ false, 12634 UnresolvedSetIterator(), 12635 UnresolvedSetIterator()); 12636 // Can't add any actual overloads yet 12637 12638 return new (Context) 12639 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12640 Context.DependentTy, VK_RValue, RLoc, FPOptions()); 12641 } 12642 12643 // Handle placeholders on both operands. 12644 if (checkPlaceholderForOverload(*this, Args[0])) 12645 return ExprError(); 12646 if (checkPlaceholderForOverload(*this, Args[1])) 12647 return ExprError(); 12648 12649 // Build an empty overload set. 12650 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12651 12652 // Subscript can only be overloaded as a member function. 12653 12654 // Add operator candidates that are member functions. 12655 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12656 12657 // Add builtin operator candidates. 12658 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12659 12660 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12661 12662 // Perform overload resolution. 12663 OverloadCandidateSet::iterator Best; 12664 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12665 case OR_Success: { 12666 // We found a built-in operator or an overloaded operator. 12667 FunctionDecl *FnDecl = Best->Function; 12668 12669 if (FnDecl) { 12670 // We matched an overloaded operator. Build a call to that 12671 // operator. 12672 12673 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12674 12675 // Convert the arguments. 12676 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12677 ExprResult Arg0 = 12678 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12679 Best->FoundDecl, Method); 12680 if (Arg0.isInvalid()) 12681 return ExprError(); 12682 Args[0] = Arg0.get(); 12683 12684 // Convert the arguments. 12685 ExprResult InputInit 12686 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12687 Context, 12688 FnDecl->getParamDecl(0)), 12689 SourceLocation(), 12690 Args[1]); 12691 if (InputInit.isInvalid()) 12692 return ExprError(); 12693 12694 Args[1] = InputInit.getAs<Expr>(); 12695 12696 // Build the actual expression node. 12697 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12698 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12699 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12700 Best->FoundDecl, 12701 Base, 12702 HadMultipleCandidates, 12703 OpLocInfo.getLoc(), 12704 OpLocInfo.getInfo()); 12705 if (FnExpr.isInvalid()) 12706 return ExprError(); 12707 12708 // Determine the result type 12709 QualType ResultTy = FnDecl->getReturnType(); 12710 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12711 ResultTy = ResultTy.getNonLValueExprType(Context); 12712 12713 CXXOperatorCallExpr *TheCall = 12714 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12715 FnExpr.get(), Args, 12716 ResultTy, VK, RLoc, 12717 FPOptions()); 12718 12719 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12720 return ExprError(); 12721 12722 if (CheckFunctionCall(Method, TheCall, 12723 Method->getType()->castAs<FunctionProtoType>())) 12724 return ExprError(); 12725 12726 return MaybeBindToTemporary(TheCall); 12727 } else { 12728 // We matched a built-in operator. Convert the arguments, then 12729 // break out so that we will build the appropriate built-in 12730 // operator node. 12731 ExprResult ArgsRes0 = PerformImplicitConversion( 12732 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12733 AA_Passing, CCK_ForBuiltinOverloadedOp); 12734 if (ArgsRes0.isInvalid()) 12735 return ExprError(); 12736 Args[0] = ArgsRes0.get(); 12737 12738 ExprResult ArgsRes1 = PerformImplicitConversion( 12739 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12740 AA_Passing, CCK_ForBuiltinOverloadedOp); 12741 if (ArgsRes1.isInvalid()) 12742 return ExprError(); 12743 Args[1] = ArgsRes1.get(); 12744 12745 break; 12746 } 12747 } 12748 12749 case OR_No_Viable_Function: { 12750 if (CandidateSet.empty()) 12751 Diag(LLoc, diag::err_ovl_no_oper) 12752 << Args[0]->getType() << /*subscript*/ 0 12753 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12754 else 12755 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12756 << Args[0]->getType() 12757 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12758 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12759 "[]", LLoc); 12760 return ExprError(); 12761 } 12762 12763 case OR_Ambiguous: 12764 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12765 << "[]" 12766 << Args[0]->getType() << Args[1]->getType() 12767 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12768 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12769 "[]", LLoc); 12770 return ExprError(); 12771 12772 case OR_Deleted: 12773 Diag(LLoc, diag::err_ovl_deleted_oper) 12774 << Best->Function->isDeleted() << "[]" 12775 << getDeletedOrUnavailableSuffix(Best->Function) 12776 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12777 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12778 "[]", LLoc); 12779 return ExprError(); 12780 } 12781 12782 // We matched a built-in operator; build it. 12783 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12784 } 12785 12786 /// BuildCallToMemberFunction - Build a call to a member 12787 /// function. MemExpr is the expression that refers to the member 12788 /// function (and includes the object parameter), Args/NumArgs are the 12789 /// arguments to the function call (not including the object 12790 /// parameter). The caller needs to validate that the member 12791 /// expression refers to a non-static member function or an overloaded 12792 /// member function. 12793 ExprResult 12794 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12795 SourceLocation LParenLoc, 12796 MultiExprArg Args, 12797 SourceLocation RParenLoc) { 12798 assert(MemExprE->getType() == Context.BoundMemberTy || 12799 MemExprE->getType() == Context.OverloadTy); 12800 12801 // Dig out the member expression. This holds both the object 12802 // argument and the member function we're referring to. 12803 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12804 12805 // Determine whether this is a call to a pointer-to-member function. 12806 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12807 assert(op->getType() == Context.BoundMemberTy); 12808 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12809 12810 QualType fnType = 12811 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12812 12813 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12814 QualType resultType = proto->getCallResultType(Context); 12815 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12816 12817 // Check that the object type isn't more qualified than the 12818 // member function we're calling. 12819 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12820 12821 QualType objectType = op->getLHS()->getType(); 12822 if (op->getOpcode() == BO_PtrMemI) 12823 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12824 Qualifiers objectQuals = objectType.getQualifiers(); 12825 12826 Qualifiers difference = objectQuals - funcQuals; 12827 difference.removeObjCGCAttr(); 12828 difference.removeAddressSpace(); 12829 if (difference) { 12830 std::string qualsString = difference.getAsString(); 12831 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12832 << fnType.getUnqualifiedType() 12833 << qualsString 12834 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12835 } 12836 12837 CXXMemberCallExpr *call 12838 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12839 resultType, valueKind, RParenLoc); 12840 12841 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12842 call, nullptr)) 12843 return ExprError(); 12844 12845 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12846 return ExprError(); 12847 12848 if (CheckOtherCall(call, proto)) 12849 return ExprError(); 12850 12851 return MaybeBindToTemporary(call); 12852 } 12853 12854 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12855 return new (Context) 12856 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12857 12858 UnbridgedCastsSet UnbridgedCasts; 12859 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12860 return ExprError(); 12861 12862 MemberExpr *MemExpr; 12863 CXXMethodDecl *Method = nullptr; 12864 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12865 NestedNameSpecifier *Qualifier = nullptr; 12866 if (isa<MemberExpr>(NakedMemExpr)) { 12867 MemExpr = cast<MemberExpr>(NakedMemExpr); 12868 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12869 FoundDecl = MemExpr->getFoundDecl(); 12870 Qualifier = MemExpr->getQualifier(); 12871 UnbridgedCasts.restore(); 12872 } else { 12873 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12874 Qualifier = UnresExpr->getQualifier(); 12875 12876 QualType ObjectType = UnresExpr->getBaseType(); 12877 Expr::Classification ObjectClassification 12878 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12879 : UnresExpr->getBase()->Classify(Context); 12880 12881 // Add overload candidates 12882 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12883 OverloadCandidateSet::CSK_Normal); 12884 12885 // FIXME: avoid copy. 12886 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12887 if (UnresExpr->hasExplicitTemplateArgs()) { 12888 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12889 TemplateArgs = &TemplateArgsBuffer; 12890 } 12891 12892 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12893 E = UnresExpr->decls_end(); I != E; ++I) { 12894 12895 NamedDecl *Func = *I; 12896 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12897 if (isa<UsingShadowDecl>(Func)) 12898 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12899 12900 12901 // Microsoft supports direct constructor calls. 12902 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12903 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12904 Args, CandidateSet); 12905 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12906 // If explicit template arguments were provided, we can't call a 12907 // non-template member function. 12908 if (TemplateArgs) 12909 continue; 12910 12911 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12912 ObjectClassification, Args, CandidateSet, 12913 /*SuppressUserConversions=*/false); 12914 } else { 12915 AddMethodTemplateCandidate( 12916 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12917 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12918 /*SuppressUsedConversions=*/false); 12919 } 12920 } 12921 12922 DeclarationName DeclName = UnresExpr->getMemberName(); 12923 12924 UnbridgedCasts.restore(); 12925 12926 OverloadCandidateSet::iterator Best; 12927 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 12928 Best)) { 12929 case OR_Success: 12930 Method = cast<CXXMethodDecl>(Best->Function); 12931 FoundDecl = Best->FoundDecl; 12932 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12933 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12934 return ExprError(); 12935 // If FoundDecl is different from Method (such as if one is a template 12936 // and the other a specialization), make sure DiagnoseUseOfDecl is 12937 // called on both. 12938 // FIXME: This would be more comprehensively addressed by modifying 12939 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12940 // being used. 12941 if (Method != FoundDecl.getDecl() && 12942 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12943 return ExprError(); 12944 break; 12945 12946 case OR_No_Viable_Function: 12947 Diag(UnresExpr->getMemberLoc(), 12948 diag::err_ovl_no_viable_member_function_in_call) 12949 << DeclName << MemExprE->getSourceRange(); 12950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12951 // FIXME: Leaking incoming expressions! 12952 return ExprError(); 12953 12954 case OR_Ambiguous: 12955 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12956 << DeclName << MemExprE->getSourceRange(); 12957 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12958 // FIXME: Leaking incoming expressions! 12959 return ExprError(); 12960 12961 case OR_Deleted: 12962 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12963 << Best->Function->isDeleted() 12964 << DeclName 12965 << getDeletedOrUnavailableSuffix(Best->Function) 12966 << MemExprE->getSourceRange(); 12967 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12968 // FIXME: Leaking incoming expressions! 12969 return ExprError(); 12970 } 12971 12972 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12973 12974 // If overload resolution picked a static member, build a 12975 // non-member call based on that function. 12976 if (Method->isStatic()) { 12977 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12978 RParenLoc); 12979 } 12980 12981 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12982 } 12983 12984 QualType ResultType = Method->getReturnType(); 12985 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12986 ResultType = ResultType.getNonLValueExprType(Context); 12987 12988 assert(Method && "Member call to something that isn't a method?"); 12989 CXXMemberCallExpr *TheCall = 12990 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12991 ResultType, VK, RParenLoc); 12992 12993 // Check for a valid return type. 12994 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12995 TheCall, Method)) 12996 return ExprError(); 12997 12998 // Convert the object argument (for a non-static member function call). 12999 // We only need to do this if there was actually an overload; otherwise 13000 // it was done at lookup. 13001 if (!Method->isStatic()) { 13002 ExprResult ObjectArg = 13003 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13004 FoundDecl, Method); 13005 if (ObjectArg.isInvalid()) 13006 return ExprError(); 13007 MemExpr->setBase(ObjectArg.get()); 13008 } 13009 13010 // Convert the rest of the arguments 13011 const FunctionProtoType *Proto = 13012 Method->getType()->getAs<FunctionProtoType>(); 13013 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13014 RParenLoc)) 13015 return ExprError(); 13016 13017 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13018 13019 if (CheckFunctionCall(Method, TheCall, Proto)) 13020 return ExprError(); 13021 13022 // In the case the method to call was not selected by the overloading 13023 // resolution process, we still need to handle the enable_if attribute. Do 13024 // that here, so it will not hide previous -- and more relevant -- errors. 13025 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13026 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13027 Diag(MemE->getMemberLoc(), 13028 diag::err_ovl_no_viable_member_function_in_call) 13029 << Method << Method->getSourceRange(); 13030 Diag(Method->getLocation(), 13031 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13032 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13033 return ExprError(); 13034 } 13035 } 13036 13037 if ((isa<CXXConstructorDecl>(CurContext) || 13038 isa<CXXDestructorDecl>(CurContext)) && 13039 TheCall->getMethodDecl()->isPure()) { 13040 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13041 13042 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13043 MemExpr->performsVirtualDispatch(getLangOpts())) { 13044 Diag(MemExpr->getBeginLoc(), 13045 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13046 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13047 << MD->getParent()->getDeclName(); 13048 13049 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13050 if (getLangOpts().AppleKext) 13051 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13052 << MD->getParent()->getDeclName() << MD->getDeclName(); 13053 } 13054 } 13055 13056 if (CXXDestructorDecl *DD = 13057 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13058 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13059 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13060 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13061 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13062 MemExpr->getMemberLoc()); 13063 } 13064 13065 return MaybeBindToTemporary(TheCall); 13066 } 13067 13068 /// BuildCallToObjectOfClassType - Build a call to an object of class 13069 /// type (C++ [over.call.object]), which can end up invoking an 13070 /// overloaded function call operator (@c operator()) or performing a 13071 /// user-defined conversion on the object argument. 13072 ExprResult 13073 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13074 SourceLocation LParenLoc, 13075 MultiExprArg Args, 13076 SourceLocation RParenLoc) { 13077 if (checkPlaceholderForOverload(*this, Obj)) 13078 return ExprError(); 13079 ExprResult Object = Obj; 13080 13081 UnbridgedCastsSet UnbridgedCasts; 13082 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13083 return ExprError(); 13084 13085 assert(Object.get()->getType()->isRecordType() && 13086 "Requires object type argument"); 13087 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13088 13089 // C++ [over.call.object]p1: 13090 // If the primary-expression E in the function call syntax 13091 // evaluates to a class object of type "cv T", then the set of 13092 // candidate functions includes at least the function call 13093 // operators of T. The function call operators of T are obtained by 13094 // ordinary lookup of the name operator() in the context of 13095 // (E).operator(). 13096 OverloadCandidateSet CandidateSet(LParenLoc, 13097 OverloadCandidateSet::CSK_Operator); 13098 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13099 13100 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13101 diag::err_incomplete_object_call, Object.get())) 13102 return true; 13103 13104 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13105 LookupQualifiedName(R, Record->getDecl()); 13106 R.suppressDiagnostics(); 13107 13108 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13109 Oper != OperEnd; ++Oper) { 13110 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13111 Object.get()->Classify(Context), Args, CandidateSet, 13112 /*SuppressUserConversions=*/false); 13113 } 13114 13115 // C++ [over.call.object]p2: 13116 // In addition, for each (non-explicit in C++0x) conversion function 13117 // declared in T of the form 13118 // 13119 // operator conversion-type-id () cv-qualifier; 13120 // 13121 // where cv-qualifier is the same cv-qualification as, or a 13122 // greater cv-qualification than, cv, and where conversion-type-id 13123 // denotes the type "pointer to function of (P1,...,Pn) returning 13124 // R", or the type "reference to pointer to function of 13125 // (P1,...,Pn) returning R", or the type "reference to function 13126 // of (P1,...,Pn) returning R", a surrogate call function [...] 13127 // is also considered as a candidate function. Similarly, 13128 // surrogate call functions are added to the set of candidate 13129 // functions for each conversion function declared in an 13130 // accessible base class provided the function is not hidden 13131 // within T by another intervening declaration. 13132 const auto &Conversions = 13133 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13134 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13135 NamedDecl *D = *I; 13136 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13137 if (isa<UsingShadowDecl>(D)) 13138 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13139 13140 // Skip over templated conversion functions; they aren't 13141 // surrogates. 13142 if (isa<FunctionTemplateDecl>(D)) 13143 continue; 13144 13145 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13146 if (!Conv->isExplicit()) { 13147 // Strip the reference type (if any) and then the pointer type (if 13148 // any) to get down to what might be a function type. 13149 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13150 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13151 ConvType = ConvPtrType->getPointeeType(); 13152 13153 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13154 { 13155 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13156 Object.get(), Args, CandidateSet); 13157 } 13158 } 13159 } 13160 13161 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13162 13163 // Perform overload resolution. 13164 OverloadCandidateSet::iterator Best; 13165 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13166 Best)) { 13167 case OR_Success: 13168 // Overload resolution succeeded; we'll build the appropriate call 13169 // below. 13170 break; 13171 13172 case OR_No_Viable_Function: 13173 if (CandidateSet.empty()) 13174 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper) 13175 << Object.get()->getType() << /*call*/ 1 13176 << Object.get()->getSourceRange(); 13177 else 13178 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call) 13179 << Object.get()->getType() << Object.get()->getSourceRange(); 13180 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13181 break; 13182 13183 case OR_Ambiguous: 13184 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call) 13185 << Object.get()->getType() << Object.get()->getSourceRange(); 13186 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13187 break; 13188 13189 case OR_Deleted: 13190 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call) 13191 << Best->Function->isDeleted() << Object.get()->getType() 13192 << getDeletedOrUnavailableSuffix(Best->Function) 13193 << Object.get()->getSourceRange(); 13194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13195 break; 13196 } 13197 13198 if (Best == CandidateSet.end()) 13199 return true; 13200 13201 UnbridgedCasts.restore(); 13202 13203 if (Best->Function == nullptr) { 13204 // Since there is no function declaration, this is one of the 13205 // surrogate candidates. Dig out the conversion function. 13206 CXXConversionDecl *Conv 13207 = cast<CXXConversionDecl>( 13208 Best->Conversions[0].UserDefined.ConversionFunction); 13209 13210 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13211 Best->FoundDecl); 13212 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13213 return ExprError(); 13214 assert(Conv == Best->FoundDecl.getDecl() && 13215 "Found Decl & conversion-to-functionptr should be same, right?!"); 13216 // We selected one of the surrogate functions that converts the 13217 // object parameter to a function pointer. Perform the conversion 13218 // on the object argument, then let ActOnCallExpr finish the job. 13219 13220 // Create an implicit member expr to refer to the conversion operator. 13221 // and then call it. 13222 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13223 Conv, HadMultipleCandidates); 13224 if (Call.isInvalid()) 13225 return ExprError(); 13226 // Record usage of conversion in an implicit cast. 13227 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13228 CK_UserDefinedConversion, Call.get(), 13229 nullptr, VK_RValue); 13230 13231 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13232 } 13233 13234 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13235 13236 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13237 // that calls this method, using Object for the implicit object 13238 // parameter and passing along the remaining arguments. 13239 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13240 13241 // An error diagnostic has already been printed when parsing the declaration. 13242 if (Method->isInvalidDecl()) 13243 return ExprError(); 13244 13245 const FunctionProtoType *Proto = 13246 Method->getType()->getAs<FunctionProtoType>(); 13247 13248 unsigned NumParams = Proto->getNumParams(); 13249 13250 DeclarationNameInfo OpLocInfo( 13251 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13252 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13253 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13254 Obj, HadMultipleCandidates, 13255 OpLocInfo.getLoc(), 13256 OpLocInfo.getInfo()); 13257 if (NewFn.isInvalid()) 13258 return true; 13259 13260 // Build the full argument list for the method call (the implicit object 13261 // parameter is placed at the beginning of the list). 13262 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 13263 MethodArgs[0] = Object.get(); 13264 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 13265 13266 // Once we've built TheCall, all of the expressions are properly 13267 // owned. 13268 QualType ResultTy = Method->getReturnType(); 13269 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13270 ResultTy = ResultTy.getNonLValueExprType(Context); 13271 13272 CXXOperatorCallExpr *TheCall = new (Context) 13273 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 13274 VK, RParenLoc, FPOptions()); 13275 13276 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13277 return true; 13278 13279 // We may have default arguments. If so, we need to allocate more 13280 // slots in the call for them. 13281 if (Args.size() < NumParams) 13282 TheCall->setNumArgs(Context, NumParams + 1); 13283 13284 bool IsError = false; 13285 13286 // Initialize the implicit object parameter. 13287 ExprResult ObjRes = 13288 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13289 Best->FoundDecl, Method); 13290 if (ObjRes.isInvalid()) 13291 IsError = true; 13292 else 13293 Object = ObjRes; 13294 TheCall->setArg(0, Object.get()); 13295 13296 // Check the argument types. 13297 for (unsigned i = 0; i != NumParams; i++) { 13298 Expr *Arg; 13299 if (i < Args.size()) { 13300 Arg = Args[i]; 13301 13302 // Pass the argument. 13303 13304 ExprResult InputInit 13305 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13306 Context, 13307 Method->getParamDecl(i)), 13308 SourceLocation(), Arg); 13309 13310 IsError |= InputInit.isInvalid(); 13311 Arg = InputInit.getAs<Expr>(); 13312 } else { 13313 ExprResult DefArg 13314 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13315 if (DefArg.isInvalid()) { 13316 IsError = true; 13317 break; 13318 } 13319 13320 Arg = DefArg.getAs<Expr>(); 13321 } 13322 13323 TheCall->setArg(i + 1, Arg); 13324 } 13325 13326 // If this is a variadic call, handle args passed through "...". 13327 if (Proto->isVariadic()) { 13328 // Promote the arguments (C99 6.5.2.2p7). 13329 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13330 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13331 nullptr); 13332 IsError |= Arg.isInvalid(); 13333 TheCall->setArg(i + 1, Arg.get()); 13334 } 13335 } 13336 13337 if (IsError) return true; 13338 13339 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13340 13341 if (CheckFunctionCall(Method, TheCall, Proto)) 13342 return true; 13343 13344 return MaybeBindToTemporary(TheCall); 13345 } 13346 13347 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13348 /// (if one exists), where @c Base is an expression of class type and 13349 /// @c Member is the name of the member we're trying to find. 13350 ExprResult 13351 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13352 bool *NoArrowOperatorFound) { 13353 assert(Base->getType()->isRecordType() && 13354 "left-hand side must have class type"); 13355 13356 if (checkPlaceholderForOverload(*this, Base)) 13357 return ExprError(); 13358 13359 SourceLocation Loc = Base->getExprLoc(); 13360 13361 // C++ [over.ref]p1: 13362 // 13363 // [...] An expression x->m is interpreted as (x.operator->())->m 13364 // for a class object x of type T if T::operator->() exists and if 13365 // the operator is selected as the best match function by the 13366 // overload resolution mechanism (13.3). 13367 DeclarationName OpName = 13368 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13369 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13370 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13371 13372 if (RequireCompleteType(Loc, Base->getType(), 13373 diag::err_typecheck_incomplete_tag, Base)) 13374 return ExprError(); 13375 13376 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13377 LookupQualifiedName(R, BaseRecord->getDecl()); 13378 R.suppressDiagnostics(); 13379 13380 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13381 Oper != OperEnd; ++Oper) { 13382 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13383 None, CandidateSet, /*SuppressUserConversions=*/false); 13384 } 13385 13386 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13387 13388 // Perform overload resolution. 13389 OverloadCandidateSet::iterator Best; 13390 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13391 case OR_Success: 13392 // Overload resolution succeeded; we'll build the call below. 13393 break; 13394 13395 case OR_No_Viable_Function: 13396 if (CandidateSet.empty()) { 13397 QualType BaseType = Base->getType(); 13398 if (NoArrowOperatorFound) { 13399 // Report this specific error to the caller instead of emitting a 13400 // diagnostic, as requested. 13401 *NoArrowOperatorFound = true; 13402 return ExprError(); 13403 } 13404 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13405 << BaseType << Base->getSourceRange(); 13406 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13407 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13408 << FixItHint::CreateReplacement(OpLoc, "."); 13409 } 13410 } else 13411 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13412 << "operator->" << Base->getSourceRange(); 13413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13414 return ExprError(); 13415 13416 case OR_Ambiguous: 13417 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13418 << "->" << Base->getType() << Base->getSourceRange(); 13419 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13420 return ExprError(); 13421 13422 case OR_Deleted: 13423 Diag(OpLoc, diag::err_ovl_deleted_oper) 13424 << Best->Function->isDeleted() 13425 << "->" 13426 << getDeletedOrUnavailableSuffix(Best->Function) 13427 << Base->getSourceRange(); 13428 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13429 return ExprError(); 13430 } 13431 13432 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13433 13434 // Convert the object parameter. 13435 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13436 ExprResult BaseResult = 13437 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13438 Best->FoundDecl, Method); 13439 if (BaseResult.isInvalid()) 13440 return ExprError(); 13441 Base = BaseResult.get(); 13442 13443 // Build the operator call. 13444 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13445 Base, HadMultipleCandidates, OpLoc); 13446 if (FnExpr.isInvalid()) 13447 return ExprError(); 13448 13449 QualType ResultTy = Method->getReturnType(); 13450 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13451 ResultTy = ResultTy.getNonLValueExprType(Context); 13452 CXXOperatorCallExpr *TheCall = 13453 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 13454 Base, ResultTy, VK, OpLoc, FPOptions()); 13455 13456 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13457 return ExprError(); 13458 13459 if (CheckFunctionCall(Method, TheCall, 13460 Method->getType()->castAs<FunctionProtoType>())) 13461 return ExprError(); 13462 13463 return MaybeBindToTemporary(TheCall); 13464 } 13465 13466 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13467 /// a literal operator described by the provided lookup results. 13468 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13469 DeclarationNameInfo &SuffixInfo, 13470 ArrayRef<Expr*> Args, 13471 SourceLocation LitEndLoc, 13472 TemplateArgumentListInfo *TemplateArgs) { 13473 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13474 13475 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13476 OverloadCandidateSet::CSK_Normal); 13477 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13478 /*SuppressUserConversions=*/true); 13479 13480 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13481 13482 // Perform overload resolution. This will usually be trivial, but might need 13483 // to perform substitutions for a literal operator template. 13484 OverloadCandidateSet::iterator Best; 13485 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13486 case OR_Success: 13487 case OR_Deleted: 13488 break; 13489 13490 case OR_No_Viable_Function: 13491 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13492 << R.getLookupName(); 13493 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13494 return ExprError(); 13495 13496 case OR_Ambiguous: 13497 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13498 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13499 return ExprError(); 13500 } 13501 13502 FunctionDecl *FD = Best->Function; 13503 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13504 nullptr, HadMultipleCandidates, 13505 SuffixInfo.getLoc(), 13506 SuffixInfo.getInfo()); 13507 if (Fn.isInvalid()) 13508 return true; 13509 13510 // Check the argument types. This should almost always be a no-op, except 13511 // that array-to-pointer decay is applied to string literals. 13512 Expr *ConvArgs[2]; 13513 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13514 ExprResult InputInit = PerformCopyInitialization( 13515 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13516 SourceLocation(), Args[ArgIdx]); 13517 if (InputInit.isInvalid()) 13518 return true; 13519 ConvArgs[ArgIdx] = InputInit.get(); 13520 } 13521 13522 QualType ResultTy = FD->getReturnType(); 13523 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13524 ResultTy = ResultTy.getNonLValueExprType(Context); 13525 13526 UserDefinedLiteral *UDL = 13527 new (Context) UserDefinedLiteral(Context, Fn.get(), 13528 llvm::makeArrayRef(ConvArgs, Args.size()), 13529 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13530 13531 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13532 return ExprError(); 13533 13534 if (CheckFunctionCall(FD, UDL, nullptr)) 13535 return ExprError(); 13536 13537 return MaybeBindToTemporary(UDL); 13538 } 13539 13540 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13541 /// given LookupResult is non-empty, it is assumed to describe a member which 13542 /// will be invoked. Otherwise, the function will be found via argument 13543 /// dependent lookup. 13544 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13545 /// otherwise CallExpr is set to ExprError() and some non-success value 13546 /// is returned. 13547 Sema::ForRangeStatus 13548 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13549 SourceLocation RangeLoc, 13550 const DeclarationNameInfo &NameInfo, 13551 LookupResult &MemberLookup, 13552 OverloadCandidateSet *CandidateSet, 13553 Expr *Range, ExprResult *CallExpr) { 13554 Scope *S = nullptr; 13555 13556 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13557 if (!MemberLookup.empty()) { 13558 ExprResult MemberRef = 13559 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13560 /*IsPtr=*/false, CXXScopeSpec(), 13561 /*TemplateKWLoc=*/SourceLocation(), 13562 /*FirstQualifierInScope=*/nullptr, 13563 MemberLookup, 13564 /*TemplateArgs=*/nullptr, S); 13565 if (MemberRef.isInvalid()) { 13566 *CallExpr = ExprError(); 13567 return FRS_DiagnosticIssued; 13568 } 13569 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13570 if (CallExpr->isInvalid()) { 13571 *CallExpr = ExprError(); 13572 return FRS_DiagnosticIssued; 13573 } 13574 } else { 13575 UnresolvedSet<0> FoundNames; 13576 UnresolvedLookupExpr *Fn = 13577 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13578 NestedNameSpecifierLoc(), NameInfo, 13579 /*NeedsADL=*/true, /*Overloaded=*/false, 13580 FoundNames.begin(), FoundNames.end()); 13581 13582 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13583 CandidateSet, CallExpr); 13584 if (CandidateSet->empty() || CandidateSetError) { 13585 *CallExpr = ExprError(); 13586 return FRS_NoViableFunction; 13587 } 13588 OverloadCandidateSet::iterator Best; 13589 OverloadingResult OverloadResult = 13590 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13591 13592 if (OverloadResult == OR_No_Viable_Function) { 13593 *CallExpr = ExprError(); 13594 return FRS_NoViableFunction; 13595 } 13596 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13597 Loc, nullptr, CandidateSet, &Best, 13598 OverloadResult, 13599 /*AllowTypoCorrection=*/false); 13600 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13601 *CallExpr = ExprError(); 13602 return FRS_DiagnosticIssued; 13603 } 13604 } 13605 return FRS_Success; 13606 } 13607 13608 13609 /// FixOverloadedFunctionReference - E is an expression that refers to 13610 /// a C++ overloaded function (possibly with some parentheses and 13611 /// perhaps a '&' around it). We have resolved the overloaded function 13612 /// to the function declaration Fn, so patch up the expression E to 13613 /// refer (possibly indirectly) to Fn. Returns the new expr. 13614 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13615 FunctionDecl *Fn) { 13616 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13617 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13618 Found, Fn); 13619 if (SubExpr == PE->getSubExpr()) 13620 return PE; 13621 13622 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13623 } 13624 13625 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13626 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13627 Found, Fn); 13628 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13629 SubExpr->getType()) && 13630 "Implicit cast type cannot be determined from overload"); 13631 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13632 if (SubExpr == ICE->getSubExpr()) 13633 return ICE; 13634 13635 return ImplicitCastExpr::Create(Context, ICE->getType(), 13636 ICE->getCastKind(), 13637 SubExpr, nullptr, 13638 ICE->getValueKind()); 13639 } 13640 13641 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13642 if (!GSE->isResultDependent()) { 13643 Expr *SubExpr = 13644 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13645 if (SubExpr == GSE->getResultExpr()) 13646 return GSE; 13647 13648 // Replace the resulting type information before rebuilding the generic 13649 // selection expression. 13650 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13651 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13652 unsigned ResultIdx = GSE->getResultIndex(); 13653 AssocExprs[ResultIdx] = SubExpr; 13654 13655 return new (Context) GenericSelectionExpr( 13656 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13657 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13658 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13659 ResultIdx); 13660 } 13661 // Rather than fall through to the unreachable, return the original generic 13662 // selection expression. 13663 return GSE; 13664 } 13665 13666 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13667 assert(UnOp->getOpcode() == UO_AddrOf && 13668 "Can only take the address of an overloaded function"); 13669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13670 if (Method->isStatic()) { 13671 // Do nothing: static member functions aren't any different 13672 // from non-member functions. 13673 } else { 13674 // Fix the subexpression, which really has to be an 13675 // UnresolvedLookupExpr holding an overloaded member function 13676 // or template. 13677 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13678 Found, Fn); 13679 if (SubExpr == UnOp->getSubExpr()) 13680 return UnOp; 13681 13682 assert(isa<DeclRefExpr>(SubExpr) 13683 && "fixed to something other than a decl ref"); 13684 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13685 && "fixed to a member ref with no nested name qualifier"); 13686 13687 // We have taken the address of a pointer to member 13688 // function. Perform the computation here so that we get the 13689 // appropriate pointer to member type. 13690 QualType ClassType 13691 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13692 QualType MemPtrType 13693 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13694 // Under the MS ABI, lock down the inheritance model now. 13695 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13696 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13697 13698 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13699 VK_RValue, OK_Ordinary, 13700 UnOp->getOperatorLoc(), false); 13701 } 13702 } 13703 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13704 Found, Fn); 13705 if (SubExpr == UnOp->getSubExpr()) 13706 return UnOp; 13707 13708 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13709 Context.getPointerType(SubExpr->getType()), 13710 VK_RValue, OK_Ordinary, 13711 UnOp->getOperatorLoc(), false); 13712 } 13713 13714 // C++ [except.spec]p17: 13715 // An exception-specification is considered to be needed when: 13716 // - in an expression the function is the unique lookup result or the 13717 // selected member of a set of overloaded functions 13718 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13719 ResolveExceptionSpec(E->getExprLoc(), FPT); 13720 13721 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13722 // FIXME: avoid copy. 13723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13724 if (ULE->hasExplicitTemplateArgs()) { 13725 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13726 TemplateArgs = &TemplateArgsBuffer; 13727 } 13728 13729 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13730 ULE->getQualifierLoc(), 13731 ULE->getTemplateKeywordLoc(), 13732 Fn, 13733 /*enclosing*/ false, // FIXME? 13734 ULE->getNameLoc(), 13735 Fn->getType(), 13736 VK_LValue, 13737 Found.getDecl(), 13738 TemplateArgs); 13739 MarkDeclRefReferenced(DRE); 13740 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13741 return DRE; 13742 } 13743 13744 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13745 // FIXME: avoid copy. 13746 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13747 if (MemExpr->hasExplicitTemplateArgs()) { 13748 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13749 TemplateArgs = &TemplateArgsBuffer; 13750 } 13751 13752 Expr *Base; 13753 13754 // If we're filling in a static method where we used to have an 13755 // implicit member access, rewrite to a simple decl ref. 13756 if (MemExpr->isImplicitAccess()) { 13757 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13758 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13759 MemExpr->getQualifierLoc(), 13760 MemExpr->getTemplateKeywordLoc(), 13761 Fn, 13762 /*enclosing*/ false, 13763 MemExpr->getMemberLoc(), 13764 Fn->getType(), 13765 VK_LValue, 13766 Found.getDecl(), 13767 TemplateArgs); 13768 MarkDeclRefReferenced(DRE); 13769 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13770 return DRE; 13771 } else { 13772 SourceLocation Loc = MemExpr->getMemberLoc(); 13773 if (MemExpr->getQualifier()) 13774 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13775 CheckCXXThisCapture(Loc); 13776 Base = new (Context) CXXThisExpr(Loc, 13777 MemExpr->getBaseType(), 13778 /*isImplicit=*/true); 13779 } 13780 } else 13781 Base = MemExpr->getBase(); 13782 13783 ExprValueKind valueKind; 13784 QualType type; 13785 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13786 valueKind = VK_LValue; 13787 type = Fn->getType(); 13788 } else { 13789 valueKind = VK_RValue; 13790 type = Context.BoundMemberTy; 13791 } 13792 13793 MemberExpr *ME = MemberExpr::Create( 13794 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13795 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13796 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13797 OK_Ordinary); 13798 ME->setHadMultipleCandidates(true); 13799 MarkMemberReferenced(ME); 13800 return ME; 13801 } 13802 13803 llvm_unreachable("Invalid reference to overloaded function"); 13804 } 13805 13806 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13807 DeclAccessPair Found, 13808 FunctionDecl *Fn) { 13809 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13810 } 13811