1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult 53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 54 const Expr *Base, bool HadMultipleCandidates, 55 SourceLocation Loc = SourceLocation(), 56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 58 return ExprError(); 59 // If FoundDecl is different from Fn (such as if one is a template 60 // and the other a specialization), make sure DiagnoseUseOfDecl is 61 // called on both. 62 // FIXME: This would be more comprehensively addressed by modifying 63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 64 // being used. 65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 66 return ExprError(); 67 DeclRefExpr *DRE = new (S.Context) 68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 69 if (HadMultipleCandidates) 70 DRE->setHadMultipleCandidates(true); 71 72 S.MarkDeclRefReferenced(DRE, Base); 73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 75 S.ResolveExceptionSpec(Loc, FPT); 76 DRE->setType(Fn->getType()); 77 } 78 } 79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 80 CK_FunctionToPointerDecay); 81 } 82 83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle, 87 bool AllowObjCWritebackConversion); 88 89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 90 QualType &ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle); 94 static OverloadingResult 95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 96 UserDefinedConversionSequence& User, 97 OverloadCandidateSet& Conversions, 98 AllowedExplicit AllowExplicit, 99 bool AllowObjCConversionOnExplicit); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 static ImplicitConversionSequence::CompareKind 107 CompareQualificationConversions(Sema &S, 108 const StandardConversionSequence& SCS1, 109 const StandardConversionSequence& SCS2); 110 111 static ImplicitConversionSequence::CompareKind 112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 113 const StandardConversionSequence& SCS1, 114 const StandardConversionSequence& SCS2); 115 116 /// GetConversionRank - Retrieve the implicit conversion rank 117 /// corresponding to the given implicit conversion kind. 118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 119 static const ImplicitConversionRank 120 Rank[(int)ICK_Num_Conversion_Kinds] = { 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Exact_Match, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Promotion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_OCL_Scalar_Widening, 141 ICR_Complex_Real_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Writeback_Conversion, 145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 146 // it was omitted by the patch that added 147 // ICK_Zero_Event_Conversion 148 ICR_C_Conversion, 149 ICR_C_Conversion_Extension 150 }; 151 return Rank[(int)Kind]; 152 } 153 154 /// GetImplicitConversionName - Return the name of this kind of 155 /// implicit conversion. 156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 158 "No conversion", 159 "Lvalue-to-rvalue", 160 "Array-to-pointer", 161 "Function-to-pointer", 162 "Function pointer conversion", 163 "Qualification", 164 "Integral promotion", 165 "Floating point promotion", 166 "Complex promotion", 167 "Integral conversion", 168 "Floating conversion", 169 "Complex conversion", 170 "Floating-integral conversion", 171 "Pointer conversion", 172 "Pointer-to-member conversion", 173 "Boolean conversion", 174 "Compatible-types conversion", 175 "Derived-to-base conversion", 176 "Vector conversion", 177 "Vector splat", 178 "Complex-real conversion", 179 "Block Pointer conversion", 180 "Transparent Union Conversion", 181 "Writeback conversion", 182 "OpenCL Zero Event Conversion", 183 "C specific type conversion", 184 "Incompatible pointer conversion" 185 }; 186 return Name[Kind]; 187 } 188 189 /// StandardConversionSequence - Set the standard conversion 190 /// sequence to the identity conversion. 191 void StandardConversionSequence::setAsIdentityConversion() { 192 First = ICK_Identity; 193 Second = ICK_Identity; 194 Third = ICK_Identity; 195 DeprecatedStringLiteralToCharPtr = false; 196 QualificationIncludesObjCLifetime = false; 197 ReferenceBinding = false; 198 DirectBinding = false; 199 IsLvalueReference = true; 200 BindsToFunctionLvalue = false; 201 BindsToRvalue = false; 202 BindsImplicitObjectArgumentWithoutRefQualifier = false; 203 ObjCLifetimeConversionBinding = false; 204 CopyConstructor = nullptr; 205 } 206 207 /// getRank - Retrieve the rank of this standard conversion sequence 208 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 209 /// implicit conversions. 210 ImplicitConversionRank StandardConversionSequence::getRank() const { 211 ImplicitConversionRank Rank = ICR_Exact_Match; 212 if (GetConversionRank(First) > Rank) 213 Rank = GetConversionRank(First); 214 if (GetConversionRank(Second) > Rank) 215 Rank = GetConversionRank(Second); 216 if (GetConversionRank(Third) > Rank) 217 Rank = GetConversionRank(Third); 218 return Rank; 219 } 220 221 /// isPointerConversionToBool - Determines whether this conversion is 222 /// a conversion of a pointer or pointer-to-member to bool. This is 223 /// used as part of the ranking of standard conversion sequences 224 /// (C++ 13.3.3.2p4). 225 bool StandardConversionSequence::isPointerConversionToBool() const { 226 // Note that FromType has not necessarily been transformed by the 227 // array-to-pointer or function-to-pointer implicit conversions, so 228 // check for their presence as well as checking whether FromType is 229 // a pointer. 230 if (getToType(1)->isBooleanType() && 231 (getFromType()->isPointerType() || 232 getFromType()->isMemberPointerType() || 233 getFromType()->isObjCObjectPointerType() || 234 getFromType()->isBlockPointerType() || 235 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 236 return true; 237 238 return false; 239 } 240 241 /// isPointerConversionToVoidPointer - Determines whether this 242 /// conversion is a conversion of a pointer to a void pointer. This is 243 /// used as part of the ranking of standard conversion sequences (C++ 244 /// 13.3.3.2p4). 245 bool 246 StandardConversionSequence:: 247 isPointerConversionToVoidPointer(ASTContext& Context) const { 248 QualType FromType = getFromType(); 249 QualType ToType = getToType(1); 250 251 // Note that FromType has not necessarily been transformed by the 252 // array-to-pointer implicit conversion, so check for its presence 253 // and redo the conversion to get a pointer. 254 if (First == ICK_Array_To_Pointer) 255 FromType = Context.getArrayDecayedType(FromType); 256 257 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 258 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 259 return ToPtrType->getPointeeType()->isVoidType(); 260 261 return false; 262 } 263 264 /// Skip any implicit casts which could be either part of a narrowing conversion 265 /// or after one in an implicit conversion. 266 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 267 const Expr *Converted) { 268 // We can have cleanups wrapping the converted expression; these need to be 269 // preserved so that destructors run if necessary. 270 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 271 Expr *Inner = 272 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 273 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 274 EWC->getObjects()); 275 } 276 277 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 278 switch (ICE->getCastKind()) { 279 case CK_NoOp: 280 case CK_IntegralCast: 281 case CK_IntegralToBoolean: 282 case CK_IntegralToFloating: 283 case CK_BooleanToSignedIntegral: 284 case CK_FloatingToIntegral: 285 case CK_FloatingToBoolean: 286 case CK_FloatingCast: 287 Converted = ICE->getSubExpr(); 288 continue; 289 290 default: 291 return Converted; 292 } 293 } 294 295 return Converted; 296 } 297 298 /// Check if this standard conversion sequence represents a narrowing 299 /// conversion, according to C++11 [dcl.init.list]p7. 300 /// 301 /// \param Ctx The AST context. 302 /// \param Converted The result of applying this standard conversion sequence. 303 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 304 /// value of the expression prior to the narrowing conversion. 305 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 306 /// type of the expression prior to the narrowing conversion. 307 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 308 /// from floating point types to integral types should be ignored. 309 NarrowingKind StandardConversionSequence::getNarrowingKind( 310 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 311 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 312 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 313 314 // C++11 [dcl.init.list]p7: 315 // A narrowing conversion is an implicit conversion ... 316 QualType FromType = getToType(0); 317 QualType ToType = getToType(1); 318 319 // A conversion to an enumeration type is narrowing if the conversion to 320 // the underlying type is narrowing. This only arises for expressions of 321 // the form 'Enum{init}'. 322 if (auto *ET = ToType->getAs<EnumType>()) 323 ToType = ET->getDecl()->getIntegerType(); 324 325 switch (Second) { 326 // 'bool' is an integral type; dispatch to the right place to handle it. 327 case ICK_Boolean_Conversion: 328 if (FromType->isRealFloatingType()) 329 goto FloatingIntegralConversion; 330 if (FromType->isIntegralOrUnscopedEnumerationType()) 331 goto IntegralConversion; 332 // -- from a pointer type or pointer-to-member type to bool, or 333 return NK_Type_Narrowing; 334 335 // -- from a floating-point type to an integer type, or 336 // 337 // -- from an integer type or unscoped enumeration type to a floating-point 338 // type, except where the source is a constant expression and the actual 339 // value after conversion will fit into the target type and will produce 340 // the original value when converted back to the original type, or 341 case ICK_Floating_Integral: 342 FloatingIntegralConversion: 343 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 344 return NK_Type_Narrowing; 345 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 346 ToType->isRealFloatingType()) { 347 if (IgnoreFloatToIntegralConversion) 348 return NK_Not_Narrowing; 349 llvm::APSInt IntConstantValue; 350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 351 assert(Initializer && "Unknown conversion expression"); 352 353 // If it's value-dependent, we can't tell whether it's narrowing. 354 if (Initializer->isValueDependent()) 355 return NK_Dependent_Narrowing; 356 357 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 358 // Convert the integer to the floating type. 359 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 360 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 361 llvm::APFloat::rmNearestTiesToEven); 362 // And back. 363 llvm::APSInt ConvertedValue = IntConstantValue; 364 bool ignored; 365 Result.convertToInteger(ConvertedValue, 366 llvm::APFloat::rmTowardZero, &ignored); 367 // If the resulting value is different, this was a narrowing conversion. 368 if (IntConstantValue != ConvertedValue) { 369 ConstantValue = APValue(IntConstantValue); 370 ConstantType = Initializer->getType(); 371 return NK_Constant_Narrowing; 372 } 373 } else { 374 // Variables are always narrowings. 375 return NK_Variable_Narrowing; 376 } 377 } 378 return NK_Not_Narrowing; 379 380 // -- from long double to double or float, or from double to float, except 381 // where the source is a constant expression and the actual value after 382 // conversion is within the range of values that can be represented (even 383 // if it cannot be represented exactly), or 384 case ICK_Floating_Conversion: 385 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 386 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 387 // FromType is larger than ToType. 388 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 389 390 // If it's value-dependent, we can't tell whether it's narrowing. 391 if (Initializer->isValueDependent()) 392 return NK_Dependent_Narrowing; 393 394 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 395 // Constant! 396 assert(ConstantValue.isFloat()); 397 llvm::APFloat FloatVal = ConstantValue.getFloat(); 398 // Convert the source value into the target type. 399 bool ignored; 400 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 401 Ctx.getFloatTypeSemantics(ToType), 402 llvm::APFloat::rmNearestTiesToEven, &ignored); 403 // If there was no overflow, the source value is within the range of 404 // values that can be represented. 405 if (ConvertStatus & llvm::APFloat::opOverflow) { 406 ConstantType = Initializer->getType(); 407 return NK_Constant_Narrowing; 408 } 409 } else { 410 return NK_Variable_Narrowing; 411 } 412 } 413 return NK_Not_Narrowing; 414 415 // -- from an integer type or unscoped enumeration type to an integer type 416 // that cannot represent all the values of the original type, except where 417 // the source is a constant expression and the actual value after 418 // conversion will fit into the target type and will produce the original 419 // value when converted back to the original type. 420 case ICK_Integral_Conversion: 421 IntegralConversion: { 422 assert(FromType->isIntegralOrUnscopedEnumerationType()); 423 assert(ToType->isIntegralOrUnscopedEnumerationType()); 424 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 425 const unsigned FromWidth = Ctx.getIntWidth(FromType); 426 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 427 const unsigned ToWidth = Ctx.getIntWidth(ToType); 428 429 if (FromWidth > ToWidth || 430 (FromWidth == ToWidth && FromSigned != ToSigned) || 431 (FromSigned && !ToSigned)) { 432 // Not all values of FromType can be represented in ToType. 433 llvm::APSInt InitializerValue; 434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 435 436 // If it's value-dependent, we can't tell whether it's narrowing. 437 if (Initializer->isValueDependent()) 438 return NK_Dependent_Narrowing; 439 440 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 441 // Such conversions on variables are always narrowing. 442 return NK_Variable_Narrowing; 443 } 444 bool Narrowing = false; 445 if (FromWidth < ToWidth) { 446 // Negative -> unsigned is narrowing. Otherwise, more bits is never 447 // narrowing. 448 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 449 Narrowing = true; 450 } else { 451 // Add a bit to the InitializerValue so we don't have to worry about 452 // signed vs. unsigned comparisons. 453 InitializerValue = InitializerValue.extend( 454 InitializerValue.getBitWidth() + 1); 455 // Convert the initializer to and from the target width and signed-ness. 456 llvm::APSInt ConvertedValue = InitializerValue; 457 ConvertedValue = ConvertedValue.trunc(ToWidth); 458 ConvertedValue.setIsSigned(ToSigned); 459 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 460 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 461 // If the result is different, this was a narrowing conversion. 462 if (ConvertedValue != InitializerValue) 463 Narrowing = true; 464 } 465 if (Narrowing) { 466 ConstantType = Initializer->getType(); 467 ConstantValue = APValue(InitializerValue); 468 return NK_Constant_Narrowing; 469 } 470 } 471 return NK_Not_Narrowing; 472 } 473 474 default: 475 // Other kinds of conversions are not narrowings. 476 return NK_Not_Narrowing; 477 } 478 } 479 480 /// dump - Print this standard conversion sequence to standard 481 /// error. Useful for debugging overloading issues. 482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 483 raw_ostream &OS = llvm::errs(); 484 bool PrintedSomething = false; 485 if (First != ICK_Identity) { 486 OS << GetImplicitConversionName(First); 487 PrintedSomething = true; 488 } 489 490 if (Second != ICK_Identity) { 491 if (PrintedSomething) { 492 OS << " -> "; 493 } 494 OS << GetImplicitConversionName(Second); 495 496 if (CopyConstructor) { 497 OS << " (by copy constructor)"; 498 } else if (DirectBinding) { 499 OS << " (direct reference binding)"; 500 } else if (ReferenceBinding) { 501 OS << " (reference binding)"; 502 } 503 PrintedSomething = true; 504 } 505 506 if (Third != ICK_Identity) { 507 if (PrintedSomething) { 508 OS << " -> "; 509 } 510 OS << GetImplicitConversionName(Third); 511 PrintedSomething = true; 512 } 513 514 if (!PrintedSomething) { 515 OS << "No conversions required"; 516 } 517 } 518 519 /// dump - Print this user-defined conversion sequence to standard 520 /// error. Useful for debugging overloading issues. 521 void UserDefinedConversionSequence::dump() const { 522 raw_ostream &OS = llvm::errs(); 523 if (Before.First || Before.Second || Before.Third) { 524 Before.dump(); 525 OS << " -> "; 526 } 527 if (ConversionFunction) 528 OS << '\'' << *ConversionFunction << '\''; 529 else 530 OS << "aggregate initialization"; 531 if (After.First || After.Second || After.Third) { 532 OS << " -> "; 533 After.dump(); 534 } 535 } 536 537 /// dump - Print this implicit conversion sequence to standard 538 /// error. Useful for debugging overloading issues. 539 void ImplicitConversionSequence::dump() const { 540 raw_ostream &OS = llvm::errs(); 541 if (isStdInitializerListElement()) 542 OS << "Worst std::initializer_list element conversion: "; 543 switch (ConversionKind) { 544 case StandardConversion: 545 OS << "Standard conversion: "; 546 Standard.dump(); 547 break; 548 case UserDefinedConversion: 549 OS << "User-defined conversion: "; 550 UserDefined.dump(); 551 break; 552 case EllipsisConversion: 553 OS << "Ellipsis conversion"; 554 break; 555 case AmbiguousConversion: 556 OS << "Ambiguous conversion"; 557 break; 558 case BadConversion: 559 OS << "Bad conversion"; 560 break; 561 } 562 563 OS << "\n"; 564 } 565 566 void AmbiguousConversionSequence::construct() { 567 new (&conversions()) ConversionSet(); 568 } 569 570 void AmbiguousConversionSequence::destruct() { 571 conversions().~ConversionSet(); 572 } 573 574 void 575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 576 FromTypePtr = O.FromTypePtr; 577 ToTypePtr = O.ToTypePtr; 578 new (&conversions()) ConversionSet(O.conversions()); 579 } 580 581 namespace { 582 // Structure used by DeductionFailureInfo to store 583 // template argument information. 584 struct DFIArguments { 585 TemplateArgument FirstArg; 586 TemplateArgument SecondArg; 587 }; 588 // Structure used by DeductionFailureInfo to store 589 // template parameter and template argument information. 590 struct DFIParamWithArguments : DFIArguments { 591 TemplateParameter Param; 592 }; 593 // Structure used by DeductionFailureInfo to store template argument 594 // information and the index of the problematic call argument. 595 struct DFIDeducedMismatchArgs : DFIArguments { 596 TemplateArgumentList *TemplateArgs; 597 unsigned CallArgIndex; 598 }; 599 // Structure used by DeductionFailureInfo to store information about 600 // unsatisfied constraints. 601 struct CNSInfo { 602 TemplateArgumentList *TemplateArgs; 603 ConstraintSatisfaction Satisfaction; 604 }; 605 } 606 607 /// Convert from Sema's representation of template deduction information 608 /// to the form used in overload-candidate information. 609 DeductionFailureInfo 610 clang::MakeDeductionFailureInfo(ASTContext &Context, 611 Sema::TemplateDeductionResult TDK, 612 TemplateDeductionInfo &Info) { 613 DeductionFailureInfo Result; 614 Result.Result = static_cast<unsigned>(TDK); 615 Result.HasDiagnostic = false; 616 switch (TDK) { 617 case Sema::TDK_Invalid: 618 case Sema::TDK_InstantiationDepth: 619 case Sema::TDK_TooManyArguments: 620 case Sema::TDK_TooFewArguments: 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 case Sema::TDK_CUDATargetMismatch: 623 Result.Data = nullptr; 624 break; 625 626 case Sema::TDK_Incomplete: 627 case Sema::TDK_InvalidExplicitArguments: 628 Result.Data = Info.Param.getOpaqueValue(); 629 break; 630 631 case Sema::TDK_DeducedMismatch: 632 case Sema::TDK_DeducedMismatchNested: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 auto *Saved = new (Context) DFIDeducedMismatchArgs; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Saved->TemplateArgs = Info.take(); 638 Saved->CallArgIndex = Info.CallArgIndex; 639 Result.Data = Saved; 640 break; 641 } 642 643 case Sema::TDK_NonDeducedMismatch: { 644 // FIXME: Should allocate from normal heap so that we can free this later. 645 DFIArguments *Saved = new (Context) DFIArguments; 646 Saved->FirstArg = Info.FirstArg; 647 Saved->SecondArg = Info.SecondArg; 648 Result.Data = Saved; 649 break; 650 } 651 652 case Sema::TDK_IncompletePack: 653 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: { 656 // FIXME: Should allocate from normal heap so that we can free this later. 657 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 658 Saved->Param = Info.Param; 659 Saved->FirstArg = Info.FirstArg; 660 Saved->SecondArg = Info.SecondArg; 661 Result.Data = Saved; 662 break; 663 } 664 665 case Sema::TDK_SubstitutionFailure: 666 Result.Data = Info.take(); 667 if (Info.hasSFINAEDiagnostic()) { 668 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 669 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 670 Info.takeSFINAEDiagnostic(*Diag); 671 Result.HasDiagnostic = true; 672 } 673 break; 674 675 case Sema::TDK_ConstraintsNotSatisfied: { 676 CNSInfo *Saved = new (Context) CNSInfo; 677 Saved->TemplateArgs = Info.take(); 678 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 679 Result.Data = Saved; 680 break; 681 } 682 683 case Sema::TDK_Success: 684 case Sema::TDK_NonDependentConversionFailure: 685 llvm_unreachable("not a deduction failure"); 686 } 687 688 return Result; 689 } 690 691 void DeductionFailureInfo::Destroy() { 692 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 693 case Sema::TDK_Success: 694 case Sema::TDK_Invalid: 695 case Sema::TDK_InstantiationDepth: 696 case Sema::TDK_Incomplete: 697 case Sema::TDK_TooManyArguments: 698 case Sema::TDK_TooFewArguments: 699 case Sema::TDK_InvalidExplicitArguments: 700 case Sema::TDK_CUDATargetMismatch: 701 case Sema::TDK_NonDependentConversionFailure: 702 break; 703 704 case Sema::TDK_IncompletePack: 705 case Sema::TDK_Inconsistent: 706 case Sema::TDK_Underqualified: 707 case Sema::TDK_DeducedMismatch: 708 case Sema::TDK_DeducedMismatchNested: 709 case Sema::TDK_NonDeducedMismatch: 710 // FIXME: Destroy the data? 711 Data = nullptr; 712 break; 713 714 case Sema::TDK_SubstitutionFailure: 715 // FIXME: Destroy the template argument list? 716 Data = nullptr; 717 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 718 Diag->~PartialDiagnosticAt(); 719 HasDiagnostic = false; 720 } 721 break; 722 723 case Sema::TDK_ConstraintsNotSatisfied: 724 // FIXME: Destroy the template argument list? 725 Data = nullptr; 726 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 727 Diag->~PartialDiagnosticAt(); 728 HasDiagnostic = false; 729 } 730 break; 731 732 // Unhandled 733 case Sema::TDK_MiscellaneousDeductionFailure: 734 break; 735 } 736 } 737 738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 739 if (HasDiagnostic) 740 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 741 return nullptr; 742 } 743 744 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 745 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 746 case Sema::TDK_Success: 747 case Sema::TDK_Invalid: 748 case Sema::TDK_InstantiationDepth: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_SubstitutionFailure: 752 case Sema::TDK_DeducedMismatch: 753 case Sema::TDK_DeducedMismatchNested: 754 case Sema::TDK_NonDeducedMismatch: 755 case Sema::TDK_CUDATargetMismatch: 756 case Sema::TDK_NonDependentConversionFailure: 757 case Sema::TDK_ConstraintsNotSatisfied: 758 return TemplateParameter(); 759 760 case Sema::TDK_Incomplete: 761 case Sema::TDK_InvalidExplicitArguments: 762 return TemplateParameter::getFromOpaqueValue(Data); 763 764 case Sema::TDK_IncompletePack: 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 return static_cast<DFIParamWithArguments*>(Data)->Param; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return TemplateParameter(); 775 } 776 777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 778 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 779 case Sema::TDK_Success: 780 case Sema::TDK_Invalid: 781 case Sema::TDK_InstantiationDepth: 782 case Sema::TDK_TooManyArguments: 783 case Sema::TDK_TooFewArguments: 784 case Sema::TDK_Incomplete: 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_InvalidExplicitArguments: 787 case Sema::TDK_Inconsistent: 788 case Sema::TDK_Underqualified: 789 case Sema::TDK_NonDeducedMismatch: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_DeducedMismatch: 795 case Sema::TDK_DeducedMismatchNested: 796 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 797 798 case Sema::TDK_SubstitutionFailure: 799 return static_cast<TemplateArgumentList*>(Data); 800 801 case Sema::TDK_ConstraintsNotSatisfied: 802 return static_cast<CNSInfo*>(Data)->TemplateArgs; 803 804 // Unhandled 805 case Sema::TDK_MiscellaneousDeductionFailure: 806 break; 807 } 808 809 return nullptr; 810 } 811 812 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 813 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 814 case Sema::TDK_Success: 815 case Sema::TDK_Invalid: 816 case Sema::TDK_InstantiationDepth: 817 case Sema::TDK_Incomplete: 818 case Sema::TDK_TooManyArguments: 819 case Sema::TDK_TooFewArguments: 820 case Sema::TDK_InvalidExplicitArguments: 821 case Sema::TDK_SubstitutionFailure: 822 case Sema::TDK_CUDATargetMismatch: 823 case Sema::TDK_NonDependentConversionFailure: 824 case Sema::TDK_ConstraintsNotSatisfied: 825 return nullptr; 826 827 case Sema::TDK_IncompletePack: 828 case Sema::TDK_Inconsistent: 829 case Sema::TDK_Underqualified: 830 case Sema::TDK_DeducedMismatch: 831 case Sema::TDK_DeducedMismatchNested: 832 case Sema::TDK_NonDeducedMismatch: 833 return &static_cast<DFIArguments*>(Data)->FirstArg; 834 835 // Unhandled 836 case Sema::TDK_MiscellaneousDeductionFailure: 837 break; 838 } 839 840 return nullptr; 841 } 842 843 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 844 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 845 case Sema::TDK_Success: 846 case Sema::TDK_Invalid: 847 case Sema::TDK_InstantiationDepth: 848 case Sema::TDK_Incomplete: 849 case Sema::TDK_IncompletePack: 850 case Sema::TDK_TooManyArguments: 851 case Sema::TDK_TooFewArguments: 852 case Sema::TDK_InvalidExplicitArguments: 853 case Sema::TDK_SubstitutionFailure: 854 case Sema::TDK_CUDATargetMismatch: 855 case Sema::TDK_NonDependentConversionFailure: 856 case Sema::TDK_ConstraintsNotSatisfied: 857 return nullptr; 858 859 case Sema::TDK_Inconsistent: 860 case Sema::TDK_Underqualified: 861 case Sema::TDK_DeducedMismatch: 862 case Sema::TDK_DeducedMismatchNested: 863 case Sema::TDK_NonDeducedMismatch: 864 return &static_cast<DFIArguments*>(Data)->SecondArg; 865 866 // Unhandled 867 case Sema::TDK_MiscellaneousDeductionFailure: 868 break; 869 } 870 871 return nullptr; 872 } 873 874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 875 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 876 case Sema::TDK_DeducedMismatch: 877 case Sema::TDK_DeducedMismatchNested: 878 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 879 880 default: 881 return llvm::None; 882 } 883 } 884 885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 886 OverloadedOperatorKind Op) { 887 if (!AllowRewrittenCandidates) 888 return false; 889 return Op == OO_EqualEqual || Op == OO_Spaceship; 890 } 891 892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 893 ASTContext &Ctx, const FunctionDecl *FD) { 894 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 895 return false; 896 // Don't bother adding a reversed candidate that can never be a better 897 // match than the non-reversed version. 898 return FD->getNumParams() != 2 || 899 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 900 FD->getParamDecl(1)->getType()) || 901 FD->hasAttr<EnableIfAttr>(); 902 } 903 904 void OverloadCandidateSet::destroyCandidates() { 905 for (iterator i = begin(), e = end(); i != e; ++i) { 906 for (auto &C : i->Conversions) 907 C.~ImplicitConversionSequence(); 908 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 909 i->DeductionFailure.Destroy(); 910 } 911 } 912 913 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 914 destroyCandidates(); 915 SlabAllocator.Reset(); 916 NumInlineBytesUsed = 0; 917 Candidates.clear(); 918 Functions.clear(); 919 Kind = CSK; 920 } 921 922 namespace { 923 class UnbridgedCastsSet { 924 struct Entry { 925 Expr **Addr; 926 Expr *Saved; 927 }; 928 SmallVector<Entry, 2> Entries; 929 930 public: 931 void save(Sema &S, Expr *&E) { 932 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 933 Entry entry = { &E, E }; 934 Entries.push_back(entry); 935 E = S.stripARCUnbridgedCast(E); 936 } 937 938 void restore() { 939 for (SmallVectorImpl<Entry>::iterator 940 i = Entries.begin(), e = Entries.end(); i != e; ++i) 941 *i->Addr = i->Saved; 942 } 943 }; 944 } 945 946 /// checkPlaceholderForOverload - Do any interesting placeholder-like 947 /// preprocessing on the given expression. 948 /// 949 /// \param unbridgedCasts a collection to which to add unbridged casts; 950 /// without this, they will be immediately diagnosed as errors 951 /// 952 /// Return true on unrecoverable error. 953 static bool 954 checkPlaceholderForOverload(Sema &S, Expr *&E, 955 UnbridgedCastsSet *unbridgedCasts = nullptr) { 956 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 957 // We can't handle overloaded expressions here because overload 958 // resolution might reasonably tweak them. 959 if (placeholder->getKind() == BuiltinType::Overload) return false; 960 961 // If the context potentially accepts unbridged ARC casts, strip 962 // the unbridged cast and add it to the collection for later restoration. 963 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 964 unbridgedCasts) { 965 unbridgedCasts->save(S, E); 966 return false; 967 } 968 969 // Go ahead and check everything else. 970 ExprResult result = S.CheckPlaceholderExpr(E); 971 if (result.isInvalid()) 972 return true; 973 974 E = result.get(); 975 return false; 976 } 977 978 // Nothing to do. 979 return false; 980 } 981 982 /// checkArgPlaceholdersForOverload - Check a set of call operands for 983 /// placeholders. 984 static bool checkArgPlaceholdersForOverload(Sema &S, 985 MultiExprArg Args, 986 UnbridgedCastsSet &unbridged) { 987 for (unsigned i = 0, e = Args.size(); i != e; ++i) 988 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 989 return true; 990 991 return false; 992 } 993 994 /// Determine whether the given New declaration is an overload of the 995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 996 /// New and Old cannot be overloaded, e.g., if New has the same signature as 997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 998 /// functions (or function templates) at all. When it does return Ovl_Match or 999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1001 /// declaration. 1002 /// 1003 /// Example: Given the following input: 1004 /// 1005 /// void f(int, float); // #1 1006 /// void f(int, int); // #2 1007 /// int f(int, int); // #3 1008 /// 1009 /// When we process #1, there is no previous declaration of "f", so IsOverload 1010 /// will not be used. 1011 /// 1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1015 /// unchanged. 1016 /// 1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1021 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1022 /// 1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1024 /// by a using declaration. The rules for whether to hide shadow declarations 1025 /// ignore some properties which otherwise figure into a function template's 1026 /// signature. 1027 Sema::OverloadKind 1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1029 NamedDecl *&Match, bool NewIsUsingDecl) { 1030 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1031 I != E; ++I) { 1032 NamedDecl *OldD = *I; 1033 1034 bool OldIsUsingDecl = false; 1035 if (isa<UsingShadowDecl>(OldD)) { 1036 OldIsUsingDecl = true; 1037 1038 // We can always introduce two using declarations into the same 1039 // context, even if they have identical signatures. 1040 if (NewIsUsingDecl) continue; 1041 1042 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1043 } 1044 1045 // A using-declaration does not conflict with another declaration 1046 // if one of them is hidden. 1047 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1048 continue; 1049 1050 // If either declaration was introduced by a using declaration, 1051 // we'll need to use slightly different rules for matching. 1052 // Essentially, these rules are the normal rules, except that 1053 // function templates hide function templates with different 1054 // return types or template parameter lists. 1055 bool UseMemberUsingDeclRules = 1056 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1057 !New->getFriendObjectKind(); 1058 1059 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1060 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1061 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1062 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1063 continue; 1064 } 1065 1066 if (!isa<FunctionTemplateDecl>(OldD) && 1067 !shouldLinkPossiblyHiddenDecl(*I, New)) 1068 continue; 1069 1070 Match = *I; 1071 return Ovl_Match; 1072 } 1073 1074 // Builtins that have custom typechecking or have a reference should 1075 // not be overloadable or redeclarable. 1076 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1077 Match = *I; 1078 return Ovl_NonFunction; 1079 } 1080 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1081 // We can overload with these, which can show up when doing 1082 // redeclaration checks for UsingDecls. 1083 assert(Old.getLookupKind() == LookupUsingDeclName); 1084 } else if (isa<TagDecl>(OldD)) { 1085 // We can always overload with tags by hiding them. 1086 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1087 // Optimistically assume that an unresolved using decl will 1088 // overload; if it doesn't, we'll have to diagnose during 1089 // template instantiation. 1090 // 1091 // Exception: if the scope is dependent and this is not a class 1092 // member, the using declaration can only introduce an enumerator. 1093 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1094 Match = *I; 1095 return Ovl_NonFunction; 1096 } 1097 } else { 1098 // (C++ 13p1): 1099 // Only function declarations can be overloaded; object and type 1100 // declarations cannot be overloaded. 1101 Match = *I; 1102 return Ovl_NonFunction; 1103 } 1104 } 1105 1106 // C++ [temp.friend]p1: 1107 // For a friend function declaration that is not a template declaration: 1108 // -- if the name of the friend is a qualified or unqualified template-id, 1109 // [...], otherwise 1110 // -- if the name of the friend is a qualified-id and a matching 1111 // non-template function is found in the specified class or namespace, 1112 // the friend declaration refers to that function, otherwise, 1113 // -- if the name of the friend is a qualified-id and a matching function 1114 // template is found in the specified class or namespace, the friend 1115 // declaration refers to the deduced specialization of that function 1116 // template, otherwise 1117 // -- the name shall be an unqualified-id [...] 1118 // If we get here for a qualified friend declaration, we've just reached the 1119 // third bullet. If the type of the friend is dependent, skip this lookup 1120 // until instantiation. 1121 if (New->getFriendObjectKind() && New->getQualifier() && 1122 !New->getDescribedFunctionTemplate() && 1123 !New->getDependentSpecializationInfo() && 1124 !New->getType()->isDependentType()) { 1125 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1126 TemplateSpecResult.addAllDecls(Old); 1127 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1128 /*QualifiedFriend*/true)) { 1129 New->setInvalidDecl(); 1130 return Ovl_Overload; 1131 } 1132 1133 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1134 return Ovl_Match; 1135 } 1136 1137 return Ovl_Overload; 1138 } 1139 1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1141 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1142 bool ConsiderRequiresClauses) { 1143 // C++ [basic.start.main]p2: This function shall not be overloaded. 1144 if (New->isMain()) 1145 return false; 1146 1147 // MSVCRT user defined entry points cannot be overloaded. 1148 if (New->isMSVCRTEntryPoint()) 1149 return false; 1150 1151 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1152 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1153 1154 // C++ [temp.fct]p2: 1155 // A function template can be overloaded with other function templates 1156 // and with normal (non-template) functions. 1157 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1158 return true; 1159 1160 // Is the function New an overload of the function Old? 1161 QualType OldQType = Context.getCanonicalType(Old->getType()); 1162 QualType NewQType = Context.getCanonicalType(New->getType()); 1163 1164 // Compare the signatures (C++ 1.3.10) of the two functions to 1165 // determine whether they are overloads. If we find any mismatch 1166 // in the signature, they are overloads. 1167 1168 // If either of these functions is a K&R-style function (no 1169 // prototype), then we consider them to have matching signatures. 1170 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1171 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1172 return false; 1173 1174 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1175 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1176 1177 // The signature of a function includes the types of its 1178 // parameters (C++ 1.3.10), which includes the presence or absence 1179 // of the ellipsis; see C++ DR 357). 1180 if (OldQType != NewQType && 1181 (OldType->getNumParams() != NewType->getNumParams() || 1182 OldType->isVariadic() != NewType->isVariadic() || 1183 !FunctionParamTypesAreEqual(OldType, NewType))) 1184 return true; 1185 1186 // C++ [temp.over.link]p4: 1187 // The signature of a function template consists of its function 1188 // signature, its return type and its template parameter list. The names 1189 // of the template parameters are significant only for establishing the 1190 // relationship between the template parameters and the rest of the 1191 // signature. 1192 // 1193 // We check the return type and template parameter lists for function 1194 // templates first; the remaining checks follow. 1195 // 1196 // However, we don't consider either of these when deciding whether 1197 // a member introduced by a shadow declaration is hidden. 1198 if (!UseMemberUsingDeclRules && NewTemplate && 1199 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1200 OldTemplate->getTemplateParameters(), 1201 false, TPL_TemplateMatch) || 1202 !Context.hasSameType(Old->getDeclaredReturnType(), 1203 New->getDeclaredReturnType()))) 1204 return true; 1205 1206 // If the function is a class member, its signature includes the 1207 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1208 // 1209 // As part of this, also check whether one of the member functions 1210 // is static, in which case they are not overloads (C++ 1211 // 13.1p2). While not part of the definition of the signature, 1212 // this check is important to determine whether these functions 1213 // can be overloaded. 1214 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1215 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1216 if (OldMethod && NewMethod && 1217 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1218 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1219 if (!UseMemberUsingDeclRules && 1220 (OldMethod->getRefQualifier() == RQ_None || 1221 NewMethod->getRefQualifier() == RQ_None)) { 1222 // C++0x [over.load]p2: 1223 // - Member function declarations with the same name and the same 1224 // parameter-type-list as well as member function template 1225 // declarations with the same name, the same parameter-type-list, and 1226 // the same template parameter lists cannot be overloaded if any of 1227 // them, but not all, have a ref-qualifier (8.3.5). 1228 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1229 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1230 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1231 } 1232 return true; 1233 } 1234 1235 // We may not have applied the implicit const for a constexpr member 1236 // function yet (because we haven't yet resolved whether this is a static 1237 // or non-static member function). Add it now, on the assumption that this 1238 // is a redeclaration of OldMethod. 1239 auto OldQuals = OldMethod->getMethodQualifiers(); 1240 auto NewQuals = NewMethod->getMethodQualifiers(); 1241 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1242 !isa<CXXConstructorDecl>(NewMethod)) 1243 NewQuals.addConst(); 1244 // We do not allow overloading based off of '__restrict'. 1245 OldQuals.removeRestrict(); 1246 NewQuals.removeRestrict(); 1247 if (OldQuals != NewQuals) 1248 return true; 1249 } 1250 1251 // Though pass_object_size is placed on parameters and takes an argument, we 1252 // consider it to be a function-level modifier for the sake of function 1253 // identity. Either the function has one or more parameters with 1254 // pass_object_size or it doesn't. 1255 if (functionHasPassObjectSizeParams(New) != 1256 functionHasPassObjectSizeParams(Old)) 1257 return true; 1258 1259 // enable_if attributes are an order-sensitive part of the signature. 1260 for (specific_attr_iterator<EnableIfAttr> 1261 NewI = New->specific_attr_begin<EnableIfAttr>(), 1262 NewE = New->specific_attr_end<EnableIfAttr>(), 1263 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1264 OldE = Old->specific_attr_end<EnableIfAttr>(); 1265 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1266 if (NewI == NewE || OldI == OldE) 1267 return true; 1268 llvm::FoldingSetNodeID NewID, OldID; 1269 NewI->getCond()->Profile(NewID, Context, true); 1270 OldI->getCond()->Profile(OldID, Context, true); 1271 if (NewID != OldID) 1272 return true; 1273 } 1274 1275 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1276 // Don't allow overloading of destructors. (In theory we could, but it 1277 // would be a giant change to clang.) 1278 if (!isa<CXXDestructorDecl>(New)) { 1279 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1280 OldTarget = IdentifyCUDATarget(Old); 1281 if (NewTarget != CFT_InvalidTarget) { 1282 assert((OldTarget != CFT_InvalidTarget) && 1283 "Unexpected invalid target."); 1284 1285 // Allow overloading of functions with same signature and different CUDA 1286 // target attributes. 1287 if (NewTarget != OldTarget) 1288 return true; 1289 } 1290 } 1291 } 1292 1293 if (ConsiderRequiresClauses) { 1294 Expr *NewRC = New->getTrailingRequiresClause(), 1295 *OldRC = Old->getTrailingRequiresClause(); 1296 if ((NewRC != nullptr) != (OldRC != nullptr)) 1297 // RC are most certainly different - these are overloads. 1298 return true; 1299 1300 if (NewRC) { 1301 llvm::FoldingSetNodeID NewID, OldID; 1302 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1303 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1304 if (NewID != OldID) 1305 // RCs are not equivalent - these are overloads. 1306 return true; 1307 } 1308 } 1309 1310 // The signatures match; this is not an overload. 1311 return false; 1312 } 1313 1314 /// Tries a user-defined conversion from From to ToType. 1315 /// 1316 /// Produces an implicit conversion sequence for when a standard conversion 1317 /// is not an option. See TryImplicitConversion for more information. 1318 static ImplicitConversionSequence 1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1320 bool SuppressUserConversions, 1321 AllowedExplicit AllowExplicit, 1322 bool InOverloadResolution, 1323 bool CStyle, 1324 bool AllowObjCWritebackConversion, 1325 bool AllowObjCConversionOnExplicit) { 1326 ImplicitConversionSequence ICS; 1327 1328 if (SuppressUserConversions) { 1329 // We're not in the case above, so there is no conversion that 1330 // we can perform. 1331 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1332 return ICS; 1333 } 1334 1335 // Attempt user-defined conversion. 1336 OverloadCandidateSet Conversions(From->getExprLoc(), 1337 OverloadCandidateSet::CSK_Normal); 1338 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1339 Conversions, AllowExplicit, 1340 AllowObjCConversionOnExplicit)) { 1341 case OR_Success: 1342 case OR_Deleted: 1343 ICS.setUserDefined(); 1344 // C++ [over.ics.user]p4: 1345 // A conversion of an expression of class type to the same class 1346 // type is given Exact Match rank, and a conversion of an 1347 // expression of class type to a base class of that type is 1348 // given Conversion rank, in spite of the fact that a copy 1349 // constructor (i.e., a user-defined conversion function) is 1350 // called for those cases. 1351 if (CXXConstructorDecl *Constructor 1352 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1353 QualType FromCanon 1354 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1355 QualType ToCanon 1356 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1357 if (Constructor->isCopyConstructor() && 1358 (FromCanon == ToCanon || 1359 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1360 // Turn this into a "standard" conversion sequence, so that it 1361 // gets ranked with standard conversion sequences. 1362 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1363 ICS.setStandard(); 1364 ICS.Standard.setAsIdentityConversion(); 1365 ICS.Standard.setFromType(From->getType()); 1366 ICS.Standard.setAllToTypes(ToType); 1367 ICS.Standard.CopyConstructor = Constructor; 1368 ICS.Standard.FoundCopyConstructor = Found; 1369 if (ToCanon != FromCanon) 1370 ICS.Standard.Second = ICK_Derived_To_Base; 1371 } 1372 } 1373 break; 1374 1375 case OR_Ambiguous: 1376 ICS.setAmbiguous(); 1377 ICS.Ambiguous.setFromType(From->getType()); 1378 ICS.Ambiguous.setToType(ToType); 1379 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1380 Cand != Conversions.end(); ++Cand) 1381 if (Cand->Best) 1382 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1383 break; 1384 1385 // Fall through. 1386 case OR_No_Viable_Function: 1387 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1388 break; 1389 } 1390 1391 return ICS; 1392 } 1393 1394 /// TryImplicitConversion - Attempt to perform an implicit conversion 1395 /// from the given expression (Expr) to the given type (ToType). This 1396 /// function returns an implicit conversion sequence that can be used 1397 /// to perform the initialization. Given 1398 /// 1399 /// void f(float f); 1400 /// void g(int i) { f(i); } 1401 /// 1402 /// this routine would produce an implicit conversion sequence to 1403 /// describe the initialization of f from i, which will be a standard 1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1406 // 1407 /// Note that this routine only determines how the conversion can be 1408 /// performed; it does not actually perform the conversion. As such, 1409 /// it will not produce any diagnostics if no conversion is available, 1410 /// but will instead return an implicit conversion sequence of kind 1411 /// "BadConversion". 1412 /// 1413 /// If @p SuppressUserConversions, then user-defined conversions are 1414 /// not permitted. 1415 /// If @p AllowExplicit, then explicit user-defined conversions are 1416 /// permitted. 1417 /// 1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1419 /// writeback conversion, which allows __autoreleasing id* parameters to 1420 /// be initialized with __strong id* or __weak id* arguments. 1421 static ImplicitConversionSequence 1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1423 bool SuppressUserConversions, 1424 AllowedExplicit AllowExplicit, 1425 bool InOverloadResolution, 1426 bool CStyle, 1427 bool AllowObjCWritebackConversion, 1428 bool AllowObjCConversionOnExplicit) { 1429 ImplicitConversionSequence ICS; 1430 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1431 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1432 ICS.setStandard(); 1433 return ICS; 1434 } 1435 1436 if (!S.getLangOpts().CPlusPlus) { 1437 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1438 return ICS; 1439 } 1440 1441 // C++ [over.ics.user]p4: 1442 // A conversion of an expression of class type to the same class 1443 // type is given Exact Match rank, and a conversion of an 1444 // expression of class type to a base class of that type is 1445 // given Conversion rank, in spite of the fact that a copy/move 1446 // constructor (i.e., a user-defined conversion function) is 1447 // called for those cases. 1448 QualType FromType = From->getType(); 1449 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1450 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1451 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1452 ICS.setStandard(); 1453 ICS.Standard.setAsIdentityConversion(); 1454 ICS.Standard.setFromType(FromType); 1455 ICS.Standard.setAllToTypes(ToType); 1456 1457 // We don't actually check at this point whether there is a valid 1458 // copy/move constructor, since overloading just assumes that it 1459 // exists. When we actually perform initialization, we'll find the 1460 // appropriate constructor to copy the returned object, if needed. 1461 ICS.Standard.CopyConstructor = nullptr; 1462 1463 // Determine whether this is considered a derived-to-base conversion. 1464 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1465 ICS.Standard.Second = ICK_Derived_To_Base; 1466 1467 return ICS; 1468 } 1469 1470 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1471 AllowExplicit, InOverloadResolution, CStyle, 1472 AllowObjCWritebackConversion, 1473 AllowObjCConversionOnExplicit); 1474 } 1475 1476 ImplicitConversionSequence 1477 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1478 bool SuppressUserConversions, 1479 AllowedExplicit AllowExplicit, 1480 bool InOverloadResolution, 1481 bool CStyle, 1482 bool AllowObjCWritebackConversion) { 1483 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1484 AllowExplicit, InOverloadResolution, CStyle, 1485 AllowObjCWritebackConversion, 1486 /*AllowObjCConversionOnExplicit=*/false); 1487 } 1488 1489 /// PerformImplicitConversion - Perform an implicit conversion of the 1490 /// expression From to the type ToType. Returns the 1491 /// converted expression. Flavor is the kind of conversion we're 1492 /// performing, used in the error message. If @p AllowExplicit, 1493 /// explicit user-defined conversions are permitted. 1494 ExprResult 1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, bool AllowExplicit) { 1497 ImplicitConversionSequence ICS; 1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1499 } 1500 1501 ExprResult 1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1503 AssignmentAction Action, bool AllowExplicit, 1504 ImplicitConversionSequence& ICS) { 1505 if (checkPlaceholderForOverload(*this, From)) 1506 return ExprError(); 1507 1508 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1509 bool AllowObjCWritebackConversion 1510 = getLangOpts().ObjCAutoRefCount && 1511 (Action == AA_Passing || Action == AA_Sending); 1512 if (getLangOpts().ObjC) 1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1514 From->getType(), From); 1515 ICS = ::TryImplicitConversion(*this, From, ToType, 1516 /*SuppressUserConversions=*/false, 1517 AllowExplicit ? AllowedExplicit::All 1518 : AllowedExplicit::None, 1519 /*InOverloadResolution=*/false, 1520 /*CStyle=*/false, AllowObjCWritebackConversion, 1521 /*AllowObjCConversionOnExplicit=*/false); 1522 return PerformImplicitConversion(From, ToType, ICS, Action); 1523 } 1524 1525 /// Determine whether the conversion from FromType to ToType is a valid 1526 /// conversion that strips "noexcept" or "noreturn" off the nested function 1527 /// type. 1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1529 QualType &ResultTy) { 1530 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1531 return false; 1532 1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1534 // or F(t noexcept) -> F(t) 1535 // where F adds one of the following at most once: 1536 // - a pointer 1537 // - a member pointer 1538 // - a block pointer 1539 // Changes here need matching changes in FindCompositePointerType. 1540 CanQualType CanTo = Context.getCanonicalType(ToType); 1541 CanQualType CanFrom = Context.getCanonicalType(FromType); 1542 Type::TypeClass TyClass = CanTo->getTypeClass(); 1543 if (TyClass != CanFrom->getTypeClass()) return false; 1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1545 if (TyClass == Type::Pointer) { 1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1548 } else if (TyClass == Type::BlockPointer) { 1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1551 } else if (TyClass == Type::MemberPointer) { 1552 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1553 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1554 // A function pointer conversion cannot change the class of the function. 1555 if (ToMPT->getClass() != FromMPT->getClass()) 1556 return false; 1557 CanTo = ToMPT->getPointeeType(); 1558 CanFrom = FromMPT->getPointeeType(); 1559 } else { 1560 return false; 1561 } 1562 1563 TyClass = CanTo->getTypeClass(); 1564 if (TyClass != CanFrom->getTypeClass()) return false; 1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1566 return false; 1567 } 1568 1569 const auto *FromFn = cast<FunctionType>(CanFrom); 1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1571 1572 const auto *ToFn = cast<FunctionType>(CanTo); 1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1574 1575 bool Changed = false; 1576 1577 // Drop 'noreturn' if not present in target type. 1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1580 Changed = true; 1581 } 1582 1583 // Drop 'noexcept' if not present in target type. 1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1587 FromFn = cast<FunctionType>( 1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1589 EST_None) 1590 .getTypePtr()); 1591 Changed = true; 1592 } 1593 1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1595 // only if the ExtParameterInfo lists of the two function prototypes can be 1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1598 bool CanUseToFPT, CanUseFromFPT; 1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1600 CanUseFromFPT, NewParamInfos) && 1601 CanUseToFPT && !CanUseFromFPT) { 1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1603 ExtInfo.ExtParameterInfos = 1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1606 FromFPT->getParamTypes(), ExtInfo); 1607 FromFn = QT->getAs<FunctionType>(); 1608 Changed = true; 1609 } 1610 } 1611 1612 if (!Changed) 1613 return false; 1614 1615 assert(QualType(FromFn, 0).isCanonical()); 1616 if (QualType(FromFn, 0) != CanTo) return false; 1617 1618 ResultTy = ToType; 1619 return true; 1620 } 1621 1622 /// Determine whether the conversion from FromType to ToType is a valid 1623 /// vector conversion. 1624 /// 1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1626 /// conversion. 1627 static bool IsVectorConversion(Sema &S, QualType FromType, 1628 QualType ToType, ImplicitConversionKind &ICK) { 1629 // We need at least one of these types to be a vector type to have a vector 1630 // conversion. 1631 if (!ToType->isVectorType() && !FromType->isVectorType()) 1632 return false; 1633 1634 // Identical types require no conversions. 1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1636 return false; 1637 1638 // There are no conversions between extended vector types, only identity. 1639 if (ToType->isExtVectorType()) { 1640 // There are no conversions between extended vector types other than the 1641 // identity conversion. 1642 if (FromType->isExtVectorType()) 1643 return false; 1644 1645 // Vector splat from any arithmetic type to a vector. 1646 if (FromType->isArithmeticType()) { 1647 ICK = ICK_Vector_Splat; 1648 return true; 1649 } 1650 } 1651 1652 // We can perform the conversion between vector types in the following cases: 1653 // 1)vector types are equivalent AltiVec and GCC vector types 1654 // 2)lax vector conversions are permitted and the vector types are of the 1655 // same size 1656 // 3)the destination type does not have the ARM MVE strict-polymorphism 1657 // attribute, which inhibits lax vector conversion for overload resolution 1658 // only 1659 if (ToType->isVectorType() && FromType->isVectorType()) { 1660 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1661 (S.isLaxVectorConversion(FromType, ToType) && 1662 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1663 ICK = ICK_Vector_Conversion; 1664 return true; 1665 } 1666 } 1667 1668 return false; 1669 } 1670 1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1672 bool InOverloadResolution, 1673 StandardConversionSequence &SCS, 1674 bool CStyle); 1675 1676 /// IsStandardConversion - Determines whether there is a standard 1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1678 /// expression From to the type ToType. Standard conversion sequences 1679 /// only consider non-class types; for conversions that involve class 1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1681 /// contain the standard conversion sequence required to perform this 1682 /// conversion and this routine will return true. Otherwise, this 1683 /// routine will return false and the value of SCS is unspecified. 1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1685 bool InOverloadResolution, 1686 StandardConversionSequence &SCS, 1687 bool CStyle, 1688 bool AllowObjCWritebackConversion) { 1689 QualType FromType = From->getType(); 1690 1691 // Standard conversions (C++ [conv]) 1692 SCS.setAsIdentityConversion(); 1693 SCS.IncompatibleObjC = false; 1694 SCS.setFromType(FromType); 1695 SCS.CopyConstructor = nullptr; 1696 1697 // There are no standard conversions for class types in C++, so 1698 // abort early. When overloading in C, however, we do permit them. 1699 if (S.getLangOpts().CPlusPlus && 1700 (FromType->isRecordType() || ToType->isRecordType())) 1701 return false; 1702 1703 // The first conversion can be an lvalue-to-rvalue conversion, 1704 // array-to-pointer conversion, or function-to-pointer conversion 1705 // (C++ 4p1). 1706 1707 if (FromType == S.Context.OverloadTy) { 1708 DeclAccessPair AccessPair; 1709 if (FunctionDecl *Fn 1710 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1711 AccessPair)) { 1712 // We were able to resolve the address of the overloaded function, 1713 // so we can convert to the type of that function. 1714 FromType = Fn->getType(); 1715 SCS.setFromType(FromType); 1716 1717 // we can sometimes resolve &foo<int> regardless of ToType, so check 1718 // if the type matches (identity) or we are converting to bool 1719 if (!S.Context.hasSameUnqualifiedType( 1720 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1721 QualType resultTy; 1722 // if the function type matches except for [[noreturn]], it's ok 1723 if (!S.IsFunctionConversion(FromType, 1724 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1725 // otherwise, only a boolean conversion is standard 1726 if (!ToType->isBooleanType()) 1727 return false; 1728 } 1729 1730 // Check if the "from" expression is taking the address of an overloaded 1731 // function and recompute the FromType accordingly. Take advantage of the 1732 // fact that non-static member functions *must* have such an address-of 1733 // expression. 1734 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1735 if (Method && !Method->isStatic()) { 1736 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1737 "Non-unary operator on non-static member address"); 1738 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1739 == UO_AddrOf && 1740 "Non-address-of operator on non-static member address"); 1741 const Type *ClassType 1742 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1743 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1744 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1745 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1746 UO_AddrOf && 1747 "Non-address-of operator for overloaded function expression"); 1748 FromType = S.Context.getPointerType(FromType); 1749 } 1750 1751 // Check that we've computed the proper type after overload resolution. 1752 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1753 // be calling it from within an NDEBUG block. 1754 assert(S.Context.hasSameType( 1755 FromType, 1756 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1757 } else { 1758 return false; 1759 } 1760 } 1761 // Lvalue-to-rvalue conversion (C++11 4.1): 1762 // A glvalue (3.10) of a non-function, non-array type T can 1763 // be converted to a prvalue. 1764 bool argIsLValue = From->isGLValue(); 1765 if (argIsLValue && 1766 !FromType->isFunctionType() && !FromType->isArrayType() && 1767 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1768 SCS.First = ICK_Lvalue_To_Rvalue; 1769 1770 // C11 6.3.2.1p2: 1771 // ... if the lvalue has atomic type, the value has the non-atomic version 1772 // of the type of the lvalue ... 1773 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1774 FromType = Atomic->getValueType(); 1775 1776 // If T is a non-class type, the type of the rvalue is the 1777 // cv-unqualified version of T. Otherwise, the type of the rvalue 1778 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1779 // just strip the qualifiers because they don't matter. 1780 FromType = FromType.getUnqualifiedType(); 1781 } else if (FromType->isArrayType()) { 1782 // Array-to-pointer conversion (C++ 4.2) 1783 SCS.First = ICK_Array_To_Pointer; 1784 1785 // An lvalue or rvalue of type "array of N T" or "array of unknown 1786 // bound of T" can be converted to an rvalue of type "pointer to 1787 // T" (C++ 4.2p1). 1788 FromType = S.Context.getArrayDecayedType(FromType); 1789 1790 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1791 // This conversion is deprecated in C++03 (D.4) 1792 SCS.DeprecatedStringLiteralToCharPtr = true; 1793 1794 // For the purpose of ranking in overload resolution 1795 // (13.3.3.1.1), this conversion is considered an 1796 // array-to-pointer conversion followed by a qualification 1797 // conversion (4.4). (C++ 4.2p2) 1798 SCS.Second = ICK_Identity; 1799 SCS.Third = ICK_Qualification; 1800 SCS.QualificationIncludesObjCLifetime = false; 1801 SCS.setAllToTypes(FromType); 1802 return true; 1803 } 1804 } else if (FromType->isFunctionType() && argIsLValue) { 1805 // Function-to-pointer conversion (C++ 4.3). 1806 SCS.First = ICK_Function_To_Pointer; 1807 1808 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1809 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1810 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1811 return false; 1812 1813 // An lvalue of function type T can be converted to an rvalue of 1814 // type "pointer to T." The result is a pointer to the 1815 // function. (C++ 4.3p1). 1816 FromType = S.Context.getPointerType(FromType); 1817 } else { 1818 // We don't require any conversions for the first step. 1819 SCS.First = ICK_Identity; 1820 } 1821 SCS.setToType(0, FromType); 1822 1823 // The second conversion can be an integral promotion, floating 1824 // point promotion, integral conversion, floating point conversion, 1825 // floating-integral conversion, pointer conversion, 1826 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1827 // For overloading in C, this can also be a "compatible-type" 1828 // conversion. 1829 bool IncompatibleObjC = false; 1830 ImplicitConversionKind SecondICK = ICK_Identity; 1831 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1832 // The unqualified versions of the types are the same: there's no 1833 // conversion to do. 1834 SCS.Second = ICK_Identity; 1835 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1836 // Integral promotion (C++ 4.5). 1837 SCS.Second = ICK_Integral_Promotion; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1840 // Floating point promotion (C++ 4.6). 1841 SCS.Second = ICK_Floating_Promotion; 1842 FromType = ToType.getUnqualifiedType(); 1843 } else if (S.IsComplexPromotion(FromType, ToType)) { 1844 // Complex promotion (Clang extension) 1845 SCS.Second = ICK_Complex_Promotion; 1846 FromType = ToType.getUnqualifiedType(); 1847 } else if (ToType->isBooleanType() && 1848 (FromType->isArithmeticType() || 1849 FromType->isAnyPointerType() || 1850 FromType->isBlockPointerType() || 1851 FromType->isMemberPointerType())) { 1852 // Boolean conversions (C++ 4.12). 1853 SCS.Second = ICK_Boolean_Conversion; 1854 FromType = S.Context.BoolTy; 1855 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1856 ToType->isIntegralType(S.Context)) { 1857 // Integral conversions (C++ 4.7). 1858 SCS.Second = ICK_Integral_Conversion; 1859 FromType = ToType.getUnqualifiedType(); 1860 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1861 // Complex conversions (C99 6.3.1.6) 1862 SCS.Second = ICK_Complex_Conversion; 1863 FromType = ToType.getUnqualifiedType(); 1864 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1865 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1866 // Complex-real conversions (C99 6.3.1.7) 1867 SCS.Second = ICK_Complex_Real; 1868 FromType = ToType.getUnqualifiedType(); 1869 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1870 // FIXME: disable conversions between long double and __float128 if 1871 // their representation is different until there is back end support 1872 // We of course allow this conversion if long double is really double. 1873 if (&S.Context.getFloatTypeSemantics(FromType) != 1874 &S.Context.getFloatTypeSemantics(ToType)) { 1875 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1876 ToType == S.Context.LongDoubleTy) || 1877 (FromType == S.Context.LongDoubleTy && 1878 ToType == S.Context.Float128Ty)); 1879 if (Float128AndLongDouble && 1880 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1881 &llvm::APFloat::PPCDoubleDouble())) 1882 return false; 1883 } 1884 // Floating point conversions (C++ 4.8). 1885 SCS.Second = ICK_Floating_Conversion; 1886 FromType = ToType.getUnqualifiedType(); 1887 } else if ((FromType->isRealFloatingType() && 1888 ToType->isIntegralType(S.Context)) || 1889 (FromType->isIntegralOrUnscopedEnumerationType() && 1890 ToType->isRealFloatingType())) { 1891 // Floating-integral conversions (C++ 4.9). 1892 SCS.Second = ICK_Floating_Integral; 1893 FromType = ToType.getUnqualifiedType(); 1894 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1895 SCS.Second = ICK_Block_Pointer_Conversion; 1896 } else if (AllowObjCWritebackConversion && 1897 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1898 SCS.Second = ICK_Writeback_Conversion; 1899 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1900 FromType, IncompatibleObjC)) { 1901 // Pointer conversions (C++ 4.10). 1902 SCS.Second = ICK_Pointer_Conversion; 1903 SCS.IncompatibleObjC = IncompatibleObjC; 1904 FromType = FromType.getUnqualifiedType(); 1905 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1906 InOverloadResolution, FromType)) { 1907 // Pointer to member conversions (4.11). 1908 SCS.Second = ICK_Pointer_Member; 1909 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1910 SCS.Second = SecondICK; 1911 FromType = ToType.getUnqualifiedType(); 1912 } else if (!S.getLangOpts().CPlusPlus && 1913 S.Context.typesAreCompatible(ToType, FromType)) { 1914 // Compatible conversions (Clang extension for C function overloading) 1915 SCS.Second = ICK_Compatible_Conversion; 1916 FromType = ToType.getUnqualifiedType(); 1917 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1918 InOverloadResolution, 1919 SCS, CStyle)) { 1920 SCS.Second = ICK_TransparentUnionConversion; 1921 FromType = ToType; 1922 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1923 CStyle)) { 1924 // tryAtomicConversion has updated the standard conversion sequence 1925 // appropriately. 1926 return true; 1927 } else if (ToType->isEventT() && 1928 From->isIntegerConstantExpr(S.getASTContext()) && 1929 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1930 SCS.Second = ICK_Zero_Event_Conversion; 1931 FromType = ToType; 1932 } else if (ToType->isQueueT() && 1933 From->isIntegerConstantExpr(S.getASTContext()) && 1934 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1935 SCS.Second = ICK_Zero_Queue_Conversion; 1936 FromType = ToType; 1937 } else if (ToType->isSamplerT() && 1938 From->isIntegerConstantExpr(S.getASTContext())) { 1939 SCS.Second = ICK_Compatible_Conversion; 1940 FromType = ToType; 1941 } else { 1942 // No second conversion required. 1943 SCS.Second = ICK_Identity; 1944 } 1945 SCS.setToType(1, FromType); 1946 1947 // The third conversion can be a function pointer conversion or a 1948 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1949 bool ObjCLifetimeConversion; 1950 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1951 // Function pointer conversions (removing 'noexcept') including removal of 1952 // 'noreturn' (Clang extension). 1953 SCS.Third = ICK_Function_Conversion; 1954 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1955 ObjCLifetimeConversion)) { 1956 SCS.Third = ICK_Qualification; 1957 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1958 FromType = ToType; 1959 } else { 1960 // No conversion required 1961 SCS.Third = ICK_Identity; 1962 } 1963 1964 // C++ [over.best.ics]p6: 1965 // [...] Any difference in top-level cv-qualification is 1966 // subsumed by the initialization itself and does not constitute 1967 // a conversion. [...] 1968 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1969 QualType CanonTo = S.Context.getCanonicalType(ToType); 1970 if (CanonFrom.getLocalUnqualifiedType() 1971 == CanonTo.getLocalUnqualifiedType() && 1972 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1973 FromType = ToType; 1974 CanonFrom = CanonTo; 1975 } 1976 1977 SCS.setToType(2, FromType); 1978 1979 if (CanonFrom == CanonTo) 1980 return true; 1981 1982 // If we have not converted the argument type to the parameter type, 1983 // this is a bad conversion sequence, unless we're resolving an overload in C. 1984 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1985 return false; 1986 1987 ExprResult ER = ExprResult{From}; 1988 Sema::AssignConvertType Conv = 1989 S.CheckSingleAssignmentConstraints(ToType, ER, 1990 /*Diagnose=*/false, 1991 /*DiagnoseCFAudited=*/false, 1992 /*ConvertRHS=*/false); 1993 ImplicitConversionKind SecondConv; 1994 switch (Conv) { 1995 case Sema::Compatible: 1996 SecondConv = ICK_C_Only_Conversion; 1997 break; 1998 // For our purposes, discarding qualifiers is just as bad as using an 1999 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2000 // qualifiers, as well. 2001 case Sema::CompatiblePointerDiscardsQualifiers: 2002 case Sema::IncompatiblePointer: 2003 case Sema::IncompatiblePointerSign: 2004 SecondConv = ICK_Incompatible_Pointer_Conversion; 2005 break; 2006 default: 2007 return false; 2008 } 2009 2010 // First can only be an lvalue conversion, so we pretend that this was the 2011 // second conversion. First should already be valid from earlier in the 2012 // function. 2013 SCS.Second = SecondConv; 2014 SCS.setToType(1, ToType); 2015 2016 // Third is Identity, because Second should rank us worse than any other 2017 // conversion. This could also be ICK_Qualification, but it's simpler to just 2018 // lump everything in with the second conversion, and we don't gain anything 2019 // from making this ICK_Qualification. 2020 SCS.Third = ICK_Identity; 2021 SCS.setToType(2, ToType); 2022 return true; 2023 } 2024 2025 static bool 2026 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2027 QualType &ToType, 2028 bool InOverloadResolution, 2029 StandardConversionSequence &SCS, 2030 bool CStyle) { 2031 2032 const RecordType *UT = ToType->getAsUnionType(); 2033 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2034 return false; 2035 // The field to initialize within the transparent union. 2036 RecordDecl *UD = UT->getDecl(); 2037 // It's compatible if the expression matches any of the fields. 2038 for (const auto *it : UD->fields()) { 2039 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2040 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2041 ToType = it->getType(); 2042 return true; 2043 } 2044 } 2045 return false; 2046 } 2047 2048 /// IsIntegralPromotion - Determines whether the conversion from the 2049 /// expression From (whose potentially-adjusted type is FromType) to 2050 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2051 /// sets PromotedType to the promoted type. 2052 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2053 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2054 // All integers are built-in. 2055 if (!To) { 2056 return false; 2057 } 2058 2059 // An rvalue of type char, signed char, unsigned char, short int, or 2060 // unsigned short int can be converted to an rvalue of type int if 2061 // int can represent all the values of the source type; otherwise, 2062 // the source rvalue can be converted to an rvalue of type unsigned 2063 // int (C++ 4.5p1). 2064 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2065 !FromType->isEnumeralType()) { 2066 if (// We can promote any signed, promotable integer type to an int 2067 (FromType->isSignedIntegerType() || 2068 // We can promote any unsigned integer type whose size is 2069 // less than int to an int. 2070 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2071 return To->getKind() == BuiltinType::Int; 2072 } 2073 2074 return To->getKind() == BuiltinType::UInt; 2075 } 2076 2077 // C++11 [conv.prom]p3: 2078 // A prvalue of an unscoped enumeration type whose underlying type is not 2079 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2080 // following types that can represent all the values of the enumeration 2081 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2082 // unsigned int, long int, unsigned long int, long long int, or unsigned 2083 // long long int. If none of the types in that list can represent all the 2084 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2085 // type can be converted to an rvalue a prvalue of the extended integer type 2086 // with lowest integer conversion rank (4.13) greater than the rank of long 2087 // long in which all the values of the enumeration can be represented. If 2088 // there are two such extended types, the signed one is chosen. 2089 // C++11 [conv.prom]p4: 2090 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2091 // can be converted to a prvalue of its underlying type. Moreover, if 2092 // integral promotion can be applied to its underlying type, a prvalue of an 2093 // unscoped enumeration type whose underlying type is fixed can also be 2094 // converted to a prvalue of the promoted underlying type. 2095 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2096 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2097 // provided for a scoped enumeration. 2098 if (FromEnumType->getDecl()->isScoped()) 2099 return false; 2100 2101 // We can perform an integral promotion to the underlying type of the enum, 2102 // even if that's not the promoted type. Note that the check for promoting 2103 // the underlying type is based on the type alone, and does not consider 2104 // the bitfield-ness of the actual source expression. 2105 if (FromEnumType->getDecl()->isFixed()) { 2106 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2107 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2108 IsIntegralPromotion(nullptr, Underlying, ToType); 2109 } 2110 2111 // We have already pre-calculated the promotion type, so this is trivial. 2112 if (ToType->isIntegerType() && 2113 isCompleteType(From->getBeginLoc(), FromType)) 2114 return Context.hasSameUnqualifiedType( 2115 ToType, FromEnumType->getDecl()->getPromotionType()); 2116 2117 // C++ [conv.prom]p5: 2118 // If the bit-field has an enumerated type, it is treated as any other 2119 // value of that type for promotion purposes. 2120 // 2121 // ... so do not fall through into the bit-field checks below in C++. 2122 if (getLangOpts().CPlusPlus) 2123 return false; 2124 } 2125 2126 // C++0x [conv.prom]p2: 2127 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2128 // to an rvalue a prvalue of the first of the following types that can 2129 // represent all the values of its underlying type: int, unsigned int, 2130 // long int, unsigned long int, long long int, or unsigned long long int. 2131 // If none of the types in that list can represent all the values of its 2132 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2133 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2134 // type. 2135 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2136 ToType->isIntegerType()) { 2137 // Determine whether the type we're converting from is signed or 2138 // unsigned. 2139 bool FromIsSigned = FromType->isSignedIntegerType(); 2140 uint64_t FromSize = Context.getTypeSize(FromType); 2141 2142 // The types we'll try to promote to, in the appropriate 2143 // order. Try each of these types. 2144 QualType PromoteTypes[6] = { 2145 Context.IntTy, Context.UnsignedIntTy, 2146 Context.LongTy, Context.UnsignedLongTy , 2147 Context.LongLongTy, Context.UnsignedLongLongTy 2148 }; 2149 for (int Idx = 0; Idx < 6; ++Idx) { 2150 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2151 if (FromSize < ToSize || 2152 (FromSize == ToSize && 2153 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2154 // We found the type that we can promote to. If this is the 2155 // type we wanted, we have a promotion. Otherwise, no 2156 // promotion. 2157 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2158 } 2159 } 2160 } 2161 2162 // An rvalue for an integral bit-field (9.6) can be converted to an 2163 // rvalue of type int if int can represent all the values of the 2164 // bit-field; otherwise, it can be converted to unsigned int if 2165 // unsigned int can represent all the values of the bit-field. If 2166 // the bit-field is larger yet, no integral promotion applies to 2167 // it. If the bit-field has an enumerated type, it is treated as any 2168 // other value of that type for promotion purposes (C++ 4.5p3). 2169 // FIXME: We should delay checking of bit-fields until we actually perform the 2170 // conversion. 2171 // 2172 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2173 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2174 // bit-fields and those whose underlying type is larger than int) for GCC 2175 // compatibility. 2176 if (From) { 2177 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2178 llvm::APSInt BitWidth; 2179 if (FromType->isIntegralType(Context) && 2180 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2181 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2182 ToSize = Context.getTypeSize(ToType); 2183 2184 // Are we promoting to an int from a bitfield that fits in an int? 2185 if (BitWidth < ToSize || 2186 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2187 return To->getKind() == BuiltinType::Int; 2188 } 2189 2190 // Are we promoting to an unsigned int from an unsigned bitfield 2191 // that fits into an unsigned int? 2192 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2193 return To->getKind() == BuiltinType::UInt; 2194 } 2195 2196 return false; 2197 } 2198 } 2199 } 2200 2201 // An rvalue of type bool can be converted to an rvalue of type int, 2202 // with false becoming zero and true becoming one (C++ 4.5p4). 2203 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2204 return true; 2205 } 2206 2207 return false; 2208 } 2209 2210 /// IsFloatingPointPromotion - Determines whether the conversion from 2211 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2212 /// returns true and sets PromotedType to the promoted type. 2213 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2214 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2215 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2216 /// An rvalue of type float can be converted to an rvalue of type 2217 /// double. (C++ 4.6p1). 2218 if (FromBuiltin->getKind() == BuiltinType::Float && 2219 ToBuiltin->getKind() == BuiltinType::Double) 2220 return true; 2221 2222 // C99 6.3.1.5p1: 2223 // When a float is promoted to double or long double, or a 2224 // double is promoted to long double [...]. 2225 if (!getLangOpts().CPlusPlus && 2226 (FromBuiltin->getKind() == BuiltinType::Float || 2227 FromBuiltin->getKind() == BuiltinType::Double) && 2228 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2229 ToBuiltin->getKind() == BuiltinType::Float128)) 2230 return true; 2231 2232 // Half can be promoted to float. 2233 if (!getLangOpts().NativeHalfType && 2234 FromBuiltin->getKind() == BuiltinType::Half && 2235 ToBuiltin->getKind() == BuiltinType::Float) 2236 return true; 2237 } 2238 2239 return false; 2240 } 2241 2242 /// Determine if a conversion is a complex promotion. 2243 /// 2244 /// A complex promotion is defined as a complex -> complex conversion 2245 /// where the conversion between the underlying real types is a 2246 /// floating-point or integral promotion. 2247 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2248 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2249 if (!FromComplex) 2250 return false; 2251 2252 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2253 if (!ToComplex) 2254 return false; 2255 2256 return IsFloatingPointPromotion(FromComplex->getElementType(), 2257 ToComplex->getElementType()) || 2258 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2259 ToComplex->getElementType()); 2260 } 2261 2262 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2263 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2264 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2265 /// if non-empty, will be a pointer to ToType that may or may not have 2266 /// the right set of qualifiers on its pointee. 2267 /// 2268 static QualType 2269 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2270 QualType ToPointee, QualType ToType, 2271 ASTContext &Context, 2272 bool StripObjCLifetime = false) { 2273 assert((FromPtr->getTypeClass() == Type::Pointer || 2274 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2275 "Invalid similarly-qualified pointer type"); 2276 2277 /// Conversions to 'id' subsume cv-qualifier conversions. 2278 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2279 return ToType.getUnqualifiedType(); 2280 2281 QualType CanonFromPointee 2282 = Context.getCanonicalType(FromPtr->getPointeeType()); 2283 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2284 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2285 2286 if (StripObjCLifetime) 2287 Quals.removeObjCLifetime(); 2288 2289 // Exact qualifier match -> return the pointer type we're converting to. 2290 if (CanonToPointee.getLocalQualifiers() == Quals) { 2291 // ToType is exactly what we need. Return it. 2292 if (!ToType.isNull()) 2293 return ToType.getUnqualifiedType(); 2294 2295 // Build a pointer to ToPointee. It has the right qualifiers 2296 // already. 2297 if (isa<ObjCObjectPointerType>(ToType)) 2298 return Context.getObjCObjectPointerType(ToPointee); 2299 return Context.getPointerType(ToPointee); 2300 } 2301 2302 // Just build a canonical type that has the right qualifiers. 2303 QualType QualifiedCanonToPointee 2304 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2305 2306 if (isa<ObjCObjectPointerType>(ToType)) 2307 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2308 return Context.getPointerType(QualifiedCanonToPointee); 2309 } 2310 2311 static bool isNullPointerConstantForConversion(Expr *Expr, 2312 bool InOverloadResolution, 2313 ASTContext &Context) { 2314 // Handle value-dependent integral null pointer constants correctly. 2315 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2316 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2317 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2318 return !InOverloadResolution; 2319 2320 return Expr->isNullPointerConstant(Context, 2321 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2322 : Expr::NPC_ValueDependentIsNull); 2323 } 2324 2325 /// IsPointerConversion - Determines whether the conversion of the 2326 /// expression From, which has the (possibly adjusted) type FromType, 2327 /// can be converted to the type ToType via a pointer conversion (C++ 2328 /// 4.10). If so, returns true and places the converted type (that 2329 /// might differ from ToType in its cv-qualifiers at some level) into 2330 /// ConvertedType. 2331 /// 2332 /// This routine also supports conversions to and from block pointers 2333 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2334 /// pointers to interfaces. FIXME: Once we've determined the 2335 /// appropriate overloading rules for Objective-C, we may want to 2336 /// split the Objective-C checks into a different routine; however, 2337 /// GCC seems to consider all of these conversions to be pointer 2338 /// conversions, so for now they live here. IncompatibleObjC will be 2339 /// set if the conversion is an allowed Objective-C conversion that 2340 /// should result in a warning. 2341 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2342 bool InOverloadResolution, 2343 QualType& ConvertedType, 2344 bool &IncompatibleObjC) { 2345 IncompatibleObjC = false; 2346 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2347 IncompatibleObjC)) 2348 return true; 2349 2350 // Conversion from a null pointer constant to any Objective-C pointer type. 2351 if (ToType->isObjCObjectPointerType() && 2352 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2353 ConvertedType = ToType; 2354 return true; 2355 } 2356 2357 // Blocks: Block pointers can be converted to void*. 2358 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2359 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2360 ConvertedType = ToType; 2361 return true; 2362 } 2363 // Blocks: A null pointer constant can be converted to a block 2364 // pointer type. 2365 if (ToType->isBlockPointerType() && 2366 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2367 ConvertedType = ToType; 2368 return true; 2369 } 2370 2371 // If the left-hand-side is nullptr_t, the right side can be a null 2372 // pointer constant. 2373 if (ToType->isNullPtrType() && 2374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2375 ConvertedType = ToType; 2376 return true; 2377 } 2378 2379 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2380 if (!ToTypePtr) 2381 return false; 2382 2383 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2384 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2385 ConvertedType = ToType; 2386 return true; 2387 } 2388 2389 // Beyond this point, both types need to be pointers 2390 // , including objective-c pointers. 2391 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2392 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2393 !getLangOpts().ObjCAutoRefCount) { 2394 ConvertedType = BuildSimilarlyQualifiedPointerType( 2395 FromType->getAs<ObjCObjectPointerType>(), 2396 ToPointeeType, 2397 ToType, Context); 2398 return true; 2399 } 2400 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2401 if (!FromTypePtr) 2402 return false; 2403 2404 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2405 2406 // If the unqualified pointee types are the same, this can't be a 2407 // pointer conversion, so don't do all of the work below. 2408 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2409 return false; 2410 2411 // An rvalue of type "pointer to cv T," where T is an object type, 2412 // can be converted to an rvalue of type "pointer to cv void" (C++ 2413 // 4.10p2). 2414 if (FromPointeeType->isIncompleteOrObjectType() && 2415 ToPointeeType->isVoidType()) { 2416 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2417 ToPointeeType, 2418 ToType, Context, 2419 /*StripObjCLifetime=*/true); 2420 return true; 2421 } 2422 2423 // MSVC allows implicit function to void* type conversion. 2424 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2425 ToPointeeType->isVoidType()) { 2426 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2427 ToPointeeType, 2428 ToType, Context); 2429 return true; 2430 } 2431 2432 // When we're overloading in C, we allow a special kind of pointer 2433 // conversion for compatible-but-not-identical pointee types. 2434 if (!getLangOpts().CPlusPlus && 2435 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2437 ToPointeeType, 2438 ToType, Context); 2439 return true; 2440 } 2441 2442 // C++ [conv.ptr]p3: 2443 // 2444 // An rvalue of type "pointer to cv D," where D is a class type, 2445 // can be converted to an rvalue of type "pointer to cv B," where 2446 // B is a base class (clause 10) of D. If B is an inaccessible 2447 // (clause 11) or ambiguous (10.2) base class of D, a program that 2448 // necessitates this conversion is ill-formed. The result of the 2449 // conversion is a pointer to the base class sub-object of the 2450 // derived class object. The null pointer value is converted to 2451 // the null pointer value of the destination type. 2452 // 2453 // Note that we do not check for ambiguity or inaccessibility 2454 // here. That is handled by CheckPointerConversion. 2455 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2456 ToPointeeType->isRecordType() && 2457 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2458 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2459 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2460 ToPointeeType, 2461 ToType, Context); 2462 return true; 2463 } 2464 2465 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2466 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2467 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2468 ToPointeeType, 2469 ToType, Context); 2470 return true; 2471 } 2472 2473 return false; 2474 } 2475 2476 /// Adopt the given qualifiers for the given type. 2477 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2478 Qualifiers TQs = T.getQualifiers(); 2479 2480 // Check whether qualifiers already match. 2481 if (TQs == Qs) 2482 return T; 2483 2484 if (Qs.compatiblyIncludes(TQs)) 2485 return Context.getQualifiedType(T, Qs); 2486 2487 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2488 } 2489 2490 /// isObjCPointerConversion - Determines whether this is an 2491 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2492 /// with the same arguments and return values. 2493 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2494 QualType& ConvertedType, 2495 bool &IncompatibleObjC) { 2496 if (!getLangOpts().ObjC) 2497 return false; 2498 2499 // The set of qualifiers on the type we're converting from. 2500 Qualifiers FromQualifiers = FromType.getQualifiers(); 2501 2502 // First, we handle all conversions on ObjC object pointer types. 2503 const ObjCObjectPointerType* ToObjCPtr = 2504 ToType->getAs<ObjCObjectPointerType>(); 2505 const ObjCObjectPointerType *FromObjCPtr = 2506 FromType->getAs<ObjCObjectPointerType>(); 2507 2508 if (ToObjCPtr && FromObjCPtr) { 2509 // If the pointee types are the same (ignoring qualifications), 2510 // then this is not a pointer conversion. 2511 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2512 FromObjCPtr->getPointeeType())) 2513 return false; 2514 2515 // Conversion between Objective-C pointers. 2516 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2517 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2518 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2519 if (getLangOpts().CPlusPlus && LHS && RHS && 2520 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2521 FromObjCPtr->getPointeeType())) 2522 return false; 2523 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2524 ToObjCPtr->getPointeeType(), 2525 ToType, Context); 2526 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2527 return true; 2528 } 2529 2530 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2531 // Okay: this is some kind of implicit downcast of Objective-C 2532 // interfaces, which is permitted. However, we're going to 2533 // complain about it. 2534 IncompatibleObjC = true; 2535 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2536 ToObjCPtr->getPointeeType(), 2537 ToType, Context); 2538 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2539 return true; 2540 } 2541 } 2542 // Beyond this point, both types need to be C pointers or block pointers. 2543 QualType ToPointeeType; 2544 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2545 ToPointeeType = ToCPtr->getPointeeType(); 2546 else if (const BlockPointerType *ToBlockPtr = 2547 ToType->getAs<BlockPointerType>()) { 2548 // Objective C++: We're able to convert from a pointer to any object 2549 // to a block pointer type. 2550 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2551 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2552 return true; 2553 } 2554 ToPointeeType = ToBlockPtr->getPointeeType(); 2555 } 2556 else if (FromType->getAs<BlockPointerType>() && 2557 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2558 // Objective C++: We're able to convert from a block pointer type to a 2559 // pointer to any object. 2560 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2561 return true; 2562 } 2563 else 2564 return false; 2565 2566 QualType FromPointeeType; 2567 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2568 FromPointeeType = FromCPtr->getPointeeType(); 2569 else if (const BlockPointerType *FromBlockPtr = 2570 FromType->getAs<BlockPointerType>()) 2571 FromPointeeType = FromBlockPtr->getPointeeType(); 2572 else 2573 return false; 2574 2575 // If we have pointers to pointers, recursively check whether this 2576 // is an Objective-C conversion. 2577 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2578 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2579 IncompatibleObjC)) { 2580 // We always complain about this conversion. 2581 IncompatibleObjC = true; 2582 ConvertedType = Context.getPointerType(ConvertedType); 2583 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2584 return true; 2585 } 2586 // Allow conversion of pointee being objective-c pointer to another one; 2587 // as in I* to id. 2588 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2589 ToPointeeType->getAs<ObjCObjectPointerType>() && 2590 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2591 IncompatibleObjC)) { 2592 2593 ConvertedType = Context.getPointerType(ConvertedType); 2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2595 return true; 2596 } 2597 2598 // If we have pointers to functions or blocks, check whether the only 2599 // differences in the argument and result types are in Objective-C 2600 // pointer conversions. If so, we permit the conversion (but 2601 // complain about it). 2602 const FunctionProtoType *FromFunctionType 2603 = FromPointeeType->getAs<FunctionProtoType>(); 2604 const FunctionProtoType *ToFunctionType 2605 = ToPointeeType->getAs<FunctionProtoType>(); 2606 if (FromFunctionType && ToFunctionType) { 2607 // If the function types are exactly the same, this isn't an 2608 // Objective-C pointer conversion. 2609 if (Context.getCanonicalType(FromPointeeType) 2610 == Context.getCanonicalType(ToPointeeType)) 2611 return false; 2612 2613 // Perform the quick checks that will tell us whether these 2614 // function types are obviously different. 2615 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2616 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2617 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2618 return false; 2619 2620 bool HasObjCConversion = false; 2621 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2622 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2623 // Okay, the types match exactly. Nothing to do. 2624 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2625 ToFunctionType->getReturnType(), 2626 ConvertedType, IncompatibleObjC)) { 2627 // Okay, we have an Objective-C pointer conversion. 2628 HasObjCConversion = true; 2629 } else { 2630 // Function types are too different. Abort. 2631 return false; 2632 } 2633 2634 // Check argument types. 2635 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2636 ArgIdx != NumArgs; ++ArgIdx) { 2637 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2638 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2639 if (Context.getCanonicalType(FromArgType) 2640 == Context.getCanonicalType(ToArgType)) { 2641 // Okay, the types match exactly. Nothing to do. 2642 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2643 ConvertedType, IncompatibleObjC)) { 2644 // Okay, we have an Objective-C pointer conversion. 2645 HasObjCConversion = true; 2646 } else { 2647 // Argument types are too different. Abort. 2648 return false; 2649 } 2650 } 2651 2652 if (HasObjCConversion) { 2653 // We had an Objective-C conversion. Allow this pointer 2654 // conversion, but complain about it. 2655 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2656 IncompatibleObjC = true; 2657 return true; 2658 } 2659 } 2660 2661 return false; 2662 } 2663 2664 /// Determine whether this is an Objective-C writeback conversion, 2665 /// used for parameter passing when performing automatic reference counting. 2666 /// 2667 /// \param FromType The type we're converting form. 2668 /// 2669 /// \param ToType The type we're converting to. 2670 /// 2671 /// \param ConvertedType The type that will be produced after applying 2672 /// this conversion. 2673 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2674 QualType &ConvertedType) { 2675 if (!getLangOpts().ObjCAutoRefCount || 2676 Context.hasSameUnqualifiedType(FromType, ToType)) 2677 return false; 2678 2679 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2680 QualType ToPointee; 2681 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2682 ToPointee = ToPointer->getPointeeType(); 2683 else 2684 return false; 2685 2686 Qualifiers ToQuals = ToPointee.getQualifiers(); 2687 if (!ToPointee->isObjCLifetimeType() || 2688 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2689 !ToQuals.withoutObjCLifetime().empty()) 2690 return false; 2691 2692 // Argument must be a pointer to __strong to __weak. 2693 QualType FromPointee; 2694 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2695 FromPointee = FromPointer->getPointeeType(); 2696 else 2697 return false; 2698 2699 Qualifiers FromQuals = FromPointee.getQualifiers(); 2700 if (!FromPointee->isObjCLifetimeType() || 2701 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2702 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2703 return false; 2704 2705 // Make sure that we have compatible qualifiers. 2706 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2707 if (!ToQuals.compatiblyIncludes(FromQuals)) 2708 return false; 2709 2710 // Remove qualifiers from the pointee type we're converting from; they 2711 // aren't used in the compatibility check belong, and we'll be adding back 2712 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2713 FromPointee = FromPointee.getUnqualifiedType(); 2714 2715 // The unqualified form of the pointee types must be compatible. 2716 ToPointee = ToPointee.getUnqualifiedType(); 2717 bool IncompatibleObjC; 2718 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2719 FromPointee = ToPointee; 2720 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2721 IncompatibleObjC)) 2722 return false; 2723 2724 /// Construct the type we're converting to, which is a pointer to 2725 /// __autoreleasing pointee. 2726 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2727 ConvertedType = Context.getPointerType(FromPointee); 2728 return true; 2729 } 2730 2731 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2732 QualType& ConvertedType) { 2733 QualType ToPointeeType; 2734 if (const BlockPointerType *ToBlockPtr = 2735 ToType->getAs<BlockPointerType>()) 2736 ToPointeeType = ToBlockPtr->getPointeeType(); 2737 else 2738 return false; 2739 2740 QualType FromPointeeType; 2741 if (const BlockPointerType *FromBlockPtr = 2742 FromType->getAs<BlockPointerType>()) 2743 FromPointeeType = FromBlockPtr->getPointeeType(); 2744 else 2745 return false; 2746 // We have pointer to blocks, check whether the only 2747 // differences in the argument and result types are in Objective-C 2748 // pointer conversions. If so, we permit the conversion. 2749 2750 const FunctionProtoType *FromFunctionType 2751 = FromPointeeType->getAs<FunctionProtoType>(); 2752 const FunctionProtoType *ToFunctionType 2753 = ToPointeeType->getAs<FunctionProtoType>(); 2754 2755 if (!FromFunctionType || !ToFunctionType) 2756 return false; 2757 2758 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2759 return true; 2760 2761 // Perform the quick checks that will tell us whether these 2762 // function types are obviously different. 2763 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2764 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2765 return false; 2766 2767 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2768 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2769 if (FromEInfo != ToEInfo) 2770 return false; 2771 2772 bool IncompatibleObjC = false; 2773 if (Context.hasSameType(FromFunctionType->getReturnType(), 2774 ToFunctionType->getReturnType())) { 2775 // Okay, the types match exactly. Nothing to do. 2776 } else { 2777 QualType RHS = FromFunctionType->getReturnType(); 2778 QualType LHS = ToFunctionType->getReturnType(); 2779 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2780 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2781 LHS = LHS.getUnqualifiedType(); 2782 2783 if (Context.hasSameType(RHS,LHS)) { 2784 // OK exact match. 2785 } else if (isObjCPointerConversion(RHS, LHS, 2786 ConvertedType, IncompatibleObjC)) { 2787 if (IncompatibleObjC) 2788 return false; 2789 // Okay, we have an Objective-C pointer conversion. 2790 } 2791 else 2792 return false; 2793 } 2794 2795 // Check argument types. 2796 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2797 ArgIdx != NumArgs; ++ArgIdx) { 2798 IncompatibleObjC = false; 2799 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2800 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2801 if (Context.hasSameType(FromArgType, ToArgType)) { 2802 // Okay, the types match exactly. Nothing to do. 2803 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2804 ConvertedType, IncompatibleObjC)) { 2805 if (IncompatibleObjC) 2806 return false; 2807 // Okay, we have an Objective-C pointer conversion. 2808 } else 2809 // Argument types are too different. Abort. 2810 return false; 2811 } 2812 2813 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2814 bool CanUseToFPT, CanUseFromFPT; 2815 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2816 CanUseToFPT, CanUseFromFPT, 2817 NewParamInfos)) 2818 return false; 2819 2820 ConvertedType = ToType; 2821 return true; 2822 } 2823 2824 enum { 2825 ft_default, 2826 ft_different_class, 2827 ft_parameter_arity, 2828 ft_parameter_mismatch, 2829 ft_return_type, 2830 ft_qualifer_mismatch, 2831 ft_noexcept 2832 }; 2833 2834 /// Attempts to get the FunctionProtoType from a Type. Handles 2835 /// MemberFunctionPointers properly. 2836 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2837 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2838 return FPT; 2839 2840 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2841 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2842 2843 return nullptr; 2844 } 2845 2846 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2847 /// function types. Catches different number of parameter, mismatch in 2848 /// parameter types, and different return types. 2849 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2850 QualType FromType, QualType ToType) { 2851 // If either type is not valid, include no extra info. 2852 if (FromType.isNull() || ToType.isNull()) { 2853 PDiag << ft_default; 2854 return; 2855 } 2856 2857 // Get the function type from the pointers. 2858 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2859 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2860 *ToMember = ToType->castAs<MemberPointerType>(); 2861 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2862 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2863 << QualType(FromMember->getClass(), 0); 2864 return; 2865 } 2866 FromType = FromMember->getPointeeType(); 2867 ToType = ToMember->getPointeeType(); 2868 } 2869 2870 if (FromType->isPointerType()) 2871 FromType = FromType->getPointeeType(); 2872 if (ToType->isPointerType()) 2873 ToType = ToType->getPointeeType(); 2874 2875 // Remove references. 2876 FromType = FromType.getNonReferenceType(); 2877 ToType = ToType.getNonReferenceType(); 2878 2879 // Don't print extra info for non-specialized template functions. 2880 if (FromType->isInstantiationDependentType() && 2881 !FromType->getAs<TemplateSpecializationType>()) { 2882 PDiag << ft_default; 2883 return; 2884 } 2885 2886 // No extra info for same types. 2887 if (Context.hasSameType(FromType, ToType)) { 2888 PDiag << ft_default; 2889 return; 2890 } 2891 2892 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2893 *ToFunction = tryGetFunctionProtoType(ToType); 2894 2895 // Both types need to be function types. 2896 if (!FromFunction || !ToFunction) { 2897 PDiag << ft_default; 2898 return; 2899 } 2900 2901 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2902 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2903 << FromFunction->getNumParams(); 2904 return; 2905 } 2906 2907 // Handle different parameter types. 2908 unsigned ArgPos; 2909 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2910 PDiag << ft_parameter_mismatch << ArgPos + 1 2911 << ToFunction->getParamType(ArgPos) 2912 << FromFunction->getParamType(ArgPos); 2913 return; 2914 } 2915 2916 // Handle different return type. 2917 if (!Context.hasSameType(FromFunction->getReturnType(), 2918 ToFunction->getReturnType())) { 2919 PDiag << ft_return_type << ToFunction->getReturnType() 2920 << FromFunction->getReturnType(); 2921 return; 2922 } 2923 2924 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2925 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2926 << FromFunction->getMethodQuals(); 2927 return; 2928 } 2929 2930 // Handle exception specification differences on canonical type (in C++17 2931 // onwards). 2932 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2933 ->isNothrow() != 2934 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2935 ->isNothrow()) { 2936 PDiag << ft_noexcept; 2937 return; 2938 } 2939 2940 // Unable to find a difference, so add no extra info. 2941 PDiag << ft_default; 2942 } 2943 2944 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2945 /// for equality of their argument types. Caller has already checked that 2946 /// they have same number of arguments. If the parameters are different, 2947 /// ArgPos will have the parameter index of the first different parameter. 2948 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2949 const FunctionProtoType *NewType, 2950 unsigned *ArgPos) { 2951 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2952 N = NewType->param_type_begin(), 2953 E = OldType->param_type_end(); 2954 O && (O != E); ++O, ++N) { 2955 // Ignore address spaces in pointee type. This is to disallow overloading 2956 // on __ptr32/__ptr64 address spaces. 2957 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2958 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2959 2960 if (!Context.hasSameType(Old, New)) { 2961 if (ArgPos) 2962 *ArgPos = O - OldType->param_type_begin(); 2963 return false; 2964 } 2965 } 2966 return true; 2967 } 2968 2969 /// CheckPointerConversion - Check the pointer conversion from the 2970 /// expression From to the type ToType. This routine checks for 2971 /// ambiguous or inaccessible derived-to-base pointer 2972 /// conversions for which IsPointerConversion has already returned 2973 /// true. It returns true and produces a diagnostic if there was an 2974 /// error, or returns false otherwise. 2975 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2976 CastKind &Kind, 2977 CXXCastPath& BasePath, 2978 bool IgnoreBaseAccess, 2979 bool Diagnose) { 2980 QualType FromType = From->getType(); 2981 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2982 2983 Kind = CK_BitCast; 2984 2985 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2986 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2987 Expr::NPCK_ZeroExpression) { 2988 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2989 DiagRuntimeBehavior(From->getExprLoc(), From, 2990 PDiag(diag::warn_impcast_bool_to_null_pointer) 2991 << ToType << From->getSourceRange()); 2992 else if (!isUnevaluatedContext()) 2993 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2994 << ToType << From->getSourceRange(); 2995 } 2996 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2997 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2998 QualType FromPointeeType = FromPtrType->getPointeeType(), 2999 ToPointeeType = ToPtrType->getPointeeType(); 3000 3001 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3002 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3003 // We must have a derived-to-base conversion. Check an 3004 // ambiguous or inaccessible conversion. 3005 unsigned InaccessibleID = 0; 3006 unsigned AmbiguousID = 0; 3007 if (Diagnose) { 3008 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3009 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3010 } 3011 if (CheckDerivedToBaseConversion( 3012 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3013 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3014 &BasePath, IgnoreBaseAccess)) 3015 return true; 3016 3017 // The conversion was successful. 3018 Kind = CK_DerivedToBase; 3019 } 3020 3021 if (Diagnose && !IsCStyleOrFunctionalCast && 3022 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3023 assert(getLangOpts().MSVCCompat && 3024 "this should only be possible with MSVCCompat!"); 3025 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3026 << From->getSourceRange(); 3027 } 3028 } 3029 } else if (const ObjCObjectPointerType *ToPtrType = 3030 ToType->getAs<ObjCObjectPointerType>()) { 3031 if (const ObjCObjectPointerType *FromPtrType = 3032 FromType->getAs<ObjCObjectPointerType>()) { 3033 // Objective-C++ conversions are always okay. 3034 // FIXME: We should have a different class of conversions for the 3035 // Objective-C++ implicit conversions. 3036 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3037 return false; 3038 } else if (FromType->isBlockPointerType()) { 3039 Kind = CK_BlockPointerToObjCPointerCast; 3040 } else { 3041 Kind = CK_CPointerToObjCPointerCast; 3042 } 3043 } else if (ToType->isBlockPointerType()) { 3044 if (!FromType->isBlockPointerType()) 3045 Kind = CK_AnyPointerToBlockPointerCast; 3046 } 3047 3048 // We shouldn't fall into this case unless it's valid for other 3049 // reasons. 3050 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3051 Kind = CK_NullToPointer; 3052 3053 return false; 3054 } 3055 3056 /// IsMemberPointerConversion - Determines whether the conversion of the 3057 /// expression From, which has the (possibly adjusted) type FromType, can be 3058 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3059 /// If so, returns true and places the converted type (that might differ from 3060 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3061 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3062 QualType ToType, 3063 bool InOverloadResolution, 3064 QualType &ConvertedType) { 3065 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3066 if (!ToTypePtr) 3067 return false; 3068 3069 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3070 if (From->isNullPointerConstant(Context, 3071 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3072 : Expr::NPC_ValueDependentIsNull)) { 3073 ConvertedType = ToType; 3074 return true; 3075 } 3076 3077 // Otherwise, both types have to be member pointers. 3078 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3079 if (!FromTypePtr) 3080 return false; 3081 3082 // A pointer to member of B can be converted to a pointer to member of D, 3083 // where D is derived from B (C++ 4.11p2). 3084 QualType FromClass(FromTypePtr->getClass(), 0); 3085 QualType ToClass(ToTypePtr->getClass(), 0); 3086 3087 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3088 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3089 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3090 ToClass.getTypePtr()); 3091 return true; 3092 } 3093 3094 return false; 3095 } 3096 3097 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3098 /// expression From to the type ToType. This routine checks for ambiguous or 3099 /// virtual or inaccessible base-to-derived member pointer conversions 3100 /// for which IsMemberPointerConversion has already returned true. It returns 3101 /// true and produces a diagnostic if there was an error, or returns false 3102 /// otherwise. 3103 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3104 CastKind &Kind, 3105 CXXCastPath &BasePath, 3106 bool IgnoreBaseAccess) { 3107 QualType FromType = From->getType(); 3108 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3109 if (!FromPtrType) { 3110 // This must be a null pointer to member pointer conversion 3111 assert(From->isNullPointerConstant(Context, 3112 Expr::NPC_ValueDependentIsNull) && 3113 "Expr must be null pointer constant!"); 3114 Kind = CK_NullToMemberPointer; 3115 return false; 3116 } 3117 3118 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3119 assert(ToPtrType && "No member pointer cast has a target type " 3120 "that is not a member pointer."); 3121 3122 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3123 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3124 3125 // FIXME: What about dependent types? 3126 assert(FromClass->isRecordType() && "Pointer into non-class."); 3127 assert(ToClass->isRecordType() && "Pointer into non-class."); 3128 3129 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3130 /*DetectVirtual=*/true); 3131 bool DerivationOkay = 3132 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3133 assert(DerivationOkay && 3134 "Should not have been called if derivation isn't OK."); 3135 (void)DerivationOkay; 3136 3137 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3138 getUnqualifiedType())) { 3139 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3140 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3141 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3142 return true; 3143 } 3144 3145 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3146 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3147 << FromClass << ToClass << QualType(VBase, 0) 3148 << From->getSourceRange(); 3149 return true; 3150 } 3151 3152 if (!IgnoreBaseAccess) 3153 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3154 Paths.front(), 3155 diag::err_downcast_from_inaccessible_base); 3156 3157 // Must be a base to derived member conversion. 3158 BuildBasePathArray(Paths, BasePath); 3159 Kind = CK_BaseToDerivedMemberPointer; 3160 return false; 3161 } 3162 3163 /// Determine whether the lifetime conversion between the two given 3164 /// qualifiers sets is nontrivial. 3165 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3166 Qualifiers ToQuals) { 3167 // Converting anything to const __unsafe_unretained is trivial. 3168 if (ToQuals.hasConst() && 3169 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3170 return false; 3171 3172 return true; 3173 } 3174 3175 /// Perform a single iteration of the loop for checking if a qualification 3176 /// conversion is valid. 3177 /// 3178 /// Specifically, check whether any change between the qualifiers of \p 3179 /// FromType and \p ToType is permissible, given knowledge about whether every 3180 /// outer layer is const-qualified. 3181 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3182 bool CStyle, bool IsTopLevel, 3183 bool &PreviousToQualsIncludeConst, 3184 bool &ObjCLifetimeConversion) { 3185 Qualifiers FromQuals = FromType.getQualifiers(); 3186 Qualifiers ToQuals = ToType.getQualifiers(); 3187 3188 // Ignore __unaligned qualifier if this type is void. 3189 if (ToType.getUnqualifiedType()->isVoidType()) 3190 FromQuals.removeUnaligned(); 3191 3192 // Objective-C ARC: 3193 // Check Objective-C lifetime conversions. 3194 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3195 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3196 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3197 ObjCLifetimeConversion = true; 3198 FromQuals.removeObjCLifetime(); 3199 ToQuals.removeObjCLifetime(); 3200 } else { 3201 // Qualification conversions cannot cast between different 3202 // Objective-C lifetime qualifiers. 3203 return false; 3204 } 3205 } 3206 3207 // Allow addition/removal of GC attributes but not changing GC attributes. 3208 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3209 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3210 FromQuals.removeObjCGCAttr(); 3211 ToQuals.removeObjCGCAttr(); 3212 } 3213 3214 // -- for every j > 0, if const is in cv 1,j then const is in cv 3215 // 2,j, and similarly for volatile. 3216 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3217 return false; 3218 3219 // If address spaces mismatch: 3220 // - in top level it is only valid to convert to addr space that is a 3221 // superset in all cases apart from C-style casts where we allow 3222 // conversions between overlapping address spaces. 3223 // - in non-top levels it is not a valid conversion. 3224 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3225 (!IsTopLevel || 3226 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3227 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3228 return false; 3229 3230 // -- if the cv 1,j and cv 2,j are different, then const is in 3231 // every cv for 0 < k < j. 3232 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3233 !PreviousToQualsIncludeConst) 3234 return false; 3235 3236 // Keep track of whether all prior cv-qualifiers in the "to" type 3237 // include const. 3238 PreviousToQualsIncludeConst = 3239 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3240 return true; 3241 } 3242 3243 /// IsQualificationConversion - Determines whether the conversion from 3244 /// an rvalue of type FromType to ToType is a qualification conversion 3245 /// (C++ 4.4). 3246 /// 3247 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3248 /// when the qualification conversion involves a change in the Objective-C 3249 /// object lifetime. 3250 bool 3251 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3252 bool CStyle, bool &ObjCLifetimeConversion) { 3253 FromType = Context.getCanonicalType(FromType); 3254 ToType = Context.getCanonicalType(ToType); 3255 ObjCLifetimeConversion = false; 3256 3257 // If FromType and ToType are the same type, this is not a 3258 // qualification conversion. 3259 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3260 return false; 3261 3262 // (C++ 4.4p4): 3263 // A conversion can add cv-qualifiers at levels other than the first 3264 // in multi-level pointers, subject to the following rules: [...] 3265 bool PreviousToQualsIncludeConst = true; 3266 bool UnwrappedAnyPointer = false; 3267 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3268 if (!isQualificationConversionStep( 3269 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3270 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3271 return false; 3272 UnwrappedAnyPointer = true; 3273 } 3274 3275 // We are left with FromType and ToType being the pointee types 3276 // after unwrapping the original FromType and ToType the same number 3277 // of times. If we unwrapped any pointers, and if FromType and 3278 // ToType have the same unqualified type (since we checked 3279 // qualifiers above), then this is a qualification conversion. 3280 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3281 } 3282 3283 /// - Determine whether this is a conversion from a scalar type to an 3284 /// atomic type. 3285 /// 3286 /// If successful, updates \c SCS's second and third steps in the conversion 3287 /// sequence to finish the conversion. 3288 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3289 bool InOverloadResolution, 3290 StandardConversionSequence &SCS, 3291 bool CStyle) { 3292 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3293 if (!ToAtomic) 3294 return false; 3295 3296 StandardConversionSequence InnerSCS; 3297 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3298 InOverloadResolution, InnerSCS, 3299 CStyle, /*AllowObjCWritebackConversion=*/false)) 3300 return false; 3301 3302 SCS.Second = InnerSCS.Second; 3303 SCS.setToType(1, InnerSCS.getToType(1)); 3304 SCS.Third = InnerSCS.Third; 3305 SCS.QualificationIncludesObjCLifetime 3306 = InnerSCS.QualificationIncludesObjCLifetime; 3307 SCS.setToType(2, InnerSCS.getToType(2)); 3308 return true; 3309 } 3310 3311 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3312 CXXConstructorDecl *Constructor, 3313 QualType Type) { 3314 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3315 if (CtorType->getNumParams() > 0) { 3316 QualType FirstArg = CtorType->getParamType(0); 3317 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3318 return true; 3319 } 3320 return false; 3321 } 3322 3323 static OverloadingResult 3324 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3325 CXXRecordDecl *To, 3326 UserDefinedConversionSequence &User, 3327 OverloadCandidateSet &CandidateSet, 3328 bool AllowExplicit) { 3329 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3330 for (auto *D : S.LookupConstructors(To)) { 3331 auto Info = getConstructorInfo(D); 3332 if (!Info) 3333 continue; 3334 3335 bool Usable = !Info.Constructor->isInvalidDecl() && 3336 S.isInitListConstructor(Info.Constructor); 3337 if (Usable) { 3338 // If the first argument is (a reference to) the target type, 3339 // suppress conversions. 3340 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3341 S.Context, Info.Constructor, ToType); 3342 if (Info.ConstructorTmpl) 3343 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3344 /*ExplicitArgs*/ nullptr, From, 3345 CandidateSet, SuppressUserConversions, 3346 /*PartialOverloading*/ false, 3347 AllowExplicit); 3348 else 3349 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3350 CandidateSet, SuppressUserConversions, 3351 /*PartialOverloading*/ false, AllowExplicit); 3352 } 3353 } 3354 3355 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3356 3357 OverloadCandidateSet::iterator Best; 3358 switch (auto Result = 3359 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3360 case OR_Deleted: 3361 case OR_Success: { 3362 // Record the standard conversion we used and the conversion function. 3363 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3364 QualType ThisType = Constructor->getThisType(); 3365 // Initializer lists don't have conversions as such. 3366 User.Before.setAsIdentityConversion(); 3367 User.HadMultipleCandidates = HadMultipleCandidates; 3368 User.ConversionFunction = Constructor; 3369 User.FoundConversionFunction = Best->FoundDecl; 3370 User.After.setAsIdentityConversion(); 3371 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3372 User.After.setAllToTypes(ToType); 3373 return Result; 3374 } 3375 3376 case OR_No_Viable_Function: 3377 return OR_No_Viable_Function; 3378 case OR_Ambiguous: 3379 return OR_Ambiguous; 3380 } 3381 3382 llvm_unreachable("Invalid OverloadResult!"); 3383 } 3384 3385 /// Determines whether there is a user-defined conversion sequence 3386 /// (C++ [over.ics.user]) that converts expression From to the type 3387 /// ToType. If such a conversion exists, User will contain the 3388 /// user-defined conversion sequence that performs such a conversion 3389 /// and this routine will return true. Otherwise, this routine returns 3390 /// false and User is unspecified. 3391 /// 3392 /// \param AllowExplicit true if the conversion should consider C++0x 3393 /// "explicit" conversion functions as well as non-explicit conversion 3394 /// functions (C++0x [class.conv.fct]p2). 3395 /// 3396 /// \param AllowObjCConversionOnExplicit true if the conversion should 3397 /// allow an extra Objective-C pointer conversion on uses of explicit 3398 /// constructors. Requires \c AllowExplicit to also be set. 3399 static OverloadingResult 3400 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3401 UserDefinedConversionSequence &User, 3402 OverloadCandidateSet &CandidateSet, 3403 AllowedExplicit AllowExplicit, 3404 bool AllowObjCConversionOnExplicit) { 3405 assert(AllowExplicit != AllowedExplicit::None || 3406 !AllowObjCConversionOnExplicit); 3407 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3408 3409 // Whether we will only visit constructors. 3410 bool ConstructorsOnly = false; 3411 3412 // If the type we are conversion to is a class type, enumerate its 3413 // constructors. 3414 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3415 // C++ [over.match.ctor]p1: 3416 // When objects of class type are direct-initialized (8.5), or 3417 // copy-initialized from an expression of the same or a 3418 // derived class type (8.5), overload resolution selects the 3419 // constructor. [...] For copy-initialization, the candidate 3420 // functions are all the converting constructors (12.3.1) of 3421 // that class. The argument list is the expression-list within 3422 // the parentheses of the initializer. 3423 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3424 (From->getType()->getAs<RecordType>() && 3425 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3426 ConstructorsOnly = true; 3427 3428 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3429 // We're not going to find any constructors. 3430 } else if (CXXRecordDecl *ToRecordDecl 3431 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3432 3433 Expr **Args = &From; 3434 unsigned NumArgs = 1; 3435 bool ListInitializing = false; 3436 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3437 // But first, see if there is an init-list-constructor that will work. 3438 OverloadingResult Result = IsInitializerListConstructorConversion( 3439 S, From, ToType, ToRecordDecl, User, CandidateSet, 3440 AllowExplicit == AllowedExplicit::All); 3441 if (Result != OR_No_Viable_Function) 3442 return Result; 3443 // Never mind. 3444 CandidateSet.clear( 3445 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3446 3447 // If we're list-initializing, we pass the individual elements as 3448 // arguments, not the entire list. 3449 Args = InitList->getInits(); 3450 NumArgs = InitList->getNumInits(); 3451 ListInitializing = true; 3452 } 3453 3454 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3455 auto Info = getConstructorInfo(D); 3456 if (!Info) 3457 continue; 3458 3459 bool Usable = !Info.Constructor->isInvalidDecl(); 3460 if (!ListInitializing) 3461 Usable = Usable && Info.Constructor->isConvertingConstructor( 3462 /*AllowExplicit*/ true); 3463 if (Usable) { 3464 bool SuppressUserConversions = !ConstructorsOnly; 3465 if (SuppressUserConversions && ListInitializing) { 3466 SuppressUserConversions = false; 3467 if (NumArgs == 1) { 3468 // If the first argument is (a reference to) the target type, 3469 // suppress conversions. 3470 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3471 S.Context, Info.Constructor, ToType); 3472 } 3473 } 3474 if (Info.ConstructorTmpl) 3475 S.AddTemplateOverloadCandidate( 3476 Info.ConstructorTmpl, Info.FoundDecl, 3477 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3478 CandidateSet, SuppressUserConversions, 3479 /*PartialOverloading*/ false, 3480 AllowExplicit == AllowedExplicit::All); 3481 else 3482 // Allow one user-defined conversion when user specifies a 3483 // From->ToType conversion via an static cast (c-style, etc). 3484 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3485 llvm::makeArrayRef(Args, NumArgs), 3486 CandidateSet, SuppressUserConversions, 3487 /*PartialOverloading*/ false, 3488 AllowExplicit == AllowedExplicit::All); 3489 } 3490 } 3491 } 3492 } 3493 3494 // Enumerate conversion functions, if we're allowed to. 3495 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3496 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3497 // No conversion functions from incomplete types. 3498 } else if (const RecordType *FromRecordType = 3499 From->getType()->getAs<RecordType>()) { 3500 if (CXXRecordDecl *FromRecordDecl 3501 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3502 // Add all of the conversion functions as candidates. 3503 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3504 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3505 DeclAccessPair FoundDecl = I.getPair(); 3506 NamedDecl *D = FoundDecl.getDecl(); 3507 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3508 if (isa<UsingShadowDecl>(D)) 3509 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3510 3511 CXXConversionDecl *Conv; 3512 FunctionTemplateDecl *ConvTemplate; 3513 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3514 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3515 else 3516 Conv = cast<CXXConversionDecl>(D); 3517 3518 if (ConvTemplate) 3519 S.AddTemplateConversionCandidate( 3520 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3521 CandidateSet, AllowObjCConversionOnExplicit, 3522 AllowExplicit != AllowedExplicit::None); 3523 else 3524 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3525 CandidateSet, AllowObjCConversionOnExplicit, 3526 AllowExplicit != AllowedExplicit::None); 3527 } 3528 } 3529 } 3530 3531 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3532 3533 OverloadCandidateSet::iterator Best; 3534 switch (auto Result = 3535 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3536 case OR_Success: 3537 case OR_Deleted: 3538 // Record the standard conversion we used and the conversion function. 3539 if (CXXConstructorDecl *Constructor 3540 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3541 // C++ [over.ics.user]p1: 3542 // If the user-defined conversion is specified by a 3543 // constructor (12.3.1), the initial standard conversion 3544 // sequence converts the source type to the type required by 3545 // the argument of the constructor. 3546 // 3547 QualType ThisType = Constructor->getThisType(); 3548 if (isa<InitListExpr>(From)) { 3549 // Initializer lists don't have conversions as such. 3550 User.Before.setAsIdentityConversion(); 3551 } else { 3552 if (Best->Conversions[0].isEllipsis()) 3553 User.EllipsisConversion = true; 3554 else { 3555 User.Before = Best->Conversions[0].Standard; 3556 User.EllipsisConversion = false; 3557 } 3558 } 3559 User.HadMultipleCandidates = HadMultipleCandidates; 3560 User.ConversionFunction = Constructor; 3561 User.FoundConversionFunction = Best->FoundDecl; 3562 User.After.setAsIdentityConversion(); 3563 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3564 User.After.setAllToTypes(ToType); 3565 return Result; 3566 } 3567 if (CXXConversionDecl *Conversion 3568 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3569 // C++ [over.ics.user]p1: 3570 // 3571 // [...] If the user-defined conversion is specified by a 3572 // conversion function (12.3.2), the initial standard 3573 // conversion sequence converts the source type to the 3574 // implicit object parameter of the conversion function. 3575 User.Before = Best->Conversions[0].Standard; 3576 User.HadMultipleCandidates = HadMultipleCandidates; 3577 User.ConversionFunction = Conversion; 3578 User.FoundConversionFunction = Best->FoundDecl; 3579 User.EllipsisConversion = false; 3580 3581 // C++ [over.ics.user]p2: 3582 // The second standard conversion sequence converts the 3583 // result of the user-defined conversion to the target type 3584 // for the sequence. Since an implicit conversion sequence 3585 // is an initialization, the special rules for 3586 // initialization by user-defined conversion apply when 3587 // selecting the best user-defined conversion for a 3588 // user-defined conversion sequence (see 13.3.3 and 3589 // 13.3.3.1). 3590 User.After = Best->FinalConversion; 3591 return Result; 3592 } 3593 llvm_unreachable("Not a constructor or conversion function?"); 3594 3595 case OR_No_Viable_Function: 3596 return OR_No_Viable_Function; 3597 3598 case OR_Ambiguous: 3599 return OR_Ambiguous; 3600 } 3601 3602 llvm_unreachable("Invalid OverloadResult!"); 3603 } 3604 3605 bool 3606 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3607 ImplicitConversionSequence ICS; 3608 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3609 OverloadCandidateSet::CSK_Normal); 3610 OverloadingResult OvResult = 3611 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3612 CandidateSet, AllowedExplicit::None, false); 3613 3614 if (!(OvResult == OR_Ambiguous || 3615 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3616 return false; 3617 3618 auto Cands = CandidateSet.CompleteCandidates( 3619 *this, 3620 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3621 From); 3622 if (OvResult == OR_Ambiguous) 3623 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3624 << From->getType() << ToType << From->getSourceRange(); 3625 else { // OR_No_Viable_Function && !CandidateSet.empty() 3626 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3627 diag::err_typecheck_nonviable_condition_incomplete, 3628 From->getType(), From->getSourceRange())) 3629 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3630 << false << From->getType() << From->getSourceRange() << ToType; 3631 } 3632 3633 CandidateSet.NoteCandidates( 3634 *this, From, Cands); 3635 return true; 3636 } 3637 3638 /// Compare the user-defined conversion functions or constructors 3639 /// of two user-defined conversion sequences to determine whether any ordering 3640 /// is possible. 3641 static ImplicitConversionSequence::CompareKind 3642 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3643 FunctionDecl *Function2) { 3644 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3645 return ImplicitConversionSequence::Indistinguishable; 3646 3647 // Objective-C++: 3648 // If both conversion functions are implicitly-declared conversions from 3649 // a lambda closure type to a function pointer and a block pointer, 3650 // respectively, always prefer the conversion to a function pointer, 3651 // because the function pointer is more lightweight and is more likely 3652 // to keep code working. 3653 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3654 if (!Conv1) 3655 return ImplicitConversionSequence::Indistinguishable; 3656 3657 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3658 if (!Conv2) 3659 return ImplicitConversionSequence::Indistinguishable; 3660 3661 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3662 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3663 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3664 if (Block1 != Block2) 3665 return Block1 ? ImplicitConversionSequence::Worse 3666 : ImplicitConversionSequence::Better; 3667 } 3668 3669 return ImplicitConversionSequence::Indistinguishable; 3670 } 3671 3672 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3673 const ImplicitConversionSequence &ICS) { 3674 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3675 (ICS.isUserDefined() && 3676 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3677 } 3678 3679 /// CompareImplicitConversionSequences - Compare two implicit 3680 /// conversion sequences to determine whether one is better than the 3681 /// other or if they are indistinguishable (C++ 13.3.3.2). 3682 static ImplicitConversionSequence::CompareKind 3683 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3684 const ImplicitConversionSequence& ICS1, 3685 const ImplicitConversionSequence& ICS2) 3686 { 3687 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3688 // conversion sequences (as defined in 13.3.3.1) 3689 // -- a standard conversion sequence (13.3.3.1.1) is a better 3690 // conversion sequence than a user-defined conversion sequence or 3691 // an ellipsis conversion sequence, and 3692 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3693 // conversion sequence than an ellipsis conversion sequence 3694 // (13.3.3.1.3). 3695 // 3696 // C++0x [over.best.ics]p10: 3697 // For the purpose of ranking implicit conversion sequences as 3698 // described in 13.3.3.2, the ambiguous conversion sequence is 3699 // treated as a user-defined sequence that is indistinguishable 3700 // from any other user-defined conversion sequence. 3701 3702 // String literal to 'char *' conversion has been deprecated in C++03. It has 3703 // been removed from C++11. We still accept this conversion, if it happens at 3704 // the best viable function. Otherwise, this conversion is considered worse 3705 // than ellipsis conversion. Consider this as an extension; this is not in the 3706 // standard. For example: 3707 // 3708 // int &f(...); // #1 3709 // void f(char*); // #2 3710 // void g() { int &r = f("foo"); } 3711 // 3712 // In C++03, we pick #2 as the best viable function. 3713 // In C++11, we pick #1 as the best viable function, because ellipsis 3714 // conversion is better than string-literal to char* conversion (since there 3715 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3716 // convert arguments, #2 would be the best viable function in C++11. 3717 // If the best viable function has this conversion, a warning will be issued 3718 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3719 3720 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3721 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3722 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3723 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3724 ? ImplicitConversionSequence::Worse 3725 : ImplicitConversionSequence::Better; 3726 3727 if (ICS1.getKindRank() < ICS2.getKindRank()) 3728 return ImplicitConversionSequence::Better; 3729 if (ICS2.getKindRank() < ICS1.getKindRank()) 3730 return ImplicitConversionSequence::Worse; 3731 3732 // The following checks require both conversion sequences to be of 3733 // the same kind. 3734 if (ICS1.getKind() != ICS2.getKind()) 3735 return ImplicitConversionSequence::Indistinguishable; 3736 3737 ImplicitConversionSequence::CompareKind Result = 3738 ImplicitConversionSequence::Indistinguishable; 3739 3740 // Two implicit conversion sequences of the same form are 3741 // indistinguishable conversion sequences unless one of the 3742 // following rules apply: (C++ 13.3.3.2p3): 3743 3744 // List-initialization sequence L1 is a better conversion sequence than 3745 // list-initialization sequence L2 if: 3746 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3747 // if not that, 3748 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3749 // and N1 is smaller than N2., 3750 // even if one of the other rules in this paragraph would otherwise apply. 3751 if (!ICS1.isBad()) { 3752 if (ICS1.isStdInitializerListElement() && 3753 !ICS2.isStdInitializerListElement()) 3754 return ImplicitConversionSequence::Better; 3755 if (!ICS1.isStdInitializerListElement() && 3756 ICS2.isStdInitializerListElement()) 3757 return ImplicitConversionSequence::Worse; 3758 } 3759 3760 if (ICS1.isStandard()) 3761 // Standard conversion sequence S1 is a better conversion sequence than 3762 // standard conversion sequence S2 if [...] 3763 Result = CompareStandardConversionSequences(S, Loc, 3764 ICS1.Standard, ICS2.Standard); 3765 else if (ICS1.isUserDefined()) { 3766 // User-defined conversion sequence U1 is a better conversion 3767 // sequence than another user-defined conversion sequence U2 if 3768 // they contain the same user-defined conversion function or 3769 // constructor and if the second standard conversion sequence of 3770 // U1 is better than the second standard conversion sequence of 3771 // U2 (C++ 13.3.3.2p3). 3772 if (ICS1.UserDefined.ConversionFunction == 3773 ICS2.UserDefined.ConversionFunction) 3774 Result = CompareStandardConversionSequences(S, Loc, 3775 ICS1.UserDefined.After, 3776 ICS2.UserDefined.After); 3777 else 3778 Result = compareConversionFunctions(S, 3779 ICS1.UserDefined.ConversionFunction, 3780 ICS2.UserDefined.ConversionFunction); 3781 } 3782 3783 return Result; 3784 } 3785 3786 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3787 // determine if one is a proper subset of the other. 3788 static ImplicitConversionSequence::CompareKind 3789 compareStandardConversionSubsets(ASTContext &Context, 3790 const StandardConversionSequence& SCS1, 3791 const StandardConversionSequence& SCS2) { 3792 ImplicitConversionSequence::CompareKind Result 3793 = ImplicitConversionSequence::Indistinguishable; 3794 3795 // the identity conversion sequence is considered to be a subsequence of 3796 // any non-identity conversion sequence 3797 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3798 return ImplicitConversionSequence::Better; 3799 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3800 return ImplicitConversionSequence::Worse; 3801 3802 if (SCS1.Second != SCS2.Second) { 3803 if (SCS1.Second == ICK_Identity) 3804 Result = ImplicitConversionSequence::Better; 3805 else if (SCS2.Second == ICK_Identity) 3806 Result = ImplicitConversionSequence::Worse; 3807 else 3808 return ImplicitConversionSequence::Indistinguishable; 3809 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3810 return ImplicitConversionSequence::Indistinguishable; 3811 3812 if (SCS1.Third == SCS2.Third) { 3813 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3814 : ImplicitConversionSequence::Indistinguishable; 3815 } 3816 3817 if (SCS1.Third == ICK_Identity) 3818 return Result == ImplicitConversionSequence::Worse 3819 ? ImplicitConversionSequence::Indistinguishable 3820 : ImplicitConversionSequence::Better; 3821 3822 if (SCS2.Third == ICK_Identity) 3823 return Result == ImplicitConversionSequence::Better 3824 ? ImplicitConversionSequence::Indistinguishable 3825 : ImplicitConversionSequence::Worse; 3826 3827 return ImplicitConversionSequence::Indistinguishable; 3828 } 3829 3830 /// Determine whether one of the given reference bindings is better 3831 /// than the other based on what kind of bindings they are. 3832 static bool 3833 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3834 const StandardConversionSequence &SCS2) { 3835 // C++0x [over.ics.rank]p3b4: 3836 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3837 // implicit object parameter of a non-static member function declared 3838 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3839 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3840 // lvalue reference to a function lvalue and S2 binds an rvalue 3841 // reference*. 3842 // 3843 // FIXME: Rvalue references. We're going rogue with the above edits, 3844 // because the semantics in the current C++0x working paper (N3225 at the 3845 // time of this writing) break the standard definition of std::forward 3846 // and std::reference_wrapper when dealing with references to functions. 3847 // Proposed wording changes submitted to CWG for consideration. 3848 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3849 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3850 return false; 3851 3852 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3853 SCS2.IsLvalueReference) || 3854 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3855 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3856 } 3857 3858 enum class FixedEnumPromotion { 3859 None, 3860 ToUnderlyingType, 3861 ToPromotedUnderlyingType 3862 }; 3863 3864 /// Returns kind of fixed enum promotion the \a SCS uses. 3865 static FixedEnumPromotion 3866 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3867 3868 if (SCS.Second != ICK_Integral_Promotion) 3869 return FixedEnumPromotion::None; 3870 3871 QualType FromType = SCS.getFromType(); 3872 if (!FromType->isEnumeralType()) 3873 return FixedEnumPromotion::None; 3874 3875 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3876 if (!Enum->isFixed()) 3877 return FixedEnumPromotion::None; 3878 3879 QualType UnderlyingType = Enum->getIntegerType(); 3880 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3881 return FixedEnumPromotion::ToUnderlyingType; 3882 3883 return FixedEnumPromotion::ToPromotedUnderlyingType; 3884 } 3885 3886 /// CompareStandardConversionSequences - Compare two standard 3887 /// conversion sequences to determine whether one is better than the 3888 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3889 static ImplicitConversionSequence::CompareKind 3890 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3891 const StandardConversionSequence& SCS1, 3892 const StandardConversionSequence& SCS2) 3893 { 3894 // Standard conversion sequence S1 is a better conversion sequence 3895 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3896 3897 // -- S1 is a proper subsequence of S2 (comparing the conversion 3898 // sequences in the canonical form defined by 13.3.3.1.1, 3899 // excluding any Lvalue Transformation; the identity conversion 3900 // sequence is considered to be a subsequence of any 3901 // non-identity conversion sequence) or, if not that, 3902 if (ImplicitConversionSequence::CompareKind CK 3903 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3904 return CK; 3905 3906 // -- the rank of S1 is better than the rank of S2 (by the rules 3907 // defined below), or, if not that, 3908 ImplicitConversionRank Rank1 = SCS1.getRank(); 3909 ImplicitConversionRank Rank2 = SCS2.getRank(); 3910 if (Rank1 < Rank2) 3911 return ImplicitConversionSequence::Better; 3912 else if (Rank2 < Rank1) 3913 return ImplicitConversionSequence::Worse; 3914 3915 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3916 // are indistinguishable unless one of the following rules 3917 // applies: 3918 3919 // A conversion that is not a conversion of a pointer, or 3920 // pointer to member, to bool is better than another conversion 3921 // that is such a conversion. 3922 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3923 return SCS2.isPointerConversionToBool() 3924 ? ImplicitConversionSequence::Better 3925 : ImplicitConversionSequence::Worse; 3926 3927 // C++14 [over.ics.rank]p4b2: 3928 // This is retroactively applied to C++11 by CWG 1601. 3929 // 3930 // A conversion that promotes an enumeration whose underlying type is fixed 3931 // to its underlying type is better than one that promotes to the promoted 3932 // underlying type, if the two are different. 3933 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3934 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3935 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3936 FEP1 != FEP2) 3937 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3938 ? ImplicitConversionSequence::Better 3939 : ImplicitConversionSequence::Worse; 3940 3941 // C++ [over.ics.rank]p4b2: 3942 // 3943 // If class B is derived directly or indirectly from class A, 3944 // conversion of B* to A* is better than conversion of B* to 3945 // void*, and conversion of A* to void* is better than conversion 3946 // of B* to void*. 3947 bool SCS1ConvertsToVoid 3948 = SCS1.isPointerConversionToVoidPointer(S.Context); 3949 bool SCS2ConvertsToVoid 3950 = SCS2.isPointerConversionToVoidPointer(S.Context); 3951 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3952 // Exactly one of the conversion sequences is a conversion to 3953 // a void pointer; it's the worse conversion. 3954 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3955 : ImplicitConversionSequence::Worse; 3956 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3957 // Neither conversion sequence converts to a void pointer; compare 3958 // their derived-to-base conversions. 3959 if (ImplicitConversionSequence::CompareKind DerivedCK 3960 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3961 return DerivedCK; 3962 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3963 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3964 // Both conversion sequences are conversions to void 3965 // pointers. Compare the source types to determine if there's an 3966 // inheritance relationship in their sources. 3967 QualType FromType1 = SCS1.getFromType(); 3968 QualType FromType2 = SCS2.getFromType(); 3969 3970 // Adjust the types we're converting from via the array-to-pointer 3971 // conversion, if we need to. 3972 if (SCS1.First == ICK_Array_To_Pointer) 3973 FromType1 = S.Context.getArrayDecayedType(FromType1); 3974 if (SCS2.First == ICK_Array_To_Pointer) 3975 FromType2 = S.Context.getArrayDecayedType(FromType2); 3976 3977 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3978 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3979 3980 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3981 return ImplicitConversionSequence::Better; 3982 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3983 return ImplicitConversionSequence::Worse; 3984 3985 // Objective-C++: If one interface is more specific than the 3986 // other, it is the better one. 3987 const ObjCObjectPointerType* FromObjCPtr1 3988 = FromType1->getAs<ObjCObjectPointerType>(); 3989 const ObjCObjectPointerType* FromObjCPtr2 3990 = FromType2->getAs<ObjCObjectPointerType>(); 3991 if (FromObjCPtr1 && FromObjCPtr2) { 3992 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3993 FromObjCPtr2); 3994 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3995 FromObjCPtr1); 3996 if (AssignLeft != AssignRight) { 3997 return AssignLeft? ImplicitConversionSequence::Better 3998 : ImplicitConversionSequence::Worse; 3999 } 4000 } 4001 } 4002 4003 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4004 // Check for a better reference binding based on the kind of bindings. 4005 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4006 return ImplicitConversionSequence::Better; 4007 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4008 return ImplicitConversionSequence::Worse; 4009 } 4010 4011 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4012 // bullet 3). 4013 if (ImplicitConversionSequence::CompareKind QualCK 4014 = CompareQualificationConversions(S, SCS1, SCS2)) 4015 return QualCK; 4016 4017 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4018 // C++ [over.ics.rank]p3b4: 4019 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4020 // which the references refer are the same type except for 4021 // top-level cv-qualifiers, and the type to which the reference 4022 // initialized by S2 refers is more cv-qualified than the type 4023 // to which the reference initialized by S1 refers. 4024 QualType T1 = SCS1.getToType(2); 4025 QualType T2 = SCS2.getToType(2); 4026 T1 = S.Context.getCanonicalType(T1); 4027 T2 = S.Context.getCanonicalType(T2); 4028 Qualifiers T1Quals, T2Quals; 4029 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4030 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4031 if (UnqualT1 == UnqualT2) { 4032 // Objective-C++ ARC: If the references refer to objects with different 4033 // lifetimes, prefer bindings that don't change lifetime. 4034 if (SCS1.ObjCLifetimeConversionBinding != 4035 SCS2.ObjCLifetimeConversionBinding) { 4036 return SCS1.ObjCLifetimeConversionBinding 4037 ? ImplicitConversionSequence::Worse 4038 : ImplicitConversionSequence::Better; 4039 } 4040 4041 // If the type is an array type, promote the element qualifiers to the 4042 // type for comparison. 4043 if (isa<ArrayType>(T1) && T1Quals) 4044 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4045 if (isa<ArrayType>(T2) && T2Quals) 4046 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4047 if (T2.isMoreQualifiedThan(T1)) 4048 return ImplicitConversionSequence::Better; 4049 if (T1.isMoreQualifiedThan(T2)) 4050 return ImplicitConversionSequence::Worse; 4051 } 4052 } 4053 4054 // In Microsoft mode, prefer an integral conversion to a 4055 // floating-to-integral conversion if the integral conversion 4056 // is between types of the same size. 4057 // For example: 4058 // void f(float); 4059 // void f(int); 4060 // int main { 4061 // long a; 4062 // f(a); 4063 // } 4064 // Here, MSVC will call f(int) instead of generating a compile error 4065 // as clang will do in standard mode. 4066 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4067 SCS2.Second == ICK_Floating_Integral && 4068 S.Context.getTypeSize(SCS1.getFromType()) == 4069 S.Context.getTypeSize(SCS1.getToType(2))) 4070 return ImplicitConversionSequence::Better; 4071 4072 // Prefer a compatible vector conversion over a lax vector conversion 4073 // For example: 4074 // 4075 // typedef float __v4sf __attribute__((__vector_size__(16))); 4076 // void f(vector float); 4077 // void f(vector signed int); 4078 // int main() { 4079 // __v4sf a; 4080 // f(a); 4081 // } 4082 // Here, we'd like to choose f(vector float) and not 4083 // report an ambiguous call error 4084 if (SCS1.Second == ICK_Vector_Conversion && 4085 SCS2.Second == ICK_Vector_Conversion) { 4086 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4087 SCS1.getFromType(), SCS1.getToType(2)); 4088 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4089 SCS2.getFromType(), SCS2.getToType(2)); 4090 4091 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4092 return SCS1IsCompatibleVectorConversion 4093 ? ImplicitConversionSequence::Better 4094 : ImplicitConversionSequence::Worse; 4095 } 4096 4097 return ImplicitConversionSequence::Indistinguishable; 4098 } 4099 4100 /// CompareQualificationConversions - Compares two standard conversion 4101 /// sequences to determine whether they can be ranked based on their 4102 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4103 static ImplicitConversionSequence::CompareKind 4104 CompareQualificationConversions(Sema &S, 4105 const StandardConversionSequence& SCS1, 4106 const StandardConversionSequence& SCS2) { 4107 // C++ 13.3.3.2p3: 4108 // -- S1 and S2 differ only in their qualification conversion and 4109 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4110 // cv-qualification signature of type T1 is a proper subset of 4111 // the cv-qualification signature of type T2, and S1 is not the 4112 // deprecated string literal array-to-pointer conversion (4.2). 4113 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4114 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4115 return ImplicitConversionSequence::Indistinguishable; 4116 4117 // FIXME: the example in the standard doesn't use a qualification 4118 // conversion (!) 4119 QualType T1 = SCS1.getToType(2); 4120 QualType T2 = SCS2.getToType(2); 4121 T1 = S.Context.getCanonicalType(T1); 4122 T2 = S.Context.getCanonicalType(T2); 4123 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4124 Qualifiers T1Quals, T2Quals; 4125 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4126 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4127 4128 // If the types are the same, we won't learn anything by unwrapping 4129 // them. 4130 if (UnqualT1 == UnqualT2) 4131 return ImplicitConversionSequence::Indistinguishable; 4132 4133 ImplicitConversionSequence::CompareKind Result 4134 = ImplicitConversionSequence::Indistinguishable; 4135 4136 // Objective-C++ ARC: 4137 // Prefer qualification conversions not involving a change in lifetime 4138 // to qualification conversions that do not change lifetime. 4139 if (SCS1.QualificationIncludesObjCLifetime != 4140 SCS2.QualificationIncludesObjCLifetime) { 4141 Result = SCS1.QualificationIncludesObjCLifetime 4142 ? ImplicitConversionSequence::Worse 4143 : ImplicitConversionSequence::Better; 4144 } 4145 4146 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4147 // Within each iteration of the loop, we check the qualifiers to 4148 // determine if this still looks like a qualification 4149 // conversion. Then, if all is well, we unwrap one more level of 4150 // pointers or pointers-to-members and do it all again 4151 // until there are no more pointers or pointers-to-members left 4152 // to unwrap. This essentially mimics what 4153 // IsQualificationConversion does, but here we're checking for a 4154 // strict subset of qualifiers. 4155 if (T1.getQualifiers().withoutObjCLifetime() == 4156 T2.getQualifiers().withoutObjCLifetime()) 4157 // The qualifiers are the same, so this doesn't tell us anything 4158 // about how the sequences rank. 4159 // ObjC ownership quals are omitted above as they interfere with 4160 // the ARC overload rule. 4161 ; 4162 else if (T2.isMoreQualifiedThan(T1)) { 4163 // T1 has fewer qualifiers, so it could be the better sequence. 4164 if (Result == ImplicitConversionSequence::Worse) 4165 // Neither has qualifiers that are a subset of the other's 4166 // qualifiers. 4167 return ImplicitConversionSequence::Indistinguishable; 4168 4169 Result = ImplicitConversionSequence::Better; 4170 } else if (T1.isMoreQualifiedThan(T2)) { 4171 // T2 has fewer qualifiers, so it could be the better sequence. 4172 if (Result == ImplicitConversionSequence::Better) 4173 // Neither has qualifiers that are a subset of the other's 4174 // qualifiers. 4175 return ImplicitConversionSequence::Indistinguishable; 4176 4177 Result = ImplicitConversionSequence::Worse; 4178 } else { 4179 // Qualifiers are disjoint. 4180 return ImplicitConversionSequence::Indistinguishable; 4181 } 4182 4183 // If the types after this point are equivalent, we're done. 4184 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4185 break; 4186 } 4187 4188 // Check that the winning standard conversion sequence isn't using 4189 // the deprecated string literal array to pointer conversion. 4190 switch (Result) { 4191 case ImplicitConversionSequence::Better: 4192 if (SCS1.DeprecatedStringLiteralToCharPtr) 4193 Result = ImplicitConversionSequence::Indistinguishable; 4194 break; 4195 4196 case ImplicitConversionSequence::Indistinguishable: 4197 break; 4198 4199 case ImplicitConversionSequence::Worse: 4200 if (SCS2.DeprecatedStringLiteralToCharPtr) 4201 Result = ImplicitConversionSequence::Indistinguishable; 4202 break; 4203 } 4204 4205 return Result; 4206 } 4207 4208 /// CompareDerivedToBaseConversions - Compares two standard conversion 4209 /// sequences to determine whether they can be ranked based on their 4210 /// various kinds of derived-to-base conversions (C++ 4211 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4212 /// conversions between Objective-C interface types. 4213 static ImplicitConversionSequence::CompareKind 4214 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4215 const StandardConversionSequence& SCS1, 4216 const StandardConversionSequence& SCS2) { 4217 QualType FromType1 = SCS1.getFromType(); 4218 QualType ToType1 = SCS1.getToType(1); 4219 QualType FromType2 = SCS2.getFromType(); 4220 QualType ToType2 = SCS2.getToType(1); 4221 4222 // Adjust the types we're converting from via the array-to-pointer 4223 // conversion, if we need to. 4224 if (SCS1.First == ICK_Array_To_Pointer) 4225 FromType1 = S.Context.getArrayDecayedType(FromType1); 4226 if (SCS2.First == ICK_Array_To_Pointer) 4227 FromType2 = S.Context.getArrayDecayedType(FromType2); 4228 4229 // Canonicalize all of the types. 4230 FromType1 = S.Context.getCanonicalType(FromType1); 4231 ToType1 = S.Context.getCanonicalType(ToType1); 4232 FromType2 = S.Context.getCanonicalType(FromType2); 4233 ToType2 = S.Context.getCanonicalType(ToType2); 4234 4235 // C++ [over.ics.rank]p4b3: 4236 // 4237 // If class B is derived directly or indirectly from class A and 4238 // class C is derived directly or indirectly from B, 4239 // 4240 // Compare based on pointer conversions. 4241 if (SCS1.Second == ICK_Pointer_Conversion && 4242 SCS2.Second == ICK_Pointer_Conversion && 4243 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4244 FromType1->isPointerType() && FromType2->isPointerType() && 4245 ToType1->isPointerType() && ToType2->isPointerType()) { 4246 QualType FromPointee1 = 4247 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4248 QualType ToPointee1 = 4249 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4250 QualType FromPointee2 = 4251 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4252 QualType ToPointee2 = 4253 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4254 4255 // -- conversion of C* to B* is better than conversion of C* to A*, 4256 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4257 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4258 return ImplicitConversionSequence::Better; 4259 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4260 return ImplicitConversionSequence::Worse; 4261 } 4262 4263 // -- conversion of B* to A* is better than conversion of C* to A*, 4264 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4265 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4266 return ImplicitConversionSequence::Better; 4267 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4268 return ImplicitConversionSequence::Worse; 4269 } 4270 } else if (SCS1.Second == ICK_Pointer_Conversion && 4271 SCS2.Second == ICK_Pointer_Conversion) { 4272 const ObjCObjectPointerType *FromPtr1 4273 = FromType1->getAs<ObjCObjectPointerType>(); 4274 const ObjCObjectPointerType *FromPtr2 4275 = FromType2->getAs<ObjCObjectPointerType>(); 4276 const ObjCObjectPointerType *ToPtr1 4277 = ToType1->getAs<ObjCObjectPointerType>(); 4278 const ObjCObjectPointerType *ToPtr2 4279 = ToType2->getAs<ObjCObjectPointerType>(); 4280 4281 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4282 // Apply the same conversion ranking rules for Objective-C pointer types 4283 // that we do for C++ pointers to class types. However, we employ the 4284 // Objective-C pseudo-subtyping relationship used for assignment of 4285 // Objective-C pointer types. 4286 bool FromAssignLeft 4287 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4288 bool FromAssignRight 4289 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4290 bool ToAssignLeft 4291 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4292 bool ToAssignRight 4293 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4294 4295 // A conversion to an a non-id object pointer type or qualified 'id' 4296 // type is better than a conversion to 'id'. 4297 if (ToPtr1->isObjCIdType() && 4298 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4299 return ImplicitConversionSequence::Worse; 4300 if (ToPtr2->isObjCIdType() && 4301 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4302 return ImplicitConversionSequence::Better; 4303 4304 // A conversion to a non-id object pointer type is better than a 4305 // conversion to a qualified 'id' type 4306 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4307 return ImplicitConversionSequence::Worse; 4308 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4309 return ImplicitConversionSequence::Better; 4310 4311 // A conversion to an a non-Class object pointer type or qualified 'Class' 4312 // type is better than a conversion to 'Class'. 4313 if (ToPtr1->isObjCClassType() && 4314 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4315 return ImplicitConversionSequence::Worse; 4316 if (ToPtr2->isObjCClassType() && 4317 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4318 return ImplicitConversionSequence::Better; 4319 4320 // A conversion to a non-Class object pointer type is better than a 4321 // conversion to a qualified 'Class' type. 4322 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4323 return ImplicitConversionSequence::Worse; 4324 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4325 return ImplicitConversionSequence::Better; 4326 4327 // -- "conversion of C* to B* is better than conversion of C* to A*," 4328 if (S.Context.hasSameType(FromType1, FromType2) && 4329 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4330 (ToAssignLeft != ToAssignRight)) { 4331 if (FromPtr1->isSpecialized()) { 4332 // "conversion of B<A> * to B * is better than conversion of B * to 4333 // C *. 4334 bool IsFirstSame = 4335 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4336 bool IsSecondSame = 4337 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4338 if (IsFirstSame) { 4339 if (!IsSecondSame) 4340 return ImplicitConversionSequence::Better; 4341 } else if (IsSecondSame) 4342 return ImplicitConversionSequence::Worse; 4343 } 4344 return ToAssignLeft? ImplicitConversionSequence::Worse 4345 : ImplicitConversionSequence::Better; 4346 } 4347 4348 // -- "conversion of B* to A* is better than conversion of C* to A*," 4349 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4350 (FromAssignLeft != FromAssignRight)) 4351 return FromAssignLeft? ImplicitConversionSequence::Better 4352 : ImplicitConversionSequence::Worse; 4353 } 4354 } 4355 4356 // Ranking of member-pointer types. 4357 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4358 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4359 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4360 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4361 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4362 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4363 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4364 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4365 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4366 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4367 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4368 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4369 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4370 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4371 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4372 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4373 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4374 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4375 return ImplicitConversionSequence::Worse; 4376 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4377 return ImplicitConversionSequence::Better; 4378 } 4379 // conversion of B::* to C::* is better than conversion of A::* to C::* 4380 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4381 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4382 return ImplicitConversionSequence::Better; 4383 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4384 return ImplicitConversionSequence::Worse; 4385 } 4386 } 4387 4388 if (SCS1.Second == ICK_Derived_To_Base) { 4389 // -- conversion of C to B is better than conversion of C to A, 4390 // -- binding of an expression of type C to a reference of type 4391 // B& is better than binding an expression of type C to a 4392 // reference of type A&, 4393 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4394 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4395 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4396 return ImplicitConversionSequence::Better; 4397 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4398 return ImplicitConversionSequence::Worse; 4399 } 4400 4401 // -- conversion of B to A is better than conversion of C to A. 4402 // -- binding of an expression of type B to a reference of type 4403 // A& is better than binding an expression of type C to a 4404 // reference of type A&, 4405 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4406 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4407 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4408 return ImplicitConversionSequence::Better; 4409 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4410 return ImplicitConversionSequence::Worse; 4411 } 4412 } 4413 4414 return ImplicitConversionSequence::Indistinguishable; 4415 } 4416 4417 /// Determine whether the given type is valid, e.g., it is not an invalid 4418 /// C++ class. 4419 static bool isTypeValid(QualType T) { 4420 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4421 return !Record->isInvalidDecl(); 4422 4423 return true; 4424 } 4425 4426 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4427 if (!T.getQualifiers().hasUnaligned()) 4428 return T; 4429 4430 Qualifiers Q; 4431 T = Ctx.getUnqualifiedArrayType(T, Q); 4432 Q.removeUnaligned(); 4433 return Ctx.getQualifiedType(T, Q); 4434 } 4435 4436 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4437 /// determine whether they are reference-compatible, 4438 /// reference-related, or incompatible, for use in C++ initialization by 4439 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4440 /// type, and the first type (T1) is the pointee type of the reference 4441 /// type being initialized. 4442 Sema::ReferenceCompareResult 4443 Sema::CompareReferenceRelationship(SourceLocation Loc, 4444 QualType OrigT1, QualType OrigT2, 4445 ReferenceConversions *ConvOut) { 4446 assert(!OrigT1->isReferenceType() && 4447 "T1 must be the pointee type of the reference type"); 4448 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4449 4450 QualType T1 = Context.getCanonicalType(OrigT1); 4451 QualType T2 = Context.getCanonicalType(OrigT2); 4452 Qualifiers T1Quals, T2Quals; 4453 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4454 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4455 4456 ReferenceConversions ConvTmp; 4457 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4458 Conv = ReferenceConversions(); 4459 4460 // C++2a [dcl.init.ref]p4: 4461 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4462 // reference-related to "cv2 T2" if T1 is similar to T2, or 4463 // T1 is a base class of T2. 4464 // "cv1 T1" is reference-compatible with "cv2 T2" if 4465 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4466 // "pointer to cv1 T1" via a standard conversion sequence. 4467 4468 // Check for standard conversions we can apply to pointers: derived-to-base 4469 // conversions, ObjC pointer conversions, and function pointer conversions. 4470 // (Qualification conversions are checked last.) 4471 QualType ConvertedT2; 4472 if (UnqualT1 == UnqualT2) { 4473 // Nothing to do. 4474 } else if (isCompleteType(Loc, OrigT2) && 4475 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4476 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4477 Conv |= ReferenceConversions::DerivedToBase; 4478 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4479 UnqualT2->isObjCObjectOrInterfaceType() && 4480 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4481 Conv |= ReferenceConversions::ObjC; 4482 else if (UnqualT2->isFunctionType() && 4483 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4484 Conv |= ReferenceConversions::Function; 4485 // No need to check qualifiers; function types don't have them. 4486 return Ref_Compatible; 4487 } 4488 bool ConvertedReferent = Conv != 0; 4489 4490 // We can have a qualification conversion. Compute whether the types are 4491 // similar at the same time. 4492 bool PreviousToQualsIncludeConst = true; 4493 bool TopLevel = true; 4494 do { 4495 if (T1 == T2) 4496 break; 4497 4498 // We will need a qualification conversion. 4499 Conv |= ReferenceConversions::Qualification; 4500 4501 // Track whether we performed a qualification conversion anywhere other 4502 // than the top level. This matters for ranking reference bindings in 4503 // overload resolution. 4504 if (!TopLevel) 4505 Conv |= ReferenceConversions::NestedQualification; 4506 4507 // MS compiler ignores __unaligned qualifier for references; do the same. 4508 T1 = withoutUnaligned(Context, T1); 4509 T2 = withoutUnaligned(Context, T2); 4510 4511 // If we find a qualifier mismatch, the types are not reference-compatible, 4512 // but are still be reference-related if they're similar. 4513 bool ObjCLifetimeConversion = false; 4514 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4515 PreviousToQualsIncludeConst, 4516 ObjCLifetimeConversion)) 4517 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4518 ? Ref_Related 4519 : Ref_Incompatible; 4520 4521 // FIXME: Should we track this for any level other than the first? 4522 if (ObjCLifetimeConversion) 4523 Conv |= ReferenceConversions::ObjCLifetime; 4524 4525 TopLevel = false; 4526 } while (Context.UnwrapSimilarTypes(T1, T2)); 4527 4528 // At this point, if the types are reference-related, we must either have the 4529 // same inner type (ignoring qualifiers), or must have already worked out how 4530 // to convert the referent. 4531 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4532 ? Ref_Compatible 4533 : Ref_Incompatible; 4534 } 4535 4536 /// Look for a user-defined conversion to a value reference-compatible 4537 /// with DeclType. Return true if something definite is found. 4538 static bool 4539 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4540 QualType DeclType, SourceLocation DeclLoc, 4541 Expr *Init, QualType T2, bool AllowRvalues, 4542 bool AllowExplicit) { 4543 assert(T2->isRecordType() && "Can only find conversions of record types."); 4544 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4545 4546 OverloadCandidateSet CandidateSet( 4547 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4548 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4549 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4550 NamedDecl *D = *I; 4551 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4552 if (isa<UsingShadowDecl>(D)) 4553 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4554 4555 FunctionTemplateDecl *ConvTemplate 4556 = dyn_cast<FunctionTemplateDecl>(D); 4557 CXXConversionDecl *Conv; 4558 if (ConvTemplate) 4559 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4560 else 4561 Conv = cast<CXXConversionDecl>(D); 4562 4563 if (AllowRvalues) { 4564 // If we are initializing an rvalue reference, don't permit conversion 4565 // functions that return lvalues. 4566 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4567 const ReferenceType *RefType 4568 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4569 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4570 continue; 4571 } 4572 4573 if (!ConvTemplate && 4574 S.CompareReferenceRelationship( 4575 DeclLoc, 4576 Conv->getConversionType() 4577 .getNonReferenceType() 4578 .getUnqualifiedType(), 4579 DeclType.getNonReferenceType().getUnqualifiedType()) == 4580 Sema::Ref_Incompatible) 4581 continue; 4582 } else { 4583 // If the conversion function doesn't return a reference type, 4584 // it can't be considered for this conversion. An rvalue reference 4585 // is only acceptable if its referencee is a function type. 4586 4587 const ReferenceType *RefType = 4588 Conv->getConversionType()->getAs<ReferenceType>(); 4589 if (!RefType || 4590 (!RefType->isLValueReferenceType() && 4591 !RefType->getPointeeType()->isFunctionType())) 4592 continue; 4593 } 4594 4595 if (ConvTemplate) 4596 S.AddTemplateConversionCandidate( 4597 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4598 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4599 else 4600 S.AddConversionCandidate( 4601 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4602 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4603 } 4604 4605 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4606 4607 OverloadCandidateSet::iterator Best; 4608 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4609 case OR_Success: 4610 // C++ [over.ics.ref]p1: 4611 // 4612 // [...] If the parameter binds directly to the result of 4613 // applying a conversion function to the argument 4614 // expression, the implicit conversion sequence is a 4615 // user-defined conversion sequence (13.3.3.1.2), with the 4616 // second standard conversion sequence either an identity 4617 // conversion or, if the conversion function returns an 4618 // entity of a type that is a derived class of the parameter 4619 // type, a derived-to-base Conversion. 4620 if (!Best->FinalConversion.DirectBinding) 4621 return false; 4622 4623 ICS.setUserDefined(); 4624 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4625 ICS.UserDefined.After = Best->FinalConversion; 4626 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4627 ICS.UserDefined.ConversionFunction = Best->Function; 4628 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4629 ICS.UserDefined.EllipsisConversion = false; 4630 assert(ICS.UserDefined.After.ReferenceBinding && 4631 ICS.UserDefined.After.DirectBinding && 4632 "Expected a direct reference binding!"); 4633 return true; 4634 4635 case OR_Ambiguous: 4636 ICS.setAmbiguous(); 4637 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4638 Cand != CandidateSet.end(); ++Cand) 4639 if (Cand->Best) 4640 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4641 return true; 4642 4643 case OR_No_Viable_Function: 4644 case OR_Deleted: 4645 // There was no suitable conversion, or we found a deleted 4646 // conversion; continue with other checks. 4647 return false; 4648 } 4649 4650 llvm_unreachable("Invalid OverloadResult!"); 4651 } 4652 4653 /// Compute an implicit conversion sequence for reference 4654 /// initialization. 4655 static ImplicitConversionSequence 4656 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4657 SourceLocation DeclLoc, 4658 bool SuppressUserConversions, 4659 bool AllowExplicit) { 4660 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4661 4662 // Most paths end in a failed conversion. 4663 ImplicitConversionSequence ICS; 4664 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4665 4666 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4667 QualType T2 = Init->getType(); 4668 4669 // If the initializer is the address of an overloaded function, try 4670 // to resolve the overloaded function. If all goes well, T2 is the 4671 // type of the resulting function. 4672 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4673 DeclAccessPair Found; 4674 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4675 false, Found)) 4676 T2 = Fn->getType(); 4677 } 4678 4679 // Compute some basic properties of the types and the initializer. 4680 bool isRValRef = DeclType->isRValueReferenceType(); 4681 Expr::Classification InitCategory = Init->Classify(S.Context); 4682 4683 Sema::ReferenceConversions RefConv; 4684 Sema::ReferenceCompareResult RefRelationship = 4685 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4686 4687 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4688 ICS.setStandard(); 4689 ICS.Standard.First = ICK_Identity; 4690 // FIXME: A reference binding can be a function conversion too. We should 4691 // consider that when ordering reference-to-function bindings. 4692 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4693 ? ICK_Derived_To_Base 4694 : (RefConv & Sema::ReferenceConversions::ObjC) 4695 ? ICK_Compatible_Conversion 4696 : ICK_Identity; 4697 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4698 // a reference binding that performs a non-top-level qualification 4699 // conversion as a qualification conversion, not as an identity conversion. 4700 ICS.Standard.Third = (RefConv & 4701 Sema::ReferenceConversions::NestedQualification) 4702 ? ICK_Qualification 4703 : ICK_Identity; 4704 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4705 ICS.Standard.setToType(0, T2); 4706 ICS.Standard.setToType(1, T1); 4707 ICS.Standard.setToType(2, T1); 4708 ICS.Standard.ReferenceBinding = true; 4709 ICS.Standard.DirectBinding = BindsDirectly; 4710 ICS.Standard.IsLvalueReference = !isRValRef; 4711 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4712 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4713 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4714 ICS.Standard.ObjCLifetimeConversionBinding = 4715 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4716 ICS.Standard.CopyConstructor = nullptr; 4717 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4718 }; 4719 4720 // C++0x [dcl.init.ref]p5: 4721 // A reference to type "cv1 T1" is initialized by an expression 4722 // of type "cv2 T2" as follows: 4723 4724 // -- If reference is an lvalue reference and the initializer expression 4725 if (!isRValRef) { 4726 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4727 // reference-compatible with "cv2 T2," or 4728 // 4729 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4730 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4731 // C++ [over.ics.ref]p1: 4732 // When a parameter of reference type binds directly (8.5.3) 4733 // to an argument expression, the implicit conversion sequence 4734 // is the identity conversion, unless the argument expression 4735 // has a type that is a derived class of the parameter type, 4736 // in which case the implicit conversion sequence is a 4737 // derived-to-base Conversion (13.3.3.1). 4738 SetAsReferenceBinding(/*BindsDirectly=*/true); 4739 4740 // Nothing more to do: the inaccessibility/ambiguity check for 4741 // derived-to-base conversions is suppressed when we're 4742 // computing the implicit conversion sequence (C++ 4743 // [over.best.ics]p2). 4744 return ICS; 4745 } 4746 4747 // -- has a class type (i.e., T2 is a class type), where T1 is 4748 // not reference-related to T2, and can be implicitly 4749 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4750 // is reference-compatible with "cv3 T3" 92) (this 4751 // conversion is selected by enumerating the applicable 4752 // conversion functions (13.3.1.6) and choosing the best 4753 // one through overload resolution (13.3)), 4754 if (!SuppressUserConversions && T2->isRecordType() && 4755 S.isCompleteType(DeclLoc, T2) && 4756 RefRelationship == Sema::Ref_Incompatible) { 4757 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4758 Init, T2, /*AllowRvalues=*/false, 4759 AllowExplicit)) 4760 return ICS; 4761 } 4762 } 4763 4764 // -- Otherwise, the reference shall be an lvalue reference to a 4765 // non-volatile const type (i.e., cv1 shall be const), or the reference 4766 // shall be an rvalue reference. 4767 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4768 return ICS; 4769 4770 // -- If the initializer expression 4771 // 4772 // -- is an xvalue, class prvalue, array prvalue or function 4773 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4774 if (RefRelationship == Sema::Ref_Compatible && 4775 (InitCategory.isXValue() || 4776 (InitCategory.isPRValue() && 4777 (T2->isRecordType() || T2->isArrayType())) || 4778 (InitCategory.isLValue() && T2->isFunctionType()))) { 4779 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4780 // binding unless we're binding to a class prvalue. 4781 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4782 // allow the use of rvalue references in C++98/03 for the benefit of 4783 // standard library implementors; therefore, we need the xvalue check here. 4784 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4785 !(InitCategory.isPRValue() || T2->isRecordType())); 4786 return ICS; 4787 } 4788 4789 // -- has a class type (i.e., T2 is a class type), where T1 is not 4790 // reference-related to T2, and can be implicitly converted to 4791 // an xvalue, class prvalue, or function lvalue of type 4792 // "cv3 T3", where "cv1 T1" is reference-compatible with 4793 // "cv3 T3", 4794 // 4795 // then the reference is bound to the value of the initializer 4796 // expression in the first case and to the result of the conversion 4797 // in the second case (or, in either case, to an appropriate base 4798 // class subobject). 4799 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4800 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4801 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4802 Init, T2, /*AllowRvalues=*/true, 4803 AllowExplicit)) { 4804 // In the second case, if the reference is an rvalue reference 4805 // and the second standard conversion sequence of the 4806 // user-defined conversion sequence includes an lvalue-to-rvalue 4807 // conversion, the program is ill-formed. 4808 if (ICS.isUserDefined() && isRValRef && 4809 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4810 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4811 4812 return ICS; 4813 } 4814 4815 // A temporary of function type cannot be created; don't even try. 4816 if (T1->isFunctionType()) 4817 return ICS; 4818 4819 // -- Otherwise, a temporary of type "cv1 T1" is created and 4820 // initialized from the initializer expression using the 4821 // rules for a non-reference copy initialization (8.5). The 4822 // reference is then bound to the temporary. If T1 is 4823 // reference-related to T2, cv1 must be the same 4824 // cv-qualification as, or greater cv-qualification than, 4825 // cv2; otherwise, the program is ill-formed. 4826 if (RefRelationship == Sema::Ref_Related) { 4827 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4828 // we would be reference-compatible or reference-compatible with 4829 // added qualification. But that wasn't the case, so the reference 4830 // initialization fails. 4831 // 4832 // Note that we only want to check address spaces and cvr-qualifiers here. 4833 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4834 Qualifiers T1Quals = T1.getQualifiers(); 4835 Qualifiers T2Quals = T2.getQualifiers(); 4836 T1Quals.removeObjCGCAttr(); 4837 T1Quals.removeObjCLifetime(); 4838 T2Quals.removeObjCGCAttr(); 4839 T2Quals.removeObjCLifetime(); 4840 // MS compiler ignores __unaligned qualifier for references; do the same. 4841 T1Quals.removeUnaligned(); 4842 T2Quals.removeUnaligned(); 4843 if (!T1Quals.compatiblyIncludes(T2Quals)) 4844 return ICS; 4845 } 4846 4847 // If at least one of the types is a class type, the types are not 4848 // related, and we aren't allowed any user conversions, the 4849 // reference binding fails. This case is important for breaking 4850 // recursion, since TryImplicitConversion below will attempt to 4851 // create a temporary through the use of a copy constructor. 4852 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4853 (T1->isRecordType() || T2->isRecordType())) 4854 return ICS; 4855 4856 // If T1 is reference-related to T2 and the reference is an rvalue 4857 // reference, the initializer expression shall not be an lvalue. 4858 if (RefRelationship >= Sema::Ref_Related && 4859 isRValRef && Init->Classify(S.Context).isLValue()) 4860 return ICS; 4861 4862 // C++ [over.ics.ref]p2: 4863 // When a parameter of reference type is not bound directly to 4864 // an argument expression, the conversion sequence is the one 4865 // required to convert the argument expression to the 4866 // underlying type of the reference according to 4867 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4868 // to copy-initializing a temporary of the underlying type with 4869 // the argument expression. Any difference in top-level 4870 // cv-qualification is subsumed by the initialization itself 4871 // and does not constitute a conversion. 4872 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4873 AllowedExplicit::None, 4874 /*InOverloadResolution=*/false, 4875 /*CStyle=*/false, 4876 /*AllowObjCWritebackConversion=*/false, 4877 /*AllowObjCConversionOnExplicit=*/false); 4878 4879 // Of course, that's still a reference binding. 4880 if (ICS.isStandard()) { 4881 ICS.Standard.ReferenceBinding = true; 4882 ICS.Standard.IsLvalueReference = !isRValRef; 4883 ICS.Standard.BindsToFunctionLvalue = false; 4884 ICS.Standard.BindsToRvalue = true; 4885 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4886 ICS.Standard.ObjCLifetimeConversionBinding = false; 4887 } else if (ICS.isUserDefined()) { 4888 const ReferenceType *LValRefType = 4889 ICS.UserDefined.ConversionFunction->getReturnType() 4890 ->getAs<LValueReferenceType>(); 4891 4892 // C++ [over.ics.ref]p3: 4893 // Except for an implicit object parameter, for which see 13.3.1, a 4894 // standard conversion sequence cannot be formed if it requires [...] 4895 // binding an rvalue reference to an lvalue other than a function 4896 // lvalue. 4897 // Note that the function case is not possible here. 4898 if (DeclType->isRValueReferenceType() && LValRefType) { 4899 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4900 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4901 // reference to an rvalue! 4902 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4903 return ICS; 4904 } 4905 4906 ICS.UserDefined.After.ReferenceBinding = true; 4907 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4908 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4909 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4910 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4911 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4912 } 4913 4914 return ICS; 4915 } 4916 4917 static ImplicitConversionSequence 4918 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4919 bool SuppressUserConversions, 4920 bool InOverloadResolution, 4921 bool AllowObjCWritebackConversion, 4922 bool AllowExplicit = false); 4923 4924 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4925 /// initializer list From. 4926 static ImplicitConversionSequence 4927 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4928 bool SuppressUserConversions, 4929 bool InOverloadResolution, 4930 bool AllowObjCWritebackConversion) { 4931 // C++11 [over.ics.list]p1: 4932 // When an argument is an initializer list, it is not an expression and 4933 // special rules apply for converting it to a parameter type. 4934 4935 ImplicitConversionSequence Result; 4936 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4937 4938 // We need a complete type for what follows. Incomplete types can never be 4939 // initialized from init lists. 4940 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4941 return Result; 4942 4943 // Per DR1467: 4944 // If the parameter type is a class X and the initializer list has a single 4945 // element of type cv U, where U is X or a class derived from X, the 4946 // implicit conversion sequence is the one required to convert the element 4947 // to the parameter type. 4948 // 4949 // Otherwise, if the parameter type is a character array [... ] 4950 // and the initializer list has a single element that is an 4951 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4952 // implicit conversion sequence is the identity conversion. 4953 if (From->getNumInits() == 1) { 4954 if (ToType->isRecordType()) { 4955 QualType InitType = From->getInit(0)->getType(); 4956 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4957 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4958 return TryCopyInitialization(S, From->getInit(0), ToType, 4959 SuppressUserConversions, 4960 InOverloadResolution, 4961 AllowObjCWritebackConversion); 4962 } 4963 // FIXME: Check the other conditions here: array of character type, 4964 // initializer is a string literal. 4965 if (ToType->isArrayType()) { 4966 InitializedEntity Entity = 4967 InitializedEntity::InitializeParameter(S.Context, ToType, 4968 /*Consumed=*/false); 4969 if (S.CanPerformCopyInitialization(Entity, From)) { 4970 Result.setStandard(); 4971 Result.Standard.setAsIdentityConversion(); 4972 Result.Standard.setFromType(ToType); 4973 Result.Standard.setAllToTypes(ToType); 4974 return Result; 4975 } 4976 } 4977 } 4978 4979 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4980 // C++11 [over.ics.list]p2: 4981 // If the parameter type is std::initializer_list<X> or "array of X" and 4982 // all the elements can be implicitly converted to X, the implicit 4983 // conversion sequence is the worst conversion necessary to convert an 4984 // element of the list to X. 4985 // 4986 // C++14 [over.ics.list]p3: 4987 // Otherwise, if the parameter type is "array of N X", if the initializer 4988 // list has exactly N elements or if it has fewer than N elements and X is 4989 // default-constructible, and if all the elements of the initializer list 4990 // can be implicitly converted to X, the implicit conversion sequence is 4991 // the worst conversion necessary to convert an element of the list to X. 4992 // 4993 // FIXME: We're missing a lot of these checks. 4994 bool toStdInitializerList = false; 4995 QualType X; 4996 if (ToType->isArrayType()) 4997 X = S.Context.getAsArrayType(ToType)->getElementType(); 4998 else 4999 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5000 if (!X.isNull()) { 5001 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5002 Expr *Init = From->getInit(i); 5003 ImplicitConversionSequence ICS = 5004 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5005 InOverloadResolution, 5006 AllowObjCWritebackConversion); 5007 // If a single element isn't convertible, fail. 5008 if (ICS.isBad()) { 5009 Result = ICS; 5010 break; 5011 } 5012 // Otherwise, look for the worst conversion. 5013 if (Result.isBad() || CompareImplicitConversionSequences( 5014 S, From->getBeginLoc(), ICS, Result) == 5015 ImplicitConversionSequence::Worse) 5016 Result = ICS; 5017 } 5018 5019 // For an empty list, we won't have computed any conversion sequence. 5020 // Introduce the identity conversion sequence. 5021 if (From->getNumInits() == 0) { 5022 Result.setStandard(); 5023 Result.Standard.setAsIdentityConversion(); 5024 Result.Standard.setFromType(ToType); 5025 Result.Standard.setAllToTypes(ToType); 5026 } 5027 5028 Result.setStdInitializerListElement(toStdInitializerList); 5029 return Result; 5030 } 5031 5032 // C++14 [over.ics.list]p4: 5033 // C++11 [over.ics.list]p3: 5034 // Otherwise, if the parameter is a non-aggregate class X and overload 5035 // resolution chooses a single best constructor [...] the implicit 5036 // conversion sequence is a user-defined conversion sequence. If multiple 5037 // constructors are viable but none is better than the others, the 5038 // implicit conversion sequence is a user-defined conversion sequence. 5039 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5040 // This function can deal with initializer lists. 5041 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5042 AllowedExplicit::None, 5043 InOverloadResolution, /*CStyle=*/false, 5044 AllowObjCWritebackConversion, 5045 /*AllowObjCConversionOnExplicit=*/false); 5046 } 5047 5048 // C++14 [over.ics.list]p5: 5049 // C++11 [over.ics.list]p4: 5050 // Otherwise, if the parameter has an aggregate type which can be 5051 // initialized from the initializer list [...] the implicit conversion 5052 // sequence is a user-defined conversion sequence. 5053 if (ToType->isAggregateType()) { 5054 // Type is an aggregate, argument is an init list. At this point it comes 5055 // down to checking whether the initialization works. 5056 // FIXME: Find out whether this parameter is consumed or not. 5057 InitializedEntity Entity = 5058 InitializedEntity::InitializeParameter(S.Context, ToType, 5059 /*Consumed=*/false); 5060 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5061 From)) { 5062 Result.setUserDefined(); 5063 Result.UserDefined.Before.setAsIdentityConversion(); 5064 // Initializer lists don't have a type. 5065 Result.UserDefined.Before.setFromType(QualType()); 5066 Result.UserDefined.Before.setAllToTypes(QualType()); 5067 5068 Result.UserDefined.After.setAsIdentityConversion(); 5069 Result.UserDefined.After.setFromType(ToType); 5070 Result.UserDefined.After.setAllToTypes(ToType); 5071 Result.UserDefined.ConversionFunction = nullptr; 5072 } 5073 return Result; 5074 } 5075 5076 // C++14 [over.ics.list]p6: 5077 // C++11 [over.ics.list]p5: 5078 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5079 if (ToType->isReferenceType()) { 5080 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5081 // mention initializer lists in any way. So we go by what list- 5082 // initialization would do and try to extrapolate from that. 5083 5084 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5085 5086 // If the initializer list has a single element that is reference-related 5087 // to the parameter type, we initialize the reference from that. 5088 if (From->getNumInits() == 1) { 5089 Expr *Init = From->getInit(0); 5090 5091 QualType T2 = Init->getType(); 5092 5093 // If the initializer is the address of an overloaded function, try 5094 // to resolve the overloaded function. If all goes well, T2 is the 5095 // type of the resulting function. 5096 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5097 DeclAccessPair Found; 5098 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5099 Init, ToType, false, Found)) 5100 T2 = Fn->getType(); 5101 } 5102 5103 // Compute some basic properties of the types and the initializer. 5104 Sema::ReferenceCompareResult RefRelationship = 5105 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5106 5107 if (RefRelationship >= Sema::Ref_Related) { 5108 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5109 SuppressUserConversions, 5110 /*AllowExplicit=*/false); 5111 } 5112 } 5113 5114 // Otherwise, we bind the reference to a temporary created from the 5115 // initializer list. 5116 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5117 InOverloadResolution, 5118 AllowObjCWritebackConversion); 5119 if (Result.isFailure()) 5120 return Result; 5121 assert(!Result.isEllipsis() && 5122 "Sub-initialization cannot result in ellipsis conversion."); 5123 5124 // Can we even bind to a temporary? 5125 if (ToType->isRValueReferenceType() || 5126 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5127 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5128 Result.UserDefined.After; 5129 SCS.ReferenceBinding = true; 5130 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5131 SCS.BindsToRvalue = true; 5132 SCS.BindsToFunctionLvalue = false; 5133 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5134 SCS.ObjCLifetimeConversionBinding = false; 5135 } else 5136 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5137 From, ToType); 5138 return Result; 5139 } 5140 5141 // C++14 [over.ics.list]p7: 5142 // C++11 [over.ics.list]p6: 5143 // Otherwise, if the parameter type is not a class: 5144 if (!ToType->isRecordType()) { 5145 // - if the initializer list has one element that is not itself an 5146 // initializer list, the implicit conversion sequence is the one 5147 // required to convert the element to the parameter type. 5148 unsigned NumInits = From->getNumInits(); 5149 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5150 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5151 SuppressUserConversions, 5152 InOverloadResolution, 5153 AllowObjCWritebackConversion); 5154 // - if the initializer list has no elements, the implicit conversion 5155 // sequence is the identity conversion. 5156 else if (NumInits == 0) { 5157 Result.setStandard(); 5158 Result.Standard.setAsIdentityConversion(); 5159 Result.Standard.setFromType(ToType); 5160 Result.Standard.setAllToTypes(ToType); 5161 } 5162 return Result; 5163 } 5164 5165 // C++14 [over.ics.list]p8: 5166 // C++11 [over.ics.list]p7: 5167 // In all cases other than those enumerated above, no conversion is possible 5168 return Result; 5169 } 5170 5171 /// TryCopyInitialization - Try to copy-initialize a value of type 5172 /// ToType from the expression From. Return the implicit conversion 5173 /// sequence required to pass this argument, which may be a bad 5174 /// conversion sequence (meaning that the argument cannot be passed to 5175 /// a parameter of this type). If @p SuppressUserConversions, then we 5176 /// do not permit any user-defined conversion sequences. 5177 static ImplicitConversionSequence 5178 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5179 bool SuppressUserConversions, 5180 bool InOverloadResolution, 5181 bool AllowObjCWritebackConversion, 5182 bool AllowExplicit) { 5183 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5184 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5185 InOverloadResolution,AllowObjCWritebackConversion); 5186 5187 if (ToType->isReferenceType()) 5188 return TryReferenceInit(S, From, ToType, 5189 /*FIXME:*/ From->getBeginLoc(), 5190 SuppressUserConversions, AllowExplicit); 5191 5192 return TryImplicitConversion(S, From, ToType, 5193 SuppressUserConversions, 5194 AllowedExplicit::None, 5195 InOverloadResolution, 5196 /*CStyle=*/false, 5197 AllowObjCWritebackConversion, 5198 /*AllowObjCConversionOnExplicit=*/false); 5199 } 5200 5201 static bool TryCopyInitialization(const CanQualType FromQTy, 5202 const CanQualType ToQTy, 5203 Sema &S, 5204 SourceLocation Loc, 5205 ExprValueKind FromVK) { 5206 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5207 ImplicitConversionSequence ICS = 5208 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5209 5210 return !ICS.isBad(); 5211 } 5212 5213 /// TryObjectArgumentInitialization - Try to initialize the object 5214 /// parameter of the given member function (@c Method) from the 5215 /// expression @p From. 5216 static ImplicitConversionSequence 5217 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5218 Expr::Classification FromClassification, 5219 CXXMethodDecl *Method, 5220 CXXRecordDecl *ActingContext) { 5221 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5222 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5223 // const volatile object. 5224 Qualifiers Quals = Method->getMethodQualifiers(); 5225 if (isa<CXXDestructorDecl>(Method)) { 5226 Quals.addConst(); 5227 Quals.addVolatile(); 5228 } 5229 5230 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5231 5232 // Set up the conversion sequence as a "bad" conversion, to allow us 5233 // to exit early. 5234 ImplicitConversionSequence ICS; 5235 5236 // We need to have an object of class type. 5237 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5238 FromType = PT->getPointeeType(); 5239 5240 // When we had a pointer, it's implicitly dereferenced, so we 5241 // better have an lvalue. 5242 assert(FromClassification.isLValue()); 5243 } 5244 5245 assert(FromType->isRecordType()); 5246 5247 // C++0x [over.match.funcs]p4: 5248 // For non-static member functions, the type of the implicit object 5249 // parameter is 5250 // 5251 // - "lvalue reference to cv X" for functions declared without a 5252 // ref-qualifier or with the & ref-qualifier 5253 // - "rvalue reference to cv X" for functions declared with the && 5254 // ref-qualifier 5255 // 5256 // where X is the class of which the function is a member and cv is the 5257 // cv-qualification on the member function declaration. 5258 // 5259 // However, when finding an implicit conversion sequence for the argument, we 5260 // are not allowed to perform user-defined conversions 5261 // (C++ [over.match.funcs]p5). We perform a simplified version of 5262 // reference binding here, that allows class rvalues to bind to 5263 // non-constant references. 5264 5265 // First check the qualifiers. 5266 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5267 if (ImplicitParamType.getCVRQualifiers() 5268 != FromTypeCanon.getLocalCVRQualifiers() && 5269 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5270 ICS.setBad(BadConversionSequence::bad_qualifiers, 5271 FromType, ImplicitParamType); 5272 return ICS; 5273 } 5274 5275 if (FromTypeCanon.hasAddressSpace()) { 5276 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5277 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5278 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5279 ICS.setBad(BadConversionSequence::bad_qualifiers, 5280 FromType, ImplicitParamType); 5281 return ICS; 5282 } 5283 } 5284 5285 // Check that we have either the same type or a derived type. It 5286 // affects the conversion rank. 5287 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5288 ImplicitConversionKind SecondKind; 5289 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5290 SecondKind = ICK_Identity; 5291 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5292 SecondKind = ICK_Derived_To_Base; 5293 else { 5294 ICS.setBad(BadConversionSequence::unrelated_class, 5295 FromType, ImplicitParamType); 5296 return ICS; 5297 } 5298 5299 // Check the ref-qualifier. 5300 switch (Method->getRefQualifier()) { 5301 case RQ_None: 5302 // Do nothing; we don't care about lvalueness or rvalueness. 5303 break; 5304 5305 case RQ_LValue: 5306 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5307 // non-const lvalue reference cannot bind to an rvalue 5308 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5309 ImplicitParamType); 5310 return ICS; 5311 } 5312 break; 5313 5314 case RQ_RValue: 5315 if (!FromClassification.isRValue()) { 5316 // rvalue reference cannot bind to an lvalue 5317 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5318 ImplicitParamType); 5319 return ICS; 5320 } 5321 break; 5322 } 5323 5324 // Success. Mark this as a reference binding. 5325 ICS.setStandard(); 5326 ICS.Standard.setAsIdentityConversion(); 5327 ICS.Standard.Second = SecondKind; 5328 ICS.Standard.setFromType(FromType); 5329 ICS.Standard.setAllToTypes(ImplicitParamType); 5330 ICS.Standard.ReferenceBinding = true; 5331 ICS.Standard.DirectBinding = true; 5332 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5333 ICS.Standard.BindsToFunctionLvalue = false; 5334 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5335 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5336 = (Method->getRefQualifier() == RQ_None); 5337 return ICS; 5338 } 5339 5340 /// PerformObjectArgumentInitialization - Perform initialization of 5341 /// the implicit object parameter for the given Method with the given 5342 /// expression. 5343 ExprResult 5344 Sema::PerformObjectArgumentInitialization(Expr *From, 5345 NestedNameSpecifier *Qualifier, 5346 NamedDecl *FoundDecl, 5347 CXXMethodDecl *Method) { 5348 QualType FromRecordType, DestType; 5349 QualType ImplicitParamRecordType = 5350 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5351 5352 Expr::Classification FromClassification; 5353 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5354 FromRecordType = PT->getPointeeType(); 5355 DestType = Method->getThisType(); 5356 FromClassification = Expr::Classification::makeSimpleLValue(); 5357 } else { 5358 FromRecordType = From->getType(); 5359 DestType = ImplicitParamRecordType; 5360 FromClassification = From->Classify(Context); 5361 5362 // When performing member access on an rvalue, materialize a temporary. 5363 if (From->isRValue()) { 5364 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5365 Method->getRefQualifier() != 5366 RefQualifierKind::RQ_RValue); 5367 } 5368 } 5369 5370 // Note that we always use the true parent context when performing 5371 // the actual argument initialization. 5372 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5373 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5374 Method->getParent()); 5375 if (ICS.isBad()) { 5376 switch (ICS.Bad.Kind) { 5377 case BadConversionSequence::bad_qualifiers: { 5378 Qualifiers FromQs = FromRecordType.getQualifiers(); 5379 Qualifiers ToQs = DestType.getQualifiers(); 5380 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5381 if (CVR) { 5382 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5383 << Method->getDeclName() << FromRecordType << (CVR - 1) 5384 << From->getSourceRange(); 5385 Diag(Method->getLocation(), diag::note_previous_decl) 5386 << Method->getDeclName(); 5387 return ExprError(); 5388 } 5389 break; 5390 } 5391 5392 case BadConversionSequence::lvalue_ref_to_rvalue: 5393 case BadConversionSequence::rvalue_ref_to_lvalue: { 5394 bool IsRValueQualified = 5395 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5396 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5397 << Method->getDeclName() << FromClassification.isRValue() 5398 << IsRValueQualified; 5399 Diag(Method->getLocation(), diag::note_previous_decl) 5400 << Method->getDeclName(); 5401 return ExprError(); 5402 } 5403 5404 case BadConversionSequence::no_conversion: 5405 case BadConversionSequence::unrelated_class: 5406 break; 5407 } 5408 5409 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5410 << ImplicitParamRecordType << FromRecordType 5411 << From->getSourceRange(); 5412 } 5413 5414 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5415 ExprResult FromRes = 5416 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5417 if (FromRes.isInvalid()) 5418 return ExprError(); 5419 From = FromRes.get(); 5420 } 5421 5422 if (!Context.hasSameType(From->getType(), DestType)) { 5423 CastKind CK; 5424 QualType PteeTy = DestType->getPointeeType(); 5425 LangAS DestAS = 5426 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5427 if (FromRecordType.getAddressSpace() != DestAS) 5428 CK = CK_AddressSpaceConversion; 5429 else 5430 CK = CK_NoOp; 5431 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5432 } 5433 return From; 5434 } 5435 5436 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5437 /// expression From to bool (C++0x [conv]p3). 5438 static ImplicitConversionSequence 5439 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5440 // C++ [dcl.init]/17.8: 5441 // - Otherwise, if the initialization is direct-initialization, the source 5442 // type is std::nullptr_t, and the destination type is bool, the initial 5443 // value of the object being initialized is false. 5444 if (From->getType()->isNullPtrType()) 5445 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5446 S.Context.BoolTy, 5447 From->isGLValue()); 5448 5449 // All other direct-initialization of bool is equivalent to an implicit 5450 // conversion to bool in which explicit conversions are permitted. 5451 return TryImplicitConversion(S, From, S.Context.BoolTy, 5452 /*SuppressUserConversions=*/false, 5453 AllowedExplicit::Conversions, 5454 /*InOverloadResolution=*/false, 5455 /*CStyle=*/false, 5456 /*AllowObjCWritebackConversion=*/false, 5457 /*AllowObjCConversionOnExplicit=*/false); 5458 } 5459 5460 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5461 /// of the expression From to bool (C++0x [conv]p3). 5462 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5463 if (checkPlaceholderForOverload(*this, From)) 5464 return ExprError(); 5465 5466 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5467 if (!ICS.isBad()) 5468 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5469 5470 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5471 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5472 << From->getType() << From->getSourceRange(); 5473 return ExprError(); 5474 } 5475 5476 /// Check that the specified conversion is permitted in a converted constant 5477 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5478 /// is acceptable. 5479 static bool CheckConvertedConstantConversions(Sema &S, 5480 StandardConversionSequence &SCS) { 5481 // Since we know that the target type is an integral or unscoped enumeration 5482 // type, most conversion kinds are impossible. All possible First and Third 5483 // conversions are fine. 5484 switch (SCS.Second) { 5485 case ICK_Identity: 5486 case ICK_Function_Conversion: 5487 case ICK_Integral_Promotion: 5488 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5489 case ICK_Zero_Queue_Conversion: 5490 return true; 5491 5492 case ICK_Boolean_Conversion: 5493 // Conversion from an integral or unscoped enumeration type to bool is 5494 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5495 // conversion, so we allow it in a converted constant expression. 5496 // 5497 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5498 // a lot of popular code. We should at least add a warning for this 5499 // (non-conforming) extension. 5500 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5501 SCS.getToType(2)->isBooleanType(); 5502 5503 case ICK_Pointer_Conversion: 5504 case ICK_Pointer_Member: 5505 // C++1z: null pointer conversions and null member pointer conversions are 5506 // only permitted if the source type is std::nullptr_t. 5507 return SCS.getFromType()->isNullPtrType(); 5508 5509 case ICK_Floating_Promotion: 5510 case ICK_Complex_Promotion: 5511 case ICK_Floating_Conversion: 5512 case ICK_Complex_Conversion: 5513 case ICK_Floating_Integral: 5514 case ICK_Compatible_Conversion: 5515 case ICK_Derived_To_Base: 5516 case ICK_Vector_Conversion: 5517 case ICK_Vector_Splat: 5518 case ICK_Complex_Real: 5519 case ICK_Block_Pointer_Conversion: 5520 case ICK_TransparentUnionConversion: 5521 case ICK_Writeback_Conversion: 5522 case ICK_Zero_Event_Conversion: 5523 case ICK_C_Only_Conversion: 5524 case ICK_Incompatible_Pointer_Conversion: 5525 return false; 5526 5527 case ICK_Lvalue_To_Rvalue: 5528 case ICK_Array_To_Pointer: 5529 case ICK_Function_To_Pointer: 5530 llvm_unreachable("found a first conversion kind in Second"); 5531 5532 case ICK_Qualification: 5533 llvm_unreachable("found a third conversion kind in Second"); 5534 5535 case ICK_Num_Conversion_Kinds: 5536 break; 5537 } 5538 5539 llvm_unreachable("unknown conversion kind"); 5540 } 5541 5542 /// CheckConvertedConstantExpression - Check that the expression From is a 5543 /// converted constant expression of type T, perform the conversion and produce 5544 /// the converted expression, per C++11 [expr.const]p3. 5545 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5546 QualType T, APValue &Value, 5547 Sema::CCEKind CCE, 5548 bool RequireInt) { 5549 assert(S.getLangOpts().CPlusPlus11 && 5550 "converted constant expression outside C++11"); 5551 5552 if (checkPlaceholderForOverload(S, From)) 5553 return ExprError(); 5554 5555 // C++1z [expr.const]p3: 5556 // A converted constant expression of type T is an expression, 5557 // implicitly converted to type T, where the converted 5558 // expression is a constant expression and the implicit conversion 5559 // sequence contains only [... list of conversions ...]. 5560 // C++1z [stmt.if]p2: 5561 // If the if statement is of the form if constexpr, the value of the 5562 // condition shall be a contextually converted constant expression of type 5563 // bool. 5564 ImplicitConversionSequence ICS = 5565 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5566 ? TryContextuallyConvertToBool(S, From) 5567 : TryCopyInitialization(S, From, T, 5568 /*SuppressUserConversions=*/false, 5569 /*InOverloadResolution=*/false, 5570 /*AllowObjCWritebackConversion=*/false, 5571 /*AllowExplicit=*/false); 5572 StandardConversionSequence *SCS = nullptr; 5573 switch (ICS.getKind()) { 5574 case ImplicitConversionSequence::StandardConversion: 5575 SCS = &ICS.Standard; 5576 break; 5577 case ImplicitConversionSequence::UserDefinedConversion: 5578 // We are converting to a non-class type, so the Before sequence 5579 // must be trivial. 5580 SCS = &ICS.UserDefined.After; 5581 break; 5582 case ImplicitConversionSequence::AmbiguousConversion: 5583 case ImplicitConversionSequence::BadConversion: 5584 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5585 return S.Diag(From->getBeginLoc(), 5586 diag::err_typecheck_converted_constant_expression) 5587 << From->getType() << From->getSourceRange() << T; 5588 return ExprError(); 5589 5590 case ImplicitConversionSequence::EllipsisConversion: 5591 llvm_unreachable("ellipsis conversion in converted constant expression"); 5592 } 5593 5594 // Check that we would only use permitted conversions. 5595 if (!CheckConvertedConstantConversions(S, *SCS)) { 5596 return S.Diag(From->getBeginLoc(), 5597 diag::err_typecheck_converted_constant_expression_disallowed) 5598 << From->getType() << From->getSourceRange() << T; 5599 } 5600 // [...] and where the reference binding (if any) binds directly. 5601 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5602 return S.Diag(From->getBeginLoc(), 5603 diag::err_typecheck_converted_constant_expression_indirect) 5604 << From->getType() << From->getSourceRange() << T; 5605 } 5606 5607 ExprResult Result = 5608 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5609 if (Result.isInvalid()) 5610 return Result; 5611 5612 // C++2a [intro.execution]p5: 5613 // A full-expression is [...] a constant-expression [...] 5614 Result = 5615 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5616 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5617 if (Result.isInvalid()) 5618 return Result; 5619 5620 // Check for a narrowing implicit conversion. 5621 APValue PreNarrowingValue; 5622 QualType PreNarrowingType; 5623 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5624 PreNarrowingType)) { 5625 case NK_Dependent_Narrowing: 5626 // Implicit conversion to a narrower type, but the expression is 5627 // value-dependent so we can't tell whether it's actually narrowing. 5628 case NK_Variable_Narrowing: 5629 // Implicit conversion to a narrower type, and the value is not a constant 5630 // expression. We'll diagnose this in a moment. 5631 case NK_Not_Narrowing: 5632 break; 5633 5634 case NK_Constant_Narrowing: 5635 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5636 << CCE << /*Constant*/ 1 5637 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5638 break; 5639 5640 case NK_Type_Narrowing: 5641 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5642 << CCE << /*Constant*/ 0 << From->getType() << T; 5643 break; 5644 } 5645 5646 if (Result.get()->isValueDependent()) { 5647 Value = APValue(); 5648 return Result; 5649 } 5650 5651 // Check the expression is a constant expression. 5652 SmallVector<PartialDiagnosticAt, 8> Notes; 5653 Expr::EvalResult Eval; 5654 Eval.Diag = &Notes; 5655 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5656 ? Expr::EvaluateForMangling 5657 : Expr::EvaluateForCodeGen; 5658 5659 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5660 (RequireInt && !Eval.Val.isInt())) { 5661 // The expression can't be folded, so we can't keep it at this position in 5662 // the AST. 5663 Result = ExprError(); 5664 } else { 5665 Value = Eval.Val; 5666 5667 if (Notes.empty()) { 5668 // It's a constant expression. 5669 return ConstantExpr::Create(S.Context, Result.get(), Value); 5670 } 5671 } 5672 5673 // It's not a constant expression. Produce an appropriate diagnostic. 5674 if (Notes.size() == 1 && 5675 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5676 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5677 else { 5678 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5679 << CCE << From->getSourceRange(); 5680 for (unsigned I = 0; I < Notes.size(); ++I) 5681 S.Diag(Notes[I].first, Notes[I].second); 5682 } 5683 return ExprError(); 5684 } 5685 5686 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5687 APValue &Value, CCEKind CCE) { 5688 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5689 } 5690 5691 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5692 llvm::APSInt &Value, 5693 CCEKind CCE) { 5694 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5695 5696 APValue V; 5697 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5698 if (!R.isInvalid() && !R.get()->isValueDependent()) 5699 Value = V.getInt(); 5700 return R; 5701 } 5702 5703 5704 /// dropPointerConversions - If the given standard conversion sequence 5705 /// involves any pointer conversions, remove them. This may change 5706 /// the result type of the conversion sequence. 5707 static void dropPointerConversion(StandardConversionSequence &SCS) { 5708 if (SCS.Second == ICK_Pointer_Conversion) { 5709 SCS.Second = ICK_Identity; 5710 SCS.Third = ICK_Identity; 5711 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5712 } 5713 } 5714 5715 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5716 /// convert the expression From to an Objective-C pointer type. 5717 static ImplicitConversionSequence 5718 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5719 // Do an implicit conversion to 'id'. 5720 QualType Ty = S.Context.getObjCIdType(); 5721 ImplicitConversionSequence ICS 5722 = TryImplicitConversion(S, From, Ty, 5723 // FIXME: Are these flags correct? 5724 /*SuppressUserConversions=*/false, 5725 AllowedExplicit::Conversions, 5726 /*InOverloadResolution=*/false, 5727 /*CStyle=*/false, 5728 /*AllowObjCWritebackConversion=*/false, 5729 /*AllowObjCConversionOnExplicit=*/true); 5730 5731 // Strip off any final conversions to 'id'. 5732 switch (ICS.getKind()) { 5733 case ImplicitConversionSequence::BadConversion: 5734 case ImplicitConversionSequence::AmbiguousConversion: 5735 case ImplicitConversionSequence::EllipsisConversion: 5736 break; 5737 5738 case ImplicitConversionSequence::UserDefinedConversion: 5739 dropPointerConversion(ICS.UserDefined.After); 5740 break; 5741 5742 case ImplicitConversionSequence::StandardConversion: 5743 dropPointerConversion(ICS.Standard); 5744 break; 5745 } 5746 5747 return ICS; 5748 } 5749 5750 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5751 /// conversion of the expression From to an Objective-C pointer type. 5752 /// Returns a valid but null ExprResult if no conversion sequence exists. 5753 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5754 if (checkPlaceholderForOverload(*this, From)) 5755 return ExprError(); 5756 5757 QualType Ty = Context.getObjCIdType(); 5758 ImplicitConversionSequence ICS = 5759 TryContextuallyConvertToObjCPointer(*this, From); 5760 if (!ICS.isBad()) 5761 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5762 return ExprResult(); 5763 } 5764 5765 /// Determine whether the provided type is an integral type, or an enumeration 5766 /// type of a permitted flavor. 5767 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5768 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5769 : T->isIntegralOrUnscopedEnumerationType(); 5770 } 5771 5772 static ExprResult 5773 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5774 Sema::ContextualImplicitConverter &Converter, 5775 QualType T, UnresolvedSetImpl &ViableConversions) { 5776 5777 if (Converter.Suppress) 5778 return ExprError(); 5779 5780 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5781 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5782 CXXConversionDecl *Conv = 5783 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5784 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5785 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5786 } 5787 return From; 5788 } 5789 5790 static bool 5791 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5792 Sema::ContextualImplicitConverter &Converter, 5793 QualType T, bool HadMultipleCandidates, 5794 UnresolvedSetImpl &ExplicitConversions) { 5795 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5796 DeclAccessPair Found = ExplicitConversions[0]; 5797 CXXConversionDecl *Conversion = 5798 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5799 5800 // The user probably meant to invoke the given explicit 5801 // conversion; use it. 5802 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5803 std::string TypeStr; 5804 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5805 5806 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5807 << FixItHint::CreateInsertion(From->getBeginLoc(), 5808 "static_cast<" + TypeStr + ">(") 5809 << FixItHint::CreateInsertion( 5810 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5811 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5812 5813 // If we aren't in a SFINAE context, build a call to the 5814 // explicit conversion function. 5815 if (SemaRef.isSFINAEContext()) 5816 return true; 5817 5818 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5819 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5820 HadMultipleCandidates); 5821 if (Result.isInvalid()) 5822 return true; 5823 // Record usage of conversion in an implicit cast. 5824 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5825 CK_UserDefinedConversion, Result.get(), 5826 nullptr, Result.get()->getValueKind()); 5827 } 5828 return false; 5829 } 5830 5831 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5832 Sema::ContextualImplicitConverter &Converter, 5833 QualType T, bool HadMultipleCandidates, 5834 DeclAccessPair &Found) { 5835 CXXConversionDecl *Conversion = 5836 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5837 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5838 5839 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5840 if (!Converter.SuppressConversion) { 5841 if (SemaRef.isSFINAEContext()) 5842 return true; 5843 5844 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5845 << From->getSourceRange(); 5846 } 5847 5848 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5849 HadMultipleCandidates); 5850 if (Result.isInvalid()) 5851 return true; 5852 // Record usage of conversion in an implicit cast. 5853 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5854 CK_UserDefinedConversion, Result.get(), 5855 nullptr, Result.get()->getValueKind()); 5856 return false; 5857 } 5858 5859 static ExprResult finishContextualImplicitConversion( 5860 Sema &SemaRef, SourceLocation Loc, Expr *From, 5861 Sema::ContextualImplicitConverter &Converter) { 5862 if (!Converter.match(From->getType()) && !Converter.Suppress) 5863 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5864 << From->getSourceRange(); 5865 5866 return SemaRef.DefaultLvalueConversion(From); 5867 } 5868 5869 static void 5870 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5871 UnresolvedSetImpl &ViableConversions, 5872 OverloadCandidateSet &CandidateSet) { 5873 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5874 DeclAccessPair FoundDecl = ViableConversions[I]; 5875 NamedDecl *D = FoundDecl.getDecl(); 5876 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5877 if (isa<UsingShadowDecl>(D)) 5878 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5879 5880 CXXConversionDecl *Conv; 5881 FunctionTemplateDecl *ConvTemplate; 5882 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5883 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5884 else 5885 Conv = cast<CXXConversionDecl>(D); 5886 5887 if (ConvTemplate) 5888 SemaRef.AddTemplateConversionCandidate( 5889 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5890 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5891 else 5892 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5893 ToType, CandidateSet, 5894 /*AllowObjCConversionOnExplicit=*/false, 5895 /*AllowExplicit*/ true); 5896 } 5897 } 5898 5899 /// Attempt to convert the given expression to a type which is accepted 5900 /// by the given converter. 5901 /// 5902 /// This routine will attempt to convert an expression of class type to a 5903 /// type accepted by the specified converter. In C++11 and before, the class 5904 /// must have a single non-explicit conversion function converting to a matching 5905 /// type. In C++1y, there can be multiple such conversion functions, but only 5906 /// one target type. 5907 /// 5908 /// \param Loc The source location of the construct that requires the 5909 /// conversion. 5910 /// 5911 /// \param From The expression we're converting from. 5912 /// 5913 /// \param Converter Used to control and diagnose the conversion process. 5914 /// 5915 /// \returns The expression, converted to an integral or enumeration type if 5916 /// successful. 5917 ExprResult Sema::PerformContextualImplicitConversion( 5918 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5919 // We can't perform any more checking for type-dependent expressions. 5920 if (From->isTypeDependent()) 5921 return From; 5922 5923 // Process placeholders immediately. 5924 if (From->hasPlaceholderType()) { 5925 ExprResult result = CheckPlaceholderExpr(From); 5926 if (result.isInvalid()) 5927 return result; 5928 From = result.get(); 5929 } 5930 5931 // If the expression already has a matching type, we're golden. 5932 QualType T = From->getType(); 5933 if (Converter.match(T)) 5934 return DefaultLvalueConversion(From); 5935 5936 // FIXME: Check for missing '()' if T is a function type? 5937 5938 // We can only perform contextual implicit conversions on objects of class 5939 // type. 5940 const RecordType *RecordTy = T->getAs<RecordType>(); 5941 if (!RecordTy || !getLangOpts().CPlusPlus) { 5942 if (!Converter.Suppress) 5943 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5944 return From; 5945 } 5946 5947 // We must have a complete class type. 5948 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5949 ContextualImplicitConverter &Converter; 5950 Expr *From; 5951 5952 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5953 : Converter(Converter), From(From) {} 5954 5955 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5956 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5957 } 5958 } IncompleteDiagnoser(Converter, From); 5959 5960 if (Converter.Suppress ? !isCompleteType(Loc, T) 5961 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5962 return From; 5963 5964 // Look for a conversion to an integral or enumeration type. 5965 UnresolvedSet<4> 5966 ViableConversions; // These are *potentially* viable in C++1y. 5967 UnresolvedSet<4> ExplicitConversions; 5968 const auto &Conversions = 5969 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5970 5971 bool HadMultipleCandidates = 5972 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5973 5974 // To check that there is only one target type, in C++1y: 5975 QualType ToType; 5976 bool HasUniqueTargetType = true; 5977 5978 // Collect explicit or viable (potentially in C++1y) conversions. 5979 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5980 NamedDecl *D = (*I)->getUnderlyingDecl(); 5981 CXXConversionDecl *Conversion; 5982 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5983 if (ConvTemplate) { 5984 if (getLangOpts().CPlusPlus14) 5985 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5986 else 5987 continue; // C++11 does not consider conversion operator templates(?). 5988 } else 5989 Conversion = cast<CXXConversionDecl>(D); 5990 5991 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5992 "Conversion operator templates are considered potentially " 5993 "viable in C++1y"); 5994 5995 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5996 if (Converter.match(CurToType) || ConvTemplate) { 5997 5998 if (Conversion->isExplicit()) { 5999 // FIXME: For C++1y, do we need this restriction? 6000 // cf. diagnoseNoViableConversion() 6001 if (!ConvTemplate) 6002 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6003 } else { 6004 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6005 if (ToType.isNull()) 6006 ToType = CurToType.getUnqualifiedType(); 6007 else if (HasUniqueTargetType && 6008 (CurToType.getUnqualifiedType() != ToType)) 6009 HasUniqueTargetType = false; 6010 } 6011 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6012 } 6013 } 6014 } 6015 6016 if (getLangOpts().CPlusPlus14) { 6017 // C++1y [conv]p6: 6018 // ... An expression e of class type E appearing in such a context 6019 // is said to be contextually implicitly converted to a specified 6020 // type T and is well-formed if and only if e can be implicitly 6021 // converted to a type T that is determined as follows: E is searched 6022 // for conversion functions whose return type is cv T or reference to 6023 // cv T such that T is allowed by the context. There shall be 6024 // exactly one such T. 6025 6026 // If no unique T is found: 6027 if (ToType.isNull()) { 6028 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6029 HadMultipleCandidates, 6030 ExplicitConversions)) 6031 return ExprError(); 6032 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6033 } 6034 6035 // If more than one unique Ts are found: 6036 if (!HasUniqueTargetType) 6037 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6038 ViableConversions); 6039 6040 // If one unique T is found: 6041 // First, build a candidate set from the previously recorded 6042 // potentially viable conversions. 6043 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6044 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6045 CandidateSet); 6046 6047 // Then, perform overload resolution over the candidate set. 6048 OverloadCandidateSet::iterator Best; 6049 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6050 case OR_Success: { 6051 // Apply this conversion. 6052 DeclAccessPair Found = 6053 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6054 if (recordConversion(*this, Loc, From, Converter, T, 6055 HadMultipleCandidates, Found)) 6056 return ExprError(); 6057 break; 6058 } 6059 case OR_Ambiguous: 6060 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6061 ViableConversions); 6062 case OR_No_Viable_Function: 6063 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6064 HadMultipleCandidates, 6065 ExplicitConversions)) 6066 return ExprError(); 6067 LLVM_FALLTHROUGH; 6068 case OR_Deleted: 6069 // We'll complain below about a non-integral condition type. 6070 break; 6071 } 6072 } else { 6073 switch (ViableConversions.size()) { 6074 case 0: { 6075 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6076 HadMultipleCandidates, 6077 ExplicitConversions)) 6078 return ExprError(); 6079 6080 // We'll complain below about a non-integral condition type. 6081 break; 6082 } 6083 case 1: { 6084 // Apply this conversion. 6085 DeclAccessPair Found = ViableConversions[0]; 6086 if (recordConversion(*this, Loc, From, Converter, T, 6087 HadMultipleCandidates, Found)) 6088 return ExprError(); 6089 break; 6090 } 6091 default: 6092 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6093 ViableConversions); 6094 } 6095 } 6096 6097 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6098 } 6099 6100 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6101 /// an acceptable non-member overloaded operator for a call whose 6102 /// arguments have types T1 (and, if non-empty, T2). This routine 6103 /// implements the check in C++ [over.match.oper]p3b2 concerning 6104 /// enumeration types. 6105 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6106 FunctionDecl *Fn, 6107 ArrayRef<Expr *> Args) { 6108 QualType T1 = Args[0]->getType(); 6109 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6110 6111 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6112 return true; 6113 6114 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6115 return true; 6116 6117 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6118 if (Proto->getNumParams() < 1) 6119 return false; 6120 6121 if (T1->isEnumeralType()) { 6122 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6123 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6124 return true; 6125 } 6126 6127 if (Proto->getNumParams() < 2) 6128 return false; 6129 6130 if (!T2.isNull() && T2->isEnumeralType()) { 6131 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6132 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6133 return true; 6134 } 6135 6136 return false; 6137 } 6138 6139 /// AddOverloadCandidate - Adds the given function to the set of 6140 /// candidate functions, using the given function call arguments. If 6141 /// @p SuppressUserConversions, then don't allow user-defined 6142 /// conversions via constructors or conversion operators. 6143 /// 6144 /// \param PartialOverloading true if we are performing "partial" overloading 6145 /// based on an incomplete set of function arguments. This feature is used by 6146 /// code completion. 6147 void Sema::AddOverloadCandidate( 6148 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6149 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6150 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6151 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6152 OverloadCandidateParamOrder PO) { 6153 const FunctionProtoType *Proto 6154 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6155 assert(Proto && "Functions without a prototype cannot be overloaded"); 6156 assert(!Function->getDescribedFunctionTemplate() && 6157 "Use AddTemplateOverloadCandidate for function templates"); 6158 6159 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6160 if (!isa<CXXConstructorDecl>(Method)) { 6161 // If we get here, it's because we're calling a member function 6162 // that is named without a member access expression (e.g., 6163 // "this->f") that was either written explicitly or created 6164 // implicitly. This can happen with a qualified call to a member 6165 // function, e.g., X::f(). We use an empty type for the implied 6166 // object argument (C++ [over.call.func]p3), and the acting context 6167 // is irrelevant. 6168 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6169 Expr::Classification::makeSimpleLValue(), Args, 6170 CandidateSet, SuppressUserConversions, 6171 PartialOverloading, EarlyConversions, PO); 6172 return; 6173 } 6174 // We treat a constructor like a non-member function, since its object 6175 // argument doesn't participate in overload resolution. 6176 } 6177 6178 if (!CandidateSet.isNewCandidate(Function, PO)) 6179 return; 6180 6181 // C++11 [class.copy]p11: [DR1402] 6182 // A defaulted move constructor that is defined as deleted is ignored by 6183 // overload resolution. 6184 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6185 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6186 Constructor->isMoveConstructor()) 6187 return; 6188 6189 // Overload resolution is always an unevaluated context. 6190 EnterExpressionEvaluationContext Unevaluated( 6191 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6192 6193 // C++ [over.match.oper]p3: 6194 // if no operand has a class type, only those non-member functions in the 6195 // lookup set that have a first parameter of type T1 or "reference to 6196 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6197 // is a right operand) a second parameter of type T2 or "reference to 6198 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6199 // candidate functions. 6200 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6201 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6202 return; 6203 6204 // Add this candidate 6205 OverloadCandidate &Candidate = 6206 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6207 Candidate.FoundDecl = FoundDecl; 6208 Candidate.Function = Function; 6209 Candidate.Viable = true; 6210 Candidate.RewriteKind = 6211 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6212 Candidate.IsSurrogate = false; 6213 Candidate.IsADLCandidate = IsADLCandidate; 6214 Candidate.IgnoreObjectArgument = false; 6215 Candidate.ExplicitCallArguments = Args.size(); 6216 6217 // Explicit functions are not actually candidates at all if we're not 6218 // allowing them in this context, but keep them around so we can point 6219 // to them in diagnostics. 6220 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6221 Candidate.Viable = false; 6222 Candidate.FailureKind = ovl_fail_explicit; 6223 return; 6224 } 6225 6226 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6227 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6228 Candidate.Viable = false; 6229 Candidate.FailureKind = ovl_non_default_multiversion_function; 6230 return; 6231 } 6232 6233 if (Constructor) { 6234 // C++ [class.copy]p3: 6235 // A member function template is never instantiated to perform the copy 6236 // of a class object to an object of its class type. 6237 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6238 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6239 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6240 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6241 ClassType))) { 6242 Candidate.Viable = false; 6243 Candidate.FailureKind = ovl_fail_illegal_constructor; 6244 return; 6245 } 6246 6247 // C++ [over.match.funcs]p8: (proposed DR resolution) 6248 // A constructor inherited from class type C that has a first parameter 6249 // of type "reference to P" (including such a constructor instantiated 6250 // from a template) is excluded from the set of candidate functions when 6251 // constructing an object of type cv D if the argument list has exactly 6252 // one argument and D is reference-related to P and P is reference-related 6253 // to C. 6254 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6255 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6256 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6257 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6258 QualType C = Context.getRecordType(Constructor->getParent()); 6259 QualType D = Context.getRecordType(Shadow->getParent()); 6260 SourceLocation Loc = Args.front()->getExprLoc(); 6261 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6262 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6263 Candidate.Viable = false; 6264 Candidate.FailureKind = ovl_fail_inhctor_slice; 6265 return; 6266 } 6267 } 6268 6269 // Check that the constructor is capable of constructing an object in the 6270 // destination address space. 6271 if (!Qualifiers::isAddressSpaceSupersetOf( 6272 Constructor->getMethodQualifiers().getAddressSpace(), 6273 CandidateSet.getDestAS())) { 6274 Candidate.Viable = false; 6275 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6276 } 6277 } 6278 6279 unsigned NumParams = Proto->getNumParams(); 6280 6281 // (C++ 13.3.2p2): A candidate function having fewer than m 6282 // parameters is viable only if it has an ellipsis in its parameter 6283 // list (8.3.5). 6284 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6285 !Proto->isVariadic()) { 6286 Candidate.Viable = false; 6287 Candidate.FailureKind = ovl_fail_too_many_arguments; 6288 return; 6289 } 6290 6291 // (C++ 13.3.2p2): A candidate function having more than m parameters 6292 // is viable only if the (m+1)st parameter has a default argument 6293 // (8.3.6). For the purposes of overload resolution, the 6294 // parameter list is truncated on the right, so that there are 6295 // exactly m parameters. 6296 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6297 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6298 // Not enough arguments. 6299 Candidate.Viable = false; 6300 Candidate.FailureKind = ovl_fail_too_few_arguments; 6301 return; 6302 } 6303 6304 // (CUDA B.1): Check for invalid calls between targets. 6305 if (getLangOpts().CUDA) 6306 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6307 // Skip the check for callers that are implicit members, because in this 6308 // case we may not yet know what the member's target is; the target is 6309 // inferred for the member automatically, based on the bases and fields of 6310 // the class. 6311 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6312 Candidate.Viable = false; 6313 Candidate.FailureKind = ovl_fail_bad_target; 6314 return; 6315 } 6316 6317 if (Function->getTrailingRequiresClause()) { 6318 ConstraintSatisfaction Satisfaction; 6319 if (CheckFunctionConstraints(Function, Satisfaction) || 6320 !Satisfaction.IsSatisfied) { 6321 Candidate.Viable = false; 6322 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6323 return; 6324 } 6325 } 6326 6327 // Determine the implicit conversion sequences for each of the 6328 // arguments. 6329 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6330 unsigned ConvIdx = 6331 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6332 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6333 // We already formed a conversion sequence for this parameter during 6334 // template argument deduction. 6335 } else if (ArgIdx < NumParams) { 6336 // (C++ 13.3.2p3): for F to be a viable function, there shall 6337 // exist for each argument an implicit conversion sequence 6338 // (13.3.3.1) that converts that argument to the corresponding 6339 // parameter of F. 6340 QualType ParamType = Proto->getParamType(ArgIdx); 6341 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6342 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6343 /*InOverloadResolution=*/true, 6344 /*AllowObjCWritebackConversion=*/ 6345 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6346 if (Candidate.Conversions[ConvIdx].isBad()) { 6347 Candidate.Viable = false; 6348 Candidate.FailureKind = ovl_fail_bad_conversion; 6349 return; 6350 } 6351 } else { 6352 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6353 // argument for which there is no corresponding parameter is 6354 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6355 Candidate.Conversions[ConvIdx].setEllipsis(); 6356 } 6357 } 6358 6359 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6360 Candidate.Viable = false; 6361 Candidate.FailureKind = ovl_fail_enable_if; 6362 Candidate.DeductionFailure.Data = FailedAttr; 6363 return; 6364 } 6365 6366 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6367 Candidate.Viable = false; 6368 Candidate.FailureKind = ovl_fail_ext_disabled; 6369 return; 6370 } 6371 } 6372 6373 ObjCMethodDecl * 6374 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6375 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6376 if (Methods.size() <= 1) 6377 return nullptr; 6378 6379 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6380 bool Match = true; 6381 ObjCMethodDecl *Method = Methods[b]; 6382 unsigned NumNamedArgs = Sel.getNumArgs(); 6383 // Method might have more arguments than selector indicates. This is due 6384 // to addition of c-style arguments in method. 6385 if (Method->param_size() > NumNamedArgs) 6386 NumNamedArgs = Method->param_size(); 6387 if (Args.size() < NumNamedArgs) 6388 continue; 6389 6390 for (unsigned i = 0; i < NumNamedArgs; i++) { 6391 // We can't do any type-checking on a type-dependent argument. 6392 if (Args[i]->isTypeDependent()) { 6393 Match = false; 6394 break; 6395 } 6396 6397 ParmVarDecl *param = Method->parameters()[i]; 6398 Expr *argExpr = Args[i]; 6399 assert(argExpr && "SelectBestMethod(): missing expression"); 6400 6401 // Strip the unbridged-cast placeholder expression off unless it's 6402 // a consumed argument. 6403 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6404 !param->hasAttr<CFConsumedAttr>()) 6405 argExpr = stripARCUnbridgedCast(argExpr); 6406 6407 // If the parameter is __unknown_anytype, move on to the next method. 6408 if (param->getType() == Context.UnknownAnyTy) { 6409 Match = false; 6410 break; 6411 } 6412 6413 ImplicitConversionSequence ConversionState 6414 = TryCopyInitialization(*this, argExpr, param->getType(), 6415 /*SuppressUserConversions*/false, 6416 /*InOverloadResolution=*/true, 6417 /*AllowObjCWritebackConversion=*/ 6418 getLangOpts().ObjCAutoRefCount, 6419 /*AllowExplicit*/false); 6420 // This function looks for a reasonably-exact match, so we consider 6421 // incompatible pointer conversions to be a failure here. 6422 if (ConversionState.isBad() || 6423 (ConversionState.isStandard() && 6424 ConversionState.Standard.Second == 6425 ICK_Incompatible_Pointer_Conversion)) { 6426 Match = false; 6427 break; 6428 } 6429 } 6430 // Promote additional arguments to variadic methods. 6431 if (Match && Method->isVariadic()) { 6432 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6433 if (Args[i]->isTypeDependent()) { 6434 Match = false; 6435 break; 6436 } 6437 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6438 nullptr); 6439 if (Arg.isInvalid()) { 6440 Match = false; 6441 break; 6442 } 6443 } 6444 } else { 6445 // Check for extra arguments to non-variadic methods. 6446 if (Args.size() != NumNamedArgs) 6447 Match = false; 6448 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6449 // Special case when selectors have no argument. In this case, select 6450 // one with the most general result type of 'id'. 6451 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6452 QualType ReturnT = Methods[b]->getReturnType(); 6453 if (ReturnT->isObjCIdType()) 6454 return Methods[b]; 6455 } 6456 } 6457 } 6458 6459 if (Match) 6460 return Method; 6461 } 6462 return nullptr; 6463 } 6464 6465 static bool 6466 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6467 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6468 bool MissingImplicitThis, Expr *&ConvertedThis, 6469 SmallVectorImpl<Expr *> &ConvertedArgs) { 6470 if (ThisArg) { 6471 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6472 assert(!isa<CXXConstructorDecl>(Method) && 6473 "Shouldn't have `this` for ctors!"); 6474 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6475 ExprResult R = S.PerformObjectArgumentInitialization( 6476 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6477 if (R.isInvalid()) 6478 return false; 6479 ConvertedThis = R.get(); 6480 } else { 6481 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6482 (void)MD; 6483 assert((MissingImplicitThis || MD->isStatic() || 6484 isa<CXXConstructorDecl>(MD)) && 6485 "Expected `this` for non-ctor instance methods"); 6486 } 6487 ConvertedThis = nullptr; 6488 } 6489 6490 // Ignore any variadic arguments. Converting them is pointless, since the 6491 // user can't refer to them in the function condition. 6492 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6493 6494 // Convert the arguments. 6495 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6496 ExprResult R; 6497 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6498 S.Context, Function->getParamDecl(I)), 6499 SourceLocation(), Args[I]); 6500 6501 if (R.isInvalid()) 6502 return false; 6503 6504 ConvertedArgs.push_back(R.get()); 6505 } 6506 6507 if (Trap.hasErrorOccurred()) 6508 return false; 6509 6510 // Push default arguments if needed. 6511 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6512 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6513 ParmVarDecl *P = Function->getParamDecl(i); 6514 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6515 ? P->getUninstantiatedDefaultArg() 6516 : P->getDefaultArg(); 6517 // This can only happen in code completion, i.e. when PartialOverloading 6518 // is true. 6519 if (!DefArg) 6520 return false; 6521 ExprResult R = 6522 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6523 S.Context, Function->getParamDecl(i)), 6524 SourceLocation(), DefArg); 6525 if (R.isInvalid()) 6526 return false; 6527 ConvertedArgs.push_back(R.get()); 6528 } 6529 6530 if (Trap.hasErrorOccurred()) 6531 return false; 6532 } 6533 return true; 6534 } 6535 6536 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6537 bool MissingImplicitThis) { 6538 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6539 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6540 return nullptr; 6541 6542 SFINAETrap Trap(*this); 6543 SmallVector<Expr *, 16> ConvertedArgs; 6544 // FIXME: We should look into making enable_if late-parsed. 6545 Expr *DiscardedThis; 6546 if (!convertArgsForAvailabilityChecks( 6547 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6548 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6549 return *EnableIfAttrs.begin(); 6550 6551 for (auto *EIA : EnableIfAttrs) { 6552 APValue Result; 6553 // FIXME: This doesn't consider value-dependent cases, because doing so is 6554 // very difficult. Ideally, we should handle them more gracefully. 6555 if (EIA->getCond()->isValueDependent() || 6556 !EIA->getCond()->EvaluateWithSubstitution( 6557 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6558 return EIA; 6559 6560 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6561 return EIA; 6562 } 6563 return nullptr; 6564 } 6565 6566 template <typename CheckFn> 6567 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6568 bool ArgDependent, SourceLocation Loc, 6569 CheckFn &&IsSuccessful) { 6570 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6571 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6572 if (ArgDependent == DIA->getArgDependent()) 6573 Attrs.push_back(DIA); 6574 } 6575 6576 // Common case: No diagnose_if attributes, so we can quit early. 6577 if (Attrs.empty()) 6578 return false; 6579 6580 auto WarningBegin = std::stable_partition( 6581 Attrs.begin(), Attrs.end(), 6582 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6583 6584 // Note that diagnose_if attributes are late-parsed, so they appear in the 6585 // correct order (unlike enable_if attributes). 6586 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6587 IsSuccessful); 6588 if (ErrAttr != WarningBegin) { 6589 const DiagnoseIfAttr *DIA = *ErrAttr; 6590 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6591 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6592 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6593 return true; 6594 } 6595 6596 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6597 if (IsSuccessful(DIA)) { 6598 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6599 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6600 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6601 } 6602 6603 return false; 6604 } 6605 6606 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6607 const Expr *ThisArg, 6608 ArrayRef<const Expr *> Args, 6609 SourceLocation Loc) { 6610 return diagnoseDiagnoseIfAttrsWith( 6611 *this, Function, /*ArgDependent=*/true, Loc, 6612 [&](const DiagnoseIfAttr *DIA) { 6613 APValue Result; 6614 // It's sane to use the same Args for any redecl of this function, since 6615 // EvaluateWithSubstitution only cares about the position of each 6616 // argument in the arg list, not the ParmVarDecl* it maps to. 6617 if (!DIA->getCond()->EvaluateWithSubstitution( 6618 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6619 return false; 6620 return Result.isInt() && Result.getInt().getBoolValue(); 6621 }); 6622 } 6623 6624 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6625 SourceLocation Loc) { 6626 return diagnoseDiagnoseIfAttrsWith( 6627 *this, ND, /*ArgDependent=*/false, Loc, 6628 [&](const DiagnoseIfAttr *DIA) { 6629 bool Result; 6630 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6631 Result; 6632 }); 6633 } 6634 6635 /// Add all of the function declarations in the given function set to 6636 /// the overload candidate set. 6637 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6638 ArrayRef<Expr *> Args, 6639 OverloadCandidateSet &CandidateSet, 6640 TemplateArgumentListInfo *ExplicitTemplateArgs, 6641 bool SuppressUserConversions, 6642 bool PartialOverloading, 6643 bool FirstArgumentIsBase) { 6644 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6645 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6646 ArrayRef<Expr *> FunctionArgs = Args; 6647 6648 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6649 FunctionDecl *FD = 6650 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6651 6652 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6653 QualType ObjectType; 6654 Expr::Classification ObjectClassification; 6655 if (Args.size() > 0) { 6656 if (Expr *E = Args[0]) { 6657 // Use the explicit base to restrict the lookup: 6658 ObjectType = E->getType(); 6659 // Pointers in the object arguments are implicitly dereferenced, so we 6660 // always classify them as l-values. 6661 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6662 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6663 else 6664 ObjectClassification = E->Classify(Context); 6665 } // .. else there is an implicit base. 6666 FunctionArgs = Args.slice(1); 6667 } 6668 if (FunTmpl) { 6669 AddMethodTemplateCandidate( 6670 FunTmpl, F.getPair(), 6671 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6672 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6673 FunctionArgs, CandidateSet, SuppressUserConversions, 6674 PartialOverloading); 6675 } else { 6676 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6677 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6678 ObjectClassification, FunctionArgs, CandidateSet, 6679 SuppressUserConversions, PartialOverloading); 6680 } 6681 } else { 6682 // This branch handles both standalone functions and static methods. 6683 6684 // Slice the first argument (which is the base) when we access 6685 // static method as non-static. 6686 if (Args.size() > 0 && 6687 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6688 !isa<CXXConstructorDecl>(FD)))) { 6689 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6690 FunctionArgs = Args.slice(1); 6691 } 6692 if (FunTmpl) { 6693 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6694 ExplicitTemplateArgs, FunctionArgs, 6695 CandidateSet, SuppressUserConversions, 6696 PartialOverloading); 6697 } else { 6698 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6699 SuppressUserConversions, PartialOverloading); 6700 } 6701 } 6702 } 6703 } 6704 6705 /// AddMethodCandidate - Adds a named decl (which is some kind of 6706 /// method) as a method candidate to the given overload set. 6707 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6708 Expr::Classification ObjectClassification, 6709 ArrayRef<Expr *> Args, 6710 OverloadCandidateSet &CandidateSet, 6711 bool SuppressUserConversions, 6712 OverloadCandidateParamOrder PO) { 6713 NamedDecl *Decl = FoundDecl.getDecl(); 6714 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6715 6716 if (isa<UsingShadowDecl>(Decl)) 6717 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6718 6719 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6720 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6721 "Expected a member function template"); 6722 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6723 /*ExplicitArgs*/ nullptr, ObjectType, 6724 ObjectClassification, Args, CandidateSet, 6725 SuppressUserConversions, false, PO); 6726 } else { 6727 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6728 ObjectType, ObjectClassification, Args, CandidateSet, 6729 SuppressUserConversions, false, None, PO); 6730 } 6731 } 6732 6733 /// AddMethodCandidate - Adds the given C++ member function to the set 6734 /// of candidate functions, using the given function call arguments 6735 /// and the object argument (@c Object). For example, in a call 6736 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6737 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6738 /// allow user-defined conversions via constructors or conversion 6739 /// operators. 6740 void 6741 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6742 CXXRecordDecl *ActingContext, QualType ObjectType, 6743 Expr::Classification ObjectClassification, 6744 ArrayRef<Expr *> Args, 6745 OverloadCandidateSet &CandidateSet, 6746 bool SuppressUserConversions, 6747 bool PartialOverloading, 6748 ConversionSequenceList EarlyConversions, 6749 OverloadCandidateParamOrder PO) { 6750 const FunctionProtoType *Proto 6751 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6752 assert(Proto && "Methods without a prototype cannot be overloaded"); 6753 assert(!isa<CXXConstructorDecl>(Method) && 6754 "Use AddOverloadCandidate for constructors"); 6755 6756 if (!CandidateSet.isNewCandidate(Method, PO)) 6757 return; 6758 6759 // C++11 [class.copy]p23: [DR1402] 6760 // A defaulted move assignment operator that is defined as deleted is 6761 // ignored by overload resolution. 6762 if (Method->isDefaulted() && Method->isDeleted() && 6763 Method->isMoveAssignmentOperator()) 6764 return; 6765 6766 // Overload resolution is always an unevaluated context. 6767 EnterExpressionEvaluationContext Unevaluated( 6768 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6769 6770 // Add this candidate 6771 OverloadCandidate &Candidate = 6772 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6773 Candidate.FoundDecl = FoundDecl; 6774 Candidate.Function = Method; 6775 Candidate.RewriteKind = 6776 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6777 Candidate.IsSurrogate = false; 6778 Candidate.IgnoreObjectArgument = false; 6779 Candidate.ExplicitCallArguments = Args.size(); 6780 6781 unsigned NumParams = Proto->getNumParams(); 6782 6783 // (C++ 13.3.2p2): A candidate function having fewer than m 6784 // parameters is viable only if it has an ellipsis in its parameter 6785 // list (8.3.5). 6786 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6787 !Proto->isVariadic()) { 6788 Candidate.Viable = false; 6789 Candidate.FailureKind = ovl_fail_too_many_arguments; 6790 return; 6791 } 6792 6793 // (C++ 13.3.2p2): A candidate function having more than m parameters 6794 // is viable only if the (m+1)st parameter has a default argument 6795 // (8.3.6). For the purposes of overload resolution, the 6796 // parameter list is truncated on the right, so that there are 6797 // exactly m parameters. 6798 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6799 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6800 // Not enough arguments. 6801 Candidate.Viable = false; 6802 Candidate.FailureKind = ovl_fail_too_few_arguments; 6803 return; 6804 } 6805 6806 Candidate.Viable = true; 6807 6808 if (Method->isStatic() || ObjectType.isNull()) 6809 // The implicit object argument is ignored. 6810 Candidate.IgnoreObjectArgument = true; 6811 else { 6812 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6813 // Determine the implicit conversion sequence for the object 6814 // parameter. 6815 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6816 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6817 Method, ActingContext); 6818 if (Candidate.Conversions[ConvIdx].isBad()) { 6819 Candidate.Viable = false; 6820 Candidate.FailureKind = ovl_fail_bad_conversion; 6821 return; 6822 } 6823 } 6824 6825 // (CUDA B.1): Check for invalid calls between targets. 6826 if (getLangOpts().CUDA) 6827 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6828 if (!IsAllowedCUDACall(Caller, Method)) { 6829 Candidate.Viable = false; 6830 Candidate.FailureKind = ovl_fail_bad_target; 6831 return; 6832 } 6833 6834 if (Method->getTrailingRequiresClause()) { 6835 ConstraintSatisfaction Satisfaction; 6836 if (CheckFunctionConstraints(Method, Satisfaction) || 6837 !Satisfaction.IsSatisfied) { 6838 Candidate.Viable = false; 6839 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6840 return; 6841 } 6842 } 6843 6844 // Determine the implicit conversion sequences for each of the 6845 // arguments. 6846 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6847 unsigned ConvIdx = 6848 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6849 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6850 // We already formed a conversion sequence for this parameter during 6851 // template argument deduction. 6852 } else if (ArgIdx < NumParams) { 6853 // (C++ 13.3.2p3): for F to be a viable function, there shall 6854 // exist for each argument an implicit conversion sequence 6855 // (13.3.3.1) that converts that argument to the corresponding 6856 // parameter of F. 6857 QualType ParamType = Proto->getParamType(ArgIdx); 6858 Candidate.Conversions[ConvIdx] 6859 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6860 SuppressUserConversions, 6861 /*InOverloadResolution=*/true, 6862 /*AllowObjCWritebackConversion=*/ 6863 getLangOpts().ObjCAutoRefCount); 6864 if (Candidate.Conversions[ConvIdx].isBad()) { 6865 Candidate.Viable = false; 6866 Candidate.FailureKind = ovl_fail_bad_conversion; 6867 return; 6868 } 6869 } else { 6870 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6871 // argument for which there is no corresponding parameter is 6872 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6873 Candidate.Conversions[ConvIdx].setEllipsis(); 6874 } 6875 } 6876 6877 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6878 Candidate.Viable = false; 6879 Candidate.FailureKind = ovl_fail_enable_if; 6880 Candidate.DeductionFailure.Data = FailedAttr; 6881 return; 6882 } 6883 6884 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6885 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6886 Candidate.Viable = false; 6887 Candidate.FailureKind = ovl_non_default_multiversion_function; 6888 } 6889 } 6890 6891 /// Add a C++ member function template as a candidate to the candidate 6892 /// set, using template argument deduction to produce an appropriate member 6893 /// function template specialization. 6894 void Sema::AddMethodTemplateCandidate( 6895 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6896 CXXRecordDecl *ActingContext, 6897 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6898 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6899 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6900 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6901 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6902 return; 6903 6904 // C++ [over.match.funcs]p7: 6905 // In each case where a candidate is a function template, candidate 6906 // function template specializations are generated using template argument 6907 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6908 // candidate functions in the usual way.113) A given name can refer to one 6909 // or more function templates and also to a set of overloaded non-template 6910 // functions. In such a case, the candidate functions generated from each 6911 // function template are combined with the set of non-template candidate 6912 // functions. 6913 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6914 FunctionDecl *Specialization = nullptr; 6915 ConversionSequenceList Conversions; 6916 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6917 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6918 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6919 return CheckNonDependentConversions( 6920 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6921 SuppressUserConversions, ActingContext, ObjectType, 6922 ObjectClassification, PO); 6923 })) { 6924 OverloadCandidate &Candidate = 6925 CandidateSet.addCandidate(Conversions.size(), Conversions); 6926 Candidate.FoundDecl = FoundDecl; 6927 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6928 Candidate.Viable = false; 6929 Candidate.RewriteKind = 6930 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6931 Candidate.IsSurrogate = false; 6932 Candidate.IgnoreObjectArgument = 6933 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6934 ObjectType.isNull(); 6935 Candidate.ExplicitCallArguments = Args.size(); 6936 if (Result == TDK_NonDependentConversionFailure) 6937 Candidate.FailureKind = ovl_fail_bad_conversion; 6938 else { 6939 Candidate.FailureKind = ovl_fail_bad_deduction; 6940 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6941 Info); 6942 } 6943 return; 6944 } 6945 6946 // Add the function template specialization produced by template argument 6947 // deduction as a candidate. 6948 assert(Specialization && "Missing member function template specialization?"); 6949 assert(isa<CXXMethodDecl>(Specialization) && 6950 "Specialization is not a member function?"); 6951 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6952 ActingContext, ObjectType, ObjectClassification, Args, 6953 CandidateSet, SuppressUserConversions, PartialOverloading, 6954 Conversions, PO); 6955 } 6956 6957 /// Determine whether a given function template has a simple explicit specifier 6958 /// or a non-value-dependent explicit-specification that evaluates to true. 6959 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6960 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6961 } 6962 6963 /// Add a C++ function template specialization as a candidate 6964 /// in the candidate set, using template argument deduction to produce 6965 /// an appropriate function template specialization. 6966 void Sema::AddTemplateOverloadCandidate( 6967 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6968 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6969 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6970 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6971 OverloadCandidateParamOrder PO) { 6972 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6973 return; 6974 6975 // If the function template has a non-dependent explicit specification, 6976 // exclude it now if appropriate; we are not permitted to perform deduction 6977 // and substitution in this case. 6978 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6979 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6980 Candidate.FoundDecl = FoundDecl; 6981 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6982 Candidate.Viable = false; 6983 Candidate.FailureKind = ovl_fail_explicit; 6984 return; 6985 } 6986 6987 // C++ [over.match.funcs]p7: 6988 // In each case where a candidate is a function template, candidate 6989 // function template specializations are generated using template argument 6990 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6991 // candidate functions in the usual way.113) A given name can refer to one 6992 // or more function templates and also to a set of overloaded non-template 6993 // functions. In such a case, the candidate functions generated from each 6994 // function template are combined with the set of non-template candidate 6995 // functions. 6996 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6997 FunctionDecl *Specialization = nullptr; 6998 ConversionSequenceList Conversions; 6999 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7000 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7001 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7002 return CheckNonDependentConversions( 7003 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7004 SuppressUserConversions, nullptr, QualType(), {}, PO); 7005 })) { 7006 OverloadCandidate &Candidate = 7007 CandidateSet.addCandidate(Conversions.size(), Conversions); 7008 Candidate.FoundDecl = FoundDecl; 7009 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7010 Candidate.Viable = false; 7011 Candidate.RewriteKind = 7012 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7013 Candidate.IsSurrogate = false; 7014 Candidate.IsADLCandidate = IsADLCandidate; 7015 // Ignore the object argument if there is one, since we don't have an object 7016 // type. 7017 Candidate.IgnoreObjectArgument = 7018 isa<CXXMethodDecl>(Candidate.Function) && 7019 !isa<CXXConstructorDecl>(Candidate.Function); 7020 Candidate.ExplicitCallArguments = Args.size(); 7021 if (Result == TDK_NonDependentConversionFailure) 7022 Candidate.FailureKind = ovl_fail_bad_conversion; 7023 else { 7024 Candidate.FailureKind = ovl_fail_bad_deduction; 7025 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7026 Info); 7027 } 7028 return; 7029 } 7030 7031 // Add the function template specialization produced by template argument 7032 // deduction as a candidate. 7033 assert(Specialization && "Missing function template specialization?"); 7034 AddOverloadCandidate( 7035 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7036 PartialOverloading, AllowExplicit, 7037 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7038 } 7039 7040 /// Check that implicit conversion sequences can be formed for each argument 7041 /// whose corresponding parameter has a non-dependent type, per DR1391's 7042 /// [temp.deduct.call]p10. 7043 bool Sema::CheckNonDependentConversions( 7044 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7045 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7046 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7047 CXXRecordDecl *ActingContext, QualType ObjectType, 7048 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7049 // FIXME: The cases in which we allow explicit conversions for constructor 7050 // arguments never consider calling a constructor template. It's not clear 7051 // that is correct. 7052 const bool AllowExplicit = false; 7053 7054 auto *FD = FunctionTemplate->getTemplatedDecl(); 7055 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7056 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7057 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7058 7059 Conversions = 7060 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7061 7062 // Overload resolution is always an unevaluated context. 7063 EnterExpressionEvaluationContext Unevaluated( 7064 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7065 7066 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7067 // require that, but this check should never result in a hard error, and 7068 // overload resolution is permitted to sidestep instantiations. 7069 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7070 !ObjectType.isNull()) { 7071 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7072 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7073 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7074 Method, ActingContext); 7075 if (Conversions[ConvIdx].isBad()) 7076 return true; 7077 } 7078 7079 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7080 ++I) { 7081 QualType ParamType = ParamTypes[I]; 7082 if (!ParamType->isDependentType()) { 7083 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7084 ? 0 7085 : (ThisConversions + I); 7086 Conversions[ConvIdx] 7087 = TryCopyInitialization(*this, Args[I], ParamType, 7088 SuppressUserConversions, 7089 /*InOverloadResolution=*/true, 7090 /*AllowObjCWritebackConversion=*/ 7091 getLangOpts().ObjCAutoRefCount, 7092 AllowExplicit); 7093 if (Conversions[ConvIdx].isBad()) 7094 return true; 7095 } 7096 } 7097 7098 return false; 7099 } 7100 7101 /// Determine whether this is an allowable conversion from the result 7102 /// of an explicit conversion operator to the expected type, per C++ 7103 /// [over.match.conv]p1 and [over.match.ref]p1. 7104 /// 7105 /// \param ConvType The return type of the conversion function. 7106 /// 7107 /// \param ToType The type we are converting to. 7108 /// 7109 /// \param AllowObjCPointerConversion Allow a conversion from one 7110 /// Objective-C pointer to another. 7111 /// 7112 /// \returns true if the conversion is allowable, false otherwise. 7113 static bool isAllowableExplicitConversion(Sema &S, 7114 QualType ConvType, QualType ToType, 7115 bool AllowObjCPointerConversion) { 7116 QualType ToNonRefType = ToType.getNonReferenceType(); 7117 7118 // Easy case: the types are the same. 7119 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7120 return true; 7121 7122 // Allow qualification conversions. 7123 bool ObjCLifetimeConversion; 7124 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7125 ObjCLifetimeConversion)) 7126 return true; 7127 7128 // If we're not allowed to consider Objective-C pointer conversions, 7129 // we're done. 7130 if (!AllowObjCPointerConversion) 7131 return false; 7132 7133 // Is this an Objective-C pointer conversion? 7134 bool IncompatibleObjC = false; 7135 QualType ConvertedType; 7136 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7137 IncompatibleObjC); 7138 } 7139 7140 /// AddConversionCandidate - Add a C++ conversion function as a 7141 /// candidate in the candidate set (C++ [over.match.conv], 7142 /// C++ [over.match.copy]). From is the expression we're converting from, 7143 /// and ToType is the type that we're eventually trying to convert to 7144 /// (which may or may not be the same type as the type that the 7145 /// conversion function produces). 7146 void Sema::AddConversionCandidate( 7147 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7148 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7149 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7150 bool AllowExplicit, bool AllowResultConversion) { 7151 assert(!Conversion->getDescribedFunctionTemplate() && 7152 "Conversion function templates use AddTemplateConversionCandidate"); 7153 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7154 if (!CandidateSet.isNewCandidate(Conversion)) 7155 return; 7156 7157 // If the conversion function has an undeduced return type, trigger its 7158 // deduction now. 7159 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7160 if (DeduceReturnType(Conversion, From->getExprLoc())) 7161 return; 7162 ConvType = Conversion->getConversionType().getNonReferenceType(); 7163 } 7164 7165 // If we don't allow any conversion of the result type, ignore conversion 7166 // functions that don't convert to exactly (possibly cv-qualified) T. 7167 if (!AllowResultConversion && 7168 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7169 return; 7170 7171 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7172 // operator is only a candidate if its return type is the target type or 7173 // can be converted to the target type with a qualification conversion. 7174 // 7175 // FIXME: Include such functions in the candidate list and explain why we 7176 // can't select them. 7177 if (Conversion->isExplicit() && 7178 !isAllowableExplicitConversion(*this, ConvType, ToType, 7179 AllowObjCConversionOnExplicit)) 7180 return; 7181 7182 // Overload resolution is always an unevaluated context. 7183 EnterExpressionEvaluationContext Unevaluated( 7184 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7185 7186 // Add this candidate 7187 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7188 Candidate.FoundDecl = FoundDecl; 7189 Candidate.Function = Conversion; 7190 Candidate.IsSurrogate = false; 7191 Candidate.IgnoreObjectArgument = false; 7192 Candidate.FinalConversion.setAsIdentityConversion(); 7193 Candidate.FinalConversion.setFromType(ConvType); 7194 Candidate.FinalConversion.setAllToTypes(ToType); 7195 Candidate.Viable = true; 7196 Candidate.ExplicitCallArguments = 1; 7197 7198 // Explicit functions are not actually candidates at all if we're not 7199 // allowing them in this context, but keep them around so we can point 7200 // to them in diagnostics. 7201 if (!AllowExplicit && Conversion->isExplicit()) { 7202 Candidate.Viable = false; 7203 Candidate.FailureKind = ovl_fail_explicit; 7204 return; 7205 } 7206 7207 // C++ [over.match.funcs]p4: 7208 // For conversion functions, the function is considered to be a member of 7209 // the class of the implicit implied object argument for the purpose of 7210 // defining the type of the implicit object parameter. 7211 // 7212 // Determine the implicit conversion sequence for the implicit 7213 // object parameter. 7214 QualType ImplicitParamType = From->getType(); 7215 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7216 ImplicitParamType = FromPtrType->getPointeeType(); 7217 CXXRecordDecl *ConversionContext 7218 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7219 7220 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7221 *this, CandidateSet.getLocation(), From->getType(), 7222 From->Classify(Context), Conversion, ConversionContext); 7223 7224 if (Candidate.Conversions[0].isBad()) { 7225 Candidate.Viable = false; 7226 Candidate.FailureKind = ovl_fail_bad_conversion; 7227 return; 7228 } 7229 7230 if (Conversion->getTrailingRequiresClause()) { 7231 ConstraintSatisfaction Satisfaction; 7232 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7233 !Satisfaction.IsSatisfied) { 7234 Candidate.Viable = false; 7235 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7236 return; 7237 } 7238 } 7239 7240 // We won't go through a user-defined type conversion function to convert a 7241 // derived to base as such conversions are given Conversion Rank. They only 7242 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7243 QualType FromCanon 7244 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7245 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7246 if (FromCanon == ToCanon || 7247 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7248 Candidate.Viable = false; 7249 Candidate.FailureKind = ovl_fail_trivial_conversion; 7250 return; 7251 } 7252 7253 // To determine what the conversion from the result of calling the 7254 // conversion function to the type we're eventually trying to 7255 // convert to (ToType), we need to synthesize a call to the 7256 // conversion function and attempt copy initialization from it. This 7257 // makes sure that we get the right semantics with respect to 7258 // lvalues/rvalues and the type. Fortunately, we can allocate this 7259 // call on the stack and we don't need its arguments to be 7260 // well-formed. 7261 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7262 VK_LValue, From->getBeginLoc()); 7263 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7264 Context.getPointerType(Conversion->getType()), 7265 CK_FunctionToPointerDecay, 7266 &ConversionRef, VK_RValue); 7267 7268 QualType ConversionType = Conversion->getConversionType(); 7269 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7270 Candidate.Viable = false; 7271 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7272 return; 7273 } 7274 7275 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7276 7277 // Note that it is safe to allocate CallExpr on the stack here because 7278 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7279 // allocator). 7280 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7281 7282 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7283 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7284 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7285 7286 ImplicitConversionSequence ICS = 7287 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7288 /*SuppressUserConversions=*/true, 7289 /*InOverloadResolution=*/false, 7290 /*AllowObjCWritebackConversion=*/false); 7291 7292 switch (ICS.getKind()) { 7293 case ImplicitConversionSequence::StandardConversion: 7294 Candidate.FinalConversion = ICS.Standard; 7295 7296 // C++ [over.ics.user]p3: 7297 // If the user-defined conversion is specified by a specialization of a 7298 // conversion function template, the second standard conversion sequence 7299 // shall have exact match rank. 7300 if (Conversion->getPrimaryTemplate() && 7301 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7302 Candidate.Viable = false; 7303 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7304 return; 7305 } 7306 7307 // C++0x [dcl.init.ref]p5: 7308 // In the second case, if the reference is an rvalue reference and 7309 // the second standard conversion sequence of the user-defined 7310 // conversion sequence includes an lvalue-to-rvalue conversion, the 7311 // program is ill-formed. 7312 if (ToType->isRValueReferenceType() && 7313 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7314 Candidate.Viable = false; 7315 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7316 return; 7317 } 7318 break; 7319 7320 case ImplicitConversionSequence::BadConversion: 7321 Candidate.Viable = false; 7322 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7323 return; 7324 7325 default: 7326 llvm_unreachable( 7327 "Can only end up with a standard conversion sequence or failure"); 7328 } 7329 7330 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7331 Candidate.Viable = false; 7332 Candidate.FailureKind = ovl_fail_enable_if; 7333 Candidate.DeductionFailure.Data = FailedAttr; 7334 return; 7335 } 7336 7337 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7338 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7339 Candidate.Viable = false; 7340 Candidate.FailureKind = ovl_non_default_multiversion_function; 7341 } 7342 } 7343 7344 /// Adds a conversion function template specialization 7345 /// candidate to the overload set, using template argument deduction 7346 /// to deduce the template arguments of the conversion function 7347 /// template from the type that we are converting to (C++ 7348 /// [temp.deduct.conv]). 7349 void Sema::AddTemplateConversionCandidate( 7350 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7351 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7352 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7353 bool AllowExplicit, bool AllowResultConversion) { 7354 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7355 "Only conversion function templates permitted here"); 7356 7357 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7358 return; 7359 7360 // If the function template has a non-dependent explicit specification, 7361 // exclude it now if appropriate; we are not permitted to perform deduction 7362 // and substitution in this case. 7363 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7364 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7365 Candidate.FoundDecl = FoundDecl; 7366 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7367 Candidate.Viable = false; 7368 Candidate.FailureKind = ovl_fail_explicit; 7369 return; 7370 } 7371 7372 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7373 CXXConversionDecl *Specialization = nullptr; 7374 if (TemplateDeductionResult Result 7375 = DeduceTemplateArguments(FunctionTemplate, ToType, 7376 Specialization, Info)) { 7377 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7378 Candidate.FoundDecl = FoundDecl; 7379 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7380 Candidate.Viable = false; 7381 Candidate.FailureKind = ovl_fail_bad_deduction; 7382 Candidate.IsSurrogate = false; 7383 Candidate.IgnoreObjectArgument = false; 7384 Candidate.ExplicitCallArguments = 1; 7385 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7386 Info); 7387 return; 7388 } 7389 7390 // Add the conversion function template specialization produced by 7391 // template argument deduction as a candidate. 7392 assert(Specialization && "Missing function template specialization?"); 7393 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7394 CandidateSet, AllowObjCConversionOnExplicit, 7395 AllowExplicit, AllowResultConversion); 7396 } 7397 7398 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7399 /// converts the given @c Object to a function pointer via the 7400 /// conversion function @c Conversion, and then attempts to call it 7401 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7402 /// the type of function that we'll eventually be calling. 7403 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7404 DeclAccessPair FoundDecl, 7405 CXXRecordDecl *ActingContext, 7406 const FunctionProtoType *Proto, 7407 Expr *Object, 7408 ArrayRef<Expr *> Args, 7409 OverloadCandidateSet& CandidateSet) { 7410 if (!CandidateSet.isNewCandidate(Conversion)) 7411 return; 7412 7413 // Overload resolution is always an unevaluated context. 7414 EnterExpressionEvaluationContext Unevaluated( 7415 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7416 7417 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7418 Candidate.FoundDecl = FoundDecl; 7419 Candidate.Function = nullptr; 7420 Candidate.Surrogate = Conversion; 7421 Candidate.Viable = true; 7422 Candidate.IsSurrogate = true; 7423 Candidate.IgnoreObjectArgument = false; 7424 Candidate.ExplicitCallArguments = Args.size(); 7425 7426 // Determine the implicit conversion sequence for the implicit 7427 // object parameter. 7428 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7429 *this, CandidateSet.getLocation(), Object->getType(), 7430 Object->Classify(Context), Conversion, ActingContext); 7431 if (ObjectInit.isBad()) { 7432 Candidate.Viable = false; 7433 Candidate.FailureKind = ovl_fail_bad_conversion; 7434 Candidate.Conversions[0] = ObjectInit; 7435 return; 7436 } 7437 7438 // The first conversion is actually a user-defined conversion whose 7439 // first conversion is ObjectInit's standard conversion (which is 7440 // effectively a reference binding). Record it as such. 7441 Candidate.Conversions[0].setUserDefined(); 7442 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7443 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7444 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7445 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7446 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7447 Candidate.Conversions[0].UserDefined.After 7448 = Candidate.Conversions[0].UserDefined.Before; 7449 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7450 7451 // Find the 7452 unsigned NumParams = Proto->getNumParams(); 7453 7454 // (C++ 13.3.2p2): A candidate function having fewer than m 7455 // parameters is viable only if it has an ellipsis in its parameter 7456 // list (8.3.5). 7457 if (Args.size() > NumParams && !Proto->isVariadic()) { 7458 Candidate.Viable = false; 7459 Candidate.FailureKind = ovl_fail_too_many_arguments; 7460 return; 7461 } 7462 7463 // Function types don't have any default arguments, so just check if 7464 // we have enough arguments. 7465 if (Args.size() < NumParams) { 7466 // Not enough arguments. 7467 Candidate.Viable = false; 7468 Candidate.FailureKind = ovl_fail_too_few_arguments; 7469 return; 7470 } 7471 7472 // Determine the implicit conversion sequences for each of the 7473 // arguments. 7474 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7475 if (ArgIdx < NumParams) { 7476 // (C++ 13.3.2p3): for F to be a viable function, there shall 7477 // exist for each argument an implicit conversion sequence 7478 // (13.3.3.1) that converts that argument to the corresponding 7479 // parameter of F. 7480 QualType ParamType = Proto->getParamType(ArgIdx); 7481 Candidate.Conversions[ArgIdx + 1] 7482 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7483 /*SuppressUserConversions=*/false, 7484 /*InOverloadResolution=*/false, 7485 /*AllowObjCWritebackConversion=*/ 7486 getLangOpts().ObjCAutoRefCount); 7487 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7488 Candidate.Viable = false; 7489 Candidate.FailureKind = ovl_fail_bad_conversion; 7490 return; 7491 } 7492 } else { 7493 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7494 // argument for which there is no corresponding parameter is 7495 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7496 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7497 } 7498 } 7499 7500 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7501 Candidate.Viable = false; 7502 Candidate.FailureKind = ovl_fail_enable_if; 7503 Candidate.DeductionFailure.Data = FailedAttr; 7504 return; 7505 } 7506 } 7507 7508 /// Add all of the non-member operator function declarations in the given 7509 /// function set to the overload candidate set. 7510 void Sema::AddNonMemberOperatorCandidates( 7511 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7512 OverloadCandidateSet &CandidateSet, 7513 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7514 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7515 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7516 ArrayRef<Expr *> FunctionArgs = Args; 7517 7518 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7519 FunctionDecl *FD = 7520 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7521 7522 // Don't consider rewritten functions if we're not rewriting. 7523 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7524 continue; 7525 7526 assert(!isa<CXXMethodDecl>(FD) && 7527 "unqualified operator lookup found a member function"); 7528 7529 if (FunTmpl) { 7530 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7531 FunctionArgs, CandidateSet); 7532 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7533 AddTemplateOverloadCandidate( 7534 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7535 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7536 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7537 } else { 7538 if (ExplicitTemplateArgs) 7539 continue; 7540 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7541 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7542 AddOverloadCandidate(FD, F.getPair(), 7543 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7544 false, false, true, false, ADLCallKind::NotADL, 7545 None, OverloadCandidateParamOrder::Reversed); 7546 } 7547 } 7548 } 7549 7550 /// Add overload candidates for overloaded operators that are 7551 /// member functions. 7552 /// 7553 /// Add the overloaded operator candidates that are member functions 7554 /// for the operator Op that was used in an operator expression such 7555 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7556 /// CandidateSet will store the added overload candidates. (C++ 7557 /// [over.match.oper]). 7558 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7559 SourceLocation OpLoc, 7560 ArrayRef<Expr *> Args, 7561 OverloadCandidateSet &CandidateSet, 7562 OverloadCandidateParamOrder PO) { 7563 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7564 7565 // C++ [over.match.oper]p3: 7566 // For a unary operator @ with an operand of a type whose 7567 // cv-unqualified version is T1, and for a binary operator @ with 7568 // a left operand of a type whose cv-unqualified version is T1 and 7569 // a right operand of a type whose cv-unqualified version is T2, 7570 // three sets of candidate functions, designated member 7571 // candidates, non-member candidates and built-in candidates, are 7572 // constructed as follows: 7573 QualType T1 = Args[0]->getType(); 7574 7575 // -- If T1 is a complete class type or a class currently being 7576 // defined, the set of member candidates is the result of the 7577 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7578 // the set of member candidates is empty. 7579 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7580 // Complete the type if it can be completed. 7581 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7582 return; 7583 // If the type is neither complete nor being defined, bail out now. 7584 if (!T1Rec->getDecl()->getDefinition()) 7585 return; 7586 7587 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7588 LookupQualifiedName(Operators, T1Rec->getDecl()); 7589 Operators.suppressDiagnostics(); 7590 7591 for (LookupResult::iterator Oper = Operators.begin(), 7592 OperEnd = Operators.end(); 7593 Oper != OperEnd; 7594 ++Oper) 7595 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7596 Args[0]->Classify(Context), Args.slice(1), 7597 CandidateSet, /*SuppressUserConversion=*/false, PO); 7598 } 7599 } 7600 7601 /// AddBuiltinCandidate - Add a candidate for a built-in 7602 /// operator. ResultTy and ParamTys are the result and parameter types 7603 /// of the built-in candidate, respectively. Args and NumArgs are the 7604 /// arguments being passed to the candidate. IsAssignmentOperator 7605 /// should be true when this built-in candidate is an assignment 7606 /// operator. NumContextualBoolArguments is the number of arguments 7607 /// (at the beginning of the argument list) that will be contextually 7608 /// converted to bool. 7609 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7610 OverloadCandidateSet& CandidateSet, 7611 bool IsAssignmentOperator, 7612 unsigned NumContextualBoolArguments) { 7613 // Overload resolution is always an unevaluated context. 7614 EnterExpressionEvaluationContext Unevaluated( 7615 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7616 7617 // Add this candidate 7618 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7619 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7620 Candidate.Function = nullptr; 7621 Candidate.IsSurrogate = false; 7622 Candidate.IgnoreObjectArgument = false; 7623 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7624 7625 // Determine the implicit conversion sequences for each of the 7626 // arguments. 7627 Candidate.Viable = true; 7628 Candidate.ExplicitCallArguments = Args.size(); 7629 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7630 // C++ [over.match.oper]p4: 7631 // For the built-in assignment operators, conversions of the 7632 // left operand are restricted as follows: 7633 // -- no temporaries are introduced to hold the left operand, and 7634 // -- no user-defined conversions are applied to the left 7635 // operand to achieve a type match with the left-most 7636 // parameter of a built-in candidate. 7637 // 7638 // We block these conversions by turning off user-defined 7639 // conversions, since that is the only way that initialization of 7640 // a reference to a non-class type can occur from something that 7641 // is not of the same type. 7642 if (ArgIdx < NumContextualBoolArguments) { 7643 assert(ParamTys[ArgIdx] == Context.BoolTy && 7644 "Contextual conversion to bool requires bool type"); 7645 Candidate.Conversions[ArgIdx] 7646 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7647 } else { 7648 Candidate.Conversions[ArgIdx] 7649 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7650 ArgIdx == 0 && IsAssignmentOperator, 7651 /*InOverloadResolution=*/false, 7652 /*AllowObjCWritebackConversion=*/ 7653 getLangOpts().ObjCAutoRefCount); 7654 } 7655 if (Candidate.Conversions[ArgIdx].isBad()) { 7656 Candidate.Viable = false; 7657 Candidate.FailureKind = ovl_fail_bad_conversion; 7658 break; 7659 } 7660 } 7661 } 7662 7663 namespace { 7664 7665 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7666 /// candidate operator functions for built-in operators (C++ 7667 /// [over.built]). The types are separated into pointer types and 7668 /// enumeration types. 7669 class BuiltinCandidateTypeSet { 7670 /// TypeSet - A set of types. 7671 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7672 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7673 7674 /// PointerTypes - The set of pointer types that will be used in the 7675 /// built-in candidates. 7676 TypeSet PointerTypes; 7677 7678 /// MemberPointerTypes - The set of member pointer types that will be 7679 /// used in the built-in candidates. 7680 TypeSet MemberPointerTypes; 7681 7682 /// EnumerationTypes - The set of enumeration types that will be 7683 /// used in the built-in candidates. 7684 TypeSet EnumerationTypes; 7685 7686 /// The set of vector types that will be used in the built-in 7687 /// candidates. 7688 TypeSet VectorTypes; 7689 7690 /// A flag indicating non-record types are viable candidates 7691 bool HasNonRecordTypes; 7692 7693 /// A flag indicating whether either arithmetic or enumeration types 7694 /// were present in the candidate set. 7695 bool HasArithmeticOrEnumeralTypes; 7696 7697 /// A flag indicating whether the nullptr type was present in the 7698 /// candidate set. 7699 bool HasNullPtrType; 7700 7701 /// Sema - The semantic analysis instance where we are building the 7702 /// candidate type set. 7703 Sema &SemaRef; 7704 7705 /// Context - The AST context in which we will build the type sets. 7706 ASTContext &Context; 7707 7708 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7709 const Qualifiers &VisibleQuals); 7710 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7711 7712 public: 7713 /// iterator - Iterates through the types that are part of the set. 7714 typedef TypeSet::iterator iterator; 7715 7716 BuiltinCandidateTypeSet(Sema &SemaRef) 7717 : HasNonRecordTypes(false), 7718 HasArithmeticOrEnumeralTypes(false), 7719 HasNullPtrType(false), 7720 SemaRef(SemaRef), 7721 Context(SemaRef.Context) { } 7722 7723 void AddTypesConvertedFrom(QualType Ty, 7724 SourceLocation Loc, 7725 bool AllowUserConversions, 7726 bool AllowExplicitConversions, 7727 const Qualifiers &VisibleTypeConversionsQuals); 7728 7729 /// pointer_begin - First pointer type found; 7730 iterator pointer_begin() { return PointerTypes.begin(); } 7731 7732 /// pointer_end - Past the last pointer type found; 7733 iterator pointer_end() { return PointerTypes.end(); } 7734 7735 /// member_pointer_begin - First member pointer type found; 7736 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7737 7738 /// member_pointer_end - Past the last member pointer type found; 7739 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7740 7741 /// enumeration_begin - First enumeration type found; 7742 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7743 7744 /// enumeration_end - Past the last enumeration type found; 7745 iterator enumeration_end() { return EnumerationTypes.end(); } 7746 7747 iterator vector_begin() { return VectorTypes.begin(); } 7748 iterator vector_end() { return VectorTypes.end(); } 7749 7750 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7751 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7752 bool hasNullPtrType() const { return HasNullPtrType; } 7753 }; 7754 7755 } // end anonymous namespace 7756 7757 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7758 /// the set of pointer types along with any more-qualified variants of 7759 /// that type. For example, if @p Ty is "int const *", this routine 7760 /// will add "int const *", "int const volatile *", "int const 7761 /// restrict *", and "int const volatile restrict *" to the set of 7762 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7763 /// false otherwise. 7764 /// 7765 /// FIXME: what to do about extended qualifiers? 7766 bool 7767 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7768 const Qualifiers &VisibleQuals) { 7769 7770 // Insert this type. 7771 if (!PointerTypes.insert(Ty)) 7772 return false; 7773 7774 QualType PointeeTy; 7775 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7776 bool buildObjCPtr = false; 7777 if (!PointerTy) { 7778 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7779 PointeeTy = PTy->getPointeeType(); 7780 buildObjCPtr = true; 7781 } else { 7782 PointeeTy = PointerTy->getPointeeType(); 7783 } 7784 7785 // Don't add qualified variants of arrays. For one, they're not allowed 7786 // (the qualifier would sink to the element type), and for another, the 7787 // only overload situation where it matters is subscript or pointer +- int, 7788 // and those shouldn't have qualifier variants anyway. 7789 if (PointeeTy->isArrayType()) 7790 return true; 7791 7792 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7793 bool hasVolatile = VisibleQuals.hasVolatile(); 7794 bool hasRestrict = VisibleQuals.hasRestrict(); 7795 7796 // Iterate through all strict supersets of BaseCVR. 7797 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7798 if ((CVR | BaseCVR) != CVR) continue; 7799 // Skip over volatile if no volatile found anywhere in the types. 7800 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7801 7802 // Skip over restrict if no restrict found anywhere in the types, or if 7803 // the type cannot be restrict-qualified. 7804 if ((CVR & Qualifiers::Restrict) && 7805 (!hasRestrict || 7806 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7807 continue; 7808 7809 // Build qualified pointee type. 7810 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7811 7812 // Build qualified pointer type. 7813 QualType QPointerTy; 7814 if (!buildObjCPtr) 7815 QPointerTy = Context.getPointerType(QPointeeTy); 7816 else 7817 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7818 7819 // Insert qualified pointer type. 7820 PointerTypes.insert(QPointerTy); 7821 } 7822 7823 return true; 7824 } 7825 7826 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7827 /// to the set of pointer types along with any more-qualified variants of 7828 /// that type. For example, if @p Ty is "int const *", this routine 7829 /// will add "int const *", "int const volatile *", "int const 7830 /// restrict *", and "int const volatile restrict *" to the set of 7831 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7832 /// false otherwise. 7833 /// 7834 /// FIXME: what to do about extended qualifiers? 7835 bool 7836 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7837 QualType Ty) { 7838 // Insert this type. 7839 if (!MemberPointerTypes.insert(Ty)) 7840 return false; 7841 7842 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7843 assert(PointerTy && "type was not a member pointer type!"); 7844 7845 QualType PointeeTy = PointerTy->getPointeeType(); 7846 // Don't add qualified variants of arrays. For one, they're not allowed 7847 // (the qualifier would sink to the element type), and for another, the 7848 // only overload situation where it matters is subscript or pointer +- int, 7849 // and those shouldn't have qualifier variants anyway. 7850 if (PointeeTy->isArrayType()) 7851 return true; 7852 const Type *ClassTy = PointerTy->getClass(); 7853 7854 // Iterate through all strict supersets of the pointee type's CVR 7855 // qualifiers. 7856 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7857 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7858 if ((CVR | BaseCVR) != CVR) continue; 7859 7860 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7861 MemberPointerTypes.insert( 7862 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7863 } 7864 7865 return true; 7866 } 7867 7868 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7869 /// Ty can be implicit converted to the given set of @p Types. We're 7870 /// primarily interested in pointer types and enumeration types. We also 7871 /// take member pointer types, for the conditional operator. 7872 /// AllowUserConversions is true if we should look at the conversion 7873 /// functions of a class type, and AllowExplicitConversions if we 7874 /// should also include the explicit conversion functions of a class 7875 /// type. 7876 void 7877 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7878 SourceLocation Loc, 7879 bool AllowUserConversions, 7880 bool AllowExplicitConversions, 7881 const Qualifiers &VisibleQuals) { 7882 // Only deal with canonical types. 7883 Ty = Context.getCanonicalType(Ty); 7884 7885 // Look through reference types; they aren't part of the type of an 7886 // expression for the purposes of conversions. 7887 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7888 Ty = RefTy->getPointeeType(); 7889 7890 // If we're dealing with an array type, decay to the pointer. 7891 if (Ty->isArrayType()) 7892 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7893 7894 // Otherwise, we don't care about qualifiers on the type. 7895 Ty = Ty.getLocalUnqualifiedType(); 7896 7897 // Flag if we ever add a non-record type. 7898 const RecordType *TyRec = Ty->getAs<RecordType>(); 7899 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7900 7901 // Flag if we encounter an arithmetic type. 7902 HasArithmeticOrEnumeralTypes = 7903 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7904 7905 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7906 PointerTypes.insert(Ty); 7907 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7908 // Insert our type, and its more-qualified variants, into the set 7909 // of types. 7910 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7911 return; 7912 } else if (Ty->isMemberPointerType()) { 7913 // Member pointers are far easier, since the pointee can't be converted. 7914 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7915 return; 7916 } else if (Ty->isEnumeralType()) { 7917 HasArithmeticOrEnumeralTypes = true; 7918 EnumerationTypes.insert(Ty); 7919 } else if (Ty->isVectorType()) { 7920 // We treat vector types as arithmetic types in many contexts as an 7921 // extension. 7922 HasArithmeticOrEnumeralTypes = true; 7923 VectorTypes.insert(Ty); 7924 } else if (Ty->isNullPtrType()) { 7925 HasNullPtrType = true; 7926 } else if (AllowUserConversions && TyRec) { 7927 // No conversion functions in incomplete types. 7928 if (!SemaRef.isCompleteType(Loc, Ty)) 7929 return; 7930 7931 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7932 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7933 if (isa<UsingShadowDecl>(D)) 7934 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7935 7936 // Skip conversion function templates; they don't tell us anything 7937 // about which builtin types we can convert to. 7938 if (isa<FunctionTemplateDecl>(D)) 7939 continue; 7940 7941 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7942 if (AllowExplicitConversions || !Conv->isExplicit()) { 7943 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7944 VisibleQuals); 7945 } 7946 } 7947 } 7948 } 7949 /// Helper function for adjusting address spaces for the pointer or reference 7950 /// operands of builtin operators depending on the argument. 7951 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7952 Expr *Arg) { 7953 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7954 } 7955 7956 /// Helper function for AddBuiltinOperatorCandidates() that adds 7957 /// the volatile- and non-volatile-qualified assignment operators for the 7958 /// given type to the candidate set. 7959 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7960 QualType T, 7961 ArrayRef<Expr *> Args, 7962 OverloadCandidateSet &CandidateSet) { 7963 QualType ParamTypes[2]; 7964 7965 // T& operator=(T&, T) 7966 ParamTypes[0] = S.Context.getLValueReferenceType( 7967 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7968 ParamTypes[1] = T; 7969 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7970 /*IsAssignmentOperator=*/true); 7971 7972 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7973 // volatile T& operator=(volatile T&, T) 7974 ParamTypes[0] = S.Context.getLValueReferenceType( 7975 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7976 Args[0])); 7977 ParamTypes[1] = T; 7978 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7979 /*IsAssignmentOperator=*/true); 7980 } 7981 } 7982 7983 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7984 /// if any, found in visible type conversion functions found in ArgExpr's type. 7985 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7986 Qualifiers VRQuals; 7987 const RecordType *TyRec; 7988 if (const MemberPointerType *RHSMPType = 7989 ArgExpr->getType()->getAs<MemberPointerType>()) 7990 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7991 else 7992 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7993 if (!TyRec) { 7994 // Just to be safe, assume the worst case. 7995 VRQuals.addVolatile(); 7996 VRQuals.addRestrict(); 7997 return VRQuals; 7998 } 7999 8000 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8001 if (!ClassDecl->hasDefinition()) 8002 return VRQuals; 8003 8004 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8005 if (isa<UsingShadowDecl>(D)) 8006 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8007 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8008 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8009 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8010 CanTy = ResTypeRef->getPointeeType(); 8011 // Need to go down the pointer/mempointer chain and add qualifiers 8012 // as see them. 8013 bool done = false; 8014 while (!done) { 8015 if (CanTy.isRestrictQualified()) 8016 VRQuals.addRestrict(); 8017 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8018 CanTy = ResTypePtr->getPointeeType(); 8019 else if (const MemberPointerType *ResTypeMPtr = 8020 CanTy->getAs<MemberPointerType>()) 8021 CanTy = ResTypeMPtr->getPointeeType(); 8022 else 8023 done = true; 8024 if (CanTy.isVolatileQualified()) 8025 VRQuals.addVolatile(); 8026 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8027 return VRQuals; 8028 } 8029 } 8030 } 8031 return VRQuals; 8032 } 8033 8034 namespace { 8035 8036 /// Helper class to manage the addition of builtin operator overload 8037 /// candidates. It provides shared state and utility methods used throughout 8038 /// the process, as well as a helper method to add each group of builtin 8039 /// operator overloads from the standard to a candidate set. 8040 class BuiltinOperatorOverloadBuilder { 8041 // Common instance state available to all overload candidate addition methods. 8042 Sema &S; 8043 ArrayRef<Expr *> Args; 8044 Qualifiers VisibleTypeConversionsQuals; 8045 bool HasArithmeticOrEnumeralCandidateType; 8046 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8047 OverloadCandidateSet &CandidateSet; 8048 8049 static constexpr int ArithmeticTypesCap = 24; 8050 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8051 8052 // Define some indices used to iterate over the arithmetic types in 8053 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8054 // types are that preserved by promotion (C++ [over.built]p2). 8055 unsigned FirstIntegralType, 8056 LastIntegralType; 8057 unsigned FirstPromotedIntegralType, 8058 LastPromotedIntegralType; 8059 unsigned FirstPromotedArithmeticType, 8060 LastPromotedArithmeticType; 8061 unsigned NumArithmeticTypes; 8062 8063 void InitArithmeticTypes() { 8064 // Start of promoted types. 8065 FirstPromotedArithmeticType = 0; 8066 ArithmeticTypes.push_back(S.Context.FloatTy); 8067 ArithmeticTypes.push_back(S.Context.DoubleTy); 8068 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8069 if (S.Context.getTargetInfo().hasFloat128Type()) 8070 ArithmeticTypes.push_back(S.Context.Float128Ty); 8071 8072 // Start of integral types. 8073 FirstIntegralType = ArithmeticTypes.size(); 8074 FirstPromotedIntegralType = ArithmeticTypes.size(); 8075 ArithmeticTypes.push_back(S.Context.IntTy); 8076 ArithmeticTypes.push_back(S.Context.LongTy); 8077 ArithmeticTypes.push_back(S.Context.LongLongTy); 8078 if (S.Context.getTargetInfo().hasInt128Type()) 8079 ArithmeticTypes.push_back(S.Context.Int128Ty); 8080 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8081 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8082 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8083 if (S.Context.getTargetInfo().hasInt128Type()) 8084 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8085 LastPromotedIntegralType = ArithmeticTypes.size(); 8086 LastPromotedArithmeticType = ArithmeticTypes.size(); 8087 // End of promoted types. 8088 8089 ArithmeticTypes.push_back(S.Context.BoolTy); 8090 ArithmeticTypes.push_back(S.Context.CharTy); 8091 ArithmeticTypes.push_back(S.Context.WCharTy); 8092 if (S.Context.getLangOpts().Char8) 8093 ArithmeticTypes.push_back(S.Context.Char8Ty); 8094 ArithmeticTypes.push_back(S.Context.Char16Ty); 8095 ArithmeticTypes.push_back(S.Context.Char32Ty); 8096 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8097 ArithmeticTypes.push_back(S.Context.ShortTy); 8098 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8099 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8100 LastIntegralType = ArithmeticTypes.size(); 8101 NumArithmeticTypes = ArithmeticTypes.size(); 8102 // End of integral types. 8103 // FIXME: What about complex? What about half? 8104 8105 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8106 "Enough inline storage for all arithmetic types."); 8107 } 8108 8109 /// Helper method to factor out the common pattern of adding overloads 8110 /// for '++' and '--' builtin operators. 8111 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8112 bool HasVolatile, 8113 bool HasRestrict) { 8114 QualType ParamTypes[2] = { 8115 S.Context.getLValueReferenceType(CandidateTy), 8116 S.Context.IntTy 8117 }; 8118 8119 // Non-volatile version. 8120 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8121 8122 // Use a heuristic to reduce number of builtin candidates in the set: 8123 // add volatile version only if there are conversions to a volatile type. 8124 if (HasVolatile) { 8125 ParamTypes[0] = 8126 S.Context.getLValueReferenceType( 8127 S.Context.getVolatileType(CandidateTy)); 8128 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8129 } 8130 8131 // Add restrict version only if there are conversions to a restrict type 8132 // and our candidate type is a non-restrict-qualified pointer. 8133 if (HasRestrict && CandidateTy->isAnyPointerType() && 8134 !CandidateTy.isRestrictQualified()) { 8135 ParamTypes[0] 8136 = S.Context.getLValueReferenceType( 8137 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8138 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8139 8140 if (HasVolatile) { 8141 ParamTypes[0] 8142 = S.Context.getLValueReferenceType( 8143 S.Context.getCVRQualifiedType(CandidateTy, 8144 (Qualifiers::Volatile | 8145 Qualifiers::Restrict))); 8146 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8147 } 8148 } 8149 8150 } 8151 8152 public: 8153 BuiltinOperatorOverloadBuilder( 8154 Sema &S, ArrayRef<Expr *> Args, 8155 Qualifiers VisibleTypeConversionsQuals, 8156 bool HasArithmeticOrEnumeralCandidateType, 8157 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8158 OverloadCandidateSet &CandidateSet) 8159 : S(S), Args(Args), 8160 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8161 HasArithmeticOrEnumeralCandidateType( 8162 HasArithmeticOrEnumeralCandidateType), 8163 CandidateTypes(CandidateTypes), 8164 CandidateSet(CandidateSet) { 8165 8166 InitArithmeticTypes(); 8167 } 8168 8169 // Increment is deprecated for bool since C++17. 8170 // 8171 // C++ [over.built]p3: 8172 // 8173 // For every pair (T, VQ), where T is an arithmetic type other 8174 // than bool, and VQ is either volatile or empty, there exist 8175 // candidate operator functions of the form 8176 // 8177 // VQ T& operator++(VQ T&); 8178 // T operator++(VQ T&, int); 8179 // 8180 // C++ [over.built]p4: 8181 // 8182 // For every pair (T, VQ), where T is an arithmetic type other 8183 // than bool, and VQ is either volatile or empty, there exist 8184 // candidate operator functions of the form 8185 // 8186 // VQ T& operator--(VQ T&); 8187 // T operator--(VQ T&, int); 8188 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8189 if (!HasArithmeticOrEnumeralCandidateType) 8190 return; 8191 8192 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8193 const auto TypeOfT = ArithmeticTypes[Arith]; 8194 if (TypeOfT == S.Context.BoolTy) { 8195 if (Op == OO_MinusMinus) 8196 continue; 8197 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8198 continue; 8199 } 8200 addPlusPlusMinusMinusStyleOverloads( 8201 TypeOfT, 8202 VisibleTypeConversionsQuals.hasVolatile(), 8203 VisibleTypeConversionsQuals.hasRestrict()); 8204 } 8205 } 8206 8207 // C++ [over.built]p5: 8208 // 8209 // For every pair (T, VQ), where T is a cv-qualified or 8210 // cv-unqualified object type, and VQ is either volatile or 8211 // empty, there exist candidate operator functions of the form 8212 // 8213 // T*VQ& operator++(T*VQ&); 8214 // T*VQ& operator--(T*VQ&); 8215 // T* operator++(T*VQ&, int); 8216 // T* operator--(T*VQ&, int); 8217 void addPlusPlusMinusMinusPointerOverloads() { 8218 for (BuiltinCandidateTypeSet::iterator 8219 Ptr = CandidateTypes[0].pointer_begin(), 8220 PtrEnd = CandidateTypes[0].pointer_end(); 8221 Ptr != PtrEnd; ++Ptr) { 8222 // Skip pointer types that aren't pointers to object types. 8223 if (!(*Ptr)->getPointeeType()->isObjectType()) 8224 continue; 8225 8226 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8227 (!(*Ptr).isVolatileQualified() && 8228 VisibleTypeConversionsQuals.hasVolatile()), 8229 (!(*Ptr).isRestrictQualified() && 8230 VisibleTypeConversionsQuals.hasRestrict())); 8231 } 8232 } 8233 8234 // C++ [over.built]p6: 8235 // For every cv-qualified or cv-unqualified object type T, there 8236 // exist candidate operator functions of the form 8237 // 8238 // T& operator*(T*); 8239 // 8240 // C++ [over.built]p7: 8241 // For every function type T that does not have cv-qualifiers or a 8242 // ref-qualifier, there exist candidate operator functions of the form 8243 // T& operator*(T*); 8244 void addUnaryStarPointerOverloads() { 8245 for (BuiltinCandidateTypeSet::iterator 8246 Ptr = CandidateTypes[0].pointer_begin(), 8247 PtrEnd = CandidateTypes[0].pointer_end(); 8248 Ptr != PtrEnd; ++Ptr) { 8249 QualType ParamTy = *Ptr; 8250 QualType PointeeTy = ParamTy->getPointeeType(); 8251 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8252 continue; 8253 8254 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8255 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8256 continue; 8257 8258 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8259 } 8260 } 8261 8262 // C++ [over.built]p9: 8263 // For every promoted arithmetic type T, there exist candidate 8264 // operator functions of the form 8265 // 8266 // T operator+(T); 8267 // T operator-(T); 8268 void addUnaryPlusOrMinusArithmeticOverloads() { 8269 if (!HasArithmeticOrEnumeralCandidateType) 8270 return; 8271 8272 for (unsigned Arith = FirstPromotedArithmeticType; 8273 Arith < LastPromotedArithmeticType; ++Arith) { 8274 QualType ArithTy = ArithmeticTypes[Arith]; 8275 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8276 } 8277 8278 // Extension: We also add these operators for vector types. 8279 for (BuiltinCandidateTypeSet::iterator 8280 Vec = CandidateTypes[0].vector_begin(), 8281 VecEnd = CandidateTypes[0].vector_end(); 8282 Vec != VecEnd; ++Vec) { 8283 QualType VecTy = *Vec; 8284 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8285 } 8286 } 8287 8288 // C++ [over.built]p8: 8289 // For every type T, there exist candidate operator functions of 8290 // the form 8291 // 8292 // T* operator+(T*); 8293 void addUnaryPlusPointerOverloads() { 8294 for (BuiltinCandidateTypeSet::iterator 8295 Ptr = CandidateTypes[0].pointer_begin(), 8296 PtrEnd = CandidateTypes[0].pointer_end(); 8297 Ptr != PtrEnd; ++Ptr) { 8298 QualType ParamTy = *Ptr; 8299 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8300 } 8301 } 8302 8303 // C++ [over.built]p10: 8304 // For every promoted integral type T, there exist candidate 8305 // operator functions of the form 8306 // 8307 // T operator~(T); 8308 void addUnaryTildePromotedIntegralOverloads() { 8309 if (!HasArithmeticOrEnumeralCandidateType) 8310 return; 8311 8312 for (unsigned Int = FirstPromotedIntegralType; 8313 Int < LastPromotedIntegralType; ++Int) { 8314 QualType IntTy = ArithmeticTypes[Int]; 8315 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8316 } 8317 8318 // Extension: We also add this operator for vector types. 8319 for (BuiltinCandidateTypeSet::iterator 8320 Vec = CandidateTypes[0].vector_begin(), 8321 VecEnd = CandidateTypes[0].vector_end(); 8322 Vec != VecEnd; ++Vec) { 8323 QualType VecTy = *Vec; 8324 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8325 } 8326 } 8327 8328 // C++ [over.match.oper]p16: 8329 // For every pointer to member type T or type std::nullptr_t, there 8330 // exist candidate operator functions of the form 8331 // 8332 // bool operator==(T,T); 8333 // bool operator!=(T,T); 8334 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8335 /// Set of (canonical) types that we've already handled. 8336 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8337 8338 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8339 for (BuiltinCandidateTypeSet::iterator 8340 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8341 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8342 MemPtr != MemPtrEnd; 8343 ++MemPtr) { 8344 // Don't add the same builtin candidate twice. 8345 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8346 continue; 8347 8348 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8349 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8350 } 8351 8352 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8353 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8354 if (AddedTypes.insert(NullPtrTy).second) { 8355 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8356 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8357 } 8358 } 8359 } 8360 } 8361 8362 // C++ [over.built]p15: 8363 // 8364 // For every T, where T is an enumeration type or a pointer type, 8365 // there exist candidate operator functions of the form 8366 // 8367 // bool operator<(T, T); 8368 // bool operator>(T, T); 8369 // bool operator<=(T, T); 8370 // bool operator>=(T, T); 8371 // bool operator==(T, T); 8372 // bool operator!=(T, T); 8373 // R operator<=>(T, T) 8374 void addGenericBinaryPointerOrEnumeralOverloads() { 8375 // C++ [over.match.oper]p3: 8376 // [...]the built-in candidates include all of the candidate operator 8377 // functions defined in 13.6 that, compared to the given operator, [...] 8378 // do not have the same parameter-type-list as any non-template non-member 8379 // candidate. 8380 // 8381 // Note that in practice, this only affects enumeration types because there 8382 // aren't any built-in candidates of record type, and a user-defined operator 8383 // must have an operand of record or enumeration type. Also, the only other 8384 // overloaded operator with enumeration arguments, operator=, 8385 // cannot be overloaded for enumeration types, so this is the only place 8386 // where we must suppress candidates like this. 8387 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8388 UserDefinedBinaryOperators; 8389 8390 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8391 if (CandidateTypes[ArgIdx].enumeration_begin() != 8392 CandidateTypes[ArgIdx].enumeration_end()) { 8393 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8394 CEnd = CandidateSet.end(); 8395 C != CEnd; ++C) { 8396 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8397 continue; 8398 8399 if (C->Function->isFunctionTemplateSpecialization()) 8400 continue; 8401 8402 // We interpret "same parameter-type-list" as applying to the 8403 // "synthesized candidate, with the order of the two parameters 8404 // reversed", not to the original function. 8405 bool Reversed = C->isReversed(); 8406 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8407 ->getType() 8408 .getUnqualifiedType(); 8409 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8410 ->getType() 8411 .getUnqualifiedType(); 8412 8413 // Skip if either parameter isn't of enumeral type. 8414 if (!FirstParamType->isEnumeralType() || 8415 !SecondParamType->isEnumeralType()) 8416 continue; 8417 8418 // Add this operator to the set of known user-defined operators. 8419 UserDefinedBinaryOperators.insert( 8420 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8421 S.Context.getCanonicalType(SecondParamType))); 8422 } 8423 } 8424 } 8425 8426 /// Set of (canonical) types that we've already handled. 8427 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8428 8429 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8430 for (BuiltinCandidateTypeSet::iterator 8431 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8432 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8433 Ptr != PtrEnd; ++Ptr) { 8434 // Don't add the same builtin candidate twice. 8435 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8436 continue; 8437 8438 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8439 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8440 } 8441 for (BuiltinCandidateTypeSet::iterator 8442 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8443 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8444 Enum != EnumEnd; ++Enum) { 8445 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8446 8447 // Don't add the same builtin candidate twice, or if a user defined 8448 // candidate exists. 8449 if (!AddedTypes.insert(CanonType).second || 8450 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8451 CanonType))) 8452 continue; 8453 QualType ParamTypes[2] = { *Enum, *Enum }; 8454 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8455 } 8456 } 8457 } 8458 8459 // C++ [over.built]p13: 8460 // 8461 // For every cv-qualified or cv-unqualified object type T 8462 // there exist candidate operator functions of the form 8463 // 8464 // T* operator+(T*, ptrdiff_t); 8465 // T& operator[](T*, ptrdiff_t); [BELOW] 8466 // T* operator-(T*, ptrdiff_t); 8467 // T* operator+(ptrdiff_t, T*); 8468 // T& operator[](ptrdiff_t, T*); [BELOW] 8469 // 8470 // C++ [over.built]p14: 8471 // 8472 // For every T, where T is a pointer to object type, there 8473 // exist candidate operator functions of the form 8474 // 8475 // ptrdiff_t operator-(T, T); 8476 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8477 /// Set of (canonical) types that we've already handled. 8478 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8479 8480 for (int Arg = 0; Arg < 2; ++Arg) { 8481 QualType AsymmetricParamTypes[2] = { 8482 S.Context.getPointerDiffType(), 8483 S.Context.getPointerDiffType(), 8484 }; 8485 for (BuiltinCandidateTypeSet::iterator 8486 Ptr = CandidateTypes[Arg].pointer_begin(), 8487 PtrEnd = CandidateTypes[Arg].pointer_end(); 8488 Ptr != PtrEnd; ++Ptr) { 8489 QualType PointeeTy = (*Ptr)->getPointeeType(); 8490 if (!PointeeTy->isObjectType()) 8491 continue; 8492 8493 AsymmetricParamTypes[Arg] = *Ptr; 8494 if (Arg == 0 || Op == OO_Plus) { 8495 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8496 // T* operator+(ptrdiff_t, T*); 8497 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8498 } 8499 if (Op == OO_Minus) { 8500 // ptrdiff_t operator-(T, T); 8501 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8502 continue; 8503 8504 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8505 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8506 } 8507 } 8508 } 8509 } 8510 8511 // C++ [over.built]p12: 8512 // 8513 // For every pair of promoted arithmetic types L and R, there 8514 // exist candidate operator functions of the form 8515 // 8516 // LR operator*(L, R); 8517 // LR operator/(L, R); 8518 // LR operator+(L, R); 8519 // LR operator-(L, R); 8520 // bool operator<(L, R); 8521 // bool operator>(L, R); 8522 // bool operator<=(L, R); 8523 // bool operator>=(L, R); 8524 // bool operator==(L, R); 8525 // bool operator!=(L, R); 8526 // 8527 // where LR is the result of the usual arithmetic conversions 8528 // between types L and R. 8529 // 8530 // C++ [over.built]p24: 8531 // 8532 // For every pair of promoted arithmetic types L and R, there exist 8533 // candidate operator functions of the form 8534 // 8535 // LR operator?(bool, L, R); 8536 // 8537 // where LR is the result of the usual arithmetic conversions 8538 // between types L and R. 8539 // Our candidates ignore the first parameter. 8540 void addGenericBinaryArithmeticOverloads() { 8541 if (!HasArithmeticOrEnumeralCandidateType) 8542 return; 8543 8544 for (unsigned Left = FirstPromotedArithmeticType; 8545 Left < LastPromotedArithmeticType; ++Left) { 8546 for (unsigned Right = FirstPromotedArithmeticType; 8547 Right < LastPromotedArithmeticType; ++Right) { 8548 QualType LandR[2] = { ArithmeticTypes[Left], 8549 ArithmeticTypes[Right] }; 8550 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8551 } 8552 } 8553 8554 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8555 // conditional operator for vector types. 8556 for (BuiltinCandidateTypeSet::iterator 8557 Vec1 = CandidateTypes[0].vector_begin(), 8558 Vec1End = CandidateTypes[0].vector_end(); 8559 Vec1 != Vec1End; ++Vec1) { 8560 for (BuiltinCandidateTypeSet::iterator 8561 Vec2 = CandidateTypes[1].vector_begin(), 8562 Vec2End = CandidateTypes[1].vector_end(); 8563 Vec2 != Vec2End; ++Vec2) { 8564 QualType LandR[2] = { *Vec1, *Vec2 }; 8565 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8566 } 8567 } 8568 } 8569 8570 // C++2a [over.built]p14: 8571 // 8572 // For every integral type T there exists a candidate operator function 8573 // of the form 8574 // 8575 // std::strong_ordering operator<=>(T, T) 8576 // 8577 // C++2a [over.built]p15: 8578 // 8579 // For every pair of floating-point types L and R, there exists a candidate 8580 // operator function of the form 8581 // 8582 // std::partial_ordering operator<=>(L, R); 8583 // 8584 // FIXME: The current specification for integral types doesn't play nice with 8585 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8586 // comparisons. Under the current spec this can lead to ambiguity during 8587 // overload resolution. For example: 8588 // 8589 // enum A : int {a}; 8590 // auto x = (a <=> (long)42); 8591 // 8592 // error: call is ambiguous for arguments 'A' and 'long'. 8593 // note: candidate operator<=>(int, int) 8594 // note: candidate operator<=>(long, long) 8595 // 8596 // To avoid this error, this function deviates from the specification and adds 8597 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8598 // arithmetic types (the same as the generic relational overloads). 8599 // 8600 // For now this function acts as a placeholder. 8601 void addThreeWayArithmeticOverloads() { 8602 addGenericBinaryArithmeticOverloads(); 8603 } 8604 8605 // C++ [over.built]p17: 8606 // 8607 // For every pair of promoted integral types L and R, there 8608 // exist candidate operator functions of the form 8609 // 8610 // LR operator%(L, R); 8611 // LR operator&(L, R); 8612 // LR operator^(L, R); 8613 // LR operator|(L, R); 8614 // L operator<<(L, R); 8615 // L operator>>(L, R); 8616 // 8617 // where LR is the result of the usual arithmetic conversions 8618 // between types L and R. 8619 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8620 if (!HasArithmeticOrEnumeralCandidateType) 8621 return; 8622 8623 for (unsigned Left = FirstPromotedIntegralType; 8624 Left < LastPromotedIntegralType; ++Left) { 8625 for (unsigned Right = FirstPromotedIntegralType; 8626 Right < LastPromotedIntegralType; ++Right) { 8627 QualType LandR[2] = { ArithmeticTypes[Left], 8628 ArithmeticTypes[Right] }; 8629 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8630 } 8631 } 8632 } 8633 8634 // C++ [over.built]p20: 8635 // 8636 // For every pair (T, VQ), where T is an enumeration or 8637 // pointer to member type and VQ is either volatile or 8638 // empty, there exist candidate operator functions of the form 8639 // 8640 // VQ T& operator=(VQ T&, T); 8641 void addAssignmentMemberPointerOrEnumeralOverloads() { 8642 /// Set of (canonical) types that we've already handled. 8643 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8644 8645 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8646 for (BuiltinCandidateTypeSet::iterator 8647 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8648 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8649 Enum != EnumEnd; ++Enum) { 8650 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8651 continue; 8652 8653 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8654 } 8655 8656 for (BuiltinCandidateTypeSet::iterator 8657 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8658 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8659 MemPtr != MemPtrEnd; ++MemPtr) { 8660 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8661 continue; 8662 8663 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8664 } 8665 } 8666 } 8667 8668 // C++ [over.built]p19: 8669 // 8670 // For every pair (T, VQ), where T is any type and VQ is either 8671 // volatile or empty, there exist candidate operator functions 8672 // of the form 8673 // 8674 // T*VQ& operator=(T*VQ&, T*); 8675 // 8676 // C++ [over.built]p21: 8677 // 8678 // For every pair (T, VQ), where T is a cv-qualified or 8679 // cv-unqualified object type and VQ is either volatile or 8680 // empty, there exist candidate operator functions of the form 8681 // 8682 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8683 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8684 void addAssignmentPointerOverloads(bool isEqualOp) { 8685 /// Set of (canonical) types that we've already handled. 8686 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8687 8688 for (BuiltinCandidateTypeSet::iterator 8689 Ptr = CandidateTypes[0].pointer_begin(), 8690 PtrEnd = CandidateTypes[0].pointer_end(); 8691 Ptr != PtrEnd; ++Ptr) { 8692 // If this is operator=, keep track of the builtin candidates we added. 8693 if (isEqualOp) 8694 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8695 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8696 continue; 8697 8698 // non-volatile version 8699 QualType ParamTypes[2] = { 8700 S.Context.getLValueReferenceType(*Ptr), 8701 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8702 }; 8703 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8704 /*IsAssignmentOperator=*/ isEqualOp); 8705 8706 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8707 VisibleTypeConversionsQuals.hasVolatile(); 8708 if (NeedVolatile) { 8709 // volatile version 8710 ParamTypes[0] = 8711 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8712 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8713 /*IsAssignmentOperator=*/isEqualOp); 8714 } 8715 8716 if (!(*Ptr).isRestrictQualified() && 8717 VisibleTypeConversionsQuals.hasRestrict()) { 8718 // restrict version 8719 ParamTypes[0] 8720 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8721 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8722 /*IsAssignmentOperator=*/isEqualOp); 8723 8724 if (NeedVolatile) { 8725 // volatile restrict version 8726 ParamTypes[0] 8727 = S.Context.getLValueReferenceType( 8728 S.Context.getCVRQualifiedType(*Ptr, 8729 (Qualifiers::Volatile | 8730 Qualifiers::Restrict))); 8731 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8732 /*IsAssignmentOperator=*/isEqualOp); 8733 } 8734 } 8735 } 8736 8737 if (isEqualOp) { 8738 for (BuiltinCandidateTypeSet::iterator 8739 Ptr = CandidateTypes[1].pointer_begin(), 8740 PtrEnd = CandidateTypes[1].pointer_end(); 8741 Ptr != PtrEnd; ++Ptr) { 8742 // Make sure we don't add the same candidate twice. 8743 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8744 continue; 8745 8746 QualType ParamTypes[2] = { 8747 S.Context.getLValueReferenceType(*Ptr), 8748 *Ptr, 8749 }; 8750 8751 // non-volatile version 8752 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8753 /*IsAssignmentOperator=*/true); 8754 8755 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8756 VisibleTypeConversionsQuals.hasVolatile(); 8757 if (NeedVolatile) { 8758 // volatile version 8759 ParamTypes[0] = 8760 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8761 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8762 /*IsAssignmentOperator=*/true); 8763 } 8764 8765 if (!(*Ptr).isRestrictQualified() && 8766 VisibleTypeConversionsQuals.hasRestrict()) { 8767 // restrict version 8768 ParamTypes[0] 8769 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8770 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8771 /*IsAssignmentOperator=*/true); 8772 8773 if (NeedVolatile) { 8774 // volatile restrict version 8775 ParamTypes[0] 8776 = S.Context.getLValueReferenceType( 8777 S.Context.getCVRQualifiedType(*Ptr, 8778 (Qualifiers::Volatile | 8779 Qualifiers::Restrict))); 8780 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8781 /*IsAssignmentOperator=*/true); 8782 } 8783 } 8784 } 8785 } 8786 } 8787 8788 // C++ [over.built]p18: 8789 // 8790 // For every triple (L, VQ, R), where L is an arithmetic type, 8791 // VQ is either volatile or empty, and R is a promoted 8792 // arithmetic type, there exist candidate operator functions of 8793 // the form 8794 // 8795 // VQ L& operator=(VQ L&, R); 8796 // VQ L& operator*=(VQ L&, R); 8797 // VQ L& operator/=(VQ L&, R); 8798 // VQ L& operator+=(VQ L&, R); 8799 // VQ L& operator-=(VQ L&, R); 8800 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8801 if (!HasArithmeticOrEnumeralCandidateType) 8802 return; 8803 8804 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8805 for (unsigned Right = FirstPromotedArithmeticType; 8806 Right < LastPromotedArithmeticType; ++Right) { 8807 QualType ParamTypes[2]; 8808 ParamTypes[1] = ArithmeticTypes[Right]; 8809 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8810 S, ArithmeticTypes[Left], Args[0]); 8811 // Add this built-in operator as a candidate (VQ is empty). 8812 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8813 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8814 /*IsAssignmentOperator=*/isEqualOp); 8815 8816 // Add this built-in operator as a candidate (VQ is 'volatile'). 8817 if (VisibleTypeConversionsQuals.hasVolatile()) { 8818 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8819 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8820 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8821 /*IsAssignmentOperator=*/isEqualOp); 8822 } 8823 } 8824 } 8825 8826 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8827 for (BuiltinCandidateTypeSet::iterator 8828 Vec1 = CandidateTypes[0].vector_begin(), 8829 Vec1End = CandidateTypes[0].vector_end(); 8830 Vec1 != Vec1End; ++Vec1) { 8831 for (BuiltinCandidateTypeSet::iterator 8832 Vec2 = CandidateTypes[1].vector_begin(), 8833 Vec2End = CandidateTypes[1].vector_end(); 8834 Vec2 != Vec2End; ++Vec2) { 8835 QualType ParamTypes[2]; 8836 ParamTypes[1] = *Vec2; 8837 // Add this built-in operator as a candidate (VQ is empty). 8838 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8839 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8840 /*IsAssignmentOperator=*/isEqualOp); 8841 8842 // Add this built-in operator as a candidate (VQ is 'volatile'). 8843 if (VisibleTypeConversionsQuals.hasVolatile()) { 8844 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8845 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8846 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8847 /*IsAssignmentOperator=*/isEqualOp); 8848 } 8849 } 8850 } 8851 } 8852 8853 // C++ [over.built]p22: 8854 // 8855 // For every triple (L, VQ, R), where L is an integral type, VQ 8856 // is either volatile or empty, and R is a promoted integral 8857 // type, there exist candidate operator functions of the form 8858 // 8859 // VQ L& operator%=(VQ L&, R); 8860 // VQ L& operator<<=(VQ L&, R); 8861 // VQ L& operator>>=(VQ L&, R); 8862 // VQ L& operator&=(VQ L&, R); 8863 // VQ L& operator^=(VQ L&, R); 8864 // VQ L& operator|=(VQ L&, R); 8865 void addAssignmentIntegralOverloads() { 8866 if (!HasArithmeticOrEnumeralCandidateType) 8867 return; 8868 8869 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8870 for (unsigned Right = FirstPromotedIntegralType; 8871 Right < LastPromotedIntegralType; ++Right) { 8872 QualType ParamTypes[2]; 8873 ParamTypes[1] = ArithmeticTypes[Right]; 8874 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8875 S, ArithmeticTypes[Left], Args[0]); 8876 // Add this built-in operator as a candidate (VQ is empty). 8877 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8878 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8879 if (VisibleTypeConversionsQuals.hasVolatile()) { 8880 // Add this built-in operator as a candidate (VQ is 'volatile'). 8881 ParamTypes[0] = LeftBaseTy; 8882 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8883 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8884 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8885 } 8886 } 8887 } 8888 } 8889 8890 // C++ [over.operator]p23: 8891 // 8892 // There also exist candidate operator functions of the form 8893 // 8894 // bool operator!(bool); 8895 // bool operator&&(bool, bool); 8896 // bool operator||(bool, bool); 8897 void addExclaimOverload() { 8898 QualType ParamTy = S.Context.BoolTy; 8899 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8900 /*IsAssignmentOperator=*/false, 8901 /*NumContextualBoolArguments=*/1); 8902 } 8903 void addAmpAmpOrPipePipeOverload() { 8904 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8905 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8906 /*IsAssignmentOperator=*/false, 8907 /*NumContextualBoolArguments=*/2); 8908 } 8909 8910 // C++ [over.built]p13: 8911 // 8912 // For every cv-qualified or cv-unqualified object type T there 8913 // exist candidate operator functions of the form 8914 // 8915 // T* operator+(T*, ptrdiff_t); [ABOVE] 8916 // T& operator[](T*, ptrdiff_t); 8917 // T* operator-(T*, ptrdiff_t); [ABOVE] 8918 // T* operator+(ptrdiff_t, T*); [ABOVE] 8919 // T& operator[](ptrdiff_t, T*); 8920 void addSubscriptOverloads() { 8921 for (BuiltinCandidateTypeSet::iterator 8922 Ptr = CandidateTypes[0].pointer_begin(), 8923 PtrEnd = CandidateTypes[0].pointer_end(); 8924 Ptr != PtrEnd; ++Ptr) { 8925 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8926 QualType PointeeType = (*Ptr)->getPointeeType(); 8927 if (!PointeeType->isObjectType()) 8928 continue; 8929 8930 // T& operator[](T*, ptrdiff_t) 8931 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8932 } 8933 8934 for (BuiltinCandidateTypeSet::iterator 8935 Ptr = CandidateTypes[1].pointer_begin(), 8936 PtrEnd = CandidateTypes[1].pointer_end(); 8937 Ptr != PtrEnd; ++Ptr) { 8938 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8939 QualType PointeeType = (*Ptr)->getPointeeType(); 8940 if (!PointeeType->isObjectType()) 8941 continue; 8942 8943 // T& operator[](ptrdiff_t, T*) 8944 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8945 } 8946 } 8947 8948 // C++ [over.built]p11: 8949 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8950 // C1 is the same type as C2 or is a derived class of C2, T is an object 8951 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8952 // there exist candidate operator functions of the form 8953 // 8954 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8955 // 8956 // where CV12 is the union of CV1 and CV2. 8957 void addArrowStarOverloads() { 8958 for (BuiltinCandidateTypeSet::iterator 8959 Ptr = CandidateTypes[0].pointer_begin(), 8960 PtrEnd = CandidateTypes[0].pointer_end(); 8961 Ptr != PtrEnd; ++Ptr) { 8962 QualType C1Ty = (*Ptr); 8963 QualType C1; 8964 QualifierCollector Q1; 8965 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8966 if (!isa<RecordType>(C1)) 8967 continue; 8968 // heuristic to reduce number of builtin candidates in the set. 8969 // Add volatile/restrict version only if there are conversions to a 8970 // volatile/restrict type. 8971 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8972 continue; 8973 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8974 continue; 8975 for (BuiltinCandidateTypeSet::iterator 8976 MemPtr = CandidateTypes[1].member_pointer_begin(), 8977 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8978 MemPtr != MemPtrEnd; ++MemPtr) { 8979 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8980 QualType C2 = QualType(mptr->getClass(), 0); 8981 C2 = C2.getUnqualifiedType(); 8982 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8983 break; 8984 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8985 // build CV12 T& 8986 QualType T = mptr->getPointeeType(); 8987 if (!VisibleTypeConversionsQuals.hasVolatile() && 8988 T.isVolatileQualified()) 8989 continue; 8990 if (!VisibleTypeConversionsQuals.hasRestrict() && 8991 T.isRestrictQualified()) 8992 continue; 8993 T = Q1.apply(S.Context, T); 8994 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8995 } 8996 } 8997 } 8998 8999 // Note that we don't consider the first argument, since it has been 9000 // contextually converted to bool long ago. The candidates below are 9001 // therefore added as binary. 9002 // 9003 // C++ [over.built]p25: 9004 // For every type T, where T is a pointer, pointer-to-member, or scoped 9005 // enumeration type, there exist candidate operator functions of the form 9006 // 9007 // T operator?(bool, T, T); 9008 // 9009 void addConditionalOperatorOverloads() { 9010 /// Set of (canonical) types that we've already handled. 9011 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9012 9013 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9014 for (BuiltinCandidateTypeSet::iterator 9015 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9016 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9017 Ptr != PtrEnd; ++Ptr) { 9018 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9019 continue; 9020 9021 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9022 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9023 } 9024 9025 for (BuiltinCandidateTypeSet::iterator 9026 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9027 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9028 MemPtr != MemPtrEnd; ++MemPtr) { 9029 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9030 continue; 9031 9032 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9033 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9034 } 9035 9036 if (S.getLangOpts().CPlusPlus11) { 9037 for (BuiltinCandidateTypeSet::iterator 9038 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9039 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9040 Enum != EnumEnd; ++Enum) { 9041 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9042 continue; 9043 9044 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9045 continue; 9046 9047 QualType ParamTypes[2] = { *Enum, *Enum }; 9048 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9049 } 9050 } 9051 } 9052 } 9053 }; 9054 9055 } // end anonymous namespace 9056 9057 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9058 /// operator overloads to the candidate set (C++ [over.built]), based 9059 /// on the operator @p Op and the arguments given. For example, if the 9060 /// operator is a binary '+', this routine might add "int 9061 /// operator+(int, int)" to cover integer addition. 9062 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9063 SourceLocation OpLoc, 9064 ArrayRef<Expr *> Args, 9065 OverloadCandidateSet &CandidateSet) { 9066 // Find all of the types that the arguments can convert to, but only 9067 // if the operator we're looking at has built-in operator candidates 9068 // that make use of these types. Also record whether we encounter non-record 9069 // candidate types or either arithmetic or enumeral candidate types. 9070 Qualifiers VisibleTypeConversionsQuals; 9071 VisibleTypeConversionsQuals.addConst(); 9072 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9073 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9074 9075 bool HasNonRecordCandidateType = false; 9076 bool HasArithmeticOrEnumeralCandidateType = false; 9077 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9078 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9079 CandidateTypes.emplace_back(*this); 9080 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9081 OpLoc, 9082 true, 9083 (Op == OO_Exclaim || 9084 Op == OO_AmpAmp || 9085 Op == OO_PipePipe), 9086 VisibleTypeConversionsQuals); 9087 HasNonRecordCandidateType = HasNonRecordCandidateType || 9088 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9089 HasArithmeticOrEnumeralCandidateType = 9090 HasArithmeticOrEnumeralCandidateType || 9091 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9092 } 9093 9094 // Exit early when no non-record types have been added to the candidate set 9095 // for any of the arguments to the operator. 9096 // 9097 // We can't exit early for !, ||, or &&, since there we have always have 9098 // 'bool' overloads. 9099 if (!HasNonRecordCandidateType && 9100 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9101 return; 9102 9103 // Setup an object to manage the common state for building overloads. 9104 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9105 VisibleTypeConversionsQuals, 9106 HasArithmeticOrEnumeralCandidateType, 9107 CandidateTypes, CandidateSet); 9108 9109 // Dispatch over the operation to add in only those overloads which apply. 9110 switch (Op) { 9111 case OO_None: 9112 case NUM_OVERLOADED_OPERATORS: 9113 llvm_unreachable("Expected an overloaded operator"); 9114 9115 case OO_New: 9116 case OO_Delete: 9117 case OO_Array_New: 9118 case OO_Array_Delete: 9119 case OO_Call: 9120 llvm_unreachable( 9121 "Special operators don't use AddBuiltinOperatorCandidates"); 9122 9123 case OO_Comma: 9124 case OO_Arrow: 9125 case OO_Coawait: 9126 // C++ [over.match.oper]p3: 9127 // -- For the operator ',', the unary operator '&', the 9128 // operator '->', or the operator 'co_await', the 9129 // built-in candidates set is empty. 9130 break; 9131 9132 case OO_Plus: // '+' is either unary or binary 9133 if (Args.size() == 1) 9134 OpBuilder.addUnaryPlusPointerOverloads(); 9135 LLVM_FALLTHROUGH; 9136 9137 case OO_Minus: // '-' is either unary or binary 9138 if (Args.size() == 1) { 9139 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9140 } else { 9141 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9142 OpBuilder.addGenericBinaryArithmeticOverloads(); 9143 } 9144 break; 9145 9146 case OO_Star: // '*' is either unary or binary 9147 if (Args.size() == 1) 9148 OpBuilder.addUnaryStarPointerOverloads(); 9149 else 9150 OpBuilder.addGenericBinaryArithmeticOverloads(); 9151 break; 9152 9153 case OO_Slash: 9154 OpBuilder.addGenericBinaryArithmeticOverloads(); 9155 break; 9156 9157 case OO_PlusPlus: 9158 case OO_MinusMinus: 9159 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9160 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9161 break; 9162 9163 case OO_EqualEqual: 9164 case OO_ExclaimEqual: 9165 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9166 LLVM_FALLTHROUGH; 9167 9168 case OO_Less: 9169 case OO_Greater: 9170 case OO_LessEqual: 9171 case OO_GreaterEqual: 9172 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9173 OpBuilder.addGenericBinaryArithmeticOverloads(); 9174 break; 9175 9176 case OO_Spaceship: 9177 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9178 OpBuilder.addThreeWayArithmeticOverloads(); 9179 break; 9180 9181 case OO_Percent: 9182 case OO_Caret: 9183 case OO_Pipe: 9184 case OO_LessLess: 9185 case OO_GreaterGreater: 9186 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9187 break; 9188 9189 case OO_Amp: // '&' is either unary or binary 9190 if (Args.size() == 1) 9191 // C++ [over.match.oper]p3: 9192 // -- For the operator ',', the unary operator '&', or the 9193 // operator '->', the built-in candidates set is empty. 9194 break; 9195 9196 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9197 break; 9198 9199 case OO_Tilde: 9200 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9201 break; 9202 9203 case OO_Equal: 9204 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9205 LLVM_FALLTHROUGH; 9206 9207 case OO_PlusEqual: 9208 case OO_MinusEqual: 9209 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9210 LLVM_FALLTHROUGH; 9211 9212 case OO_StarEqual: 9213 case OO_SlashEqual: 9214 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9215 break; 9216 9217 case OO_PercentEqual: 9218 case OO_LessLessEqual: 9219 case OO_GreaterGreaterEqual: 9220 case OO_AmpEqual: 9221 case OO_CaretEqual: 9222 case OO_PipeEqual: 9223 OpBuilder.addAssignmentIntegralOverloads(); 9224 break; 9225 9226 case OO_Exclaim: 9227 OpBuilder.addExclaimOverload(); 9228 break; 9229 9230 case OO_AmpAmp: 9231 case OO_PipePipe: 9232 OpBuilder.addAmpAmpOrPipePipeOverload(); 9233 break; 9234 9235 case OO_Subscript: 9236 OpBuilder.addSubscriptOverloads(); 9237 break; 9238 9239 case OO_ArrowStar: 9240 OpBuilder.addArrowStarOverloads(); 9241 break; 9242 9243 case OO_Conditional: 9244 OpBuilder.addConditionalOperatorOverloads(); 9245 OpBuilder.addGenericBinaryArithmeticOverloads(); 9246 break; 9247 } 9248 } 9249 9250 /// Add function candidates found via argument-dependent lookup 9251 /// to the set of overloading candidates. 9252 /// 9253 /// This routine performs argument-dependent name lookup based on the 9254 /// given function name (which may also be an operator name) and adds 9255 /// all of the overload candidates found by ADL to the overload 9256 /// candidate set (C++ [basic.lookup.argdep]). 9257 void 9258 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9259 SourceLocation Loc, 9260 ArrayRef<Expr *> Args, 9261 TemplateArgumentListInfo *ExplicitTemplateArgs, 9262 OverloadCandidateSet& CandidateSet, 9263 bool PartialOverloading) { 9264 ADLResult Fns; 9265 9266 // FIXME: This approach for uniquing ADL results (and removing 9267 // redundant candidates from the set) relies on pointer-equality, 9268 // which means we need to key off the canonical decl. However, 9269 // always going back to the canonical decl might not get us the 9270 // right set of default arguments. What default arguments are 9271 // we supposed to consider on ADL candidates, anyway? 9272 9273 // FIXME: Pass in the explicit template arguments? 9274 ArgumentDependentLookup(Name, Loc, Args, Fns); 9275 9276 // Erase all of the candidates we already knew about. 9277 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9278 CandEnd = CandidateSet.end(); 9279 Cand != CandEnd; ++Cand) 9280 if (Cand->Function) { 9281 Fns.erase(Cand->Function); 9282 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9283 Fns.erase(FunTmpl); 9284 } 9285 9286 // For each of the ADL candidates we found, add it to the overload 9287 // set. 9288 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9289 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9290 9291 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9292 if (ExplicitTemplateArgs) 9293 continue; 9294 9295 AddOverloadCandidate( 9296 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9297 PartialOverloading, /*AllowExplicit=*/true, 9298 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9299 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9300 AddOverloadCandidate( 9301 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9302 /*SuppressUserConversions=*/false, PartialOverloading, 9303 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9304 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9305 } 9306 } else { 9307 auto *FTD = cast<FunctionTemplateDecl>(*I); 9308 AddTemplateOverloadCandidate( 9309 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9310 /*SuppressUserConversions=*/false, PartialOverloading, 9311 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9312 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9313 Context, FTD->getTemplatedDecl())) { 9314 AddTemplateOverloadCandidate( 9315 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9316 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9317 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9318 OverloadCandidateParamOrder::Reversed); 9319 } 9320 } 9321 } 9322 } 9323 9324 namespace { 9325 enum class Comparison { Equal, Better, Worse }; 9326 } 9327 9328 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9329 /// overload resolution. 9330 /// 9331 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9332 /// Cand1's first N enable_if attributes have precisely the same conditions as 9333 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9334 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9335 /// 9336 /// Note that you can have a pair of candidates such that Cand1's enable_if 9337 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9338 /// worse than Cand1's. 9339 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9340 const FunctionDecl *Cand2) { 9341 // Common case: One (or both) decls don't have enable_if attrs. 9342 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9343 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9344 if (!Cand1Attr || !Cand2Attr) { 9345 if (Cand1Attr == Cand2Attr) 9346 return Comparison::Equal; 9347 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9348 } 9349 9350 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9351 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9352 9353 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9354 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9355 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9356 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9357 9358 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9359 // has fewer enable_if attributes than Cand2, and vice versa. 9360 if (!Cand1A) 9361 return Comparison::Worse; 9362 if (!Cand2A) 9363 return Comparison::Better; 9364 9365 Cand1ID.clear(); 9366 Cand2ID.clear(); 9367 9368 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9369 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9370 if (Cand1ID != Cand2ID) 9371 return Comparison::Worse; 9372 } 9373 9374 return Comparison::Equal; 9375 } 9376 9377 static Comparison 9378 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9379 const OverloadCandidate &Cand2) { 9380 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9381 !Cand2.Function->isMultiVersion()) 9382 return Comparison::Equal; 9383 9384 // If both are invalid, they are equal. If one of them is invalid, the other 9385 // is better. 9386 if (Cand1.Function->isInvalidDecl()) { 9387 if (Cand2.Function->isInvalidDecl()) 9388 return Comparison::Equal; 9389 return Comparison::Worse; 9390 } 9391 if (Cand2.Function->isInvalidDecl()) 9392 return Comparison::Better; 9393 9394 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9395 // cpu_dispatch, else arbitrarily based on the identifiers. 9396 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9397 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9398 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9399 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9400 9401 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9402 return Comparison::Equal; 9403 9404 if (Cand1CPUDisp && !Cand2CPUDisp) 9405 return Comparison::Better; 9406 if (Cand2CPUDisp && !Cand1CPUDisp) 9407 return Comparison::Worse; 9408 9409 if (Cand1CPUSpec && Cand2CPUSpec) { 9410 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9411 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9412 ? Comparison::Better 9413 : Comparison::Worse; 9414 9415 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9416 FirstDiff = std::mismatch( 9417 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9418 Cand2CPUSpec->cpus_begin(), 9419 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9420 return LHS->getName() == RHS->getName(); 9421 }); 9422 9423 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9424 "Two different cpu-specific versions should not have the same " 9425 "identifier list, otherwise they'd be the same decl!"); 9426 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9427 ? Comparison::Better 9428 : Comparison::Worse; 9429 } 9430 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9431 } 9432 9433 /// Compute the type of the implicit object parameter for the given function, 9434 /// if any. Returns None if there is no implicit object parameter, and a null 9435 /// QualType if there is a 'matches anything' implicit object parameter. 9436 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9437 const FunctionDecl *F) { 9438 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9439 return llvm::None; 9440 9441 auto *M = cast<CXXMethodDecl>(F); 9442 // Static member functions' object parameters match all types. 9443 if (M->isStatic()) 9444 return QualType(); 9445 9446 QualType T = M->getThisObjectType(); 9447 if (M->getRefQualifier() == RQ_RValue) 9448 return Context.getRValueReferenceType(T); 9449 return Context.getLValueReferenceType(T); 9450 } 9451 9452 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9453 const FunctionDecl *F2, unsigned NumParams) { 9454 if (declaresSameEntity(F1, F2)) 9455 return true; 9456 9457 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9458 if (First) { 9459 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9460 return *T; 9461 } 9462 assert(I < F->getNumParams()); 9463 return F->getParamDecl(I++)->getType(); 9464 }; 9465 9466 unsigned I1 = 0, I2 = 0; 9467 for (unsigned I = 0; I != NumParams; ++I) { 9468 QualType T1 = NextParam(F1, I1, I == 0); 9469 QualType T2 = NextParam(F2, I2, I == 0); 9470 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9471 return false; 9472 } 9473 return true; 9474 } 9475 9476 /// isBetterOverloadCandidate - Determines whether the first overload 9477 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9478 bool clang::isBetterOverloadCandidate( 9479 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9480 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9481 // Define viable functions to be better candidates than non-viable 9482 // functions. 9483 if (!Cand2.Viable) 9484 return Cand1.Viable; 9485 else if (!Cand1.Viable) 9486 return false; 9487 9488 // [CUDA] A function with 'never' preference is marked not viable, therefore 9489 // is never shown up here. The worst preference shown up here is 'wrong side', 9490 // e.g. a host function called by a device host function in device 9491 // compilation. This is valid AST as long as the host device function is not 9492 // emitted, e.g. it is an inline function which is called only by a host 9493 // function. A deferred diagnostic will be triggered if it is emitted. 9494 // However a wrong-sided function is still a viable candidate here. 9495 // 9496 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9497 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9498 // can be emitted, Cand1 is not better than Cand2. This rule should have 9499 // precedence over other rules. 9500 // 9501 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9502 // other rules should be used to determine which is better. This is because 9503 // host/device based overloading resolution is mostly for determining 9504 // viability of a function. If two functions are both viable, other factors 9505 // should take precedence in preference, e.g. the standard-defined preferences 9506 // like argument conversion ranks or enable_if partial-ordering. The 9507 // preference for pass-object-size parameters is probably most similar to a 9508 // type-based-overloading decision and so should take priority. 9509 // 9510 // If other rules cannot determine which is better, CUDA preference will be 9511 // used again to determine which is better. 9512 // 9513 // TODO: Currently IdentifyCUDAPreference does not return correct values 9514 // for functions called in global variable initializers due to missing 9515 // correct context about device/host. Therefore we can only enforce this 9516 // rule when there is a caller. We should enforce this rule for functions 9517 // in global variable initializers once proper context is added. 9518 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9519 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9520 bool IsCallerImplicitHD = Sema::IsCUDAImplicitHostDeviceFunction(Caller); 9521 bool IsCand1ImplicitHD = 9522 Sema::IsCUDAImplicitHostDeviceFunction(Cand1.Function); 9523 bool IsCand2ImplicitHD = 9524 Sema::IsCUDAImplicitHostDeviceFunction(Cand2.Function); 9525 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9526 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9527 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9528 // The implicit HD function may be a function in a system header which 9529 // is forced by pragma. In device compilation, if we prefer HD candidates 9530 // over wrong-sided candidates, overloading resolution may change, which 9531 // may result in non-deferrable diagnostics. As a workaround, we let 9532 // implicit HD candidates take equal preference as wrong-sided candidates. 9533 // This will preserve the overloading resolution. 9534 auto EmitThreshold = 9535 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9536 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9537 ? Sema::CFP_HostDevice 9538 : Sema::CFP_WrongSide; 9539 auto Cand1Emittable = P1 > EmitThreshold; 9540 auto Cand2Emittable = P2 > EmitThreshold; 9541 if (Cand1Emittable && !Cand2Emittable) 9542 return true; 9543 if (!Cand1Emittable && Cand2Emittable) 9544 return false; 9545 } 9546 } 9547 9548 // C++ [over.match.best]p1: 9549 // 9550 // -- if F is a static member function, ICS1(F) is defined such 9551 // that ICS1(F) is neither better nor worse than ICS1(G) for 9552 // any function G, and, symmetrically, ICS1(G) is neither 9553 // better nor worse than ICS1(F). 9554 unsigned StartArg = 0; 9555 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9556 StartArg = 1; 9557 9558 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9559 // We don't allow incompatible pointer conversions in C++. 9560 if (!S.getLangOpts().CPlusPlus) 9561 return ICS.isStandard() && 9562 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9563 9564 // The only ill-formed conversion we allow in C++ is the string literal to 9565 // char* conversion, which is only considered ill-formed after C++11. 9566 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9567 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9568 }; 9569 9570 // Define functions that don't require ill-formed conversions for a given 9571 // argument to be better candidates than functions that do. 9572 unsigned NumArgs = Cand1.Conversions.size(); 9573 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9574 bool HasBetterConversion = false; 9575 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9576 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9577 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9578 if (Cand1Bad != Cand2Bad) { 9579 if (Cand1Bad) 9580 return false; 9581 HasBetterConversion = true; 9582 } 9583 } 9584 9585 if (HasBetterConversion) 9586 return true; 9587 9588 // C++ [over.match.best]p1: 9589 // A viable function F1 is defined to be a better function than another 9590 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9591 // conversion sequence than ICSi(F2), and then... 9592 bool HasWorseConversion = false; 9593 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9594 switch (CompareImplicitConversionSequences(S, Loc, 9595 Cand1.Conversions[ArgIdx], 9596 Cand2.Conversions[ArgIdx])) { 9597 case ImplicitConversionSequence::Better: 9598 // Cand1 has a better conversion sequence. 9599 HasBetterConversion = true; 9600 break; 9601 9602 case ImplicitConversionSequence::Worse: 9603 if (Cand1.Function && Cand2.Function && 9604 Cand1.isReversed() != Cand2.isReversed() && 9605 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9606 NumArgs)) { 9607 // Work around large-scale breakage caused by considering reversed 9608 // forms of operator== in C++20: 9609 // 9610 // When comparing a function against a reversed function with the same 9611 // parameter types, if we have a better conversion for one argument and 9612 // a worse conversion for the other, the implicit conversion sequences 9613 // are treated as being equally good. 9614 // 9615 // This prevents a comparison function from being considered ambiguous 9616 // with a reversed form that is written in the same way. 9617 // 9618 // We diagnose this as an extension from CreateOverloadedBinOp. 9619 HasWorseConversion = true; 9620 break; 9621 } 9622 9623 // Cand1 can't be better than Cand2. 9624 return false; 9625 9626 case ImplicitConversionSequence::Indistinguishable: 9627 // Do nothing. 9628 break; 9629 } 9630 } 9631 9632 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9633 // ICSj(F2), or, if not that, 9634 if (HasBetterConversion && !HasWorseConversion) 9635 return true; 9636 9637 // -- the context is an initialization by user-defined conversion 9638 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9639 // from the return type of F1 to the destination type (i.e., 9640 // the type of the entity being initialized) is a better 9641 // conversion sequence than the standard conversion sequence 9642 // from the return type of F2 to the destination type. 9643 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9644 Cand1.Function && Cand2.Function && 9645 isa<CXXConversionDecl>(Cand1.Function) && 9646 isa<CXXConversionDecl>(Cand2.Function)) { 9647 // First check whether we prefer one of the conversion functions over the 9648 // other. This only distinguishes the results in non-standard, extension 9649 // cases such as the conversion from a lambda closure type to a function 9650 // pointer or block. 9651 ImplicitConversionSequence::CompareKind Result = 9652 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9653 if (Result == ImplicitConversionSequence::Indistinguishable) 9654 Result = CompareStandardConversionSequences(S, Loc, 9655 Cand1.FinalConversion, 9656 Cand2.FinalConversion); 9657 9658 if (Result != ImplicitConversionSequence::Indistinguishable) 9659 return Result == ImplicitConversionSequence::Better; 9660 9661 // FIXME: Compare kind of reference binding if conversion functions 9662 // convert to a reference type used in direct reference binding, per 9663 // C++14 [over.match.best]p1 section 2 bullet 3. 9664 } 9665 9666 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9667 // as combined with the resolution to CWG issue 243. 9668 // 9669 // When the context is initialization by constructor ([over.match.ctor] or 9670 // either phase of [over.match.list]), a constructor is preferred over 9671 // a conversion function. 9672 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9673 Cand1.Function && Cand2.Function && 9674 isa<CXXConstructorDecl>(Cand1.Function) != 9675 isa<CXXConstructorDecl>(Cand2.Function)) 9676 return isa<CXXConstructorDecl>(Cand1.Function); 9677 9678 // -- F1 is a non-template function and F2 is a function template 9679 // specialization, or, if not that, 9680 bool Cand1IsSpecialization = Cand1.Function && 9681 Cand1.Function->getPrimaryTemplate(); 9682 bool Cand2IsSpecialization = Cand2.Function && 9683 Cand2.Function->getPrimaryTemplate(); 9684 if (Cand1IsSpecialization != Cand2IsSpecialization) 9685 return Cand2IsSpecialization; 9686 9687 // -- F1 and F2 are function template specializations, and the function 9688 // template for F1 is more specialized than the template for F2 9689 // according to the partial ordering rules described in 14.5.5.2, or, 9690 // if not that, 9691 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9692 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9693 Cand1.Function->getPrimaryTemplate(), 9694 Cand2.Function->getPrimaryTemplate(), Loc, 9695 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9696 : TPOC_Call, 9697 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9698 Cand1.isReversed() ^ Cand2.isReversed())) 9699 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9700 } 9701 9702 // -— F1 and F2 are non-template functions with the same 9703 // parameter-type-lists, and F1 is more constrained than F2 [...], 9704 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9705 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9706 Cand2.Function->hasPrototype()) { 9707 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9708 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9709 if (PT1->getNumParams() == PT2->getNumParams() && 9710 PT1->isVariadic() == PT2->isVariadic() && 9711 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9712 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9713 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9714 if (RC1 && RC2) { 9715 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9716 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9717 {RC2}, AtLeastAsConstrained1) || 9718 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9719 {RC1}, AtLeastAsConstrained2)) 9720 return false; 9721 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9722 return AtLeastAsConstrained1; 9723 } else if (RC1 || RC2) { 9724 return RC1 != nullptr; 9725 } 9726 } 9727 } 9728 9729 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9730 // class B of D, and for all arguments the corresponding parameters of 9731 // F1 and F2 have the same type. 9732 // FIXME: Implement the "all parameters have the same type" check. 9733 bool Cand1IsInherited = 9734 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9735 bool Cand2IsInherited = 9736 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9737 if (Cand1IsInherited != Cand2IsInherited) 9738 return Cand2IsInherited; 9739 else if (Cand1IsInherited) { 9740 assert(Cand2IsInherited); 9741 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9742 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9743 if (Cand1Class->isDerivedFrom(Cand2Class)) 9744 return true; 9745 if (Cand2Class->isDerivedFrom(Cand1Class)) 9746 return false; 9747 // Inherited from sibling base classes: still ambiguous. 9748 } 9749 9750 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9751 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9752 // with reversed order of parameters and F1 is not 9753 // 9754 // We rank reversed + different operator as worse than just reversed, but 9755 // that comparison can never happen, because we only consider reversing for 9756 // the maximally-rewritten operator (== or <=>). 9757 if (Cand1.RewriteKind != Cand2.RewriteKind) 9758 return Cand1.RewriteKind < Cand2.RewriteKind; 9759 9760 // Check C++17 tie-breakers for deduction guides. 9761 { 9762 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9763 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9764 if (Guide1 && Guide2) { 9765 // -- F1 is generated from a deduction-guide and F2 is not 9766 if (Guide1->isImplicit() != Guide2->isImplicit()) 9767 return Guide2->isImplicit(); 9768 9769 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9770 if (Guide1->isCopyDeductionCandidate()) 9771 return true; 9772 } 9773 } 9774 9775 // Check for enable_if value-based overload resolution. 9776 if (Cand1.Function && Cand2.Function) { 9777 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9778 if (Cmp != Comparison::Equal) 9779 return Cmp == Comparison::Better; 9780 } 9781 9782 bool HasPS1 = Cand1.Function != nullptr && 9783 functionHasPassObjectSizeParams(Cand1.Function); 9784 bool HasPS2 = Cand2.Function != nullptr && 9785 functionHasPassObjectSizeParams(Cand2.Function); 9786 if (HasPS1 != HasPS2 && HasPS1) 9787 return true; 9788 9789 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9790 if (MV == Comparison::Better) 9791 return true; 9792 if (MV == Comparison::Worse) 9793 return false; 9794 9795 // If other rules cannot determine which is better, CUDA preference is used 9796 // to determine which is better. 9797 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9798 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9799 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9800 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9801 } 9802 9803 return false; 9804 } 9805 9806 /// Determine whether two declarations are "equivalent" for the purposes of 9807 /// name lookup and overload resolution. This applies when the same internal/no 9808 /// linkage entity is defined by two modules (probably by textually including 9809 /// the same header). In such a case, we don't consider the declarations to 9810 /// declare the same entity, but we also don't want lookups with both 9811 /// declarations visible to be ambiguous in some cases (this happens when using 9812 /// a modularized libstdc++). 9813 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9814 const NamedDecl *B) { 9815 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9816 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9817 if (!VA || !VB) 9818 return false; 9819 9820 // The declarations must be declaring the same name as an internal linkage 9821 // entity in different modules. 9822 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9823 VB->getDeclContext()->getRedeclContext()) || 9824 getOwningModule(VA) == getOwningModule(VB) || 9825 VA->isExternallyVisible() || VB->isExternallyVisible()) 9826 return false; 9827 9828 // Check that the declarations appear to be equivalent. 9829 // 9830 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9831 // For constants and functions, we should check the initializer or body is 9832 // the same. For non-constant variables, we shouldn't allow it at all. 9833 if (Context.hasSameType(VA->getType(), VB->getType())) 9834 return true; 9835 9836 // Enum constants within unnamed enumerations will have different types, but 9837 // may still be similar enough to be interchangeable for our purposes. 9838 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9839 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9840 // Only handle anonymous enums. If the enumerations were named and 9841 // equivalent, they would have been merged to the same type. 9842 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9843 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9844 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9845 !Context.hasSameType(EnumA->getIntegerType(), 9846 EnumB->getIntegerType())) 9847 return false; 9848 // Allow this only if the value is the same for both enumerators. 9849 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9850 } 9851 } 9852 9853 // Nothing else is sufficiently similar. 9854 return false; 9855 } 9856 9857 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9858 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9859 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9860 9861 Module *M = getOwningModule(D); 9862 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9863 << !M << (M ? M->getFullModuleName() : ""); 9864 9865 for (auto *E : Equiv) { 9866 Module *M = getOwningModule(E); 9867 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9868 << !M << (M ? M->getFullModuleName() : ""); 9869 } 9870 } 9871 9872 /// Computes the best viable function (C++ 13.3.3) 9873 /// within an overload candidate set. 9874 /// 9875 /// \param Loc The location of the function name (or operator symbol) for 9876 /// which overload resolution occurs. 9877 /// 9878 /// \param Best If overload resolution was successful or found a deleted 9879 /// function, \p Best points to the candidate function found. 9880 /// 9881 /// \returns The result of overload resolution. 9882 OverloadingResult 9883 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9884 iterator &Best) { 9885 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9886 std::transform(begin(), end(), std::back_inserter(Candidates), 9887 [](OverloadCandidate &Cand) { return &Cand; }); 9888 9889 // Find the best viable function. 9890 Best = end(); 9891 for (auto *Cand : Candidates) { 9892 Cand->Best = false; 9893 if (Cand->Viable) 9894 if (Best == end() || 9895 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9896 Best = Cand; 9897 } 9898 9899 // If we didn't find any viable functions, abort. 9900 if (Best == end()) 9901 return OR_No_Viable_Function; 9902 9903 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9904 9905 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9906 PendingBest.push_back(&*Best); 9907 Best->Best = true; 9908 9909 // Make sure that this function is better than every other viable 9910 // function. If not, we have an ambiguity. 9911 while (!PendingBest.empty()) { 9912 auto *Curr = PendingBest.pop_back_val(); 9913 for (auto *Cand : Candidates) { 9914 if (Cand->Viable && !Cand->Best && 9915 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9916 PendingBest.push_back(Cand); 9917 Cand->Best = true; 9918 9919 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9920 Curr->Function)) 9921 EquivalentCands.push_back(Cand->Function); 9922 else 9923 Best = end(); 9924 } 9925 } 9926 } 9927 9928 // If we found more than one best candidate, this is ambiguous. 9929 if (Best == end()) 9930 return OR_Ambiguous; 9931 9932 // Best is the best viable function. 9933 if (Best->Function && Best->Function->isDeleted()) 9934 return OR_Deleted; 9935 9936 if (!EquivalentCands.empty()) 9937 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9938 EquivalentCands); 9939 9940 return OR_Success; 9941 } 9942 9943 namespace { 9944 9945 enum OverloadCandidateKind { 9946 oc_function, 9947 oc_method, 9948 oc_reversed_binary_operator, 9949 oc_constructor, 9950 oc_implicit_default_constructor, 9951 oc_implicit_copy_constructor, 9952 oc_implicit_move_constructor, 9953 oc_implicit_copy_assignment, 9954 oc_implicit_move_assignment, 9955 oc_implicit_equality_comparison, 9956 oc_inherited_constructor 9957 }; 9958 9959 enum OverloadCandidateSelect { 9960 ocs_non_template, 9961 ocs_template, 9962 ocs_described_template, 9963 }; 9964 9965 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9966 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9967 OverloadCandidateRewriteKind CRK, 9968 std::string &Description) { 9969 9970 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9971 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9972 isTemplate = true; 9973 Description = S.getTemplateArgumentBindingsText( 9974 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9975 } 9976 9977 OverloadCandidateSelect Select = [&]() { 9978 if (!Description.empty()) 9979 return ocs_described_template; 9980 return isTemplate ? ocs_template : ocs_non_template; 9981 }(); 9982 9983 OverloadCandidateKind Kind = [&]() { 9984 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9985 return oc_implicit_equality_comparison; 9986 9987 if (CRK & CRK_Reversed) 9988 return oc_reversed_binary_operator; 9989 9990 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9991 if (!Ctor->isImplicit()) { 9992 if (isa<ConstructorUsingShadowDecl>(Found)) 9993 return oc_inherited_constructor; 9994 else 9995 return oc_constructor; 9996 } 9997 9998 if (Ctor->isDefaultConstructor()) 9999 return oc_implicit_default_constructor; 10000 10001 if (Ctor->isMoveConstructor()) 10002 return oc_implicit_move_constructor; 10003 10004 assert(Ctor->isCopyConstructor() && 10005 "unexpected sort of implicit constructor"); 10006 return oc_implicit_copy_constructor; 10007 } 10008 10009 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10010 // This actually gets spelled 'candidate function' for now, but 10011 // it doesn't hurt to split it out. 10012 if (!Meth->isImplicit()) 10013 return oc_method; 10014 10015 if (Meth->isMoveAssignmentOperator()) 10016 return oc_implicit_move_assignment; 10017 10018 if (Meth->isCopyAssignmentOperator()) 10019 return oc_implicit_copy_assignment; 10020 10021 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10022 return oc_method; 10023 } 10024 10025 return oc_function; 10026 }(); 10027 10028 return std::make_pair(Kind, Select); 10029 } 10030 10031 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10032 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10033 // set. 10034 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10035 S.Diag(FoundDecl->getLocation(), 10036 diag::note_ovl_candidate_inherited_constructor) 10037 << Shadow->getNominatedBaseClass(); 10038 } 10039 10040 } // end anonymous namespace 10041 10042 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10043 const FunctionDecl *FD) { 10044 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10045 bool AlwaysTrue; 10046 if (EnableIf->getCond()->isValueDependent() || 10047 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10048 return false; 10049 if (!AlwaysTrue) 10050 return false; 10051 } 10052 return true; 10053 } 10054 10055 /// Returns true if we can take the address of the function. 10056 /// 10057 /// \param Complain - If true, we'll emit a diagnostic 10058 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10059 /// we in overload resolution? 10060 /// \param Loc - The location of the statement we're complaining about. Ignored 10061 /// if we're not complaining, or if we're in overload resolution. 10062 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10063 bool Complain, 10064 bool InOverloadResolution, 10065 SourceLocation Loc) { 10066 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10067 if (Complain) { 10068 if (InOverloadResolution) 10069 S.Diag(FD->getBeginLoc(), 10070 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10071 else 10072 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10073 } 10074 return false; 10075 } 10076 10077 if (FD->getTrailingRequiresClause()) { 10078 ConstraintSatisfaction Satisfaction; 10079 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10080 return false; 10081 if (!Satisfaction.IsSatisfied) { 10082 if (Complain) { 10083 if (InOverloadResolution) 10084 S.Diag(FD->getBeginLoc(), 10085 diag::note_ovl_candidate_unsatisfied_constraints); 10086 else 10087 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10088 << FD; 10089 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10090 } 10091 return false; 10092 } 10093 } 10094 10095 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10096 return P->hasAttr<PassObjectSizeAttr>(); 10097 }); 10098 if (I == FD->param_end()) 10099 return true; 10100 10101 if (Complain) { 10102 // Add one to ParamNo because it's user-facing 10103 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10104 if (InOverloadResolution) 10105 S.Diag(FD->getLocation(), 10106 diag::note_ovl_candidate_has_pass_object_size_params) 10107 << ParamNo; 10108 else 10109 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10110 << FD << ParamNo; 10111 } 10112 return false; 10113 } 10114 10115 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10116 const FunctionDecl *FD) { 10117 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10118 /*InOverloadResolution=*/true, 10119 /*Loc=*/SourceLocation()); 10120 } 10121 10122 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10123 bool Complain, 10124 SourceLocation Loc) { 10125 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10126 /*InOverloadResolution=*/false, 10127 Loc); 10128 } 10129 10130 // Notes the location of an overload candidate. 10131 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10132 OverloadCandidateRewriteKind RewriteKind, 10133 QualType DestType, bool TakingAddress) { 10134 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10135 return; 10136 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10137 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10138 return; 10139 10140 std::string FnDesc; 10141 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10142 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10143 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10144 << (unsigned)KSPair.first << (unsigned)KSPair.second 10145 << Fn << FnDesc; 10146 10147 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10148 Diag(Fn->getLocation(), PD); 10149 MaybeEmitInheritedConstructorNote(*this, Found); 10150 } 10151 10152 static void 10153 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10154 // Perhaps the ambiguity was caused by two atomic constraints that are 10155 // 'identical' but not equivalent: 10156 // 10157 // void foo() requires (sizeof(T) > 4) { } // #1 10158 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10159 // 10160 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10161 // #2 to subsume #1, but these constraint are not considered equivalent 10162 // according to the subsumption rules because they are not the same 10163 // source-level construct. This behavior is quite confusing and we should try 10164 // to help the user figure out what happened. 10165 10166 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10167 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10168 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10169 if (!I->Function) 10170 continue; 10171 SmallVector<const Expr *, 3> AC; 10172 if (auto *Template = I->Function->getPrimaryTemplate()) 10173 Template->getAssociatedConstraints(AC); 10174 else 10175 I->Function->getAssociatedConstraints(AC); 10176 if (AC.empty()) 10177 continue; 10178 if (FirstCand == nullptr) { 10179 FirstCand = I->Function; 10180 FirstAC = AC; 10181 } else if (SecondCand == nullptr) { 10182 SecondCand = I->Function; 10183 SecondAC = AC; 10184 } else { 10185 // We have more than one pair of constrained functions - this check is 10186 // expensive and we'd rather not try to diagnose it. 10187 return; 10188 } 10189 } 10190 if (!SecondCand) 10191 return; 10192 // The diagnostic can only happen if there are associated constraints on 10193 // both sides (there needs to be some identical atomic constraint). 10194 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10195 SecondCand, SecondAC)) 10196 // Just show the user one diagnostic, they'll probably figure it out 10197 // from here. 10198 return; 10199 } 10200 10201 // Notes the location of all overload candidates designated through 10202 // OverloadedExpr 10203 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10204 bool TakingAddress) { 10205 assert(OverloadedExpr->getType() == Context.OverloadTy); 10206 10207 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10208 OverloadExpr *OvlExpr = Ovl.Expression; 10209 10210 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10211 IEnd = OvlExpr->decls_end(); 10212 I != IEnd; ++I) { 10213 if (FunctionTemplateDecl *FunTmpl = 10214 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10215 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10216 TakingAddress); 10217 } else if (FunctionDecl *Fun 10218 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10219 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10220 } 10221 } 10222 } 10223 10224 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10225 /// "lead" diagnostic; it will be given two arguments, the source and 10226 /// target types of the conversion. 10227 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10228 Sema &S, 10229 SourceLocation CaretLoc, 10230 const PartialDiagnostic &PDiag) const { 10231 S.Diag(CaretLoc, PDiag) 10232 << Ambiguous.getFromType() << Ambiguous.getToType(); 10233 // FIXME: The note limiting machinery is borrowed from 10234 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10235 // refactoring here. 10236 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10237 unsigned CandsShown = 0; 10238 AmbiguousConversionSequence::const_iterator I, E; 10239 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10240 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10241 break; 10242 ++CandsShown; 10243 S.NoteOverloadCandidate(I->first, I->second); 10244 } 10245 if (I != E) 10246 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10247 } 10248 10249 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10250 unsigned I, bool TakingCandidateAddress) { 10251 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10252 assert(Conv.isBad()); 10253 assert(Cand->Function && "for now, candidate must be a function"); 10254 FunctionDecl *Fn = Cand->Function; 10255 10256 // There's a conversion slot for the object argument if this is a 10257 // non-constructor method. Note that 'I' corresponds the 10258 // conversion-slot index. 10259 bool isObjectArgument = false; 10260 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10261 if (I == 0) 10262 isObjectArgument = true; 10263 else 10264 I--; 10265 } 10266 10267 std::string FnDesc; 10268 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10269 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10270 FnDesc); 10271 10272 Expr *FromExpr = Conv.Bad.FromExpr; 10273 QualType FromTy = Conv.Bad.getFromType(); 10274 QualType ToTy = Conv.Bad.getToType(); 10275 10276 if (FromTy == S.Context.OverloadTy) { 10277 assert(FromExpr && "overload set argument came from implicit argument?"); 10278 Expr *E = FromExpr->IgnoreParens(); 10279 if (isa<UnaryOperator>(E)) 10280 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10281 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10282 10283 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10284 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10285 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10286 << Name << I + 1; 10287 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10288 return; 10289 } 10290 10291 // Do some hand-waving analysis to see if the non-viability is due 10292 // to a qualifier mismatch. 10293 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10294 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10295 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10296 CToTy = RT->getPointeeType(); 10297 else { 10298 // TODO: detect and diagnose the full richness of const mismatches. 10299 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10300 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10301 CFromTy = FromPT->getPointeeType(); 10302 CToTy = ToPT->getPointeeType(); 10303 } 10304 } 10305 10306 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10307 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10308 Qualifiers FromQs = CFromTy.getQualifiers(); 10309 Qualifiers ToQs = CToTy.getQualifiers(); 10310 10311 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10312 if (isObjectArgument) 10313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10314 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10315 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10316 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10317 else 10318 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10319 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10320 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10321 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10322 << ToTy->isReferenceType() << I + 1; 10323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10324 return; 10325 } 10326 10327 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10328 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10329 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10330 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10331 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10332 << (unsigned)isObjectArgument << I + 1; 10333 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10334 return; 10335 } 10336 10337 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10339 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10340 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10341 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10342 << (unsigned)isObjectArgument << I + 1; 10343 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10344 return; 10345 } 10346 10347 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10349 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10351 << FromQs.hasUnaligned() << I + 1; 10352 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10353 return; 10354 } 10355 10356 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10357 assert(CVR && "unexpected qualifiers mismatch"); 10358 10359 if (isObjectArgument) { 10360 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10361 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10362 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10363 << (CVR - 1); 10364 } else { 10365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10366 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10367 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10368 << (CVR - 1) << I + 1; 10369 } 10370 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10371 return; 10372 } 10373 10374 // Special diagnostic for failure to convert an initializer list, since 10375 // telling the user that it has type void is not useful. 10376 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10378 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10379 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10380 << ToTy << (unsigned)isObjectArgument << I + 1; 10381 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10382 return; 10383 } 10384 10385 // Diagnose references or pointers to incomplete types differently, 10386 // since it's far from impossible that the incompleteness triggered 10387 // the failure. 10388 QualType TempFromTy = FromTy.getNonReferenceType(); 10389 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10390 TempFromTy = PTy->getPointeeType(); 10391 if (TempFromTy->isIncompleteType()) { 10392 // Emit the generic diagnostic and, optionally, add the hints to it. 10393 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10394 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10395 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10396 << ToTy << (unsigned)isObjectArgument << I + 1 10397 << (unsigned)(Cand->Fix.Kind); 10398 10399 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10400 return; 10401 } 10402 10403 // Diagnose base -> derived pointer conversions. 10404 unsigned BaseToDerivedConversion = 0; 10405 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10406 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10407 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10408 FromPtrTy->getPointeeType()) && 10409 !FromPtrTy->getPointeeType()->isIncompleteType() && 10410 !ToPtrTy->getPointeeType()->isIncompleteType() && 10411 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10412 FromPtrTy->getPointeeType())) 10413 BaseToDerivedConversion = 1; 10414 } 10415 } else if (const ObjCObjectPointerType *FromPtrTy 10416 = FromTy->getAs<ObjCObjectPointerType>()) { 10417 if (const ObjCObjectPointerType *ToPtrTy 10418 = ToTy->getAs<ObjCObjectPointerType>()) 10419 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10420 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10421 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10422 FromPtrTy->getPointeeType()) && 10423 FromIface->isSuperClassOf(ToIface)) 10424 BaseToDerivedConversion = 2; 10425 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10426 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10427 !FromTy->isIncompleteType() && 10428 !ToRefTy->getPointeeType()->isIncompleteType() && 10429 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10430 BaseToDerivedConversion = 3; 10431 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10432 ToTy.getNonReferenceType().getCanonicalType() == 10433 FromTy.getNonReferenceType().getCanonicalType()) { 10434 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10435 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10436 << (unsigned)isObjectArgument << I + 1 10437 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10438 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10439 return; 10440 } 10441 } 10442 10443 if (BaseToDerivedConversion) { 10444 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10445 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10446 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10447 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10448 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10449 return; 10450 } 10451 10452 if (isa<ObjCObjectPointerType>(CFromTy) && 10453 isa<PointerType>(CToTy)) { 10454 Qualifiers FromQs = CFromTy.getQualifiers(); 10455 Qualifiers ToQs = CToTy.getQualifiers(); 10456 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10457 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10458 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10459 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10460 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10461 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10462 return; 10463 } 10464 } 10465 10466 if (TakingCandidateAddress && 10467 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10468 return; 10469 10470 // Emit the generic diagnostic and, optionally, add the hints to it. 10471 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10472 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10473 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10474 << ToTy << (unsigned)isObjectArgument << I + 1 10475 << (unsigned)(Cand->Fix.Kind); 10476 10477 // If we can fix the conversion, suggest the FixIts. 10478 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10479 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10480 FDiag << *HI; 10481 S.Diag(Fn->getLocation(), FDiag); 10482 10483 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10484 } 10485 10486 /// Additional arity mismatch diagnosis specific to a function overload 10487 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10488 /// over a candidate in any candidate set. 10489 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10490 unsigned NumArgs) { 10491 FunctionDecl *Fn = Cand->Function; 10492 unsigned MinParams = Fn->getMinRequiredArguments(); 10493 10494 // With invalid overloaded operators, it's possible that we think we 10495 // have an arity mismatch when in fact it looks like we have the 10496 // right number of arguments, because only overloaded operators have 10497 // the weird behavior of overloading member and non-member functions. 10498 // Just don't report anything. 10499 if (Fn->isInvalidDecl() && 10500 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10501 return true; 10502 10503 if (NumArgs < MinParams) { 10504 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10505 (Cand->FailureKind == ovl_fail_bad_deduction && 10506 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10507 } else { 10508 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10509 (Cand->FailureKind == ovl_fail_bad_deduction && 10510 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10511 } 10512 10513 return false; 10514 } 10515 10516 /// General arity mismatch diagnosis over a candidate in a candidate set. 10517 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10518 unsigned NumFormalArgs) { 10519 assert(isa<FunctionDecl>(D) && 10520 "The templated declaration should at least be a function" 10521 " when diagnosing bad template argument deduction due to too many" 10522 " or too few arguments"); 10523 10524 FunctionDecl *Fn = cast<FunctionDecl>(D); 10525 10526 // TODO: treat calls to a missing default constructor as a special case 10527 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10528 unsigned MinParams = Fn->getMinRequiredArguments(); 10529 10530 // at least / at most / exactly 10531 unsigned mode, modeCount; 10532 if (NumFormalArgs < MinParams) { 10533 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10534 FnTy->isTemplateVariadic()) 10535 mode = 0; // "at least" 10536 else 10537 mode = 2; // "exactly" 10538 modeCount = MinParams; 10539 } else { 10540 if (MinParams != FnTy->getNumParams()) 10541 mode = 1; // "at most" 10542 else 10543 mode = 2; // "exactly" 10544 modeCount = FnTy->getNumParams(); 10545 } 10546 10547 std::string Description; 10548 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10549 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10550 10551 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10552 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10553 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10554 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10555 else 10556 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10557 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10558 << Description << mode << modeCount << NumFormalArgs; 10559 10560 MaybeEmitInheritedConstructorNote(S, Found); 10561 } 10562 10563 /// Arity mismatch diagnosis specific to a function overload candidate. 10564 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10565 unsigned NumFormalArgs) { 10566 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10567 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10568 } 10569 10570 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10571 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10572 return TD; 10573 llvm_unreachable("Unsupported: Getting the described template declaration" 10574 " for bad deduction diagnosis"); 10575 } 10576 10577 /// Diagnose a failed template-argument deduction. 10578 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10579 DeductionFailureInfo &DeductionFailure, 10580 unsigned NumArgs, 10581 bool TakingCandidateAddress) { 10582 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10583 NamedDecl *ParamD; 10584 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10585 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10586 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10587 switch (DeductionFailure.Result) { 10588 case Sema::TDK_Success: 10589 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10590 10591 case Sema::TDK_Incomplete: { 10592 assert(ParamD && "no parameter found for incomplete deduction result"); 10593 S.Diag(Templated->getLocation(), 10594 diag::note_ovl_candidate_incomplete_deduction) 10595 << ParamD->getDeclName(); 10596 MaybeEmitInheritedConstructorNote(S, Found); 10597 return; 10598 } 10599 10600 case Sema::TDK_IncompletePack: { 10601 assert(ParamD && "no parameter found for incomplete deduction result"); 10602 S.Diag(Templated->getLocation(), 10603 diag::note_ovl_candidate_incomplete_deduction_pack) 10604 << ParamD->getDeclName() 10605 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10606 << *DeductionFailure.getFirstArg(); 10607 MaybeEmitInheritedConstructorNote(S, Found); 10608 return; 10609 } 10610 10611 case Sema::TDK_Underqualified: { 10612 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10613 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10614 10615 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10616 10617 // Param will have been canonicalized, but it should just be a 10618 // qualified version of ParamD, so move the qualifiers to that. 10619 QualifierCollector Qs; 10620 Qs.strip(Param); 10621 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10622 assert(S.Context.hasSameType(Param, NonCanonParam)); 10623 10624 // Arg has also been canonicalized, but there's nothing we can do 10625 // about that. It also doesn't matter as much, because it won't 10626 // have any template parameters in it (because deduction isn't 10627 // done on dependent types). 10628 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10629 10630 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10631 << ParamD->getDeclName() << Arg << NonCanonParam; 10632 MaybeEmitInheritedConstructorNote(S, Found); 10633 return; 10634 } 10635 10636 case Sema::TDK_Inconsistent: { 10637 assert(ParamD && "no parameter found for inconsistent deduction result"); 10638 int which = 0; 10639 if (isa<TemplateTypeParmDecl>(ParamD)) 10640 which = 0; 10641 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10642 // Deduction might have failed because we deduced arguments of two 10643 // different types for a non-type template parameter. 10644 // FIXME: Use a different TDK value for this. 10645 QualType T1 = 10646 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10647 QualType T2 = 10648 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10649 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10650 S.Diag(Templated->getLocation(), 10651 diag::note_ovl_candidate_inconsistent_deduction_types) 10652 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10653 << *DeductionFailure.getSecondArg() << T2; 10654 MaybeEmitInheritedConstructorNote(S, Found); 10655 return; 10656 } 10657 10658 which = 1; 10659 } else { 10660 which = 2; 10661 } 10662 10663 // Tweak the diagnostic if the problem is that we deduced packs of 10664 // different arities. We'll print the actual packs anyway in case that 10665 // includes additional useful information. 10666 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10667 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10668 DeductionFailure.getFirstArg()->pack_size() != 10669 DeductionFailure.getSecondArg()->pack_size()) { 10670 which = 3; 10671 } 10672 10673 S.Diag(Templated->getLocation(), 10674 diag::note_ovl_candidate_inconsistent_deduction) 10675 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10676 << *DeductionFailure.getSecondArg(); 10677 MaybeEmitInheritedConstructorNote(S, Found); 10678 return; 10679 } 10680 10681 case Sema::TDK_InvalidExplicitArguments: 10682 assert(ParamD && "no parameter found for invalid explicit arguments"); 10683 if (ParamD->getDeclName()) 10684 S.Diag(Templated->getLocation(), 10685 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10686 << ParamD->getDeclName(); 10687 else { 10688 int index = 0; 10689 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10690 index = TTP->getIndex(); 10691 else if (NonTypeTemplateParmDecl *NTTP 10692 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10693 index = NTTP->getIndex(); 10694 else 10695 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10696 S.Diag(Templated->getLocation(), 10697 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10698 << (index + 1); 10699 } 10700 MaybeEmitInheritedConstructorNote(S, Found); 10701 return; 10702 10703 case Sema::TDK_ConstraintsNotSatisfied: { 10704 // Format the template argument list into the argument string. 10705 SmallString<128> TemplateArgString; 10706 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10707 TemplateArgString = " "; 10708 TemplateArgString += S.getTemplateArgumentBindingsText( 10709 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10710 if (TemplateArgString.size() == 1) 10711 TemplateArgString.clear(); 10712 S.Diag(Templated->getLocation(), 10713 diag::note_ovl_candidate_unsatisfied_constraints) 10714 << TemplateArgString; 10715 10716 S.DiagnoseUnsatisfiedConstraint( 10717 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10718 return; 10719 } 10720 case Sema::TDK_TooManyArguments: 10721 case Sema::TDK_TooFewArguments: 10722 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10723 return; 10724 10725 case Sema::TDK_InstantiationDepth: 10726 S.Diag(Templated->getLocation(), 10727 diag::note_ovl_candidate_instantiation_depth); 10728 MaybeEmitInheritedConstructorNote(S, Found); 10729 return; 10730 10731 case Sema::TDK_SubstitutionFailure: { 10732 // Format the template argument list into the argument string. 10733 SmallString<128> TemplateArgString; 10734 if (TemplateArgumentList *Args = 10735 DeductionFailure.getTemplateArgumentList()) { 10736 TemplateArgString = " "; 10737 TemplateArgString += S.getTemplateArgumentBindingsText( 10738 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10739 if (TemplateArgString.size() == 1) 10740 TemplateArgString.clear(); 10741 } 10742 10743 // If this candidate was disabled by enable_if, say so. 10744 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10745 if (PDiag && PDiag->second.getDiagID() == 10746 diag::err_typename_nested_not_found_enable_if) { 10747 // FIXME: Use the source range of the condition, and the fully-qualified 10748 // name of the enable_if template. These are both present in PDiag. 10749 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10750 << "'enable_if'" << TemplateArgString; 10751 return; 10752 } 10753 10754 // We found a specific requirement that disabled the enable_if. 10755 if (PDiag && PDiag->second.getDiagID() == 10756 diag::err_typename_nested_not_found_requirement) { 10757 S.Diag(Templated->getLocation(), 10758 diag::note_ovl_candidate_disabled_by_requirement) 10759 << PDiag->second.getStringArg(0) << TemplateArgString; 10760 return; 10761 } 10762 10763 // Format the SFINAE diagnostic into the argument string. 10764 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10765 // formatted message in another diagnostic. 10766 SmallString<128> SFINAEArgString; 10767 SourceRange R; 10768 if (PDiag) { 10769 SFINAEArgString = ": "; 10770 R = SourceRange(PDiag->first, PDiag->first); 10771 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10772 } 10773 10774 S.Diag(Templated->getLocation(), 10775 diag::note_ovl_candidate_substitution_failure) 10776 << TemplateArgString << SFINAEArgString << R; 10777 MaybeEmitInheritedConstructorNote(S, Found); 10778 return; 10779 } 10780 10781 case Sema::TDK_DeducedMismatch: 10782 case Sema::TDK_DeducedMismatchNested: { 10783 // Format the template argument list into the argument string. 10784 SmallString<128> TemplateArgString; 10785 if (TemplateArgumentList *Args = 10786 DeductionFailure.getTemplateArgumentList()) { 10787 TemplateArgString = " "; 10788 TemplateArgString += S.getTemplateArgumentBindingsText( 10789 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10790 if (TemplateArgString.size() == 1) 10791 TemplateArgString.clear(); 10792 } 10793 10794 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10795 << (*DeductionFailure.getCallArgIndex() + 1) 10796 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10797 << TemplateArgString 10798 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10799 break; 10800 } 10801 10802 case Sema::TDK_NonDeducedMismatch: { 10803 // FIXME: Provide a source location to indicate what we couldn't match. 10804 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10805 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10806 if (FirstTA.getKind() == TemplateArgument::Template && 10807 SecondTA.getKind() == TemplateArgument::Template) { 10808 TemplateName FirstTN = FirstTA.getAsTemplate(); 10809 TemplateName SecondTN = SecondTA.getAsTemplate(); 10810 if (FirstTN.getKind() == TemplateName::Template && 10811 SecondTN.getKind() == TemplateName::Template) { 10812 if (FirstTN.getAsTemplateDecl()->getName() == 10813 SecondTN.getAsTemplateDecl()->getName()) { 10814 // FIXME: This fixes a bad diagnostic where both templates are named 10815 // the same. This particular case is a bit difficult since: 10816 // 1) It is passed as a string to the diagnostic printer. 10817 // 2) The diagnostic printer only attempts to find a better 10818 // name for types, not decls. 10819 // Ideally, this should folded into the diagnostic printer. 10820 S.Diag(Templated->getLocation(), 10821 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10822 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10823 return; 10824 } 10825 } 10826 } 10827 10828 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10829 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10830 return; 10831 10832 // FIXME: For generic lambda parameters, check if the function is a lambda 10833 // call operator, and if so, emit a prettier and more informative 10834 // diagnostic that mentions 'auto' and lambda in addition to 10835 // (or instead of?) the canonical template type parameters. 10836 S.Diag(Templated->getLocation(), 10837 diag::note_ovl_candidate_non_deduced_mismatch) 10838 << FirstTA << SecondTA; 10839 return; 10840 } 10841 // TODO: diagnose these individually, then kill off 10842 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10843 case Sema::TDK_MiscellaneousDeductionFailure: 10844 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10845 MaybeEmitInheritedConstructorNote(S, Found); 10846 return; 10847 case Sema::TDK_CUDATargetMismatch: 10848 S.Diag(Templated->getLocation(), 10849 diag::note_cuda_ovl_candidate_target_mismatch); 10850 return; 10851 } 10852 } 10853 10854 /// Diagnose a failed template-argument deduction, for function calls. 10855 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10856 unsigned NumArgs, 10857 bool TakingCandidateAddress) { 10858 unsigned TDK = Cand->DeductionFailure.Result; 10859 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10860 if (CheckArityMismatch(S, Cand, NumArgs)) 10861 return; 10862 } 10863 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10864 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10865 } 10866 10867 /// CUDA: diagnose an invalid call across targets. 10868 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10869 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10870 FunctionDecl *Callee = Cand->Function; 10871 10872 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10873 CalleeTarget = S.IdentifyCUDATarget(Callee); 10874 10875 std::string FnDesc; 10876 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10877 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10878 Cand->getRewriteKind(), FnDesc); 10879 10880 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10881 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10882 << FnDesc /* Ignored */ 10883 << CalleeTarget << CallerTarget; 10884 10885 // This could be an implicit constructor for which we could not infer the 10886 // target due to a collsion. Diagnose that case. 10887 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10888 if (Meth != nullptr && Meth->isImplicit()) { 10889 CXXRecordDecl *ParentClass = Meth->getParent(); 10890 Sema::CXXSpecialMember CSM; 10891 10892 switch (FnKindPair.first) { 10893 default: 10894 return; 10895 case oc_implicit_default_constructor: 10896 CSM = Sema::CXXDefaultConstructor; 10897 break; 10898 case oc_implicit_copy_constructor: 10899 CSM = Sema::CXXCopyConstructor; 10900 break; 10901 case oc_implicit_move_constructor: 10902 CSM = Sema::CXXMoveConstructor; 10903 break; 10904 case oc_implicit_copy_assignment: 10905 CSM = Sema::CXXCopyAssignment; 10906 break; 10907 case oc_implicit_move_assignment: 10908 CSM = Sema::CXXMoveAssignment; 10909 break; 10910 }; 10911 10912 bool ConstRHS = false; 10913 if (Meth->getNumParams()) { 10914 if (const ReferenceType *RT = 10915 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10916 ConstRHS = RT->getPointeeType().isConstQualified(); 10917 } 10918 } 10919 10920 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10921 /* ConstRHS */ ConstRHS, 10922 /* Diagnose */ true); 10923 } 10924 } 10925 10926 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10927 FunctionDecl *Callee = Cand->Function; 10928 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10929 10930 S.Diag(Callee->getLocation(), 10931 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10932 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10933 } 10934 10935 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10936 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10937 assert(ES.isExplicit() && "not an explicit candidate"); 10938 10939 unsigned Kind; 10940 switch (Cand->Function->getDeclKind()) { 10941 case Decl::Kind::CXXConstructor: 10942 Kind = 0; 10943 break; 10944 case Decl::Kind::CXXConversion: 10945 Kind = 1; 10946 break; 10947 case Decl::Kind::CXXDeductionGuide: 10948 Kind = Cand->Function->isImplicit() ? 0 : 2; 10949 break; 10950 default: 10951 llvm_unreachable("invalid Decl"); 10952 } 10953 10954 // Note the location of the first (in-class) declaration; a redeclaration 10955 // (particularly an out-of-class definition) will typically lack the 10956 // 'explicit' specifier. 10957 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10958 FunctionDecl *First = Cand->Function->getFirstDecl(); 10959 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10960 First = Pattern->getFirstDecl(); 10961 10962 S.Diag(First->getLocation(), 10963 diag::note_ovl_candidate_explicit) 10964 << Kind << (ES.getExpr() ? 1 : 0) 10965 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10966 } 10967 10968 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10969 FunctionDecl *Callee = Cand->Function; 10970 10971 S.Diag(Callee->getLocation(), 10972 diag::note_ovl_candidate_disabled_by_extension) 10973 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10974 } 10975 10976 /// Generates a 'note' diagnostic for an overload candidate. We've 10977 /// already generated a primary error at the call site. 10978 /// 10979 /// It really does need to be a single diagnostic with its caret 10980 /// pointed at the candidate declaration. Yes, this creates some 10981 /// major challenges of technical writing. Yes, this makes pointing 10982 /// out problems with specific arguments quite awkward. It's still 10983 /// better than generating twenty screens of text for every failed 10984 /// overload. 10985 /// 10986 /// It would be great to be able to express per-candidate problems 10987 /// more richly for those diagnostic clients that cared, but we'd 10988 /// still have to be just as careful with the default diagnostics. 10989 /// \param CtorDestAS Addr space of object being constructed (for ctor 10990 /// candidates only). 10991 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10992 unsigned NumArgs, 10993 bool TakingCandidateAddress, 10994 LangAS CtorDestAS = LangAS::Default) { 10995 FunctionDecl *Fn = Cand->Function; 10996 10997 // Note deleted candidates, but only if they're viable. 10998 if (Cand->Viable) { 10999 if (Fn->isDeleted()) { 11000 std::string FnDesc; 11001 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11002 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11003 Cand->getRewriteKind(), FnDesc); 11004 11005 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11006 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11007 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11008 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11009 return; 11010 } 11011 11012 // We don't really have anything else to say about viable candidates. 11013 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11014 return; 11015 } 11016 11017 switch (Cand->FailureKind) { 11018 case ovl_fail_too_many_arguments: 11019 case ovl_fail_too_few_arguments: 11020 return DiagnoseArityMismatch(S, Cand, NumArgs); 11021 11022 case ovl_fail_bad_deduction: 11023 return DiagnoseBadDeduction(S, Cand, NumArgs, 11024 TakingCandidateAddress); 11025 11026 case ovl_fail_illegal_constructor: { 11027 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11028 << (Fn->getPrimaryTemplate() ? 1 : 0); 11029 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11030 return; 11031 } 11032 11033 case ovl_fail_object_addrspace_mismatch: { 11034 Qualifiers QualsForPrinting; 11035 QualsForPrinting.setAddressSpace(CtorDestAS); 11036 S.Diag(Fn->getLocation(), 11037 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11038 << QualsForPrinting; 11039 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11040 return; 11041 } 11042 11043 case ovl_fail_trivial_conversion: 11044 case ovl_fail_bad_final_conversion: 11045 case ovl_fail_final_conversion_not_exact: 11046 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11047 11048 case ovl_fail_bad_conversion: { 11049 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11050 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11051 if (Cand->Conversions[I].isBad()) 11052 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11053 11054 // FIXME: this currently happens when we're called from SemaInit 11055 // when user-conversion overload fails. Figure out how to handle 11056 // those conditions and diagnose them well. 11057 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11058 } 11059 11060 case ovl_fail_bad_target: 11061 return DiagnoseBadTarget(S, Cand); 11062 11063 case ovl_fail_enable_if: 11064 return DiagnoseFailedEnableIfAttr(S, Cand); 11065 11066 case ovl_fail_explicit: 11067 return DiagnoseFailedExplicitSpec(S, Cand); 11068 11069 case ovl_fail_ext_disabled: 11070 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11071 11072 case ovl_fail_inhctor_slice: 11073 // It's generally not interesting to note copy/move constructors here. 11074 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11075 return; 11076 S.Diag(Fn->getLocation(), 11077 diag::note_ovl_candidate_inherited_constructor_slice) 11078 << (Fn->getPrimaryTemplate() ? 1 : 0) 11079 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11080 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11081 return; 11082 11083 case ovl_fail_addr_not_available: { 11084 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11085 (void)Available; 11086 assert(!Available); 11087 break; 11088 } 11089 case ovl_non_default_multiversion_function: 11090 // Do nothing, these should simply be ignored. 11091 break; 11092 11093 case ovl_fail_constraints_not_satisfied: { 11094 std::string FnDesc; 11095 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11096 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11097 Cand->getRewriteKind(), FnDesc); 11098 11099 S.Diag(Fn->getLocation(), 11100 diag::note_ovl_candidate_constraints_not_satisfied) 11101 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11102 << FnDesc /* Ignored */; 11103 ConstraintSatisfaction Satisfaction; 11104 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11105 break; 11106 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11107 } 11108 } 11109 } 11110 11111 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11112 // Desugar the type of the surrogate down to a function type, 11113 // retaining as many typedefs as possible while still showing 11114 // the function type (and, therefore, its parameter types). 11115 QualType FnType = Cand->Surrogate->getConversionType(); 11116 bool isLValueReference = false; 11117 bool isRValueReference = false; 11118 bool isPointer = false; 11119 if (const LValueReferenceType *FnTypeRef = 11120 FnType->getAs<LValueReferenceType>()) { 11121 FnType = FnTypeRef->getPointeeType(); 11122 isLValueReference = true; 11123 } else if (const RValueReferenceType *FnTypeRef = 11124 FnType->getAs<RValueReferenceType>()) { 11125 FnType = FnTypeRef->getPointeeType(); 11126 isRValueReference = true; 11127 } 11128 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11129 FnType = FnTypePtr->getPointeeType(); 11130 isPointer = true; 11131 } 11132 // Desugar down to a function type. 11133 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11134 // Reconstruct the pointer/reference as appropriate. 11135 if (isPointer) FnType = S.Context.getPointerType(FnType); 11136 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11137 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11138 11139 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11140 << FnType; 11141 } 11142 11143 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11144 SourceLocation OpLoc, 11145 OverloadCandidate *Cand) { 11146 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11147 std::string TypeStr("operator"); 11148 TypeStr += Opc; 11149 TypeStr += "("; 11150 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11151 if (Cand->Conversions.size() == 1) { 11152 TypeStr += ")"; 11153 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11154 } else { 11155 TypeStr += ", "; 11156 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11157 TypeStr += ")"; 11158 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11159 } 11160 } 11161 11162 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11163 OverloadCandidate *Cand) { 11164 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11165 if (ICS.isBad()) break; // all meaningless after first invalid 11166 if (!ICS.isAmbiguous()) continue; 11167 11168 ICS.DiagnoseAmbiguousConversion( 11169 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11170 } 11171 } 11172 11173 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11174 if (Cand->Function) 11175 return Cand->Function->getLocation(); 11176 if (Cand->IsSurrogate) 11177 return Cand->Surrogate->getLocation(); 11178 return SourceLocation(); 11179 } 11180 11181 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11182 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11183 case Sema::TDK_Success: 11184 case Sema::TDK_NonDependentConversionFailure: 11185 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11186 11187 case Sema::TDK_Invalid: 11188 case Sema::TDK_Incomplete: 11189 case Sema::TDK_IncompletePack: 11190 return 1; 11191 11192 case Sema::TDK_Underqualified: 11193 case Sema::TDK_Inconsistent: 11194 return 2; 11195 11196 case Sema::TDK_SubstitutionFailure: 11197 case Sema::TDK_DeducedMismatch: 11198 case Sema::TDK_ConstraintsNotSatisfied: 11199 case Sema::TDK_DeducedMismatchNested: 11200 case Sema::TDK_NonDeducedMismatch: 11201 case Sema::TDK_MiscellaneousDeductionFailure: 11202 case Sema::TDK_CUDATargetMismatch: 11203 return 3; 11204 11205 case Sema::TDK_InstantiationDepth: 11206 return 4; 11207 11208 case Sema::TDK_InvalidExplicitArguments: 11209 return 5; 11210 11211 case Sema::TDK_TooManyArguments: 11212 case Sema::TDK_TooFewArguments: 11213 return 6; 11214 } 11215 llvm_unreachable("Unhandled deduction result"); 11216 } 11217 11218 namespace { 11219 struct CompareOverloadCandidatesForDisplay { 11220 Sema &S; 11221 SourceLocation Loc; 11222 size_t NumArgs; 11223 OverloadCandidateSet::CandidateSetKind CSK; 11224 11225 CompareOverloadCandidatesForDisplay( 11226 Sema &S, SourceLocation Loc, size_t NArgs, 11227 OverloadCandidateSet::CandidateSetKind CSK) 11228 : S(S), NumArgs(NArgs), CSK(CSK) {} 11229 11230 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11231 // If there are too many or too few arguments, that's the high-order bit we 11232 // want to sort by, even if the immediate failure kind was something else. 11233 if (C->FailureKind == ovl_fail_too_many_arguments || 11234 C->FailureKind == ovl_fail_too_few_arguments) 11235 return static_cast<OverloadFailureKind>(C->FailureKind); 11236 11237 if (C->Function) { 11238 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11239 return ovl_fail_too_many_arguments; 11240 if (NumArgs < C->Function->getMinRequiredArguments()) 11241 return ovl_fail_too_few_arguments; 11242 } 11243 11244 return static_cast<OverloadFailureKind>(C->FailureKind); 11245 } 11246 11247 bool operator()(const OverloadCandidate *L, 11248 const OverloadCandidate *R) { 11249 // Fast-path this check. 11250 if (L == R) return false; 11251 11252 // Order first by viability. 11253 if (L->Viable) { 11254 if (!R->Viable) return true; 11255 11256 // TODO: introduce a tri-valued comparison for overload 11257 // candidates. Would be more worthwhile if we had a sort 11258 // that could exploit it. 11259 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11260 return true; 11261 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11262 return false; 11263 } else if (R->Viable) 11264 return false; 11265 11266 assert(L->Viable == R->Viable); 11267 11268 // Criteria by which we can sort non-viable candidates: 11269 if (!L->Viable) { 11270 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11271 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11272 11273 // 1. Arity mismatches come after other candidates. 11274 if (LFailureKind == ovl_fail_too_many_arguments || 11275 LFailureKind == ovl_fail_too_few_arguments) { 11276 if (RFailureKind == ovl_fail_too_many_arguments || 11277 RFailureKind == ovl_fail_too_few_arguments) { 11278 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11279 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11280 if (LDist == RDist) { 11281 if (LFailureKind == RFailureKind) 11282 // Sort non-surrogates before surrogates. 11283 return !L->IsSurrogate && R->IsSurrogate; 11284 // Sort candidates requiring fewer parameters than there were 11285 // arguments given after candidates requiring more parameters 11286 // than there were arguments given. 11287 return LFailureKind == ovl_fail_too_many_arguments; 11288 } 11289 return LDist < RDist; 11290 } 11291 return false; 11292 } 11293 if (RFailureKind == ovl_fail_too_many_arguments || 11294 RFailureKind == ovl_fail_too_few_arguments) 11295 return true; 11296 11297 // 2. Bad conversions come first and are ordered by the number 11298 // of bad conversions and quality of good conversions. 11299 if (LFailureKind == ovl_fail_bad_conversion) { 11300 if (RFailureKind != ovl_fail_bad_conversion) 11301 return true; 11302 11303 // The conversion that can be fixed with a smaller number of changes, 11304 // comes first. 11305 unsigned numLFixes = L->Fix.NumConversionsFixed; 11306 unsigned numRFixes = R->Fix.NumConversionsFixed; 11307 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11308 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11309 if (numLFixes != numRFixes) { 11310 return numLFixes < numRFixes; 11311 } 11312 11313 // If there's any ordering between the defined conversions... 11314 // FIXME: this might not be transitive. 11315 assert(L->Conversions.size() == R->Conversions.size()); 11316 11317 int leftBetter = 0; 11318 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11319 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11320 switch (CompareImplicitConversionSequences(S, Loc, 11321 L->Conversions[I], 11322 R->Conversions[I])) { 11323 case ImplicitConversionSequence::Better: 11324 leftBetter++; 11325 break; 11326 11327 case ImplicitConversionSequence::Worse: 11328 leftBetter--; 11329 break; 11330 11331 case ImplicitConversionSequence::Indistinguishable: 11332 break; 11333 } 11334 } 11335 if (leftBetter > 0) return true; 11336 if (leftBetter < 0) return false; 11337 11338 } else if (RFailureKind == ovl_fail_bad_conversion) 11339 return false; 11340 11341 if (LFailureKind == ovl_fail_bad_deduction) { 11342 if (RFailureKind != ovl_fail_bad_deduction) 11343 return true; 11344 11345 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11346 return RankDeductionFailure(L->DeductionFailure) 11347 < RankDeductionFailure(R->DeductionFailure); 11348 } else if (RFailureKind == ovl_fail_bad_deduction) 11349 return false; 11350 11351 // TODO: others? 11352 } 11353 11354 // Sort everything else by location. 11355 SourceLocation LLoc = GetLocationForCandidate(L); 11356 SourceLocation RLoc = GetLocationForCandidate(R); 11357 11358 // Put candidates without locations (e.g. builtins) at the end. 11359 if (LLoc.isInvalid()) return false; 11360 if (RLoc.isInvalid()) return true; 11361 11362 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11363 } 11364 }; 11365 } 11366 11367 /// CompleteNonViableCandidate - Normally, overload resolution only 11368 /// computes up to the first bad conversion. Produces the FixIt set if 11369 /// possible. 11370 static void 11371 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11372 ArrayRef<Expr *> Args, 11373 OverloadCandidateSet::CandidateSetKind CSK) { 11374 assert(!Cand->Viable); 11375 11376 // Don't do anything on failures other than bad conversion. 11377 if (Cand->FailureKind != ovl_fail_bad_conversion) 11378 return; 11379 11380 // We only want the FixIts if all the arguments can be corrected. 11381 bool Unfixable = false; 11382 // Use a implicit copy initialization to check conversion fixes. 11383 Cand->Fix.setConversionChecker(TryCopyInitialization); 11384 11385 // Attempt to fix the bad conversion. 11386 unsigned ConvCount = Cand->Conversions.size(); 11387 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11388 ++ConvIdx) { 11389 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11390 if (Cand->Conversions[ConvIdx].isInitialized() && 11391 Cand->Conversions[ConvIdx].isBad()) { 11392 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11393 break; 11394 } 11395 } 11396 11397 // FIXME: this should probably be preserved from the overload 11398 // operation somehow. 11399 bool SuppressUserConversions = false; 11400 11401 unsigned ConvIdx = 0; 11402 unsigned ArgIdx = 0; 11403 ArrayRef<QualType> ParamTypes; 11404 bool Reversed = Cand->isReversed(); 11405 11406 if (Cand->IsSurrogate) { 11407 QualType ConvType 11408 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11409 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11410 ConvType = ConvPtrType->getPointeeType(); 11411 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11412 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11413 ConvIdx = 1; 11414 } else if (Cand->Function) { 11415 ParamTypes = 11416 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11417 if (isa<CXXMethodDecl>(Cand->Function) && 11418 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11419 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11420 ConvIdx = 1; 11421 if (CSK == OverloadCandidateSet::CSK_Operator && 11422 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11423 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11424 ArgIdx = 1; 11425 } 11426 } else { 11427 // Builtin operator. 11428 assert(ConvCount <= 3); 11429 ParamTypes = Cand->BuiltinParamTypes; 11430 } 11431 11432 // Fill in the rest of the conversions. 11433 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11434 ConvIdx != ConvCount; 11435 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11436 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11437 if (Cand->Conversions[ConvIdx].isInitialized()) { 11438 // We've already checked this conversion. 11439 } else if (ParamIdx < ParamTypes.size()) { 11440 if (ParamTypes[ParamIdx]->isDependentType()) 11441 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11442 Args[ArgIdx]->getType()); 11443 else { 11444 Cand->Conversions[ConvIdx] = 11445 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11446 SuppressUserConversions, 11447 /*InOverloadResolution=*/true, 11448 /*AllowObjCWritebackConversion=*/ 11449 S.getLangOpts().ObjCAutoRefCount); 11450 // Store the FixIt in the candidate if it exists. 11451 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11452 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11453 } 11454 } else 11455 Cand->Conversions[ConvIdx].setEllipsis(); 11456 } 11457 } 11458 11459 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11460 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11461 SourceLocation OpLoc, 11462 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11463 // Sort the candidates by viability and position. Sorting directly would 11464 // be prohibitive, so we make a set of pointers and sort those. 11465 SmallVector<OverloadCandidate*, 32> Cands; 11466 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11467 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11468 if (!Filter(*Cand)) 11469 continue; 11470 switch (OCD) { 11471 case OCD_AllCandidates: 11472 if (!Cand->Viable) { 11473 if (!Cand->Function && !Cand->IsSurrogate) { 11474 // This a non-viable builtin candidate. We do not, in general, 11475 // want to list every possible builtin candidate. 11476 continue; 11477 } 11478 CompleteNonViableCandidate(S, Cand, Args, Kind); 11479 } 11480 break; 11481 11482 case OCD_ViableCandidates: 11483 if (!Cand->Viable) 11484 continue; 11485 break; 11486 11487 case OCD_AmbiguousCandidates: 11488 if (!Cand->Best) 11489 continue; 11490 break; 11491 } 11492 11493 Cands.push_back(Cand); 11494 } 11495 11496 llvm::stable_sort( 11497 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11498 11499 return Cands; 11500 } 11501 11502 /// When overload resolution fails, prints diagnostic messages containing the 11503 /// candidates in the candidate set. 11504 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11505 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11506 StringRef Opc, SourceLocation OpLoc, 11507 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11508 11509 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11510 11511 S.Diag(PD.first, PD.second); 11512 11513 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11514 11515 if (OCD == OCD_AmbiguousCandidates) 11516 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11517 } 11518 11519 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11520 ArrayRef<OverloadCandidate *> Cands, 11521 StringRef Opc, SourceLocation OpLoc) { 11522 bool ReportedAmbiguousConversions = false; 11523 11524 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11525 unsigned CandsShown = 0; 11526 auto I = Cands.begin(), E = Cands.end(); 11527 for (; I != E; ++I) { 11528 OverloadCandidate *Cand = *I; 11529 11530 // Set an arbitrary limit on the number of candidate functions we'll spam 11531 // the user with. FIXME: This limit should depend on details of the 11532 // candidate list. 11533 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11534 break; 11535 } 11536 ++CandsShown; 11537 11538 if (Cand->Function) 11539 NoteFunctionCandidate(S, Cand, Args.size(), 11540 /*TakingCandidateAddress=*/false, DestAS); 11541 else if (Cand->IsSurrogate) 11542 NoteSurrogateCandidate(S, Cand); 11543 else { 11544 assert(Cand->Viable && 11545 "Non-viable built-in candidates are not added to Cands."); 11546 // Generally we only see ambiguities including viable builtin 11547 // operators if overload resolution got screwed up by an 11548 // ambiguous user-defined conversion. 11549 // 11550 // FIXME: It's quite possible for different conversions to see 11551 // different ambiguities, though. 11552 if (!ReportedAmbiguousConversions) { 11553 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11554 ReportedAmbiguousConversions = true; 11555 } 11556 11557 // If this is a viable builtin, print it. 11558 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11559 } 11560 } 11561 11562 if (I != E) 11563 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11564 } 11565 11566 static SourceLocation 11567 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11568 return Cand->Specialization ? Cand->Specialization->getLocation() 11569 : SourceLocation(); 11570 } 11571 11572 namespace { 11573 struct CompareTemplateSpecCandidatesForDisplay { 11574 Sema &S; 11575 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11576 11577 bool operator()(const TemplateSpecCandidate *L, 11578 const TemplateSpecCandidate *R) { 11579 // Fast-path this check. 11580 if (L == R) 11581 return false; 11582 11583 // Assuming that both candidates are not matches... 11584 11585 // Sort by the ranking of deduction failures. 11586 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11587 return RankDeductionFailure(L->DeductionFailure) < 11588 RankDeductionFailure(R->DeductionFailure); 11589 11590 // Sort everything else by location. 11591 SourceLocation LLoc = GetLocationForCandidate(L); 11592 SourceLocation RLoc = GetLocationForCandidate(R); 11593 11594 // Put candidates without locations (e.g. builtins) at the end. 11595 if (LLoc.isInvalid()) 11596 return false; 11597 if (RLoc.isInvalid()) 11598 return true; 11599 11600 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11601 } 11602 }; 11603 } 11604 11605 /// Diagnose a template argument deduction failure. 11606 /// We are treating these failures as overload failures due to bad 11607 /// deductions. 11608 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11609 bool ForTakingAddress) { 11610 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11611 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11612 } 11613 11614 void TemplateSpecCandidateSet::destroyCandidates() { 11615 for (iterator i = begin(), e = end(); i != e; ++i) { 11616 i->DeductionFailure.Destroy(); 11617 } 11618 } 11619 11620 void TemplateSpecCandidateSet::clear() { 11621 destroyCandidates(); 11622 Candidates.clear(); 11623 } 11624 11625 /// NoteCandidates - When no template specialization match is found, prints 11626 /// diagnostic messages containing the non-matching specializations that form 11627 /// the candidate set. 11628 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11629 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11630 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11631 // Sort the candidates by position (assuming no candidate is a match). 11632 // Sorting directly would be prohibitive, so we make a set of pointers 11633 // and sort those. 11634 SmallVector<TemplateSpecCandidate *, 32> Cands; 11635 Cands.reserve(size()); 11636 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11637 if (Cand->Specialization) 11638 Cands.push_back(Cand); 11639 // Otherwise, this is a non-matching builtin candidate. We do not, 11640 // in general, want to list every possible builtin candidate. 11641 } 11642 11643 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11644 11645 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11646 // for generalization purposes (?). 11647 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11648 11649 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11650 unsigned CandsShown = 0; 11651 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11652 TemplateSpecCandidate *Cand = *I; 11653 11654 // Set an arbitrary limit on the number of candidates we'll spam 11655 // the user with. FIXME: This limit should depend on details of the 11656 // candidate list. 11657 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11658 break; 11659 ++CandsShown; 11660 11661 assert(Cand->Specialization && 11662 "Non-matching built-in candidates are not added to Cands."); 11663 Cand->NoteDeductionFailure(S, ForTakingAddress); 11664 } 11665 11666 if (I != E) 11667 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11668 } 11669 11670 // [PossiblyAFunctionType] --> [Return] 11671 // NonFunctionType --> NonFunctionType 11672 // R (A) --> R(A) 11673 // R (*)(A) --> R (A) 11674 // R (&)(A) --> R (A) 11675 // R (S::*)(A) --> R (A) 11676 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11677 QualType Ret = PossiblyAFunctionType; 11678 if (const PointerType *ToTypePtr = 11679 PossiblyAFunctionType->getAs<PointerType>()) 11680 Ret = ToTypePtr->getPointeeType(); 11681 else if (const ReferenceType *ToTypeRef = 11682 PossiblyAFunctionType->getAs<ReferenceType>()) 11683 Ret = ToTypeRef->getPointeeType(); 11684 else if (const MemberPointerType *MemTypePtr = 11685 PossiblyAFunctionType->getAs<MemberPointerType>()) 11686 Ret = MemTypePtr->getPointeeType(); 11687 Ret = 11688 Context.getCanonicalType(Ret).getUnqualifiedType(); 11689 return Ret; 11690 } 11691 11692 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11693 bool Complain = true) { 11694 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11695 S.DeduceReturnType(FD, Loc, Complain)) 11696 return true; 11697 11698 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11699 if (S.getLangOpts().CPlusPlus17 && 11700 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11701 !S.ResolveExceptionSpec(Loc, FPT)) 11702 return true; 11703 11704 return false; 11705 } 11706 11707 namespace { 11708 // A helper class to help with address of function resolution 11709 // - allows us to avoid passing around all those ugly parameters 11710 class AddressOfFunctionResolver { 11711 Sema& S; 11712 Expr* SourceExpr; 11713 const QualType& TargetType; 11714 QualType TargetFunctionType; // Extracted function type from target type 11715 11716 bool Complain; 11717 //DeclAccessPair& ResultFunctionAccessPair; 11718 ASTContext& Context; 11719 11720 bool TargetTypeIsNonStaticMemberFunction; 11721 bool FoundNonTemplateFunction; 11722 bool StaticMemberFunctionFromBoundPointer; 11723 bool HasComplained; 11724 11725 OverloadExpr::FindResult OvlExprInfo; 11726 OverloadExpr *OvlExpr; 11727 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11728 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11729 TemplateSpecCandidateSet FailedCandidates; 11730 11731 public: 11732 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11733 const QualType &TargetType, bool Complain) 11734 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11735 Complain(Complain), Context(S.getASTContext()), 11736 TargetTypeIsNonStaticMemberFunction( 11737 !!TargetType->getAs<MemberPointerType>()), 11738 FoundNonTemplateFunction(false), 11739 StaticMemberFunctionFromBoundPointer(false), 11740 HasComplained(false), 11741 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11742 OvlExpr(OvlExprInfo.Expression), 11743 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11744 ExtractUnqualifiedFunctionTypeFromTargetType(); 11745 11746 if (TargetFunctionType->isFunctionType()) { 11747 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11748 if (!UME->isImplicitAccess() && 11749 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11750 StaticMemberFunctionFromBoundPointer = true; 11751 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11752 DeclAccessPair dap; 11753 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11754 OvlExpr, false, &dap)) { 11755 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11756 if (!Method->isStatic()) { 11757 // If the target type is a non-function type and the function found 11758 // is a non-static member function, pretend as if that was the 11759 // target, it's the only possible type to end up with. 11760 TargetTypeIsNonStaticMemberFunction = true; 11761 11762 // And skip adding the function if its not in the proper form. 11763 // We'll diagnose this due to an empty set of functions. 11764 if (!OvlExprInfo.HasFormOfMemberPointer) 11765 return; 11766 } 11767 11768 Matches.push_back(std::make_pair(dap, Fn)); 11769 } 11770 return; 11771 } 11772 11773 if (OvlExpr->hasExplicitTemplateArgs()) 11774 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11775 11776 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11777 // C++ [over.over]p4: 11778 // If more than one function is selected, [...] 11779 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11780 if (FoundNonTemplateFunction) 11781 EliminateAllTemplateMatches(); 11782 else 11783 EliminateAllExceptMostSpecializedTemplate(); 11784 } 11785 } 11786 11787 if (S.getLangOpts().CUDA && Matches.size() > 1) 11788 EliminateSuboptimalCudaMatches(); 11789 } 11790 11791 bool hasComplained() const { return HasComplained; } 11792 11793 private: 11794 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11795 QualType Discard; 11796 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11797 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11798 } 11799 11800 /// \return true if A is considered a better overload candidate for the 11801 /// desired type than B. 11802 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11803 // If A doesn't have exactly the correct type, we don't want to classify it 11804 // as "better" than anything else. This way, the user is required to 11805 // disambiguate for us if there are multiple candidates and no exact match. 11806 return candidateHasExactlyCorrectType(A) && 11807 (!candidateHasExactlyCorrectType(B) || 11808 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11809 } 11810 11811 /// \return true if we were able to eliminate all but one overload candidate, 11812 /// false otherwise. 11813 bool eliminiateSuboptimalOverloadCandidates() { 11814 // Same algorithm as overload resolution -- one pass to pick the "best", 11815 // another pass to be sure that nothing is better than the best. 11816 auto Best = Matches.begin(); 11817 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11818 if (isBetterCandidate(I->second, Best->second)) 11819 Best = I; 11820 11821 const FunctionDecl *BestFn = Best->second; 11822 auto IsBestOrInferiorToBest = [this, BestFn]( 11823 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11824 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11825 }; 11826 11827 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11828 // option, so we can potentially give the user a better error 11829 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11830 return false; 11831 Matches[0] = *Best; 11832 Matches.resize(1); 11833 return true; 11834 } 11835 11836 bool isTargetTypeAFunction() const { 11837 return TargetFunctionType->isFunctionType(); 11838 } 11839 11840 // [ToType] [Return] 11841 11842 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11843 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11844 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11845 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11846 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11847 } 11848 11849 // return true if any matching specializations were found 11850 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11851 const DeclAccessPair& CurAccessFunPair) { 11852 if (CXXMethodDecl *Method 11853 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11854 // Skip non-static function templates when converting to pointer, and 11855 // static when converting to member pointer. 11856 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11857 return false; 11858 } 11859 else if (TargetTypeIsNonStaticMemberFunction) 11860 return false; 11861 11862 // C++ [over.over]p2: 11863 // If the name is a function template, template argument deduction is 11864 // done (14.8.2.2), and if the argument deduction succeeds, the 11865 // resulting template argument list is used to generate a single 11866 // function template specialization, which is added to the set of 11867 // overloaded functions considered. 11868 FunctionDecl *Specialization = nullptr; 11869 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11870 if (Sema::TemplateDeductionResult Result 11871 = S.DeduceTemplateArguments(FunctionTemplate, 11872 &OvlExplicitTemplateArgs, 11873 TargetFunctionType, Specialization, 11874 Info, /*IsAddressOfFunction*/true)) { 11875 // Make a note of the failed deduction for diagnostics. 11876 FailedCandidates.addCandidate() 11877 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11878 MakeDeductionFailureInfo(Context, Result, Info)); 11879 return false; 11880 } 11881 11882 // Template argument deduction ensures that we have an exact match or 11883 // compatible pointer-to-function arguments that would be adjusted by ICS. 11884 // This function template specicalization works. 11885 assert(S.isSameOrCompatibleFunctionType( 11886 Context.getCanonicalType(Specialization->getType()), 11887 Context.getCanonicalType(TargetFunctionType))); 11888 11889 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11890 return false; 11891 11892 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11893 return true; 11894 } 11895 11896 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11897 const DeclAccessPair& CurAccessFunPair) { 11898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11899 // Skip non-static functions when converting to pointer, and static 11900 // when converting to member pointer. 11901 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11902 return false; 11903 } 11904 else if (TargetTypeIsNonStaticMemberFunction) 11905 return false; 11906 11907 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11908 if (S.getLangOpts().CUDA) 11909 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11910 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11911 return false; 11912 if (FunDecl->isMultiVersion()) { 11913 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11914 if (TA && !TA->isDefaultVersion()) 11915 return false; 11916 } 11917 11918 // If any candidate has a placeholder return type, trigger its deduction 11919 // now. 11920 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11921 Complain)) { 11922 HasComplained |= Complain; 11923 return false; 11924 } 11925 11926 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11927 return false; 11928 11929 // If we're in C, we need to support types that aren't exactly identical. 11930 if (!S.getLangOpts().CPlusPlus || 11931 candidateHasExactlyCorrectType(FunDecl)) { 11932 Matches.push_back(std::make_pair( 11933 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11934 FoundNonTemplateFunction = true; 11935 return true; 11936 } 11937 } 11938 11939 return false; 11940 } 11941 11942 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11943 bool Ret = false; 11944 11945 // If the overload expression doesn't have the form of a pointer to 11946 // member, don't try to convert it to a pointer-to-member type. 11947 if (IsInvalidFormOfPointerToMemberFunction()) 11948 return false; 11949 11950 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11951 E = OvlExpr->decls_end(); 11952 I != E; ++I) { 11953 // Look through any using declarations to find the underlying function. 11954 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11955 11956 // C++ [over.over]p3: 11957 // Non-member functions and static member functions match 11958 // targets of type "pointer-to-function" or "reference-to-function." 11959 // Nonstatic member functions match targets of 11960 // type "pointer-to-member-function." 11961 // Note that according to DR 247, the containing class does not matter. 11962 if (FunctionTemplateDecl *FunctionTemplate 11963 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11964 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11965 Ret = true; 11966 } 11967 // If we have explicit template arguments supplied, skip non-templates. 11968 else if (!OvlExpr->hasExplicitTemplateArgs() && 11969 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11970 Ret = true; 11971 } 11972 assert(Ret || Matches.empty()); 11973 return Ret; 11974 } 11975 11976 void EliminateAllExceptMostSpecializedTemplate() { 11977 // [...] and any given function template specialization F1 is 11978 // eliminated if the set contains a second function template 11979 // specialization whose function template is more specialized 11980 // than the function template of F1 according to the partial 11981 // ordering rules of 14.5.5.2. 11982 11983 // The algorithm specified above is quadratic. We instead use a 11984 // two-pass algorithm (similar to the one used to identify the 11985 // best viable function in an overload set) that identifies the 11986 // best function template (if it exists). 11987 11988 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11989 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11990 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11991 11992 // TODO: It looks like FailedCandidates does not serve much purpose 11993 // here, since the no_viable diagnostic has index 0. 11994 UnresolvedSetIterator Result = S.getMostSpecialized( 11995 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11996 SourceExpr->getBeginLoc(), S.PDiag(), 11997 S.PDiag(diag::err_addr_ovl_ambiguous) 11998 << Matches[0].second->getDeclName(), 11999 S.PDiag(diag::note_ovl_candidate) 12000 << (unsigned)oc_function << (unsigned)ocs_described_template, 12001 Complain, TargetFunctionType); 12002 12003 if (Result != MatchesCopy.end()) { 12004 // Make it the first and only element 12005 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12006 Matches[0].second = cast<FunctionDecl>(*Result); 12007 Matches.resize(1); 12008 } else 12009 HasComplained |= Complain; 12010 } 12011 12012 void EliminateAllTemplateMatches() { 12013 // [...] any function template specializations in the set are 12014 // eliminated if the set also contains a non-template function, [...] 12015 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12016 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12017 ++I; 12018 else { 12019 Matches[I] = Matches[--N]; 12020 Matches.resize(N); 12021 } 12022 } 12023 } 12024 12025 void EliminateSuboptimalCudaMatches() { 12026 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12027 } 12028 12029 public: 12030 void ComplainNoMatchesFound() const { 12031 assert(Matches.empty()); 12032 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12033 << OvlExpr->getName() << TargetFunctionType 12034 << OvlExpr->getSourceRange(); 12035 if (FailedCandidates.empty()) 12036 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12037 /*TakingAddress=*/true); 12038 else { 12039 // We have some deduction failure messages. Use them to diagnose 12040 // the function templates, and diagnose the non-template candidates 12041 // normally. 12042 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12043 IEnd = OvlExpr->decls_end(); 12044 I != IEnd; ++I) 12045 if (FunctionDecl *Fun = 12046 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12047 if (!functionHasPassObjectSizeParams(Fun)) 12048 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12049 /*TakingAddress=*/true); 12050 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12051 } 12052 } 12053 12054 bool IsInvalidFormOfPointerToMemberFunction() const { 12055 return TargetTypeIsNonStaticMemberFunction && 12056 !OvlExprInfo.HasFormOfMemberPointer; 12057 } 12058 12059 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12060 // TODO: Should we condition this on whether any functions might 12061 // have matched, or is it more appropriate to do that in callers? 12062 // TODO: a fixit wouldn't hurt. 12063 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12064 << TargetType << OvlExpr->getSourceRange(); 12065 } 12066 12067 bool IsStaticMemberFunctionFromBoundPointer() const { 12068 return StaticMemberFunctionFromBoundPointer; 12069 } 12070 12071 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12072 S.Diag(OvlExpr->getBeginLoc(), 12073 diag::err_invalid_form_pointer_member_function) 12074 << OvlExpr->getSourceRange(); 12075 } 12076 12077 void ComplainOfInvalidConversion() const { 12078 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12079 << OvlExpr->getName() << TargetType; 12080 } 12081 12082 void ComplainMultipleMatchesFound() const { 12083 assert(Matches.size() > 1); 12084 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12085 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12086 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12087 /*TakingAddress=*/true); 12088 } 12089 12090 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12091 12092 int getNumMatches() const { return Matches.size(); } 12093 12094 FunctionDecl* getMatchingFunctionDecl() const { 12095 if (Matches.size() != 1) return nullptr; 12096 return Matches[0].second; 12097 } 12098 12099 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12100 if (Matches.size() != 1) return nullptr; 12101 return &Matches[0].first; 12102 } 12103 }; 12104 } 12105 12106 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12107 /// an overloaded function (C++ [over.over]), where @p From is an 12108 /// expression with overloaded function type and @p ToType is the type 12109 /// we're trying to resolve to. For example: 12110 /// 12111 /// @code 12112 /// int f(double); 12113 /// int f(int); 12114 /// 12115 /// int (*pfd)(double) = f; // selects f(double) 12116 /// @endcode 12117 /// 12118 /// This routine returns the resulting FunctionDecl if it could be 12119 /// resolved, and NULL otherwise. When @p Complain is true, this 12120 /// routine will emit diagnostics if there is an error. 12121 FunctionDecl * 12122 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12123 QualType TargetType, 12124 bool Complain, 12125 DeclAccessPair &FoundResult, 12126 bool *pHadMultipleCandidates) { 12127 assert(AddressOfExpr->getType() == Context.OverloadTy); 12128 12129 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12130 Complain); 12131 int NumMatches = Resolver.getNumMatches(); 12132 FunctionDecl *Fn = nullptr; 12133 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12134 if (NumMatches == 0 && ShouldComplain) { 12135 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12136 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12137 else 12138 Resolver.ComplainNoMatchesFound(); 12139 } 12140 else if (NumMatches > 1 && ShouldComplain) 12141 Resolver.ComplainMultipleMatchesFound(); 12142 else if (NumMatches == 1) { 12143 Fn = Resolver.getMatchingFunctionDecl(); 12144 assert(Fn); 12145 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12146 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12147 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12148 if (Complain) { 12149 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12150 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12151 else 12152 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12153 } 12154 } 12155 12156 if (pHadMultipleCandidates) 12157 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12158 return Fn; 12159 } 12160 12161 /// Given an expression that refers to an overloaded function, try to 12162 /// resolve that function to a single function that can have its address taken. 12163 /// This will modify `Pair` iff it returns non-null. 12164 /// 12165 /// This routine can only succeed if from all of the candidates in the overload 12166 /// set for SrcExpr that can have their addresses taken, there is one candidate 12167 /// that is more constrained than the rest. 12168 FunctionDecl * 12169 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12170 OverloadExpr::FindResult R = OverloadExpr::find(E); 12171 OverloadExpr *Ovl = R.Expression; 12172 bool IsResultAmbiguous = false; 12173 FunctionDecl *Result = nullptr; 12174 DeclAccessPair DAP; 12175 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12176 12177 auto CheckMoreConstrained = 12178 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12179 SmallVector<const Expr *, 1> AC1, AC2; 12180 FD1->getAssociatedConstraints(AC1); 12181 FD2->getAssociatedConstraints(AC2); 12182 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12183 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12184 return None; 12185 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12186 return None; 12187 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12188 return None; 12189 return AtLeastAsConstrained1; 12190 }; 12191 12192 // Don't use the AddressOfResolver because we're specifically looking for 12193 // cases where we have one overload candidate that lacks 12194 // enable_if/pass_object_size/... 12195 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12196 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12197 if (!FD) 12198 return nullptr; 12199 12200 if (!checkAddressOfFunctionIsAvailable(FD)) 12201 continue; 12202 12203 // We have more than one result - see if it is more constrained than the 12204 // previous one. 12205 if (Result) { 12206 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12207 Result); 12208 if (!MoreConstrainedThanPrevious) { 12209 IsResultAmbiguous = true; 12210 AmbiguousDecls.push_back(FD); 12211 continue; 12212 } 12213 if (!*MoreConstrainedThanPrevious) 12214 continue; 12215 // FD is more constrained - replace Result with it. 12216 } 12217 IsResultAmbiguous = false; 12218 DAP = I.getPair(); 12219 Result = FD; 12220 } 12221 12222 if (IsResultAmbiguous) 12223 return nullptr; 12224 12225 if (Result) { 12226 SmallVector<const Expr *, 1> ResultAC; 12227 // We skipped over some ambiguous declarations which might be ambiguous with 12228 // the selected result. 12229 for (FunctionDecl *Skipped : AmbiguousDecls) 12230 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12231 return nullptr; 12232 Pair = DAP; 12233 } 12234 return Result; 12235 } 12236 12237 /// Given an overloaded function, tries to turn it into a non-overloaded 12238 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12239 /// will perform access checks, diagnose the use of the resultant decl, and, if 12240 /// requested, potentially perform a function-to-pointer decay. 12241 /// 12242 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12243 /// Otherwise, returns true. This may emit diagnostics and return true. 12244 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12245 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12246 Expr *E = SrcExpr.get(); 12247 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12248 12249 DeclAccessPair DAP; 12250 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12251 if (!Found || Found->isCPUDispatchMultiVersion() || 12252 Found->isCPUSpecificMultiVersion()) 12253 return false; 12254 12255 // Emitting multiple diagnostics for a function that is both inaccessible and 12256 // unavailable is consistent with our behavior elsewhere. So, always check 12257 // for both. 12258 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12259 CheckAddressOfMemberAccess(E, DAP); 12260 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12261 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12262 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12263 else 12264 SrcExpr = Fixed; 12265 return true; 12266 } 12267 12268 /// Given an expression that refers to an overloaded function, try to 12269 /// resolve that overloaded function expression down to a single function. 12270 /// 12271 /// This routine can only resolve template-ids that refer to a single function 12272 /// template, where that template-id refers to a single template whose template 12273 /// arguments are either provided by the template-id or have defaults, 12274 /// as described in C++0x [temp.arg.explicit]p3. 12275 /// 12276 /// If no template-ids are found, no diagnostics are emitted and NULL is 12277 /// returned. 12278 FunctionDecl * 12279 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12280 bool Complain, 12281 DeclAccessPair *FoundResult) { 12282 // C++ [over.over]p1: 12283 // [...] [Note: any redundant set of parentheses surrounding the 12284 // overloaded function name is ignored (5.1). ] 12285 // C++ [over.over]p1: 12286 // [...] The overloaded function name can be preceded by the & 12287 // operator. 12288 12289 // If we didn't actually find any template-ids, we're done. 12290 if (!ovl->hasExplicitTemplateArgs()) 12291 return nullptr; 12292 12293 TemplateArgumentListInfo ExplicitTemplateArgs; 12294 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12295 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12296 12297 // Look through all of the overloaded functions, searching for one 12298 // whose type matches exactly. 12299 FunctionDecl *Matched = nullptr; 12300 for (UnresolvedSetIterator I = ovl->decls_begin(), 12301 E = ovl->decls_end(); I != E; ++I) { 12302 // C++0x [temp.arg.explicit]p3: 12303 // [...] In contexts where deduction is done and fails, or in contexts 12304 // where deduction is not done, if a template argument list is 12305 // specified and it, along with any default template arguments, 12306 // identifies a single function template specialization, then the 12307 // template-id is an lvalue for the function template specialization. 12308 FunctionTemplateDecl *FunctionTemplate 12309 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12310 12311 // C++ [over.over]p2: 12312 // If the name is a function template, template argument deduction is 12313 // done (14.8.2.2), and if the argument deduction succeeds, the 12314 // resulting template argument list is used to generate a single 12315 // function template specialization, which is added to the set of 12316 // overloaded functions considered. 12317 FunctionDecl *Specialization = nullptr; 12318 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12319 if (TemplateDeductionResult Result 12320 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12321 Specialization, Info, 12322 /*IsAddressOfFunction*/true)) { 12323 // Make a note of the failed deduction for diagnostics. 12324 // TODO: Actually use the failed-deduction info? 12325 FailedCandidates.addCandidate() 12326 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12327 MakeDeductionFailureInfo(Context, Result, Info)); 12328 continue; 12329 } 12330 12331 assert(Specialization && "no specialization and no error?"); 12332 12333 // Multiple matches; we can't resolve to a single declaration. 12334 if (Matched) { 12335 if (Complain) { 12336 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12337 << ovl->getName(); 12338 NoteAllOverloadCandidates(ovl); 12339 } 12340 return nullptr; 12341 } 12342 12343 Matched = Specialization; 12344 if (FoundResult) *FoundResult = I.getPair(); 12345 } 12346 12347 if (Matched && 12348 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12349 return nullptr; 12350 12351 return Matched; 12352 } 12353 12354 // Resolve and fix an overloaded expression that can be resolved 12355 // because it identifies a single function template specialization. 12356 // 12357 // Last three arguments should only be supplied if Complain = true 12358 // 12359 // Return true if it was logically possible to so resolve the 12360 // expression, regardless of whether or not it succeeded. Always 12361 // returns true if 'complain' is set. 12362 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12363 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12364 bool complain, SourceRange OpRangeForComplaining, 12365 QualType DestTypeForComplaining, 12366 unsigned DiagIDForComplaining) { 12367 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12368 12369 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12370 12371 DeclAccessPair found; 12372 ExprResult SingleFunctionExpression; 12373 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12374 ovl.Expression, /*complain*/ false, &found)) { 12375 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12376 SrcExpr = ExprError(); 12377 return true; 12378 } 12379 12380 // It is only correct to resolve to an instance method if we're 12381 // resolving a form that's permitted to be a pointer to member. 12382 // Otherwise we'll end up making a bound member expression, which 12383 // is illegal in all the contexts we resolve like this. 12384 if (!ovl.HasFormOfMemberPointer && 12385 isa<CXXMethodDecl>(fn) && 12386 cast<CXXMethodDecl>(fn)->isInstance()) { 12387 if (!complain) return false; 12388 12389 Diag(ovl.Expression->getExprLoc(), 12390 diag::err_bound_member_function) 12391 << 0 << ovl.Expression->getSourceRange(); 12392 12393 // TODO: I believe we only end up here if there's a mix of 12394 // static and non-static candidates (otherwise the expression 12395 // would have 'bound member' type, not 'overload' type). 12396 // Ideally we would note which candidate was chosen and why 12397 // the static candidates were rejected. 12398 SrcExpr = ExprError(); 12399 return true; 12400 } 12401 12402 // Fix the expression to refer to 'fn'. 12403 SingleFunctionExpression = 12404 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12405 12406 // If desired, do function-to-pointer decay. 12407 if (doFunctionPointerConverion) { 12408 SingleFunctionExpression = 12409 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12410 if (SingleFunctionExpression.isInvalid()) { 12411 SrcExpr = ExprError(); 12412 return true; 12413 } 12414 } 12415 } 12416 12417 if (!SingleFunctionExpression.isUsable()) { 12418 if (complain) { 12419 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12420 << ovl.Expression->getName() 12421 << DestTypeForComplaining 12422 << OpRangeForComplaining 12423 << ovl.Expression->getQualifierLoc().getSourceRange(); 12424 NoteAllOverloadCandidates(SrcExpr.get()); 12425 12426 SrcExpr = ExprError(); 12427 return true; 12428 } 12429 12430 return false; 12431 } 12432 12433 SrcExpr = SingleFunctionExpression; 12434 return true; 12435 } 12436 12437 /// Add a single candidate to the overload set. 12438 static void AddOverloadedCallCandidate(Sema &S, 12439 DeclAccessPair FoundDecl, 12440 TemplateArgumentListInfo *ExplicitTemplateArgs, 12441 ArrayRef<Expr *> Args, 12442 OverloadCandidateSet &CandidateSet, 12443 bool PartialOverloading, 12444 bool KnownValid) { 12445 NamedDecl *Callee = FoundDecl.getDecl(); 12446 if (isa<UsingShadowDecl>(Callee)) 12447 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12448 12449 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12450 if (ExplicitTemplateArgs) { 12451 assert(!KnownValid && "Explicit template arguments?"); 12452 return; 12453 } 12454 // Prevent ill-formed function decls to be added as overload candidates. 12455 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12456 return; 12457 12458 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12459 /*SuppressUserConversions=*/false, 12460 PartialOverloading); 12461 return; 12462 } 12463 12464 if (FunctionTemplateDecl *FuncTemplate 12465 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12466 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12467 ExplicitTemplateArgs, Args, CandidateSet, 12468 /*SuppressUserConversions=*/false, 12469 PartialOverloading); 12470 return; 12471 } 12472 12473 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12474 } 12475 12476 /// Add the overload candidates named by callee and/or found by argument 12477 /// dependent lookup to the given overload set. 12478 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12479 ArrayRef<Expr *> Args, 12480 OverloadCandidateSet &CandidateSet, 12481 bool PartialOverloading) { 12482 12483 #ifndef NDEBUG 12484 // Verify that ArgumentDependentLookup is consistent with the rules 12485 // in C++0x [basic.lookup.argdep]p3: 12486 // 12487 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12488 // and let Y be the lookup set produced by argument dependent 12489 // lookup (defined as follows). If X contains 12490 // 12491 // -- a declaration of a class member, or 12492 // 12493 // -- a block-scope function declaration that is not a 12494 // using-declaration, or 12495 // 12496 // -- a declaration that is neither a function or a function 12497 // template 12498 // 12499 // then Y is empty. 12500 12501 if (ULE->requiresADL()) { 12502 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12503 E = ULE->decls_end(); I != E; ++I) { 12504 assert(!(*I)->getDeclContext()->isRecord()); 12505 assert(isa<UsingShadowDecl>(*I) || 12506 !(*I)->getDeclContext()->isFunctionOrMethod()); 12507 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12508 } 12509 } 12510 #endif 12511 12512 // It would be nice to avoid this copy. 12513 TemplateArgumentListInfo TABuffer; 12514 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12515 if (ULE->hasExplicitTemplateArgs()) { 12516 ULE->copyTemplateArgumentsInto(TABuffer); 12517 ExplicitTemplateArgs = &TABuffer; 12518 } 12519 12520 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12521 E = ULE->decls_end(); I != E; ++I) 12522 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12523 CandidateSet, PartialOverloading, 12524 /*KnownValid*/ true); 12525 12526 if (ULE->requiresADL()) 12527 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12528 Args, ExplicitTemplateArgs, 12529 CandidateSet, PartialOverloading); 12530 } 12531 12532 /// Determine whether a declaration with the specified name could be moved into 12533 /// a different namespace. 12534 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12535 switch (Name.getCXXOverloadedOperator()) { 12536 case OO_New: case OO_Array_New: 12537 case OO_Delete: case OO_Array_Delete: 12538 return false; 12539 12540 default: 12541 return true; 12542 } 12543 } 12544 12545 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12546 /// template, where the non-dependent name was declared after the template 12547 /// was defined. This is common in code written for a compilers which do not 12548 /// correctly implement two-stage name lookup. 12549 /// 12550 /// Returns true if a viable candidate was found and a diagnostic was issued. 12551 static bool 12552 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12553 const CXXScopeSpec &SS, LookupResult &R, 12554 OverloadCandidateSet::CandidateSetKind CSK, 12555 TemplateArgumentListInfo *ExplicitTemplateArgs, 12556 ArrayRef<Expr *> Args, 12557 bool *DoDiagnoseEmptyLookup = nullptr) { 12558 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12559 return false; 12560 12561 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12562 if (DC->isTransparentContext()) 12563 continue; 12564 12565 SemaRef.LookupQualifiedName(R, DC); 12566 12567 if (!R.empty()) { 12568 R.suppressDiagnostics(); 12569 12570 if (isa<CXXRecordDecl>(DC)) { 12571 // Don't diagnose names we find in classes; we get much better 12572 // diagnostics for these from DiagnoseEmptyLookup. 12573 R.clear(); 12574 if (DoDiagnoseEmptyLookup) 12575 *DoDiagnoseEmptyLookup = true; 12576 return false; 12577 } 12578 12579 OverloadCandidateSet Candidates(FnLoc, CSK); 12580 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12581 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12582 ExplicitTemplateArgs, Args, 12583 Candidates, false, /*KnownValid*/ false); 12584 12585 OverloadCandidateSet::iterator Best; 12586 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12587 // No viable functions. Don't bother the user with notes for functions 12588 // which don't work and shouldn't be found anyway. 12589 R.clear(); 12590 return false; 12591 } 12592 12593 // Find the namespaces where ADL would have looked, and suggest 12594 // declaring the function there instead. 12595 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12596 Sema::AssociatedClassSet AssociatedClasses; 12597 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12598 AssociatedNamespaces, 12599 AssociatedClasses); 12600 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12601 if (canBeDeclaredInNamespace(R.getLookupName())) { 12602 DeclContext *Std = SemaRef.getStdNamespace(); 12603 for (Sema::AssociatedNamespaceSet::iterator 12604 it = AssociatedNamespaces.begin(), 12605 end = AssociatedNamespaces.end(); it != end; ++it) { 12606 // Never suggest declaring a function within namespace 'std'. 12607 if (Std && Std->Encloses(*it)) 12608 continue; 12609 12610 // Never suggest declaring a function within a namespace with a 12611 // reserved name, like __gnu_cxx. 12612 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12613 if (NS && 12614 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12615 continue; 12616 12617 SuggestedNamespaces.insert(*it); 12618 } 12619 } 12620 12621 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12622 << R.getLookupName(); 12623 if (SuggestedNamespaces.empty()) { 12624 SemaRef.Diag(Best->Function->getLocation(), 12625 diag::note_not_found_by_two_phase_lookup) 12626 << R.getLookupName() << 0; 12627 } else if (SuggestedNamespaces.size() == 1) { 12628 SemaRef.Diag(Best->Function->getLocation(), 12629 diag::note_not_found_by_two_phase_lookup) 12630 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12631 } else { 12632 // FIXME: It would be useful to list the associated namespaces here, 12633 // but the diagnostics infrastructure doesn't provide a way to produce 12634 // a localized representation of a list of items. 12635 SemaRef.Diag(Best->Function->getLocation(), 12636 diag::note_not_found_by_two_phase_lookup) 12637 << R.getLookupName() << 2; 12638 } 12639 12640 // Try to recover by calling this function. 12641 return true; 12642 } 12643 12644 R.clear(); 12645 } 12646 12647 return false; 12648 } 12649 12650 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12651 /// template, where the non-dependent operator was declared after the template 12652 /// was defined. 12653 /// 12654 /// Returns true if a viable candidate was found and a diagnostic was issued. 12655 static bool 12656 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12657 SourceLocation OpLoc, 12658 ArrayRef<Expr *> Args) { 12659 DeclarationName OpName = 12660 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12661 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12662 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12663 OverloadCandidateSet::CSK_Operator, 12664 /*ExplicitTemplateArgs=*/nullptr, Args); 12665 } 12666 12667 namespace { 12668 class BuildRecoveryCallExprRAII { 12669 Sema &SemaRef; 12670 public: 12671 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12672 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12673 SemaRef.IsBuildingRecoveryCallExpr = true; 12674 } 12675 12676 ~BuildRecoveryCallExprRAII() { 12677 SemaRef.IsBuildingRecoveryCallExpr = false; 12678 } 12679 }; 12680 12681 } 12682 12683 /// Attempts to recover from a call where no functions were found. 12684 /// 12685 /// Returns true if new candidates were found. 12686 static ExprResult 12687 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12688 UnresolvedLookupExpr *ULE, 12689 SourceLocation LParenLoc, 12690 MutableArrayRef<Expr *> Args, 12691 SourceLocation RParenLoc, 12692 bool EmptyLookup, bool AllowTypoCorrection) { 12693 // Do not try to recover if it is already building a recovery call. 12694 // This stops infinite loops for template instantiations like 12695 // 12696 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12697 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12698 // 12699 if (SemaRef.IsBuildingRecoveryCallExpr) 12700 return ExprError(); 12701 BuildRecoveryCallExprRAII RCE(SemaRef); 12702 12703 CXXScopeSpec SS; 12704 SS.Adopt(ULE->getQualifierLoc()); 12705 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12706 12707 TemplateArgumentListInfo TABuffer; 12708 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12709 if (ULE->hasExplicitTemplateArgs()) { 12710 ULE->copyTemplateArgumentsInto(TABuffer); 12711 ExplicitTemplateArgs = &TABuffer; 12712 } 12713 12714 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12715 Sema::LookupOrdinaryName); 12716 bool DoDiagnoseEmptyLookup = EmptyLookup; 12717 if (!DiagnoseTwoPhaseLookup( 12718 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12719 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12720 NoTypoCorrectionCCC NoTypoValidator{}; 12721 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12722 ExplicitTemplateArgs != nullptr, 12723 dyn_cast<MemberExpr>(Fn)); 12724 CorrectionCandidateCallback &Validator = 12725 AllowTypoCorrection 12726 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12727 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12728 if (!DoDiagnoseEmptyLookup || 12729 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12730 Args)) 12731 return ExprError(); 12732 } 12733 12734 assert(!R.empty() && "lookup results empty despite recovery"); 12735 12736 // If recovery created an ambiguity, just bail out. 12737 if (R.isAmbiguous()) { 12738 R.suppressDiagnostics(); 12739 return ExprError(); 12740 } 12741 12742 // Build an implicit member call if appropriate. Just drop the 12743 // casts and such from the call, we don't really care. 12744 ExprResult NewFn = ExprError(); 12745 if ((*R.begin())->isCXXClassMember()) 12746 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12747 ExplicitTemplateArgs, S); 12748 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12749 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12750 ExplicitTemplateArgs); 12751 else 12752 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12753 12754 if (NewFn.isInvalid()) 12755 return ExprError(); 12756 12757 // This shouldn't cause an infinite loop because we're giving it 12758 // an expression with viable lookup results, which should never 12759 // end up here. 12760 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12761 MultiExprArg(Args.data(), Args.size()), 12762 RParenLoc); 12763 } 12764 12765 /// Constructs and populates an OverloadedCandidateSet from 12766 /// the given function. 12767 /// \returns true when an the ExprResult output parameter has been set. 12768 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12769 UnresolvedLookupExpr *ULE, 12770 MultiExprArg Args, 12771 SourceLocation RParenLoc, 12772 OverloadCandidateSet *CandidateSet, 12773 ExprResult *Result) { 12774 #ifndef NDEBUG 12775 if (ULE->requiresADL()) { 12776 // To do ADL, we must have found an unqualified name. 12777 assert(!ULE->getQualifier() && "qualified name with ADL"); 12778 12779 // We don't perform ADL for implicit declarations of builtins. 12780 // Verify that this was correctly set up. 12781 FunctionDecl *F; 12782 if (ULE->decls_begin() != ULE->decls_end() && 12783 ULE->decls_begin() + 1 == ULE->decls_end() && 12784 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12785 F->getBuiltinID() && F->isImplicit()) 12786 llvm_unreachable("performing ADL for builtin"); 12787 12788 // We don't perform ADL in C. 12789 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12790 } 12791 #endif 12792 12793 UnbridgedCastsSet UnbridgedCasts; 12794 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12795 *Result = ExprError(); 12796 return true; 12797 } 12798 12799 // Add the functions denoted by the callee to the set of candidate 12800 // functions, including those from argument-dependent lookup. 12801 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12802 12803 if (getLangOpts().MSVCCompat && 12804 CurContext->isDependentContext() && !isSFINAEContext() && 12805 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12806 12807 OverloadCandidateSet::iterator Best; 12808 if (CandidateSet->empty() || 12809 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12810 OR_No_Viable_Function) { 12811 // In Microsoft mode, if we are inside a template class member function 12812 // then create a type dependent CallExpr. The goal is to postpone name 12813 // lookup to instantiation time to be able to search into type dependent 12814 // base classes. 12815 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12816 VK_RValue, RParenLoc); 12817 CE->markDependentForPostponedNameLookup(); 12818 *Result = CE; 12819 return true; 12820 } 12821 } 12822 12823 if (CandidateSet->empty()) 12824 return false; 12825 12826 UnbridgedCasts.restore(); 12827 return false; 12828 } 12829 12830 // Guess at what the return type for an unresolvable overload should be. 12831 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12832 OverloadCandidateSet::iterator *Best) { 12833 llvm::Optional<QualType> Result; 12834 // Adjust Type after seeing a candidate. 12835 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12836 if (!Candidate.Function) 12837 return; 12838 QualType T = Candidate.Function->getCallResultType(); 12839 if (T.isNull()) 12840 return; 12841 if (!Result) 12842 Result = T; 12843 else if (Result != T) 12844 Result = QualType(); 12845 }; 12846 12847 // Look for an unambiguous type from a progressively larger subset. 12848 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12849 // 12850 // First, consider only the best candidate. 12851 if (Best && *Best != CS.end()) 12852 ConsiderCandidate(**Best); 12853 // Next, consider only viable candidates. 12854 if (!Result) 12855 for (const auto &C : CS) 12856 if (C.Viable) 12857 ConsiderCandidate(C); 12858 // Finally, consider all candidates. 12859 if (!Result) 12860 for (const auto &C : CS) 12861 ConsiderCandidate(C); 12862 12863 return Result.getValueOr(QualType()); 12864 } 12865 12866 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12867 /// the completed call expression. If overload resolution fails, emits 12868 /// diagnostics and returns ExprError() 12869 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12870 UnresolvedLookupExpr *ULE, 12871 SourceLocation LParenLoc, 12872 MultiExprArg Args, 12873 SourceLocation RParenLoc, 12874 Expr *ExecConfig, 12875 OverloadCandidateSet *CandidateSet, 12876 OverloadCandidateSet::iterator *Best, 12877 OverloadingResult OverloadResult, 12878 bool AllowTypoCorrection) { 12879 if (CandidateSet->empty()) 12880 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12881 RParenLoc, /*EmptyLookup=*/true, 12882 AllowTypoCorrection); 12883 12884 switch (OverloadResult) { 12885 case OR_Success: { 12886 FunctionDecl *FDecl = (*Best)->Function; 12887 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12888 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12889 return ExprError(); 12890 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12891 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12892 ExecConfig, /*IsExecConfig=*/false, 12893 (*Best)->IsADLCandidate); 12894 } 12895 12896 case OR_No_Viable_Function: { 12897 // Try to recover by looking for viable functions which the user might 12898 // have meant to call. 12899 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12900 Args, RParenLoc, 12901 /*EmptyLookup=*/false, 12902 AllowTypoCorrection); 12903 if (!Recovery.isInvalid()) 12904 return Recovery; 12905 12906 // If the user passes in a function that we can't take the address of, we 12907 // generally end up emitting really bad error messages. Here, we attempt to 12908 // emit better ones. 12909 for (const Expr *Arg : Args) { 12910 if (!Arg->getType()->isFunctionType()) 12911 continue; 12912 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12913 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12914 if (FD && 12915 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12916 Arg->getExprLoc())) 12917 return ExprError(); 12918 } 12919 } 12920 12921 CandidateSet->NoteCandidates( 12922 PartialDiagnosticAt( 12923 Fn->getBeginLoc(), 12924 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12925 << ULE->getName() << Fn->getSourceRange()), 12926 SemaRef, OCD_AllCandidates, Args); 12927 break; 12928 } 12929 12930 case OR_Ambiguous: 12931 CandidateSet->NoteCandidates( 12932 PartialDiagnosticAt(Fn->getBeginLoc(), 12933 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12934 << ULE->getName() << Fn->getSourceRange()), 12935 SemaRef, OCD_AmbiguousCandidates, Args); 12936 break; 12937 12938 case OR_Deleted: { 12939 CandidateSet->NoteCandidates( 12940 PartialDiagnosticAt(Fn->getBeginLoc(), 12941 SemaRef.PDiag(diag::err_ovl_deleted_call) 12942 << ULE->getName() << Fn->getSourceRange()), 12943 SemaRef, OCD_AllCandidates, Args); 12944 12945 // We emitted an error for the unavailable/deleted function call but keep 12946 // the call in the AST. 12947 FunctionDecl *FDecl = (*Best)->Function; 12948 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12949 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12950 ExecConfig, /*IsExecConfig=*/false, 12951 (*Best)->IsADLCandidate); 12952 } 12953 } 12954 12955 // Overload resolution failed, try to recover. 12956 SmallVector<Expr *, 8> SubExprs = {Fn}; 12957 SubExprs.append(Args.begin(), Args.end()); 12958 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 12959 chooseRecoveryType(*CandidateSet, Best)); 12960 } 12961 12962 static void markUnaddressableCandidatesUnviable(Sema &S, 12963 OverloadCandidateSet &CS) { 12964 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12965 if (I->Viable && 12966 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12967 I->Viable = false; 12968 I->FailureKind = ovl_fail_addr_not_available; 12969 } 12970 } 12971 } 12972 12973 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12974 /// (which eventually refers to the declaration Func) and the call 12975 /// arguments Args/NumArgs, attempt to resolve the function call down 12976 /// to a specific function. If overload resolution succeeds, returns 12977 /// the call expression produced by overload resolution. 12978 /// Otherwise, emits diagnostics and returns ExprError. 12979 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12980 UnresolvedLookupExpr *ULE, 12981 SourceLocation LParenLoc, 12982 MultiExprArg Args, 12983 SourceLocation RParenLoc, 12984 Expr *ExecConfig, 12985 bool AllowTypoCorrection, 12986 bool CalleesAddressIsTaken) { 12987 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12988 OverloadCandidateSet::CSK_Normal); 12989 ExprResult result; 12990 12991 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12992 &result)) 12993 return result; 12994 12995 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12996 // functions that aren't addressible are considered unviable. 12997 if (CalleesAddressIsTaken) 12998 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12999 13000 OverloadCandidateSet::iterator Best; 13001 OverloadingResult OverloadResult = 13002 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13003 13004 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13005 ExecConfig, &CandidateSet, &Best, 13006 OverloadResult, AllowTypoCorrection); 13007 } 13008 13009 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13010 return Functions.size() > 1 || 13011 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 13012 } 13013 13014 /// Create a unary operation that may resolve to an overloaded 13015 /// operator. 13016 /// 13017 /// \param OpLoc The location of the operator itself (e.g., '*'). 13018 /// 13019 /// \param Opc The UnaryOperatorKind that describes this operator. 13020 /// 13021 /// \param Fns The set of non-member functions that will be 13022 /// considered by overload resolution. The caller needs to build this 13023 /// set based on the context using, e.g., 13024 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13025 /// set should not contain any member functions; those will be added 13026 /// by CreateOverloadedUnaryOp(). 13027 /// 13028 /// \param Input The input argument. 13029 ExprResult 13030 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13031 const UnresolvedSetImpl &Fns, 13032 Expr *Input, bool PerformADL) { 13033 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13034 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13035 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13036 // TODO: provide better source location info. 13037 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13038 13039 if (checkPlaceholderForOverload(*this, Input)) 13040 return ExprError(); 13041 13042 Expr *Args[2] = { Input, nullptr }; 13043 unsigned NumArgs = 1; 13044 13045 // For post-increment and post-decrement, add the implicit '0' as 13046 // the second argument, so that we know this is a post-increment or 13047 // post-decrement. 13048 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13049 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13050 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13051 SourceLocation()); 13052 NumArgs = 2; 13053 } 13054 13055 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13056 13057 if (Input->isTypeDependent()) { 13058 if (Fns.empty()) 13059 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13060 VK_RValue, OK_Ordinary, OpLoc, false, 13061 CurFPFeatures); 13062 13063 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13064 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13065 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13066 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13067 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 13068 Context.DependentTy, VK_RValue, OpLoc, 13069 CurFPFeatures); 13070 } 13071 13072 // Build an empty overload set. 13073 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13074 13075 // Add the candidates from the given function set. 13076 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13077 13078 // Add operator candidates that are member functions. 13079 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13080 13081 // Add candidates from ADL. 13082 if (PerformADL) { 13083 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13084 /*ExplicitTemplateArgs*/nullptr, 13085 CandidateSet); 13086 } 13087 13088 // Add builtin operator candidates. 13089 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13090 13091 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13092 13093 // Perform overload resolution. 13094 OverloadCandidateSet::iterator Best; 13095 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13096 case OR_Success: { 13097 // We found a built-in operator or an overloaded operator. 13098 FunctionDecl *FnDecl = Best->Function; 13099 13100 if (FnDecl) { 13101 Expr *Base = nullptr; 13102 // We matched an overloaded operator. Build a call to that 13103 // operator. 13104 13105 // Convert the arguments. 13106 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13107 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13108 13109 ExprResult InputRes = 13110 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13111 Best->FoundDecl, Method); 13112 if (InputRes.isInvalid()) 13113 return ExprError(); 13114 Base = Input = InputRes.get(); 13115 } else { 13116 // Convert the arguments. 13117 ExprResult InputInit 13118 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13119 Context, 13120 FnDecl->getParamDecl(0)), 13121 SourceLocation(), 13122 Input); 13123 if (InputInit.isInvalid()) 13124 return ExprError(); 13125 Input = InputInit.get(); 13126 } 13127 13128 // Build the actual expression node. 13129 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13130 Base, HadMultipleCandidates, 13131 OpLoc); 13132 if (FnExpr.isInvalid()) 13133 return ExprError(); 13134 13135 // Determine the result type. 13136 QualType ResultTy = FnDecl->getReturnType(); 13137 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13138 ResultTy = ResultTy.getNonLValueExprType(Context); 13139 13140 Args[0] = Input; 13141 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13142 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13143 CurFPFeatures, Best->IsADLCandidate); 13144 13145 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13146 return ExprError(); 13147 13148 if (CheckFunctionCall(FnDecl, TheCall, 13149 FnDecl->getType()->castAs<FunctionProtoType>())) 13150 return ExprError(); 13151 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13152 } else { 13153 // We matched a built-in operator. Convert the arguments, then 13154 // break out so that we will build the appropriate built-in 13155 // operator node. 13156 ExprResult InputRes = PerformImplicitConversion( 13157 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13158 CCK_ForBuiltinOverloadedOp); 13159 if (InputRes.isInvalid()) 13160 return ExprError(); 13161 Input = InputRes.get(); 13162 break; 13163 } 13164 } 13165 13166 case OR_No_Viable_Function: 13167 // This is an erroneous use of an operator which can be overloaded by 13168 // a non-member function. Check for non-member operators which were 13169 // defined too late to be candidates. 13170 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13171 // FIXME: Recover by calling the found function. 13172 return ExprError(); 13173 13174 // No viable function; fall through to handling this as a 13175 // built-in operator, which will produce an error message for us. 13176 break; 13177 13178 case OR_Ambiguous: 13179 CandidateSet.NoteCandidates( 13180 PartialDiagnosticAt(OpLoc, 13181 PDiag(diag::err_ovl_ambiguous_oper_unary) 13182 << UnaryOperator::getOpcodeStr(Opc) 13183 << Input->getType() << Input->getSourceRange()), 13184 *this, OCD_AmbiguousCandidates, ArgsArray, 13185 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13186 return ExprError(); 13187 13188 case OR_Deleted: 13189 CandidateSet.NoteCandidates( 13190 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13191 << UnaryOperator::getOpcodeStr(Opc) 13192 << Input->getSourceRange()), 13193 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13194 OpLoc); 13195 return ExprError(); 13196 } 13197 13198 // Either we found no viable overloaded operator or we matched a 13199 // built-in operator. In either case, fall through to trying to 13200 // build a built-in operation. 13201 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13202 } 13203 13204 /// Perform lookup for an overloaded binary operator. 13205 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13206 OverloadedOperatorKind Op, 13207 const UnresolvedSetImpl &Fns, 13208 ArrayRef<Expr *> Args, bool PerformADL) { 13209 SourceLocation OpLoc = CandidateSet.getLocation(); 13210 13211 OverloadedOperatorKind ExtraOp = 13212 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13213 ? getRewrittenOverloadedOperator(Op) 13214 : OO_None; 13215 13216 // Add the candidates from the given function set. This also adds the 13217 // rewritten candidates using these functions if necessary. 13218 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13219 13220 // Add operator candidates that are member functions. 13221 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13222 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13223 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13224 OverloadCandidateParamOrder::Reversed); 13225 13226 // In C++20, also add any rewritten member candidates. 13227 if (ExtraOp) { 13228 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13229 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13230 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13231 CandidateSet, 13232 OverloadCandidateParamOrder::Reversed); 13233 } 13234 13235 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13236 // performed for an assignment operator (nor for operator[] nor operator->, 13237 // which don't get here). 13238 if (Op != OO_Equal && PerformADL) { 13239 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13240 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13241 /*ExplicitTemplateArgs*/ nullptr, 13242 CandidateSet); 13243 if (ExtraOp) { 13244 DeclarationName ExtraOpName = 13245 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13246 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13247 /*ExplicitTemplateArgs*/ nullptr, 13248 CandidateSet); 13249 } 13250 } 13251 13252 // Add builtin operator candidates. 13253 // 13254 // FIXME: We don't add any rewritten candidates here. This is strictly 13255 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13256 // resulting in our selecting a rewritten builtin candidate. For example: 13257 // 13258 // enum class E { e }; 13259 // bool operator!=(E, E) requires false; 13260 // bool k = E::e != E::e; 13261 // 13262 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13263 // it seems unreasonable to consider rewritten builtin candidates. A core 13264 // issue has been filed proposing to removed this requirement. 13265 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13266 } 13267 13268 /// Create a binary operation that may resolve to an overloaded 13269 /// operator. 13270 /// 13271 /// \param OpLoc The location of the operator itself (e.g., '+'). 13272 /// 13273 /// \param Opc The BinaryOperatorKind that describes this operator. 13274 /// 13275 /// \param Fns The set of non-member functions that will be 13276 /// considered by overload resolution. The caller needs to build this 13277 /// set based on the context using, e.g., 13278 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13279 /// set should not contain any member functions; those will be added 13280 /// by CreateOverloadedBinOp(). 13281 /// 13282 /// \param LHS Left-hand argument. 13283 /// \param RHS Right-hand argument. 13284 /// \param PerformADL Whether to consider operator candidates found by ADL. 13285 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13286 /// C++20 operator rewrites. 13287 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13288 /// the function in question. Such a function is never a candidate in 13289 /// our overload resolution. This also enables synthesizing a three-way 13290 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13291 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13292 BinaryOperatorKind Opc, 13293 const UnresolvedSetImpl &Fns, Expr *LHS, 13294 Expr *RHS, bool PerformADL, 13295 bool AllowRewrittenCandidates, 13296 FunctionDecl *DefaultedFn) { 13297 Expr *Args[2] = { LHS, RHS }; 13298 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13299 13300 if (!getLangOpts().CPlusPlus20) 13301 AllowRewrittenCandidates = false; 13302 13303 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13304 13305 // If either side is type-dependent, create an appropriate dependent 13306 // expression. 13307 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13308 if (Fns.empty()) { 13309 // If there are no functions to store, just build a dependent 13310 // BinaryOperator or CompoundAssignment. 13311 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13312 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13313 Context.DependentTy, VK_RValue, 13314 OK_Ordinary, OpLoc, CurFPFeatures); 13315 return CompoundAssignOperator::Create( 13316 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13317 OK_Ordinary, OpLoc, CurFPFeatures, Context.DependentTy, 13318 Context.DependentTy); 13319 } 13320 13321 // FIXME: save results of ADL from here? 13322 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13323 // TODO: provide better source location info in DNLoc component. 13324 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13325 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13326 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13327 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13328 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13329 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13330 Context.DependentTy, VK_RValue, OpLoc, 13331 CurFPFeatures); 13332 } 13333 13334 // Always do placeholder-like conversions on the RHS. 13335 if (checkPlaceholderForOverload(*this, Args[1])) 13336 return ExprError(); 13337 13338 // Do placeholder-like conversion on the LHS; note that we should 13339 // not get here with a PseudoObject LHS. 13340 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13341 if (checkPlaceholderForOverload(*this, Args[0])) 13342 return ExprError(); 13343 13344 // If this is the assignment operator, we only perform overload resolution 13345 // if the left-hand side is a class or enumeration type. This is actually 13346 // a hack. The standard requires that we do overload resolution between the 13347 // various built-in candidates, but as DR507 points out, this can lead to 13348 // problems. So we do it this way, which pretty much follows what GCC does. 13349 // Note that we go the traditional code path for compound assignment forms. 13350 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13351 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13352 13353 // If this is the .* operator, which is not overloadable, just 13354 // create a built-in binary operator. 13355 if (Opc == BO_PtrMemD) 13356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13357 13358 // Build the overload set. 13359 OverloadCandidateSet CandidateSet( 13360 OpLoc, OverloadCandidateSet::CSK_Operator, 13361 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13362 if (DefaultedFn) 13363 CandidateSet.exclude(DefaultedFn); 13364 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13365 13366 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13367 13368 // Perform overload resolution. 13369 OverloadCandidateSet::iterator Best; 13370 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13371 case OR_Success: { 13372 // We found a built-in operator or an overloaded operator. 13373 FunctionDecl *FnDecl = Best->Function; 13374 13375 bool IsReversed = Best->isReversed(); 13376 if (IsReversed) 13377 std::swap(Args[0], Args[1]); 13378 13379 if (FnDecl) { 13380 Expr *Base = nullptr; 13381 // We matched an overloaded operator. Build a call to that 13382 // operator. 13383 13384 OverloadedOperatorKind ChosenOp = 13385 FnDecl->getDeclName().getCXXOverloadedOperator(); 13386 13387 // C++2a [over.match.oper]p9: 13388 // If a rewritten operator== candidate is selected by overload 13389 // resolution for an operator@, its return type shall be cv bool 13390 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13391 !FnDecl->getReturnType()->isBooleanType()) { 13392 bool IsExtension = 13393 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13394 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13395 : diag::err_ovl_rewrite_equalequal_not_bool) 13396 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13397 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13398 Diag(FnDecl->getLocation(), diag::note_declared_at); 13399 if (!IsExtension) 13400 return ExprError(); 13401 } 13402 13403 if (AllowRewrittenCandidates && !IsReversed && 13404 CandidateSet.getRewriteInfo().isReversible()) { 13405 // We could have reversed this operator, but didn't. Check if some 13406 // reversed form was a viable candidate, and if so, if it had a 13407 // better conversion for either parameter. If so, this call is 13408 // formally ambiguous, and allowing it is an extension. 13409 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13410 for (OverloadCandidate &Cand : CandidateSet) { 13411 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13412 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13413 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13414 if (CompareImplicitConversionSequences( 13415 *this, OpLoc, Cand.Conversions[ArgIdx], 13416 Best->Conversions[ArgIdx]) == 13417 ImplicitConversionSequence::Better) { 13418 AmbiguousWith.push_back(Cand.Function); 13419 break; 13420 } 13421 } 13422 } 13423 } 13424 13425 if (!AmbiguousWith.empty()) { 13426 bool AmbiguousWithSelf = 13427 AmbiguousWith.size() == 1 && 13428 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13429 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13430 << BinaryOperator::getOpcodeStr(Opc) 13431 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13432 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13433 if (AmbiguousWithSelf) { 13434 Diag(FnDecl->getLocation(), 13435 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13436 } else { 13437 Diag(FnDecl->getLocation(), 13438 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13439 for (auto *F : AmbiguousWith) 13440 Diag(F->getLocation(), 13441 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13442 } 13443 } 13444 } 13445 13446 // Convert the arguments. 13447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13448 // Best->Access is only meaningful for class members. 13449 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13450 13451 ExprResult Arg1 = 13452 PerformCopyInitialization( 13453 InitializedEntity::InitializeParameter(Context, 13454 FnDecl->getParamDecl(0)), 13455 SourceLocation(), Args[1]); 13456 if (Arg1.isInvalid()) 13457 return ExprError(); 13458 13459 ExprResult Arg0 = 13460 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13461 Best->FoundDecl, Method); 13462 if (Arg0.isInvalid()) 13463 return ExprError(); 13464 Base = Args[0] = Arg0.getAs<Expr>(); 13465 Args[1] = RHS = Arg1.getAs<Expr>(); 13466 } else { 13467 // Convert the arguments. 13468 ExprResult Arg0 = PerformCopyInitialization( 13469 InitializedEntity::InitializeParameter(Context, 13470 FnDecl->getParamDecl(0)), 13471 SourceLocation(), Args[0]); 13472 if (Arg0.isInvalid()) 13473 return ExprError(); 13474 13475 ExprResult Arg1 = 13476 PerformCopyInitialization( 13477 InitializedEntity::InitializeParameter(Context, 13478 FnDecl->getParamDecl(1)), 13479 SourceLocation(), Args[1]); 13480 if (Arg1.isInvalid()) 13481 return ExprError(); 13482 Args[0] = LHS = Arg0.getAs<Expr>(); 13483 Args[1] = RHS = Arg1.getAs<Expr>(); 13484 } 13485 13486 // Build the actual expression node. 13487 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13488 Best->FoundDecl, Base, 13489 HadMultipleCandidates, OpLoc); 13490 if (FnExpr.isInvalid()) 13491 return ExprError(); 13492 13493 // Determine the result type. 13494 QualType ResultTy = FnDecl->getReturnType(); 13495 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13496 ResultTy = ResultTy.getNonLValueExprType(Context); 13497 13498 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13499 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13500 CurFPFeatures, Best->IsADLCandidate); 13501 13502 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13503 FnDecl)) 13504 return ExprError(); 13505 13506 ArrayRef<const Expr *> ArgsArray(Args, 2); 13507 const Expr *ImplicitThis = nullptr; 13508 // Cut off the implicit 'this'. 13509 if (isa<CXXMethodDecl>(FnDecl)) { 13510 ImplicitThis = ArgsArray[0]; 13511 ArgsArray = ArgsArray.slice(1); 13512 } 13513 13514 // Check for a self move. 13515 if (Op == OO_Equal) 13516 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13517 13518 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13519 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13520 VariadicDoesNotApply); 13521 13522 ExprResult R = MaybeBindToTemporary(TheCall); 13523 if (R.isInvalid()) 13524 return ExprError(); 13525 13526 // For a rewritten candidate, we've already reversed the arguments 13527 // if needed. Perform the rest of the rewrite now. 13528 if ((Best->RewriteKind & CRK_DifferentOperator) || 13529 (Op == OO_Spaceship && IsReversed)) { 13530 if (Op == OO_ExclaimEqual) { 13531 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13532 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13533 } else { 13534 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13535 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13536 Expr *ZeroLiteral = 13537 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13538 13539 Sema::CodeSynthesisContext Ctx; 13540 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13541 Ctx.Entity = FnDecl; 13542 pushCodeSynthesisContext(Ctx); 13543 13544 R = CreateOverloadedBinOp( 13545 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13546 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13547 /*AllowRewrittenCandidates=*/false); 13548 13549 popCodeSynthesisContext(); 13550 } 13551 if (R.isInvalid()) 13552 return ExprError(); 13553 } else { 13554 assert(ChosenOp == Op && "unexpected operator name"); 13555 } 13556 13557 // Make a note in the AST if we did any rewriting. 13558 if (Best->RewriteKind != CRK_None) 13559 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13560 13561 return CheckForImmediateInvocation(R, FnDecl); 13562 } else { 13563 // We matched a built-in operator. Convert the arguments, then 13564 // break out so that we will build the appropriate built-in 13565 // operator node. 13566 ExprResult ArgsRes0 = PerformImplicitConversion( 13567 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13568 AA_Passing, CCK_ForBuiltinOverloadedOp); 13569 if (ArgsRes0.isInvalid()) 13570 return ExprError(); 13571 Args[0] = ArgsRes0.get(); 13572 13573 ExprResult ArgsRes1 = PerformImplicitConversion( 13574 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13575 AA_Passing, CCK_ForBuiltinOverloadedOp); 13576 if (ArgsRes1.isInvalid()) 13577 return ExprError(); 13578 Args[1] = ArgsRes1.get(); 13579 break; 13580 } 13581 } 13582 13583 case OR_No_Viable_Function: { 13584 // C++ [over.match.oper]p9: 13585 // If the operator is the operator , [...] and there are no 13586 // viable functions, then the operator is assumed to be the 13587 // built-in operator and interpreted according to clause 5. 13588 if (Opc == BO_Comma) 13589 break; 13590 13591 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13592 // compare result using '==' and '<'. 13593 if (DefaultedFn && Opc == BO_Cmp) { 13594 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13595 Args[1], DefaultedFn); 13596 if (E.isInvalid() || E.isUsable()) 13597 return E; 13598 } 13599 13600 // For class as left operand for assignment or compound assignment 13601 // operator do not fall through to handling in built-in, but report that 13602 // no overloaded assignment operator found 13603 ExprResult Result = ExprError(); 13604 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13605 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13606 Args, OpLoc); 13607 if (Args[0]->getType()->isRecordType() && 13608 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13609 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13610 << BinaryOperator::getOpcodeStr(Opc) 13611 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13612 if (Args[0]->getType()->isIncompleteType()) { 13613 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13614 << Args[0]->getType() 13615 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13616 } 13617 } else { 13618 // This is an erroneous use of an operator which can be overloaded by 13619 // a non-member function. Check for non-member operators which were 13620 // defined too late to be candidates. 13621 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13622 // FIXME: Recover by calling the found function. 13623 return ExprError(); 13624 13625 // No viable function; try to create a built-in operation, which will 13626 // produce an error. Then, show the non-viable candidates. 13627 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13628 } 13629 assert(Result.isInvalid() && 13630 "C++ binary operator overloading is missing candidates!"); 13631 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13632 return Result; 13633 } 13634 13635 case OR_Ambiguous: 13636 CandidateSet.NoteCandidates( 13637 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13638 << BinaryOperator::getOpcodeStr(Opc) 13639 << Args[0]->getType() 13640 << Args[1]->getType() 13641 << Args[0]->getSourceRange() 13642 << Args[1]->getSourceRange()), 13643 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13644 OpLoc); 13645 return ExprError(); 13646 13647 case OR_Deleted: 13648 if (isImplicitlyDeleted(Best->Function)) { 13649 FunctionDecl *DeletedFD = Best->Function; 13650 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13651 if (DFK.isSpecialMember()) { 13652 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13653 << Args[0]->getType() << DFK.asSpecialMember(); 13654 } else { 13655 assert(DFK.isComparison()); 13656 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13657 << Args[0]->getType() << DeletedFD; 13658 } 13659 13660 // The user probably meant to call this special member. Just 13661 // explain why it's deleted. 13662 NoteDeletedFunction(DeletedFD); 13663 return ExprError(); 13664 } 13665 CandidateSet.NoteCandidates( 13666 PartialDiagnosticAt( 13667 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13668 << getOperatorSpelling(Best->Function->getDeclName() 13669 .getCXXOverloadedOperator()) 13670 << Args[0]->getSourceRange() 13671 << Args[1]->getSourceRange()), 13672 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13673 OpLoc); 13674 return ExprError(); 13675 } 13676 13677 // We matched a built-in operator; build it. 13678 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13679 } 13680 13681 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13682 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13683 FunctionDecl *DefaultedFn) { 13684 const ComparisonCategoryInfo *Info = 13685 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13686 // If we're not producing a known comparison category type, we can't 13687 // synthesize a three-way comparison. Let the caller diagnose this. 13688 if (!Info) 13689 return ExprResult((Expr*)nullptr); 13690 13691 // If we ever want to perform this synthesis more generally, we will need to 13692 // apply the temporary materialization conversion to the operands. 13693 assert(LHS->isGLValue() && RHS->isGLValue() && 13694 "cannot use prvalue expressions more than once"); 13695 Expr *OrigLHS = LHS; 13696 Expr *OrigRHS = RHS; 13697 13698 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13699 // each of them multiple times below. 13700 LHS = new (Context) 13701 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13702 LHS->getObjectKind(), LHS); 13703 RHS = new (Context) 13704 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13705 RHS->getObjectKind(), RHS); 13706 13707 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13708 DefaultedFn); 13709 if (Eq.isInvalid()) 13710 return ExprError(); 13711 13712 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13713 true, DefaultedFn); 13714 if (Less.isInvalid()) 13715 return ExprError(); 13716 13717 ExprResult Greater; 13718 if (Info->isPartial()) { 13719 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13720 DefaultedFn); 13721 if (Greater.isInvalid()) 13722 return ExprError(); 13723 } 13724 13725 // Form the list of comparisons we're going to perform. 13726 struct Comparison { 13727 ExprResult Cmp; 13728 ComparisonCategoryResult Result; 13729 } Comparisons[4] = 13730 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13731 : ComparisonCategoryResult::Equivalent}, 13732 {Less, ComparisonCategoryResult::Less}, 13733 {Greater, ComparisonCategoryResult::Greater}, 13734 {ExprResult(), ComparisonCategoryResult::Unordered}, 13735 }; 13736 13737 int I = Info->isPartial() ? 3 : 2; 13738 13739 // Combine the comparisons with suitable conditional expressions. 13740 ExprResult Result; 13741 for (; I >= 0; --I) { 13742 // Build a reference to the comparison category constant. 13743 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13744 // FIXME: Missing a constant for a comparison category. Diagnose this? 13745 if (!VI) 13746 return ExprResult((Expr*)nullptr); 13747 ExprResult ThisResult = 13748 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13749 if (ThisResult.isInvalid()) 13750 return ExprError(); 13751 13752 // Build a conditional unless this is the final case. 13753 if (Result.get()) { 13754 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13755 ThisResult.get(), Result.get()); 13756 if (Result.isInvalid()) 13757 return ExprError(); 13758 } else { 13759 Result = ThisResult; 13760 } 13761 } 13762 13763 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13764 // bind the OpaqueValueExprs before they're (repeatedly) used. 13765 Expr *SyntacticForm = BinaryOperator::Create( 13766 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13767 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13768 CurFPFeatures); 13769 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13770 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13771 } 13772 13773 ExprResult 13774 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13775 SourceLocation RLoc, 13776 Expr *Base, Expr *Idx) { 13777 Expr *Args[2] = { Base, Idx }; 13778 DeclarationName OpName = 13779 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13780 13781 // If either side is type-dependent, create an appropriate dependent 13782 // expression. 13783 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13784 13785 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13786 // CHECKME: no 'operator' keyword? 13787 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13788 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13789 UnresolvedLookupExpr *Fn 13790 = UnresolvedLookupExpr::Create(Context, NamingClass, 13791 NestedNameSpecifierLoc(), OpNameInfo, 13792 /*ADL*/ true, /*Overloaded*/ false, 13793 UnresolvedSetIterator(), 13794 UnresolvedSetIterator()); 13795 // Can't add any actual overloads yet 13796 13797 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13798 Context.DependentTy, VK_RValue, RLoc, 13799 CurFPFeatures); 13800 } 13801 13802 // Handle placeholders on both operands. 13803 if (checkPlaceholderForOverload(*this, Args[0])) 13804 return ExprError(); 13805 if (checkPlaceholderForOverload(*this, Args[1])) 13806 return ExprError(); 13807 13808 // Build an empty overload set. 13809 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13810 13811 // Subscript can only be overloaded as a member function. 13812 13813 // Add operator candidates that are member functions. 13814 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13815 13816 // Add builtin operator candidates. 13817 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13818 13819 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13820 13821 // Perform overload resolution. 13822 OverloadCandidateSet::iterator Best; 13823 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13824 case OR_Success: { 13825 // We found a built-in operator or an overloaded operator. 13826 FunctionDecl *FnDecl = Best->Function; 13827 13828 if (FnDecl) { 13829 // We matched an overloaded operator. Build a call to that 13830 // operator. 13831 13832 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13833 13834 // Convert the arguments. 13835 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13836 ExprResult Arg0 = 13837 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13838 Best->FoundDecl, Method); 13839 if (Arg0.isInvalid()) 13840 return ExprError(); 13841 Args[0] = Arg0.get(); 13842 13843 // Convert the arguments. 13844 ExprResult InputInit 13845 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13846 Context, 13847 FnDecl->getParamDecl(0)), 13848 SourceLocation(), 13849 Args[1]); 13850 if (InputInit.isInvalid()) 13851 return ExprError(); 13852 13853 Args[1] = InputInit.getAs<Expr>(); 13854 13855 // Build the actual expression node. 13856 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13857 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13858 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13859 Best->FoundDecl, 13860 Base, 13861 HadMultipleCandidates, 13862 OpLocInfo.getLoc(), 13863 OpLocInfo.getInfo()); 13864 if (FnExpr.isInvalid()) 13865 return ExprError(); 13866 13867 // Determine the result type 13868 QualType ResultTy = FnDecl->getReturnType(); 13869 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13870 ResultTy = ResultTy.getNonLValueExprType(Context); 13871 13872 CXXOperatorCallExpr *TheCall = 13873 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13874 Args, ResultTy, VK, RLoc, CurFPFeatures); 13875 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13876 return ExprError(); 13877 13878 if (CheckFunctionCall(Method, TheCall, 13879 Method->getType()->castAs<FunctionProtoType>())) 13880 return ExprError(); 13881 13882 return MaybeBindToTemporary(TheCall); 13883 } else { 13884 // We matched a built-in operator. Convert the arguments, then 13885 // break out so that we will build the appropriate built-in 13886 // operator node. 13887 ExprResult ArgsRes0 = PerformImplicitConversion( 13888 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13889 AA_Passing, CCK_ForBuiltinOverloadedOp); 13890 if (ArgsRes0.isInvalid()) 13891 return ExprError(); 13892 Args[0] = ArgsRes0.get(); 13893 13894 ExprResult ArgsRes1 = PerformImplicitConversion( 13895 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13896 AA_Passing, CCK_ForBuiltinOverloadedOp); 13897 if (ArgsRes1.isInvalid()) 13898 return ExprError(); 13899 Args[1] = ArgsRes1.get(); 13900 13901 break; 13902 } 13903 } 13904 13905 case OR_No_Viable_Function: { 13906 PartialDiagnostic PD = CandidateSet.empty() 13907 ? (PDiag(diag::err_ovl_no_oper) 13908 << Args[0]->getType() << /*subscript*/ 0 13909 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13910 : (PDiag(diag::err_ovl_no_viable_subscript) 13911 << Args[0]->getType() << Args[0]->getSourceRange() 13912 << Args[1]->getSourceRange()); 13913 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13914 OCD_AllCandidates, Args, "[]", LLoc); 13915 return ExprError(); 13916 } 13917 13918 case OR_Ambiguous: 13919 CandidateSet.NoteCandidates( 13920 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13921 << "[]" << Args[0]->getType() 13922 << Args[1]->getType() 13923 << Args[0]->getSourceRange() 13924 << Args[1]->getSourceRange()), 13925 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13926 return ExprError(); 13927 13928 case OR_Deleted: 13929 CandidateSet.NoteCandidates( 13930 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13931 << "[]" << Args[0]->getSourceRange() 13932 << Args[1]->getSourceRange()), 13933 *this, OCD_AllCandidates, Args, "[]", LLoc); 13934 return ExprError(); 13935 } 13936 13937 // We matched a built-in operator; build it. 13938 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13939 } 13940 13941 /// BuildCallToMemberFunction - Build a call to a member 13942 /// function. MemExpr is the expression that refers to the member 13943 /// function (and includes the object parameter), Args/NumArgs are the 13944 /// arguments to the function call (not including the object 13945 /// parameter). The caller needs to validate that the member 13946 /// expression refers to a non-static member function or an overloaded 13947 /// member function. 13948 ExprResult 13949 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13950 SourceLocation LParenLoc, 13951 MultiExprArg Args, 13952 SourceLocation RParenLoc) { 13953 assert(MemExprE->getType() == Context.BoundMemberTy || 13954 MemExprE->getType() == Context.OverloadTy); 13955 13956 // Dig out the member expression. This holds both the object 13957 // argument and the member function we're referring to. 13958 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13959 13960 // Determine whether this is a call to a pointer-to-member function. 13961 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13962 assert(op->getType() == Context.BoundMemberTy); 13963 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13964 13965 QualType fnType = 13966 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13967 13968 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13969 QualType resultType = proto->getCallResultType(Context); 13970 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13971 13972 // Check that the object type isn't more qualified than the 13973 // member function we're calling. 13974 Qualifiers funcQuals = proto->getMethodQuals(); 13975 13976 QualType objectType = op->getLHS()->getType(); 13977 if (op->getOpcode() == BO_PtrMemI) 13978 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13979 Qualifiers objectQuals = objectType.getQualifiers(); 13980 13981 Qualifiers difference = objectQuals - funcQuals; 13982 difference.removeObjCGCAttr(); 13983 difference.removeAddressSpace(); 13984 if (difference) { 13985 std::string qualsString = difference.getAsString(); 13986 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13987 << fnType.getUnqualifiedType() 13988 << qualsString 13989 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13990 } 13991 13992 CXXMemberCallExpr *call = 13993 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13994 valueKind, RParenLoc, proto->getNumParams()); 13995 13996 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13997 call, nullptr)) 13998 return ExprError(); 13999 14000 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14001 return ExprError(); 14002 14003 if (CheckOtherCall(call, proto)) 14004 return ExprError(); 14005 14006 return MaybeBindToTemporary(call); 14007 } 14008 14009 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14010 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14011 RParenLoc); 14012 14013 UnbridgedCastsSet UnbridgedCasts; 14014 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14015 return ExprError(); 14016 14017 MemberExpr *MemExpr; 14018 CXXMethodDecl *Method = nullptr; 14019 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14020 NestedNameSpecifier *Qualifier = nullptr; 14021 if (isa<MemberExpr>(NakedMemExpr)) { 14022 MemExpr = cast<MemberExpr>(NakedMemExpr); 14023 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14024 FoundDecl = MemExpr->getFoundDecl(); 14025 Qualifier = MemExpr->getQualifier(); 14026 UnbridgedCasts.restore(); 14027 } else { 14028 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14029 Qualifier = UnresExpr->getQualifier(); 14030 14031 QualType ObjectType = UnresExpr->getBaseType(); 14032 Expr::Classification ObjectClassification 14033 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14034 : UnresExpr->getBase()->Classify(Context); 14035 14036 // Add overload candidates 14037 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14038 OverloadCandidateSet::CSK_Normal); 14039 14040 // FIXME: avoid copy. 14041 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14042 if (UnresExpr->hasExplicitTemplateArgs()) { 14043 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14044 TemplateArgs = &TemplateArgsBuffer; 14045 } 14046 14047 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14048 E = UnresExpr->decls_end(); I != E; ++I) { 14049 14050 NamedDecl *Func = *I; 14051 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14052 if (isa<UsingShadowDecl>(Func)) 14053 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14054 14055 14056 // Microsoft supports direct constructor calls. 14057 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14058 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14059 CandidateSet, 14060 /*SuppressUserConversions*/ false); 14061 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14062 // If explicit template arguments were provided, we can't call a 14063 // non-template member function. 14064 if (TemplateArgs) 14065 continue; 14066 14067 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14068 ObjectClassification, Args, CandidateSet, 14069 /*SuppressUserConversions=*/false); 14070 } else { 14071 AddMethodTemplateCandidate( 14072 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14073 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14074 /*SuppressUserConversions=*/false); 14075 } 14076 } 14077 14078 DeclarationName DeclName = UnresExpr->getMemberName(); 14079 14080 UnbridgedCasts.restore(); 14081 14082 OverloadCandidateSet::iterator Best; 14083 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14084 Best)) { 14085 case OR_Success: 14086 Method = cast<CXXMethodDecl>(Best->Function); 14087 FoundDecl = Best->FoundDecl; 14088 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14089 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14090 return ExprError(); 14091 // If FoundDecl is different from Method (such as if one is a template 14092 // and the other a specialization), make sure DiagnoseUseOfDecl is 14093 // called on both. 14094 // FIXME: This would be more comprehensively addressed by modifying 14095 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14096 // being used. 14097 if (Method != FoundDecl.getDecl() && 14098 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14099 return ExprError(); 14100 break; 14101 14102 case OR_No_Viable_Function: 14103 CandidateSet.NoteCandidates( 14104 PartialDiagnosticAt( 14105 UnresExpr->getMemberLoc(), 14106 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14107 << DeclName << MemExprE->getSourceRange()), 14108 *this, OCD_AllCandidates, Args); 14109 // FIXME: Leaking incoming expressions! 14110 return ExprError(); 14111 14112 case OR_Ambiguous: 14113 CandidateSet.NoteCandidates( 14114 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14115 PDiag(diag::err_ovl_ambiguous_member_call) 14116 << DeclName << MemExprE->getSourceRange()), 14117 *this, OCD_AmbiguousCandidates, Args); 14118 // FIXME: Leaking incoming expressions! 14119 return ExprError(); 14120 14121 case OR_Deleted: 14122 CandidateSet.NoteCandidates( 14123 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14124 PDiag(diag::err_ovl_deleted_member_call) 14125 << DeclName << MemExprE->getSourceRange()), 14126 *this, OCD_AllCandidates, Args); 14127 // FIXME: Leaking incoming expressions! 14128 return ExprError(); 14129 } 14130 14131 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14132 14133 // If overload resolution picked a static member, build a 14134 // non-member call based on that function. 14135 if (Method->isStatic()) { 14136 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14137 RParenLoc); 14138 } 14139 14140 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14141 } 14142 14143 QualType ResultType = Method->getReturnType(); 14144 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14145 ResultType = ResultType.getNonLValueExprType(Context); 14146 14147 assert(Method && "Member call to something that isn't a method?"); 14148 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14149 CXXMemberCallExpr *TheCall = 14150 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 14151 RParenLoc, Proto->getNumParams()); 14152 14153 // Check for a valid return type. 14154 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14155 TheCall, Method)) 14156 return ExprError(); 14157 14158 // Convert the object argument (for a non-static member function call). 14159 // We only need to do this if there was actually an overload; otherwise 14160 // it was done at lookup. 14161 if (!Method->isStatic()) { 14162 ExprResult ObjectArg = 14163 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14164 FoundDecl, Method); 14165 if (ObjectArg.isInvalid()) 14166 return ExprError(); 14167 MemExpr->setBase(ObjectArg.get()); 14168 } 14169 14170 // Convert the rest of the arguments 14171 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14172 RParenLoc)) 14173 return ExprError(); 14174 14175 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14176 14177 if (CheckFunctionCall(Method, TheCall, Proto)) 14178 return ExprError(); 14179 14180 // In the case the method to call was not selected by the overloading 14181 // resolution process, we still need to handle the enable_if attribute. Do 14182 // that here, so it will not hide previous -- and more relevant -- errors. 14183 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14184 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 14185 Diag(MemE->getMemberLoc(), 14186 diag::err_ovl_no_viable_member_function_in_call) 14187 << Method << Method->getSourceRange(); 14188 Diag(Method->getLocation(), 14189 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14190 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14191 return ExprError(); 14192 } 14193 } 14194 14195 if ((isa<CXXConstructorDecl>(CurContext) || 14196 isa<CXXDestructorDecl>(CurContext)) && 14197 TheCall->getMethodDecl()->isPure()) { 14198 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14199 14200 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14201 MemExpr->performsVirtualDispatch(getLangOpts())) { 14202 Diag(MemExpr->getBeginLoc(), 14203 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14204 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14205 << MD->getParent()->getDeclName(); 14206 14207 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14208 if (getLangOpts().AppleKext) 14209 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14210 << MD->getParent()->getDeclName() << MD->getDeclName(); 14211 } 14212 } 14213 14214 if (CXXDestructorDecl *DD = 14215 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14216 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14217 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14218 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14219 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14220 MemExpr->getMemberLoc()); 14221 } 14222 14223 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14224 TheCall->getMethodDecl()); 14225 } 14226 14227 /// BuildCallToObjectOfClassType - Build a call to an object of class 14228 /// type (C++ [over.call.object]), which can end up invoking an 14229 /// overloaded function call operator (@c operator()) or performing a 14230 /// user-defined conversion on the object argument. 14231 ExprResult 14232 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14233 SourceLocation LParenLoc, 14234 MultiExprArg Args, 14235 SourceLocation RParenLoc) { 14236 if (checkPlaceholderForOverload(*this, Obj)) 14237 return ExprError(); 14238 ExprResult Object = Obj; 14239 14240 UnbridgedCastsSet UnbridgedCasts; 14241 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14242 return ExprError(); 14243 14244 assert(Object.get()->getType()->isRecordType() && 14245 "Requires object type argument"); 14246 14247 // C++ [over.call.object]p1: 14248 // If the primary-expression E in the function call syntax 14249 // evaluates to a class object of type "cv T", then the set of 14250 // candidate functions includes at least the function call 14251 // operators of T. The function call operators of T are obtained by 14252 // ordinary lookup of the name operator() in the context of 14253 // (E).operator(). 14254 OverloadCandidateSet CandidateSet(LParenLoc, 14255 OverloadCandidateSet::CSK_Operator); 14256 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14257 14258 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14259 diag::err_incomplete_object_call, Object.get())) 14260 return true; 14261 14262 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14263 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14264 LookupQualifiedName(R, Record->getDecl()); 14265 R.suppressDiagnostics(); 14266 14267 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14268 Oper != OperEnd; ++Oper) { 14269 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14270 Object.get()->Classify(Context), Args, CandidateSet, 14271 /*SuppressUserConversion=*/false); 14272 } 14273 14274 // C++ [over.call.object]p2: 14275 // In addition, for each (non-explicit in C++0x) conversion function 14276 // declared in T of the form 14277 // 14278 // operator conversion-type-id () cv-qualifier; 14279 // 14280 // where cv-qualifier is the same cv-qualification as, or a 14281 // greater cv-qualification than, cv, and where conversion-type-id 14282 // denotes the type "pointer to function of (P1,...,Pn) returning 14283 // R", or the type "reference to pointer to function of 14284 // (P1,...,Pn) returning R", or the type "reference to function 14285 // of (P1,...,Pn) returning R", a surrogate call function [...] 14286 // is also considered as a candidate function. Similarly, 14287 // surrogate call functions are added to the set of candidate 14288 // functions for each conversion function declared in an 14289 // accessible base class provided the function is not hidden 14290 // within T by another intervening declaration. 14291 const auto &Conversions = 14292 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14293 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14294 NamedDecl *D = *I; 14295 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14296 if (isa<UsingShadowDecl>(D)) 14297 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14298 14299 // Skip over templated conversion functions; they aren't 14300 // surrogates. 14301 if (isa<FunctionTemplateDecl>(D)) 14302 continue; 14303 14304 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14305 if (!Conv->isExplicit()) { 14306 // Strip the reference type (if any) and then the pointer type (if 14307 // any) to get down to what might be a function type. 14308 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14309 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14310 ConvType = ConvPtrType->getPointeeType(); 14311 14312 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14313 { 14314 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14315 Object.get(), Args, CandidateSet); 14316 } 14317 } 14318 } 14319 14320 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14321 14322 // Perform overload resolution. 14323 OverloadCandidateSet::iterator Best; 14324 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14325 Best)) { 14326 case OR_Success: 14327 // Overload resolution succeeded; we'll build the appropriate call 14328 // below. 14329 break; 14330 14331 case OR_No_Viable_Function: { 14332 PartialDiagnostic PD = 14333 CandidateSet.empty() 14334 ? (PDiag(diag::err_ovl_no_oper) 14335 << Object.get()->getType() << /*call*/ 1 14336 << Object.get()->getSourceRange()) 14337 : (PDiag(diag::err_ovl_no_viable_object_call) 14338 << Object.get()->getType() << Object.get()->getSourceRange()); 14339 CandidateSet.NoteCandidates( 14340 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14341 OCD_AllCandidates, Args); 14342 break; 14343 } 14344 case OR_Ambiguous: 14345 CandidateSet.NoteCandidates( 14346 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14347 PDiag(diag::err_ovl_ambiguous_object_call) 14348 << Object.get()->getType() 14349 << Object.get()->getSourceRange()), 14350 *this, OCD_AmbiguousCandidates, Args); 14351 break; 14352 14353 case OR_Deleted: 14354 CandidateSet.NoteCandidates( 14355 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14356 PDiag(diag::err_ovl_deleted_object_call) 14357 << Object.get()->getType() 14358 << Object.get()->getSourceRange()), 14359 *this, OCD_AllCandidates, Args); 14360 break; 14361 } 14362 14363 if (Best == CandidateSet.end()) 14364 return true; 14365 14366 UnbridgedCasts.restore(); 14367 14368 if (Best->Function == nullptr) { 14369 // Since there is no function declaration, this is one of the 14370 // surrogate candidates. Dig out the conversion function. 14371 CXXConversionDecl *Conv 14372 = cast<CXXConversionDecl>( 14373 Best->Conversions[0].UserDefined.ConversionFunction); 14374 14375 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14376 Best->FoundDecl); 14377 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14378 return ExprError(); 14379 assert(Conv == Best->FoundDecl.getDecl() && 14380 "Found Decl & conversion-to-functionptr should be same, right?!"); 14381 // We selected one of the surrogate functions that converts the 14382 // object parameter to a function pointer. Perform the conversion 14383 // on the object argument, then let BuildCallExpr finish the job. 14384 14385 // Create an implicit member expr to refer to the conversion operator. 14386 // and then call it. 14387 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14388 Conv, HadMultipleCandidates); 14389 if (Call.isInvalid()) 14390 return ExprError(); 14391 // Record usage of conversion in an implicit cast. 14392 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14393 CK_UserDefinedConversion, Call.get(), 14394 nullptr, VK_RValue); 14395 14396 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14397 } 14398 14399 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14400 14401 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14402 // that calls this method, using Object for the implicit object 14403 // parameter and passing along the remaining arguments. 14404 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14405 14406 // An error diagnostic has already been printed when parsing the declaration. 14407 if (Method->isInvalidDecl()) 14408 return ExprError(); 14409 14410 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14411 unsigned NumParams = Proto->getNumParams(); 14412 14413 DeclarationNameInfo OpLocInfo( 14414 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14415 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14416 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14417 Obj, HadMultipleCandidates, 14418 OpLocInfo.getLoc(), 14419 OpLocInfo.getInfo()); 14420 if (NewFn.isInvalid()) 14421 return true; 14422 14423 // The number of argument slots to allocate in the call. If we have default 14424 // arguments we need to allocate space for them as well. We additionally 14425 // need one more slot for the object parameter. 14426 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14427 14428 // Build the full argument list for the method call (the implicit object 14429 // parameter is placed at the beginning of the list). 14430 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14431 14432 bool IsError = false; 14433 14434 // Initialize the implicit object parameter. 14435 ExprResult ObjRes = 14436 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14437 Best->FoundDecl, Method); 14438 if (ObjRes.isInvalid()) 14439 IsError = true; 14440 else 14441 Object = ObjRes; 14442 MethodArgs[0] = Object.get(); 14443 14444 // Check the argument types. 14445 for (unsigned i = 0; i != NumParams; i++) { 14446 Expr *Arg; 14447 if (i < Args.size()) { 14448 Arg = Args[i]; 14449 14450 // Pass the argument. 14451 14452 ExprResult InputInit 14453 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14454 Context, 14455 Method->getParamDecl(i)), 14456 SourceLocation(), Arg); 14457 14458 IsError |= InputInit.isInvalid(); 14459 Arg = InputInit.getAs<Expr>(); 14460 } else { 14461 ExprResult DefArg 14462 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14463 if (DefArg.isInvalid()) { 14464 IsError = true; 14465 break; 14466 } 14467 14468 Arg = DefArg.getAs<Expr>(); 14469 } 14470 14471 MethodArgs[i + 1] = Arg; 14472 } 14473 14474 // If this is a variadic call, handle args passed through "...". 14475 if (Proto->isVariadic()) { 14476 // Promote the arguments (C99 6.5.2.2p7). 14477 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14478 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14479 nullptr); 14480 IsError |= Arg.isInvalid(); 14481 MethodArgs[i + 1] = Arg.get(); 14482 } 14483 } 14484 14485 if (IsError) 14486 return true; 14487 14488 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14489 14490 // Once we've built TheCall, all of the expressions are properly owned. 14491 QualType ResultTy = Method->getReturnType(); 14492 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14493 ResultTy = ResultTy.getNonLValueExprType(Context); 14494 14495 CXXOperatorCallExpr *TheCall = 14496 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14497 ResultTy, VK, RParenLoc, CurFPFeatures); 14498 14499 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14500 return true; 14501 14502 if (CheckFunctionCall(Method, TheCall, Proto)) 14503 return true; 14504 14505 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14506 } 14507 14508 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14509 /// (if one exists), where @c Base is an expression of class type and 14510 /// @c Member is the name of the member we're trying to find. 14511 ExprResult 14512 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14513 bool *NoArrowOperatorFound) { 14514 assert(Base->getType()->isRecordType() && 14515 "left-hand side must have class type"); 14516 14517 if (checkPlaceholderForOverload(*this, Base)) 14518 return ExprError(); 14519 14520 SourceLocation Loc = Base->getExprLoc(); 14521 14522 // C++ [over.ref]p1: 14523 // 14524 // [...] An expression x->m is interpreted as (x.operator->())->m 14525 // for a class object x of type T if T::operator->() exists and if 14526 // the operator is selected as the best match function by the 14527 // overload resolution mechanism (13.3). 14528 DeclarationName OpName = 14529 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14530 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14531 14532 if (RequireCompleteType(Loc, Base->getType(), 14533 diag::err_typecheck_incomplete_tag, Base)) 14534 return ExprError(); 14535 14536 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14537 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14538 R.suppressDiagnostics(); 14539 14540 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14541 Oper != OperEnd; ++Oper) { 14542 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14543 None, CandidateSet, /*SuppressUserConversion=*/false); 14544 } 14545 14546 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14547 14548 // Perform overload resolution. 14549 OverloadCandidateSet::iterator Best; 14550 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14551 case OR_Success: 14552 // Overload resolution succeeded; we'll build the call below. 14553 break; 14554 14555 case OR_No_Viable_Function: { 14556 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14557 if (CandidateSet.empty()) { 14558 QualType BaseType = Base->getType(); 14559 if (NoArrowOperatorFound) { 14560 // Report this specific error to the caller instead of emitting a 14561 // diagnostic, as requested. 14562 *NoArrowOperatorFound = true; 14563 return ExprError(); 14564 } 14565 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14566 << BaseType << Base->getSourceRange(); 14567 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14568 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14569 << FixItHint::CreateReplacement(OpLoc, "."); 14570 } 14571 } else 14572 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14573 << "operator->" << Base->getSourceRange(); 14574 CandidateSet.NoteCandidates(*this, Base, Cands); 14575 return ExprError(); 14576 } 14577 case OR_Ambiguous: 14578 CandidateSet.NoteCandidates( 14579 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14580 << "->" << Base->getType() 14581 << Base->getSourceRange()), 14582 *this, OCD_AmbiguousCandidates, Base); 14583 return ExprError(); 14584 14585 case OR_Deleted: 14586 CandidateSet.NoteCandidates( 14587 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14588 << "->" << Base->getSourceRange()), 14589 *this, OCD_AllCandidates, Base); 14590 return ExprError(); 14591 } 14592 14593 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14594 14595 // Convert the object parameter. 14596 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14597 ExprResult BaseResult = 14598 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14599 Best->FoundDecl, Method); 14600 if (BaseResult.isInvalid()) 14601 return ExprError(); 14602 Base = BaseResult.get(); 14603 14604 // Build the operator call. 14605 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14606 Base, HadMultipleCandidates, OpLoc); 14607 if (FnExpr.isInvalid()) 14608 return ExprError(); 14609 14610 QualType ResultTy = Method->getReturnType(); 14611 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14612 ResultTy = ResultTy.getNonLValueExprType(Context); 14613 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14614 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, CurFPFeatures); 14615 14616 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14617 return ExprError(); 14618 14619 if (CheckFunctionCall(Method, TheCall, 14620 Method->getType()->castAs<FunctionProtoType>())) 14621 return ExprError(); 14622 14623 return MaybeBindToTemporary(TheCall); 14624 } 14625 14626 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14627 /// a literal operator described by the provided lookup results. 14628 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14629 DeclarationNameInfo &SuffixInfo, 14630 ArrayRef<Expr*> Args, 14631 SourceLocation LitEndLoc, 14632 TemplateArgumentListInfo *TemplateArgs) { 14633 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14634 14635 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14636 OverloadCandidateSet::CSK_Normal); 14637 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14638 TemplateArgs); 14639 14640 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14641 14642 // Perform overload resolution. This will usually be trivial, but might need 14643 // to perform substitutions for a literal operator template. 14644 OverloadCandidateSet::iterator Best; 14645 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14646 case OR_Success: 14647 case OR_Deleted: 14648 break; 14649 14650 case OR_No_Viable_Function: 14651 CandidateSet.NoteCandidates( 14652 PartialDiagnosticAt(UDSuffixLoc, 14653 PDiag(diag::err_ovl_no_viable_function_in_call) 14654 << R.getLookupName()), 14655 *this, OCD_AllCandidates, Args); 14656 return ExprError(); 14657 14658 case OR_Ambiguous: 14659 CandidateSet.NoteCandidates( 14660 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14661 << R.getLookupName()), 14662 *this, OCD_AmbiguousCandidates, Args); 14663 return ExprError(); 14664 } 14665 14666 FunctionDecl *FD = Best->Function; 14667 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14668 nullptr, HadMultipleCandidates, 14669 SuffixInfo.getLoc(), 14670 SuffixInfo.getInfo()); 14671 if (Fn.isInvalid()) 14672 return true; 14673 14674 // Check the argument types. This should almost always be a no-op, except 14675 // that array-to-pointer decay is applied to string literals. 14676 Expr *ConvArgs[2]; 14677 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14678 ExprResult InputInit = PerformCopyInitialization( 14679 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14680 SourceLocation(), Args[ArgIdx]); 14681 if (InputInit.isInvalid()) 14682 return true; 14683 ConvArgs[ArgIdx] = InputInit.get(); 14684 } 14685 14686 QualType ResultTy = FD->getReturnType(); 14687 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14688 ResultTy = ResultTy.getNonLValueExprType(Context); 14689 14690 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14691 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14692 VK, LitEndLoc, UDSuffixLoc); 14693 14694 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14695 return ExprError(); 14696 14697 if (CheckFunctionCall(FD, UDL, nullptr)) 14698 return ExprError(); 14699 14700 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14701 } 14702 14703 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14704 /// given LookupResult is non-empty, it is assumed to describe a member which 14705 /// will be invoked. Otherwise, the function will be found via argument 14706 /// dependent lookup. 14707 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14708 /// otherwise CallExpr is set to ExprError() and some non-success value 14709 /// is returned. 14710 Sema::ForRangeStatus 14711 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14712 SourceLocation RangeLoc, 14713 const DeclarationNameInfo &NameInfo, 14714 LookupResult &MemberLookup, 14715 OverloadCandidateSet *CandidateSet, 14716 Expr *Range, ExprResult *CallExpr) { 14717 Scope *S = nullptr; 14718 14719 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14720 if (!MemberLookup.empty()) { 14721 ExprResult MemberRef = 14722 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14723 /*IsPtr=*/false, CXXScopeSpec(), 14724 /*TemplateKWLoc=*/SourceLocation(), 14725 /*FirstQualifierInScope=*/nullptr, 14726 MemberLookup, 14727 /*TemplateArgs=*/nullptr, S); 14728 if (MemberRef.isInvalid()) { 14729 *CallExpr = ExprError(); 14730 return FRS_DiagnosticIssued; 14731 } 14732 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14733 if (CallExpr->isInvalid()) { 14734 *CallExpr = ExprError(); 14735 return FRS_DiagnosticIssued; 14736 } 14737 } else { 14738 UnresolvedSet<0> FoundNames; 14739 UnresolvedLookupExpr *Fn = 14740 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14741 NestedNameSpecifierLoc(), NameInfo, 14742 /*NeedsADL=*/true, /*Overloaded=*/false, 14743 FoundNames.begin(), FoundNames.end()); 14744 14745 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14746 CandidateSet, CallExpr); 14747 if (CandidateSet->empty() || CandidateSetError) { 14748 *CallExpr = ExprError(); 14749 return FRS_NoViableFunction; 14750 } 14751 OverloadCandidateSet::iterator Best; 14752 OverloadingResult OverloadResult = 14753 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14754 14755 if (OverloadResult == OR_No_Viable_Function) { 14756 *CallExpr = ExprError(); 14757 return FRS_NoViableFunction; 14758 } 14759 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14760 Loc, nullptr, CandidateSet, &Best, 14761 OverloadResult, 14762 /*AllowTypoCorrection=*/false); 14763 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14764 *CallExpr = ExprError(); 14765 return FRS_DiagnosticIssued; 14766 } 14767 } 14768 return FRS_Success; 14769 } 14770 14771 14772 /// FixOverloadedFunctionReference - E is an expression that refers to 14773 /// a C++ overloaded function (possibly with some parentheses and 14774 /// perhaps a '&' around it). We have resolved the overloaded function 14775 /// to the function declaration Fn, so patch up the expression E to 14776 /// refer (possibly indirectly) to Fn. Returns the new expr. 14777 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14778 FunctionDecl *Fn) { 14779 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14780 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14781 Found, Fn); 14782 if (SubExpr == PE->getSubExpr()) 14783 return PE; 14784 14785 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14786 } 14787 14788 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14789 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14790 Found, Fn); 14791 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14792 SubExpr->getType()) && 14793 "Implicit cast type cannot be determined from overload"); 14794 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14795 if (SubExpr == ICE->getSubExpr()) 14796 return ICE; 14797 14798 return ImplicitCastExpr::Create(Context, ICE->getType(), 14799 ICE->getCastKind(), 14800 SubExpr, nullptr, 14801 ICE->getValueKind()); 14802 } 14803 14804 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14805 if (!GSE->isResultDependent()) { 14806 Expr *SubExpr = 14807 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14808 if (SubExpr == GSE->getResultExpr()) 14809 return GSE; 14810 14811 // Replace the resulting type information before rebuilding the generic 14812 // selection expression. 14813 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14814 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14815 unsigned ResultIdx = GSE->getResultIndex(); 14816 AssocExprs[ResultIdx] = SubExpr; 14817 14818 return GenericSelectionExpr::Create( 14819 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14820 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14821 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14822 ResultIdx); 14823 } 14824 // Rather than fall through to the unreachable, return the original generic 14825 // selection expression. 14826 return GSE; 14827 } 14828 14829 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14830 assert(UnOp->getOpcode() == UO_AddrOf && 14831 "Can only take the address of an overloaded function"); 14832 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14833 if (Method->isStatic()) { 14834 // Do nothing: static member functions aren't any different 14835 // from non-member functions. 14836 } else { 14837 // Fix the subexpression, which really has to be an 14838 // UnresolvedLookupExpr holding an overloaded member function 14839 // or template. 14840 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14841 Found, Fn); 14842 if (SubExpr == UnOp->getSubExpr()) 14843 return UnOp; 14844 14845 assert(isa<DeclRefExpr>(SubExpr) 14846 && "fixed to something other than a decl ref"); 14847 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14848 && "fixed to a member ref with no nested name qualifier"); 14849 14850 // We have taken the address of a pointer to member 14851 // function. Perform the computation here so that we get the 14852 // appropriate pointer to member type. 14853 QualType ClassType 14854 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14855 QualType MemPtrType 14856 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14857 // Under the MS ABI, lock down the inheritance model now. 14858 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14859 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14860 14861 return UnaryOperator::Create( 14862 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 14863 UnOp->getOperatorLoc(), false, CurFPFeatures); 14864 } 14865 } 14866 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14867 Found, Fn); 14868 if (SubExpr == UnOp->getSubExpr()) 14869 return UnOp; 14870 14871 return UnaryOperator::Create( 14872 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()), 14873 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), false, CurFPFeatures); 14874 } 14875 14876 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14877 // FIXME: avoid copy. 14878 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14879 if (ULE->hasExplicitTemplateArgs()) { 14880 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14881 TemplateArgs = &TemplateArgsBuffer; 14882 } 14883 14884 DeclRefExpr *DRE = 14885 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14886 ULE->getQualifierLoc(), Found.getDecl(), 14887 ULE->getTemplateKeywordLoc(), TemplateArgs); 14888 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14889 return DRE; 14890 } 14891 14892 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14893 // FIXME: avoid copy. 14894 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14895 if (MemExpr->hasExplicitTemplateArgs()) { 14896 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14897 TemplateArgs = &TemplateArgsBuffer; 14898 } 14899 14900 Expr *Base; 14901 14902 // If we're filling in a static method where we used to have an 14903 // implicit member access, rewrite to a simple decl ref. 14904 if (MemExpr->isImplicitAccess()) { 14905 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14906 DeclRefExpr *DRE = BuildDeclRefExpr( 14907 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14908 MemExpr->getQualifierLoc(), Found.getDecl(), 14909 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14910 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14911 return DRE; 14912 } else { 14913 SourceLocation Loc = MemExpr->getMemberLoc(); 14914 if (MemExpr->getQualifier()) 14915 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14916 Base = 14917 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14918 } 14919 } else 14920 Base = MemExpr->getBase(); 14921 14922 ExprValueKind valueKind; 14923 QualType type; 14924 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14925 valueKind = VK_LValue; 14926 type = Fn->getType(); 14927 } else { 14928 valueKind = VK_RValue; 14929 type = Context.BoundMemberTy; 14930 } 14931 14932 return BuildMemberExpr( 14933 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14934 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14935 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14936 type, valueKind, OK_Ordinary, TemplateArgs); 14937 } 14938 14939 llvm_unreachable("Invalid reference to overloaded function"); 14940 } 14941 14942 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14943 DeclAccessPair Found, 14944 FunctionDecl *Fn) { 14945 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14946 } 14947