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 CreateFunctionRefExpr( 53 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 54 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 55 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 56 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 57 return ExprError(); 58 // If FoundDecl is different from Fn (such as if one is a template 59 // and the other a specialization), make sure DiagnoseUseOfDecl is 60 // called on both. 61 // FIXME: This would be more comprehensively addressed by modifying 62 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 63 // being used. 64 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 65 return ExprError(); 66 DeclRefExpr *DRE = new (S.Context) 67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 73 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 74 S.ResolveExceptionSpec(Loc, FPT); 75 DRE->setType(Fn->getType()); 76 } 77 } 78 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 79 CK_FunctionToPointerDecay); 80 } 81 82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle, 86 bool AllowObjCWritebackConversion); 87 88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 89 QualType &ToType, 90 bool InOverloadResolution, 91 StandardConversionSequence &SCS, 92 bool CStyle); 93 static OverloadingResult 94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 95 UserDefinedConversionSequence& User, 96 OverloadCandidateSet& Conversions, 97 AllowedExplicit AllowExplicit, 98 bool AllowObjCConversionOnExplicit); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareQualificationConversions(Sema &S, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 static ImplicitConversionSequence::CompareKind 111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 112 const StandardConversionSequence& SCS1, 113 const StandardConversionSequence& SCS2); 114 115 /// GetConversionRank - Retrieve the implicit conversion rank 116 /// corresponding to the given implicit conversion kind. 117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 118 static const ImplicitConversionRank 119 Rank[(int)ICK_Num_Conversion_Kinds] = { 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Promotion, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Conversion, 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 "SVE Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion", 182 "Writeback conversion", 183 "OpenCL Zero Event Conversion", 184 "C specific type conversion", 185 "Incompatible pointer conversion" 186 }; 187 return Name[Kind]; 188 } 189 190 /// StandardConversionSequence - Set the standard conversion 191 /// sequence to the identity conversion. 192 void StandardConversionSequence::setAsIdentityConversion() { 193 First = ICK_Identity; 194 Second = ICK_Identity; 195 Third = ICK_Identity; 196 DeprecatedStringLiteralToCharPtr = false; 197 QualificationIncludesObjCLifetime = false; 198 ReferenceBinding = false; 199 DirectBinding = false; 200 IsLvalueReference = true; 201 BindsToFunctionLvalue = false; 202 BindsToRvalue = false; 203 BindsImplicitObjectArgumentWithoutRefQualifier = false; 204 ObjCLifetimeConversionBinding = false; 205 CopyConstructor = nullptr; 206 } 207 208 /// getRank - Retrieve the rank of this standard conversion sequence 209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 210 /// implicit conversions. 211 ImplicitConversionRank StandardConversionSequence::getRank() const { 212 ImplicitConversionRank Rank = ICR_Exact_Match; 213 if (GetConversionRank(First) > Rank) 214 Rank = GetConversionRank(First); 215 if (GetConversionRank(Second) > Rank) 216 Rank = GetConversionRank(Second); 217 if (GetConversionRank(Third) > Rank) 218 Rank = GetConversionRank(Third); 219 return Rank; 220 } 221 222 /// isPointerConversionToBool - Determines whether this conversion is 223 /// a conversion of a pointer or pointer-to-member to bool. This is 224 /// used as part of the ranking of standard conversion sequences 225 /// (C++ 13.3.3.2p4). 226 bool StandardConversionSequence::isPointerConversionToBool() const { 227 // Note that FromType has not necessarily been transformed by the 228 // array-to-pointer or function-to-pointer implicit conversions, so 229 // check for their presence as well as checking whether FromType is 230 // a pointer. 231 if (getToType(1)->isBooleanType() && 232 (getFromType()->isPointerType() || 233 getFromType()->isMemberPointerType() || 234 getFromType()->isObjCObjectPointerType() || 235 getFromType()->isBlockPointerType() || 236 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 237 return true; 238 239 return false; 240 } 241 242 /// isPointerConversionToVoidPointer - Determines whether this 243 /// conversion is a conversion of a pointer to a void pointer. This is 244 /// used as part of the ranking of standard conversion sequences (C++ 245 /// 13.3.3.2p4). 246 bool 247 StandardConversionSequence:: 248 isPointerConversionToVoidPointer(ASTContext& Context) const { 249 QualType FromType = getFromType(); 250 QualType ToType = getToType(1); 251 252 // Note that FromType has not necessarily been transformed by the 253 // array-to-pointer implicit conversion, so check for its presence 254 // and redo the conversion to get a pointer. 255 if (First == ICK_Array_To_Pointer) 256 FromType = Context.getArrayDecayedType(FromType); 257 258 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 259 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 260 return ToPtrType->getPointeeType()->isVoidType(); 261 262 return false; 263 } 264 265 /// Skip any implicit casts which could be either part of a narrowing conversion 266 /// or after one in an implicit conversion. 267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 268 const Expr *Converted) { 269 // We can have cleanups wrapping the converted expression; these need to be 270 // preserved so that destructors run if necessary. 271 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 272 Expr *Inner = 273 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 274 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 275 EWC->getObjects()); 276 } 277 278 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 279 switch (ICE->getCastKind()) { 280 case CK_NoOp: 281 case CK_IntegralCast: 282 case CK_IntegralToBoolean: 283 case CK_IntegralToFloating: 284 case CK_BooleanToSignedIntegral: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297 } 298 299 /// Check if this standard conversion sequence represents a narrowing 300 /// conversion, according to C++11 [dcl.init.list]p7. 301 /// 302 /// \param Ctx The AST context. 303 /// \param Converted The result of applying this standard conversion sequence. 304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305 /// value of the expression prior to the narrowing conversion. 306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307 /// type of the expression prior to the narrowing conversion. 308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 309 /// from floating point types to integral types should be ignored. 310 NarrowingKind StandardConversionSequence::getNarrowingKind( 311 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 312 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 320 // A conversion to an enumeration type is narrowing if the conversion to 321 // the underlying type is narrowing. This only arises for expressions of 322 // the form 'Enum{init}'. 323 if (auto *ET = ToType->getAs<EnumType>()) 324 ToType = ET->getDecl()->getIntegerType(); 325 326 switch (Second) { 327 // 'bool' is an integral type; dispatch to the right place to handle it. 328 case ICK_Boolean_Conversion: 329 if (FromType->isRealFloatingType()) 330 goto FloatingIntegralConversion; 331 if (FromType->isIntegralOrUnscopedEnumerationType()) 332 goto IntegralConversion; 333 // -- from a pointer type or pointer-to-member type to bool, or 334 return NK_Type_Narrowing; 335 336 // -- from a floating-point type to an integer type, or 337 // 338 // -- from an integer type or unscoped enumeration type to a floating-point 339 // type, except where the source is a constant expression and the actual 340 // value after conversion will fit into the target type and will produce 341 // the original value when converted back to the original type, or 342 case ICK_Floating_Integral: 343 FloatingIntegralConversion: 344 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 345 return NK_Type_Narrowing; 346 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 347 ToType->isRealFloatingType()) { 348 if (IgnoreFloatToIntegralConversion) 349 return NK_Not_Narrowing; 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 (Optional<llvm::APSInt> IntConstantValue = 358 Initializer->getIntegerConstantExpr(Ctx)) { 359 // Convert the integer to the floating type. 360 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 361 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 362 llvm::APFloat::rmNearestTiesToEven); 363 // And back. 364 llvm::APSInt ConvertedValue = *IntConstantValue; 365 bool ignored; 366 Result.convertToInteger(ConvertedValue, 367 llvm::APFloat::rmTowardZero, &ignored); 368 // If the resulting value is different, this was a narrowing conversion. 369 if (*IntConstantValue != ConvertedValue) { 370 ConstantValue = APValue(*IntConstantValue); 371 ConstantType = Initializer->getType(); 372 return NK_Constant_Narrowing; 373 } 374 } else { 375 // Variables are always narrowings. 376 return NK_Variable_Narrowing; 377 } 378 } 379 return NK_Not_Narrowing; 380 381 // -- from long double to double or float, or from double to float, except 382 // where the source is a constant expression and the actual value after 383 // conversion is within the range of values that can be represented (even 384 // if it cannot be represented exactly), or 385 case ICK_Floating_Conversion: 386 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 387 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 388 // FromType is larger than ToType. 389 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 390 391 // If it's value-dependent, we can't tell whether it's narrowing. 392 if (Initializer->isValueDependent()) 393 return NK_Dependent_Narrowing; 394 395 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 396 // Constant! 397 assert(ConstantValue.isFloat()); 398 llvm::APFloat FloatVal = ConstantValue.getFloat(); 399 // Convert the source value into the target type. 400 bool ignored; 401 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 402 Ctx.getFloatTypeSemantics(ToType), 403 llvm::APFloat::rmNearestTiesToEven, &ignored); 404 // If there was no overflow, the source value is within the range of 405 // values that can be represented. 406 if (ConvertStatus & llvm::APFloat::opOverflow) { 407 ConstantType = Initializer->getType(); 408 return NK_Constant_Narrowing; 409 } 410 } else { 411 return NK_Variable_Narrowing; 412 } 413 } 414 return NK_Not_Narrowing; 415 416 // -- from an integer type or unscoped enumeration type to an integer type 417 // that cannot represent all the values of the original type, except where 418 // the source is a constant expression and the actual value after 419 // conversion will fit into the target type and will produce the original 420 // value when converted back to the original type. 421 case ICK_Integral_Conversion: 422 IntegralConversion: { 423 assert(FromType->isIntegralOrUnscopedEnumerationType()); 424 assert(ToType->isIntegralOrUnscopedEnumerationType()); 425 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 426 const unsigned FromWidth = Ctx.getIntWidth(FromType); 427 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 428 const unsigned ToWidth = Ctx.getIntWidth(ToType); 429 430 if (FromWidth > ToWidth || 431 (FromWidth == ToWidth && FromSigned != ToSigned) || 432 (FromSigned && !ToSigned)) { 433 // Not all values of FromType can be represented in ToType. 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 Optional<llvm::APSInt> OptInitializerValue; 441 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 442 // Such conversions on variables are always narrowing. 443 return NK_Variable_Narrowing; 444 } 445 llvm::APSInt &InitializerValue = *OptInitializerValue; 446 bool Narrowing = false; 447 if (FromWidth < ToWidth) { 448 // Negative -> unsigned is narrowing. Otherwise, more bits is never 449 // narrowing. 450 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 451 Narrowing = true; 452 } else { 453 // Add a bit to the InitializerValue so we don't have to worry about 454 // signed vs. unsigned comparisons. 455 InitializerValue = InitializerValue.extend( 456 InitializerValue.getBitWidth() + 1); 457 // Convert the initializer to and from the target width and signed-ness. 458 llvm::APSInt ConvertedValue = InitializerValue; 459 ConvertedValue = ConvertedValue.trunc(ToWidth); 460 ConvertedValue.setIsSigned(ToSigned); 461 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 462 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 463 // If the result is different, this was a narrowing conversion. 464 if (ConvertedValue != InitializerValue) 465 Narrowing = true; 466 } 467 if (Narrowing) { 468 ConstantType = Initializer->getType(); 469 ConstantValue = APValue(InitializerValue); 470 return NK_Constant_Narrowing; 471 } 472 } 473 return NK_Not_Narrowing; 474 } 475 476 default: 477 // Other kinds of conversions are not narrowings. 478 return NK_Not_Narrowing; 479 } 480 } 481 482 /// dump - Print this standard conversion sequence to standard 483 /// error. Useful for debugging overloading issues. 484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 485 raw_ostream &OS = llvm::errs(); 486 bool PrintedSomething = false; 487 if (First != ICK_Identity) { 488 OS << GetImplicitConversionName(First); 489 PrintedSomething = true; 490 } 491 492 if (Second != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Second); 497 498 if (CopyConstructor) { 499 OS << " (by copy constructor)"; 500 } else if (DirectBinding) { 501 OS << " (direct reference binding)"; 502 } else if (ReferenceBinding) { 503 OS << " (reference binding)"; 504 } 505 PrintedSomething = true; 506 } 507 508 if (Third != ICK_Identity) { 509 if (PrintedSomething) { 510 OS << " -> "; 511 } 512 OS << GetImplicitConversionName(Third); 513 PrintedSomething = true; 514 } 515 516 if (!PrintedSomething) { 517 OS << "No conversions required"; 518 } 519 } 520 521 /// dump - Print this user-defined conversion sequence to standard 522 /// error. Useful for debugging overloading issues. 523 void UserDefinedConversionSequence::dump() const { 524 raw_ostream &OS = llvm::errs(); 525 if (Before.First || Before.Second || Before.Third) { 526 Before.dump(); 527 OS << " -> "; 528 } 529 if (ConversionFunction) 530 OS << '\'' << *ConversionFunction << '\''; 531 else 532 OS << "aggregate initialization"; 533 if (After.First || After.Second || After.Third) { 534 OS << " -> "; 535 After.dump(); 536 } 537 } 538 539 /// dump - Print this implicit conversion sequence to standard 540 /// error. Useful for debugging overloading issues. 541 void ImplicitConversionSequence::dump() const { 542 raw_ostream &OS = llvm::errs(); 543 if (hasInitializerListContainerType()) 544 OS << "Worst list element conversion: "; 545 switch (ConversionKind) { 546 case StandardConversion: 547 OS << "Standard conversion: "; 548 Standard.dump(); 549 break; 550 case UserDefinedConversion: 551 OS << "User-defined conversion: "; 552 UserDefined.dump(); 553 break; 554 case EllipsisConversion: 555 OS << "Ellipsis conversion"; 556 break; 557 case AmbiguousConversion: 558 OS << "Ambiguous conversion"; 559 break; 560 case BadConversion: 561 OS << "Bad conversion"; 562 break; 563 } 564 565 OS << "\n"; 566 } 567 568 void AmbiguousConversionSequence::construct() { 569 new (&conversions()) ConversionSet(); 570 } 571 572 void AmbiguousConversionSequence::destruct() { 573 conversions().~ConversionSet(); 574 } 575 576 void 577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 578 FromTypePtr = O.FromTypePtr; 579 ToTypePtr = O.ToTypePtr; 580 new (&conversions()) ConversionSet(O.conversions()); 581 } 582 583 namespace { 584 // Structure used by DeductionFailureInfo to store 585 // template argument information. 586 struct DFIArguments { 587 TemplateArgument FirstArg; 588 TemplateArgument SecondArg; 589 }; 590 // Structure used by DeductionFailureInfo to store 591 // template parameter and template argument information. 592 struct DFIParamWithArguments : DFIArguments { 593 TemplateParameter Param; 594 }; 595 // Structure used by DeductionFailureInfo to store template argument 596 // information and the index of the problematic call argument. 597 struct DFIDeducedMismatchArgs : DFIArguments { 598 TemplateArgumentList *TemplateArgs; 599 unsigned CallArgIndex; 600 }; 601 // Structure used by DeductionFailureInfo to store information about 602 // unsatisfied constraints. 603 struct CNSInfo { 604 TemplateArgumentList *TemplateArgs; 605 ConstraintSatisfaction Satisfaction; 606 }; 607 } 608 609 /// Convert from Sema's representation of template deduction information 610 /// to the form used in overload-candidate information. 611 DeductionFailureInfo 612 clang::MakeDeductionFailureInfo(ASTContext &Context, 613 Sema::TemplateDeductionResult TDK, 614 TemplateDeductionInfo &Info) { 615 DeductionFailureInfo Result; 616 Result.Result = static_cast<unsigned>(TDK); 617 Result.HasDiagnostic = false; 618 switch (TDK) { 619 case Sema::TDK_Invalid: 620 case Sema::TDK_InstantiationDepth: 621 case Sema::TDK_TooManyArguments: 622 case Sema::TDK_TooFewArguments: 623 case Sema::TDK_MiscellaneousDeductionFailure: 624 case Sema::TDK_CUDATargetMismatch: 625 Result.Data = nullptr; 626 break; 627 628 case Sema::TDK_Incomplete: 629 case Sema::TDK_InvalidExplicitArguments: 630 Result.Data = Info.Param.getOpaqueValue(); 631 break; 632 633 case Sema::TDK_DeducedMismatch: 634 case Sema::TDK_DeducedMismatchNested: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 auto *Saved = new (Context) DFIDeducedMismatchArgs; 637 Saved->FirstArg = Info.FirstArg; 638 Saved->SecondArg = Info.SecondArg; 639 Saved->TemplateArgs = Info.take(); 640 Saved->CallArgIndex = Info.CallArgIndex; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_NonDeducedMismatch: { 646 // FIXME: Should allocate from normal heap so that we can free this later. 647 DFIArguments *Saved = new (Context) DFIArguments; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_IncompletePack: 655 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 656 case Sema::TDK_Inconsistent: 657 case Sema::TDK_Underqualified: { 658 // FIXME: Should allocate from normal heap so that we can free this later. 659 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 660 Saved->Param = Info.Param; 661 Saved->FirstArg = Info.FirstArg; 662 Saved->SecondArg = Info.SecondArg; 663 Result.Data = Saved; 664 break; 665 } 666 667 case Sema::TDK_SubstitutionFailure: 668 Result.Data = Info.take(); 669 if (Info.hasSFINAEDiagnostic()) { 670 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 671 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 672 Info.takeSFINAEDiagnostic(*Diag); 673 Result.HasDiagnostic = true; 674 } 675 break; 676 677 case Sema::TDK_ConstraintsNotSatisfied: { 678 CNSInfo *Saved = new (Context) CNSInfo; 679 Saved->TemplateArgs = Info.take(); 680 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 681 Result.Data = Saved; 682 break; 683 } 684 685 case Sema::TDK_Success: 686 case Sema::TDK_NonDependentConversionFailure: 687 llvm_unreachable("not a deduction failure"); 688 } 689 690 return Result; 691 } 692 693 void DeductionFailureInfo::Destroy() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_CUDATargetMismatch: 703 case Sema::TDK_NonDependentConversionFailure: 704 break; 705 706 case Sema::TDK_IncompletePack: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_DeducedMismatch: 710 case Sema::TDK_DeducedMismatchNested: 711 case Sema::TDK_NonDeducedMismatch: 712 // FIXME: Destroy the data? 713 Data = nullptr; 714 break; 715 716 case Sema::TDK_SubstitutionFailure: 717 // FIXME: Destroy the template argument list? 718 Data = nullptr; 719 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 720 Diag->~PartialDiagnosticAt(); 721 HasDiagnostic = false; 722 } 723 break; 724 725 case Sema::TDK_ConstraintsNotSatisfied: 726 // FIXME: Destroy the template argument list? 727 Data = nullptr; 728 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 729 Diag->~PartialDiagnosticAt(); 730 HasDiagnostic = false; 731 } 732 break; 733 734 // Unhandled 735 case Sema::TDK_MiscellaneousDeductionFailure: 736 break; 737 } 738 } 739 740 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 741 if (HasDiagnostic) 742 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 743 return nullptr; 744 } 745 746 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 747 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 748 case Sema::TDK_Success: 749 case Sema::TDK_Invalid: 750 case Sema::TDK_InstantiationDepth: 751 case Sema::TDK_TooManyArguments: 752 case Sema::TDK_TooFewArguments: 753 case Sema::TDK_SubstitutionFailure: 754 case Sema::TDK_DeducedMismatch: 755 case Sema::TDK_DeducedMismatchNested: 756 case Sema::TDK_NonDeducedMismatch: 757 case Sema::TDK_CUDATargetMismatch: 758 case Sema::TDK_NonDependentConversionFailure: 759 case Sema::TDK_ConstraintsNotSatisfied: 760 return TemplateParameter(); 761 762 case Sema::TDK_Incomplete: 763 case Sema::TDK_InvalidExplicitArguments: 764 return TemplateParameter::getFromOpaqueValue(Data); 765 766 case Sema::TDK_IncompletePack: 767 case Sema::TDK_Inconsistent: 768 case Sema::TDK_Underqualified: 769 return static_cast<DFIParamWithArguments*>(Data)->Param; 770 771 // Unhandled 772 case Sema::TDK_MiscellaneousDeductionFailure: 773 break; 774 } 775 776 return TemplateParameter(); 777 } 778 779 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 780 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 781 case Sema::TDK_Success: 782 case Sema::TDK_Invalid: 783 case Sema::TDK_InstantiationDepth: 784 case Sema::TDK_TooManyArguments: 785 case Sema::TDK_TooFewArguments: 786 case Sema::TDK_Incomplete: 787 case Sema::TDK_IncompletePack: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_Inconsistent: 790 case Sema::TDK_Underqualified: 791 case Sema::TDK_NonDeducedMismatch: 792 case Sema::TDK_CUDATargetMismatch: 793 case Sema::TDK_NonDependentConversionFailure: 794 return nullptr; 795 796 case Sema::TDK_DeducedMismatch: 797 case Sema::TDK_DeducedMismatchNested: 798 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 799 800 case Sema::TDK_SubstitutionFailure: 801 return static_cast<TemplateArgumentList*>(Data); 802 803 case Sema::TDK_ConstraintsNotSatisfied: 804 return static_cast<CNSInfo*>(Data)->TemplateArgs; 805 806 // Unhandled 807 case Sema::TDK_MiscellaneousDeductionFailure: 808 break; 809 } 810 811 return nullptr; 812 } 813 814 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 815 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 816 case Sema::TDK_Success: 817 case Sema::TDK_Invalid: 818 case Sema::TDK_InstantiationDepth: 819 case Sema::TDK_Incomplete: 820 case Sema::TDK_TooManyArguments: 821 case Sema::TDK_TooFewArguments: 822 case Sema::TDK_InvalidExplicitArguments: 823 case Sema::TDK_SubstitutionFailure: 824 case Sema::TDK_CUDATargetMismatch: 825 case Sema::TDK_NonDependentConversionFailure: 826 case Sema::TDK_ConstraintsNotSatisfied: 827 return nullptr; 828 829 case Sema::TDK_IncompletePack: 830 case Sema::TDK_Inconsistent: 831 case Sema::TDK_Underqualified: 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 case Sema::TDK_NonDeducedMismatch: 835 return &static_cast<DFIArguments*>(Data)->FirstArg; 836 837 // Unhandled 838 case Sema::TDK_MiscellaneousDeductionFailure: 839 break; 840 } 841 842 return nullptr; 843 } 844 845 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 846 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 847 case Sema::TDK_Success: 848 case Sema::TDK_Invalid: 849 case Sema::TDK_InstantiationDepth: 850 case Sema::TDK_Incomplete: 851 case Sema::TDK_IncompletePack: 852 case Sema::TDK_TooManyArguments: 853 case Sema::TDK_TooFewArguments: 854 case Sema::TDK_InvalidExplicitArguments: 855 case Sema::TDK_SubstitutionFailure: 856 case Sema::TDK_CUDATargetMismatch: 857 case Sema::TDK_NonDependentConversionFailure: 858 case Sema::TDK_ConstraintsNotSatisfied: 859 return nullptr; 860 861 case Sema::TDK_Inconsistent: 862 case Sema::TDK_Underqualified: 863 case Sema::TDK_DeducedMismatch: 864 case Sema::TDK_DeducedMismatchNested: 865 case Sema::TDK_NonDeducedMismatch: 866 return &static_cast<DFIArguments*>(Data)->SecondArg; 867 868 // Unhandled 869 case Sema::TDK_MiscellaneousDeductionFailure: 870 break; 871 } 872 873 return nullptr; 874 } 875 876 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 877 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 878 case Sema::TDK_DeducedMismatch: 879 case Sema::TDK_DeducedMismatchNested: 880 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 881 882 default: 883 return llvm::None; 884 } 885 } 886 887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 888 OverloadedOperatorKind Op) { 889 if (!AllowRewrittenCandidates) 890 return false; 891 return Op == OO_EqualEqual || Op == OO_Spaceship; 892 } 893 894 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 895 ASTContext &Ctx, const FunctionDecl *FD) { 896 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 897 return false; 898 // Don't bother adding a reversed candidate that can never be a better 899 // match than the non-reversed version. 900 return FD->getNumParams() != 2 || 901 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 902 FD->getParamDecl(1)->getType()) || 903 FD->hasAttr<EnableIfAttr>(); 904 } 905 906 void OverloadCandidateSet::destroyCandidates() { 907 for (iterator i = begin(), e = end(); i != e; ++i) { 908 for (auto &C : i->Conversions) 909 C.~ImplicitConversionSequence(); 910 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 911 i->DeductionFailure.Destroy(); 912 } 913 } 914 915 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 916 destroyCandidates(); 917 SlabAllocator.Reset(); 918 NumInlineBytesUsed = 0; 919 Candidates.clear(); 920 Functions.clear(); 921 Kind = CSK; 922 } 923 924 namespace { 925 class UnbridgedCastsSet { 926 struct Entry { 927 Expr **Addr; 928 Expr *Saved; 929 }; 930 SmallVector<Entry, 2> Entries; 931 932 public: 933 void save(Sema &S, Expr *&E) { 934 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 935 Entry entry = { &E, E }; 936 Entries.push_back(entry); 937 E = S.stripARCUnbridgedCast(E); 938 } 939 940 void restore() { 941 for (SmallVectorImpl<Entry>::iterator 942 i = Entries.begin(), e = Entries.end(); i != e; ++i) 943 *i->Addr = i->Saved; 944 } 945 }; 946 } 947 948 /// checkPlaceholderForOverload - Do any interesting placeholder-like 949 /// preprocessing on the given expression. 950 /// 951 /// \param unbridgedCasts a collection to which to add unbridged casts; 952 /// without this, they will be immediately diagnosed as errors 953 /// 954 /// Return true on unrecoverable error. 955 static bool 956 checkPlaceholderForOverload(Sema &S, Expr *&E, 957 UnbridgedCastsSet *unbridgedCasts = nullptr) { 958 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 959 // We can't handle overloaded expressions here because overload 960 // resolution might reasonably tweak them. 961 if (placeholder->getKind() == BuiltinType::Overload) return false; 962 963 // If the context potentially accepts unbridged ARC casts, strip 964 // the unbridged cast and add it to the collection for later restoration. 965 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 966 unbridgedCasts) { 967 unbridgedCasts->save(S, E); 968 return false; 969 } 970 971 // Go ahead and check everything else. 972 ExprResult result = S.CheckPlaceholderExpr(E); 973 if (result.isInvalid()) 974 return true; 975 976 E = result.get(); 977 return false; 978 } 979 980 // Nothing to do. 981 return false; 982 } 983 984 /// checkArgPlaceholdersForOverload - Check a set of call operands for 985 /// placeholders. 986 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 987 UnbridgedCastsSet &unbridged) { 988 for (unsigned i = 0, e = Args.size(); i != e; ++i) 989 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 990 return true; 991 992 return false; 993 } 994 995 /// Determine whether the given New declaration is an overload of the 996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 997 /// New and Old cannot be overloaded, e.g., if New has the same signature as 998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 999 /// functions (or function templates) at all. When it does return Ovl_Match or 1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1002 /// declaration. 1003 /// 1004 /// Example: Given the following input: 1005 /// 1006 /// void f(int, float); // #1 1007 /// void f(int, int); // #2 1008 /// int f(int, int); // #3 1009 /// 1010 /// When we process #1, there is no previous declaration of "f", so IsOverload 1011 /// will not be used. 1012 /// 1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1016 /// unchanged. 1017 /// 1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1022 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1023 /// 1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1025 /// by a using declaration. The rules for whether to hide shadow declarations 1026 /// ignore some properties which otherwise figure into a function template's 1027 /// signature. 1028 Sema::OverloadKind 1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1030 NamedDecl *&Match, bool NewIsUsingDecl) { 1031 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1032 I != E; ++I) { 1033 NamedDecl *OldD = *I; 1034 1035 bool OldIsUsingDecl = false; 1036 if (isa<UsingShadowDecl>(OldD)) { 1037 OldIsUsingDecl = true; 1038 1039 // We can always introduce two using declarations into the same 1040 // context, even if they have identical signatures. 1041 if (NewIsUsingDecl) continue; 1042 1043 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1044 } 1045 1046 // A using-declaration does not conflict with another declaration 1047 // if one of them is hidden. 1048 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1049 continue; 1050 1051 // If either declaration was introduced by a using declaration, 1052 // we'll need to use slightly different rules for matching. 1053 // Essentially, these rules are the normal rules, except that 1054 // function templates hide function templates with different 1055 // return types or template parameter lists. 1056 bool UseMemberUsingDeclRules = 1057 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1058 !New->getFriendObjectKind(); 1059 1060 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1061 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1062 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1063 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1064 continue; 1065 } 1066 1067 if (!isa<FunctionTemplateDecl>(OldD) && 1068 !shouldLinkPossiblyHiddenDecl(*I, New)) 1069 continue; 1070 1071 Match = *I; 1072 return Ovl_Match; 1073 } 1074 1075 // Builtins that have custom typechecking or have a reference should 1076 // not be overloadable or redeclarable. 1077 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1078 Match = *I; 1079 return Ovl_NonFunction; 1080 } 1081 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1082 // We can overload with these, which can show up when doing 1083 // redeclaration checks for UsingDecls. 1084 assert(Old.getLookupKind() == LookupUsingDeclName); 1085 } else if (isa<TagDecl>(OldD)) { 1086 // We can always overload with tags by hiding them. 1087 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1088 // Optimistically assume that an unresolved using decl will 1089 // overload; if it doesn't, we'll have to diagnose during 1090 // template instantiation. 1091 // 1092 // Exception: if the scope is dependent and this is not a class 1093 // member, the using declaration can only introduce an enumerator. 1094 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1095 Match = *I; 1096 return Ovl_NonFunction; 1097 } 1098 } else { 1099 // (C++ 13p1): 1100 // Only function declarations can be overloaded; object and type 1101 // declarations cannot be overloaded. 1102 Match = *I; 1103 return Ovl_NonFunction; 1104 } 1105 } 1106 1107 // C++ [temp.friend]p1: 1108 // For a friend function declaration that is not a template declaration: 1109 // -- if the name of the friend is a qualified or unqualified template-id, 1110 // [...], otherwise 1111 // -- if the name of the friend is a qualified-id and a matching 1112 // non-template function is found in the specified class or namespace, 1113 // the friend declaration refers to that function, otherwise, 1114 // -- if the name of the friend is a qualified-id and a matching function 1115 // template is found in the specified class or namespace, the friend 1116 // declaration refers to the deduced specialization of that function 1117 // template, otherwise 1118 // -- the name shall be an unqualified-id [...] 1119 // If we get here for a qualified friend declaration, we've just reached the 1120 // third bullet. If the type of the friend is dependent, skip this lookup 1121 // until instantiation. 1122 if (New->getFriendObjectKind() && New->getQualifier() && 1123 !New->getDescribedFunctionTemplate() && 1124 !New->getDependentSpecializationInfo() && 1125 !New->getType()->isDependentType()) { 1126 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1127 TemplateSpecResult.addAllDecls(Old); 1128 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1129 /*QualifiedFriend*/true)) { 1130 New->setInvalidDecl(); 1131 return Ovl_Overload; 1132 } 1133 1134 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1135 return Ovl_Match; 1136 } 1137 1138 return Ovl_Overload; 1139 } 1140 1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1142 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1143 bool ConsiderRequiresClauses) { 1144 // C++ [basic.start.main]p2: This function shall not be overloaded. 1145 if (New->isMain()) 1146 return false; 1147 1148 // MSVCRT user defined entry points cannot be overloaded. 1149 if (New->isMSVCRTEntryPoint()) 1150 return false; 1151 1152 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1153 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1154 1155 // C++ [temp.fct]p2: 1156 // A function template can be overloaded with other function templates 1157 // and with normal (non-template) functions. 1158 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1159 return true; 1160 1161 // Is the function New an overload of the function Old? 1162 QualType OldQType = Context.getCanonicalType(Old->getType()); 1163 QualType NewQType = Context.getCanonicalType(New->getType()); 1164 1165 // Compare the signatures (C++ 1.3.10) of the two functions to 1166 // determine whether they are overloads. If we find any mismatch 1167 // in the signature, they are overloads. 1168 1169 // If either of these functions is a K&R-style function (no 1170 // prototype), then we consider them to have matching signatures. 1171 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1172 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1173 return false; 1174 1175 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1176 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1177 1178 // The signature of a function includes the types of its 1179 // parameters (C++ 1.3.10), which includes the presence or absence 1180 // of the ellipsis; see C++ DR 357). 1181 if (OldQType != NewQType && 1182 (OldType->getNumParams() != NewType->getNumParams() || 1183 OldType->isVariadic() != NewType->isVariadic() || 1184 !FunctionParamTypesAreEqual(OldType, NewType))) 1185 return true; 1186 1187 // C++ [temp.over.link]p4: 1188 // The signature of a function template consists of its function 1189 // signature, its return type and its template parameter list. The names 1190 // of the template parameters are significant only for establishing the 1191 // relationship between the template parameters and the rest of the 1192 // signature. 1193 // 1194 // We check the return type and template parameter lists for function 1195 // templates first; the remaining checks follow. 1196 // 1197 // However, we don't consider either of these when deciding whether 1198 // a member introduced by a shadow declaration is hidden. 1199 if (!UseMemberUsingDeclRules && NewTemplate && 1200 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1201 OldTemplate->getTemplateParameters(), 1202 false, TPL_TemplateMatch) || 1203 !Context.hasSameType(Old->getDeclaredReturnType(), 1204 New->getDeclaredReturnType()))) 1205 return true; 1206 1207 // If the function is a class member, its signature includes the 1208 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1209 // 1210 // As part of this, also check whether one of the member functions 1211 // is static, in which case they are not overloads (C++ 1212 // 13.1p2). While not part of the definition of the signature, 1213 // this check is important to determine whether these functions 1214 // can be overloaded. 1215 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1216 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1217 if (OldMethod && NewMethod && 1218 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1219 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1220 if (!UseMemberUsingDeclRules && 1221 (OldMethod->getRefQualifier() == RQ_None || 1222 NewMethod->getRefQualifier() == RQ_None)) { 1223 // C++0x [over.load]p2: 1224 // - Member function declarations with the same name and the same 1225 // parameter-type-list as well as member function template 1226 // declarations with the same name, the same parameter-type-list, and 1227 // the same template parameter lists cannot be overloaded if any of 1228 // them, but not all, have a ref-qualifier (8.3.5). 1229 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1230 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1231 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1232 } 1233 return true; 1234 } 1235 1236 // We may not have applied the implicit const for a constexpr member 1237 // function yet (because we haven't yet resolved whether this is a static 1238 // or non-static member function). Add it now, on the assumption that this 1239 // is a redeclaration of OldMethod. 1240 auto OldQuals = OldMethod->getMethodQualifiers(); 1241 auto NewQuals = NewMethod->getMethodQualifiers(); 1242 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1243 !isa<CXXConstructorDecl>(NewMethod)) 1244 NewQuals.addConst(); 1245 // We do not allow overloading based off of '__restrict'. 1246 OldQuals.removeRestrict(); 1247 NewQuals.removeRestrict(); 1248 if (OldQuals != NewQuals) 1249 return true; 1250 } 1251 1252 // Though pass_object_size is placed on parameters and takes an argument, we 1253 // consider it to be a function-level modifier for the sake of function 1254 // identity. Either the function has one or more parameters with 1255 // pass_object_size or it doesn't. 1256 if (functionHasPassObjectSizeParams(New) != 1257 functionHasPassObjectSizeParams(Old)) 1258 return true; 1259 1260 // enable_if attributes are an order-sensitive part of the signature. 1261 for (specific_attr_iterator<EnableIfAttr> 1262 NewI = New->specific_attr_begin<EnableIfAttr>(), 1263 NewE = New->specific_attr_end<EnableIfAttr>(), 1264 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1265 OldE = Old->specific_attr_end<EnableIfAttr>(); 1266 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1267 if (NewI == NewE || OldI == OldE) 1268 return true; 1269 llvm::FoldingSetNodeID NewID, OldID; 1270 NewI->getCond()->Profile(NewID, Context, true); 1271 OldI->getCond()->Profile(OldID, Context, true); 1272 if (NewID != OldID) 1273 return true; 1274 } 1275 1276 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1277 // Don't allow overloading of destructors. (In theory we could, but it 1278 // would be a giant change to clang.) 1279 if (!isa<CXXDestructorDecl>(New)) { 1280 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1281 OldTarget = IdentifyCUDATarget(Old); 1282 if (NewTarget != CFT_InvalidTarget) { 1283 assert((OldTarget != CFT_InvalidTarget) && 1284 "Unexpected invalid target."); 1285 1286 // Allow overloading of functions with same signature and different CUDA 1287 // target attributes. 1288 if (NewTarget != OldTarget) 1289 return true; 1290 } 1291 } 1292 } 1293 1294 if (ConsiderRequiresClauses) { 1295 Expr *NewRC = New->getTrailingRequiresClause(), 1296 *OldRC = Old->getTrailingRequiresClause(); 1297 if ((NewRC != nullptr) != (OldRC != nullptr)) 1298 // RC are most certainly different - these are overloads. 1299 return true; 1300 1301 if (NewRC) { 1302 llvm::FoldingSetNodeID NewID, OldID; 1303 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1304 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1305 if (NewID != OldID) 1306 // RCs are not equivalent - these are overloads. 1307 return true; 1308 } 1309 } 1310 1311 // The signatures match; this is not an overload. 1312 return false; 1313 } 1314 1315 /// Tries a user-defined conversion from From to ToType. 1316 /// 1317 /// Produces an implicit conversion sequence for when a standard conversion 1318 /// is not an option. See TryImplicitConversion for more information. 1319 static ImplicitConversionSequence 1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1321 bool SuppressUserConversions, 1322 AllowedExplicit AllowExplicit, 1323 bool InOverloadResolution, 1324 bool CStyle, 1325 bool AllowObjCWritebackConversion, 1326 bool AllowObjCConversionOnExplicit) { 1327 ImplicitConversionSequence ICS; 1328 1329 if (SuppressUserConversions) { 1330 // We're not in the case above, so there is no conversion that 1331 // we can perform. 1332 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1333 return ICS; 1334 } 1335 1336 // Attempt user-defined conversion. 1337 OverloadCandidateSet Conversions(From->getExprLoc(), 1338 OverloadCandidateSet::CSK_Normal); 1339 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1340 Conversions, AllowExplicit, 1341 AllowObjCConversionOnExplicit)) { 1342 case OR_Success: 1343 case OR_Deleted: 1344 ICS.setUserDefined(); 1345 // C++ [over.ics.user]p4: 1346 // A conversion of an expression of class type to the same class 1347 // type is given Exact Match rank, and a conversion of an 1348 // expression of class type to a base class of that type is 1349 // given Conversion rank, in spite of the fact that a copy 1350 // constructor (i.e., a user-defined conversion function) is 1351 // called for those cases. 1352 if (CXXConstructorDecl *Constructor 1353 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1354 QualType FromCanon 1355 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1356 QualType ToCanon 1357 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1358 if (Constructor->isCopyConstructor() && 1359 (FromCanon == ToCanon || 1360 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1361 // Turn this into a "standard" conversion sequence, so that it 1362 // gets ranked with standard conversion sequences. 1363 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1364 ICS.setStandard(); 1365 ICS.Standard.setAsIdentityConversion(); 1366 ICS.Standard.setFromType(From->getType()); 1367 ICS.Standard.setAllToTypes(ToType); 1368 ICS.Standard.CopyConstructor = Constructor; 1369 ICS.Standard.FoundCopyConstructor = Found; 1370 if (ToCanon != FromCanon) 1371 ICS.Standard.Second = ICK_Derived_To_Base; 1372 } 1373 } 1374 break; 1375 1376 case OR_Ambiguous: 1377 ICS.setAmbiguous(); 1378 ICS.Ambiguous.setFromType(From->getType()); 1379 ICS.Ambiguous.setToType(ToType); 1380 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1381 Cand != Conversions.end(); ++Cand) 1382 if (Cand->Best) 1383 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1384 break; 1385 1386 // Fall through. 1387 case OR_No_Viable_Function: 1388 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1389 break; 1390 } 1391 1392 return ICS; 1393 } 1394 1395 /// TryImplicitConversion - Attempt to perform an implicit conversion 1396 /// from the given expression (Expr) to the given type (ToType). This 1397 /// function returns an implicit conversion sequence that can be used 1398 /// to perform the initialization. Given 1399 /// 1400 /// void f(float f); 1401 /// void g(int i) { f(i); } 1402 /// 1403 /// this routine would produce an implicit conversion sequence to 1404 /// describe the initialization of f from i, which will be a standard 1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1407 // 1408 /// Note that this routine only determines how the conversion can be 1409 /// performed; it does not actually perform the conversion. As such, 1410 /// it will not produce any diagnostics if no conversion is available, 1411 /// but will instead return an implicit conversion sequence of kind 1412 /// "BadConversion". 1413 /// 1414 /// If @p SuppressUserConversions, then user-defined conversions are 1415 /// not permitted. 1416 /// If @p AllowExplicit, then explicit user-defined conversions are 1417 /// permitted. 1418 /// 1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1420 /// writeback conversion, which allows __autoreleasing id* parameters to 1421 /// be initialized with __strong id* or __weak id* arguments. 1422 static ImplicitConversionSequence 1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1424 bool SuppressUserConversions, 1425 AllowedExplicit AllowExplicit, 1426 bool InOverloadResolution, 1427 bool CStyle, 1428 bool AllowObjCWritebackConversion, 1429 bool AllowObjCConversionOnExplicit) { 1430 ImplicitConversionSequence ICS; 1431 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1432 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1433 ICS.setStandard(); 1434 return ICS; 1435 } 1436 1437 if (!S.getLangOpts().CPlusPlus) { 1438 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1439 return ICS; 1440 } 1441 1442 // C++ [over.ics.user]p4: 1443 // A conversion of an expression of class type to the same class 1444 // type is given Exact Match rank, and a conversion of an 1445 // expression of class type to a base class of that type is 1446 // given Conversion rank, in spite of the fact that a copy/move 1447 // constructor (i.e., a user-defined conversion function) is 1448 // called for those cases. 1449 QualType FromType = From->getType(); 1450 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1451 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1452 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1453 ICS.setStandard(); 1454 ICS.Standard.setAsIdentityConversion(); 1455 ICS.Standard.setFromType(FromType); 1456 ICS.Standard.setAllToTypes(ToType); 1457 1458 // We don't actually check at this point whether there is a valid 1459 // copy/move constructor, since overloading just assumes that it 1460 // exists. When we actually perform initialization, we'll find the 1461 // appropriate constructor to copy the returned object, if needed. 1462 ICS.Standard.CopyConstructor = nullptr; 1463 1464 // Determine whether this is considered a derived-to-base conversion. 1465 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1466 ICS.Standard.Second = ICK_Derived_To_Base; 1467 1468 return ICS; 1469 } 1470 1471 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1472 AllowExplicit, InOverloadResolution, CStyle, 1473 AllowObjCWritebackConversion, 1474 AllowObjCConversionOnExplicit); 1475 } 1476 1477 ImplicitConversionSequence 1478 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1479 bool SuppressUserConversions, 1480 AllowedExplicit AllowExplicit, 1481 bool InOverloadResolution, 1482 bool CStyle, 1483 bool AllowObjCWritebackConversion) { 1484 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1485 AllowExplicit, InOverloadResolution, CStyle, 1486 AllowObjCWritebackConversion, 1487 /*AllowObjCConversionOnExplicit=*/false); 1488 } 1489 1490 /// PerformImplicitConversion - Perform an implicit conversion of the 1491 /// expression From to the type ToType. Returns the 1492 /// converted expression. Flavor is the kind of conversion we're 1493 /// performing, used in the error message. If @p AllowExplicit, 1494 /// explicit user-defined conversions are permitted. 1495 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, 1497 bool AllowExplicit) { 1498 if (checkPlaceholderForOverload(*this, From)) 1499 return ExprError(); 1500 1501 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1502 bool AllowObjCWritebackConversion 1503 = getLangOpts().ObjCAutoRefCount && 1504 (Action == AA_Passing || Action == AA_Sending); 1505 if (getLangOpts().ObjC) 1506 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1507 From->getType(), From); 1508 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1509 *this, From, ToType, 1510 /*SuppressUserConversions=*/false, 1511 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1512 /*InOverloadResolution=*/false, 1513 /*CStyle=*/false, AllowObjCWritebackConversion, 1514 /*AllowObjCConversionOnExplicit=*/false); 1515 return PerformImplicitConversion(From, ToType, ICS, Action); 1516 } 1517 1518 /// Determine whether the conversion from FromType to ToType is a valid 1519 /// conversion that strips "noexcept" or "noreturn" off the nested function 1520 /// type. 1521 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1522 QualType &ResultTy) { 1523 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1524 return false; 1525 1526 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1527 // or F(t noexcept) -> F(t) 1528 // where F adds one of the following at most once: 1529 // - a pointer 1530 // - a member pointer 1531 // - a block pointer 1532 // Changes here need matching changes in FindCompositePointerType. 1533 CanQualType CanTo = Context.getCanonicalType(ToType); 1534 CanQualType CanFrom = Context.getCanonicalType(FromType); 1535 Type::TypeClass TyClass = CanTo->getTypeClass(); 1536 if (TyClass != CanFrom->getTypeClass()) return false; 1537 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1538 if (TyClass == Type::Pointer) { 1539 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1540 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1541 } else if (TyClass == Type::BlockPointer) { 1542 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1543 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1544 } else if (TyClass == Type::MemberPointer) { 1545 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1546 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1547 // A function pointer conversion cannot change the class of the function. 1548 if (ToMPT->getClass() != FromMPT->getClass()) 1549 return false; 1550 CanTo = ToMPT->getPointeeType(); 1551 CanFrom = FromMPT->getPointeeType(); 1552 } else { 1553 return false; 1554 } 1555 1556 TyClass = CanTo->getTypeClass(); 1557 if (TyClass != CanFrom->getTypeClass()) return false; 1558 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1559 return false; 1560 } 1561 1562 const auto *FromFn = cast<FunctionType>(CanFrom); 1563 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1564 1565 const auto *ToFn = cast<FunctionType>(CanTo); 1566 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1567 1568 bool Changed = false; 1569 1570 // Drop 'noreturn' if not present in target type. 1571 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1572 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1573 Changed = true; 1574 } 1575 1576 // Drop 'noexcept' if not present in target type. 1577 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1578 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1579 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1580 FromFn = cast<FunctionType>( 1581 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1582 EST_None) 1583 .getTypePtr()); 1584 Changed = true; 1585 } 1586 1587 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1588 // only if the ExtParameterInfo lists of the two function prototypes can be 1589 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1590 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1591 bool CanUseToFPT, CanUseFromFPT; 1592 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1593 CanUseFromFPT, NewParamInfos) && 1594 CanUseToFPT && !CanUseFromFPT) { 1595 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1596 ExtInfo.ExtParameterInfos = 1597 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1598 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1599 FromFPT->getParamTypes(), ExtInfo); 1600 FromFn = QT->getAs<FunctionType>(); 1601 Changed = true; 1602 } 1603 } 1604 1605 if (!Changed) 1606 return false; 1607 1608 assert(QualType(FromFn, 0).isCanonical()); 1609 if (QualType(FromFn, 0) != CanTo) return false; 1610 1611 ResultTy = ToType; 1612 return true; 1613 } 1614 1615 /// Determine whether the conversion from FromType to ToType is a valid 1616 /// vector conversion. 1617 /// 1618 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1619 /// conversion. 1620 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, 1621 ImplicitConversionKind &ICK, Expr *From, 1622 bool InOverloadResolution) { 1623 // We need at least one of these types to be a vector type to have a vector 1624 // conversion. 1625 if (!ToType->isVectorType() && !FromType->isVectorType()) 1626 return false; 1627 1628 // Identical types require no conversions. 1629 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1630 return false; 1631 1632 // There are no conversions between extended vector types, only identity. 1633 if (ToType->isExtVectorType()) { 1634 // There are no conversions between extended vector types other than the 1635 // identity conversion. 1636 if (FromType->isExtVectorType()) 1637 return false; 1638 1639 // Vector splat from any arithmetic type to a vector. 1640 if (FromType->isArithmeticType()) { 1641 ICK = ICK_Vector_Splat; 1642 return true; 1643 } 1644 } 1645 1646 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1647 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1648 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1649 ICK = ICK_SVE_Vector_Conversion; 1650 return true; 1651 } 1652 1653 // We can perform the conversion between vector types in the following cases: 1654 // 1)vector types are equivalent AltiVec and GCC vector types 1655 // 2)lax vector conversions are permitted and the vector types are of the 1656 // same size 1657 // 3)the destination type does not have the ARM MVE strict-polymorphism 1658 // attribute, which inhibits lax vector conversion for overload resolution 1659 // only 1660 if (ToType->isVectorType() && FromType->isVectorType()) { 1661 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1662 (S.isLaxVectorConversion(FromType, ToType) && 1663 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1664 if (S.isLaxVectorConversion(FromType, ToType) && 1665 S.anyAltivecTypes(FromType, ToType) && 1666 !S.areSameVectorElemTypes(FromType, ToType) && 1667 !InOverloadResolution) { 1668 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) 1669 << FromType << ToType; 1670 } 1671 ICK = ICK_Vector_Conversion; 1672 return true; 1673 } 1674 } 1675 1676 return false; 1677 } 1678 1679 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1680 bool InOverloadResolution, 1681 StandardConversionSequence &SCS, 1682 bool CStyle); 1683 1684 /// IsStandardConversion - Determines whether there is a standard 1685 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1686 /// expression From to the type ToType. Standard conversion sequences 1687 /// only consider non-class types; for conversions that involve class 1688 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1689 /// contain the standard conversion sequence required to perform this 1690 /// conversion and this routine will return true. Otherwise, this 1691 /// routine will return false and the value of SCS is unspecified. 1692 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1693 bool InOverloadResolution, 1694 StandardConversionSequence &SCS, 1695 bool CStyle, 1696 bool AllowObjCWritebackConversion) { 1697 QualType FromType = From->getType(); 1698 1699 // Standard conversions (C++ [conv]) 1700 SCS.setAsIdentityConversion(); 1701 SCS.IncompatibleObjC = false; 1702 SCS.setFromType(FromType); 1703 SCS.CopyConstructor = nullptr; 1704 1705 // There are no standard conversions for class types in C++, so 1706 // abort early. When overloading in C, however, we do permit them. 1707 if (S.getLangOpts().CPlusPlus && 1708 (FromType->isRecordType() || ToType->isRecordType())) 1709 return false; 1710 1711 // The first conversion can be an lvalue-to-rvalue conversion, 1712 // array-to-pointer conversion, or function-to-pointer conversion 1713 // (C++ 4p1). 1714 1715 if (FromType == S.Context.OverloadTy) { 1716 DeclAccessPair AccessPair; 1717 if (FunctionDecl *Fn 1718 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1719 AccessPair)) { 1720 // We were able to resolve the address of the overloaded function, 1721 // so we can convert to the type of that function. 1722 FromType = Fn->getType(); 1723 SCS.setFromType(FromType); 1724 1725 // we can sometimes resolve &foo<int> regardless of ToType, so check 1726 // if the type matches (identity) or we are converting to bool 1727 if (!S.Context.hasSameUnqualifiedType( 1728 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1729 QualType resultTy; 1730 // if the function type matches except for [[noreturn]], it's ok 1731 if (!S.IsFunctionConversion(FromType, 1732 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1733 // otherwise, only a boolean conversion is standard 1734 if (!ToType->isBooleanType()) 1735 return false; 1736 } 1737 1738 // Check if the "from" expression is taking the address of an overloaded 1739 // function and recompute the FromType accordingly. Take advantage of the 1740 // fact that non-static member functions *must* have such an address-of 1741 // expression. 1742 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1743 if (Method && !Method->isStatic()) { 1744 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1745 "Non-unary operator on non-static member address"); 1746 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1747 == UO_AddrOf && 1748 "Non-address-of operator on non-static member address"); 1749 const Type *ClassType 1750 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1751 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1752 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1753 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1754 UO_AddrOf && 1755 "Non-address-of operator for overloaded function expression"); 1756 FromType = S.Context.getPointerType(FromType); 1757 } 1758 } else { 1759 return false; 1760 } 1761 } 1762 // Lvalue-to-rvalue conversion (C++11 4.1): 1763 // A glvalue (3.10) of a non-function, non-array type T can 1764 // be converted to a prvalue. 1765 bool argIsLValue = From->isGLValue(); 1766 if (argIsLValue && 1767 !FromType->isFunctionType() && !FromType->isArrayType() && 1768 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1769 SCS.First = ICK_Lvalue_To_Rvalue; 1770 1771 // C11 6.3.2.1p2: 1772 // ... if the lvalue has atomic type, the value has the non-atomic version 1773 // of the type of the lvalue ... 1774 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1775 FromType = Atomic->getValueType(); 1776 1777 // If T is a non-class type, the type of the rvalue is the 1778 // cv-unqualified version of T. Otherwise, the type of the rvalue 1779 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1780 // just strip the qualifiers because they don't matter. 1781 FromType = FromType.getUnqualifiedType(); 1782 } else if (FromType->isArrayType()) { 1783 // Array-to-pointer conversion (C++ 4.2) 1784 SCS.First = ICK_Array_To_Pointer; 1785 1786 // An lvalue or rvalue of type "array of N T" or "array of unknown 1787 // bound of T" can be converted to an rvalue of type "pointer to 1788 // T" (C++ 4.2p1). 1789 FromType = S.Context.getArrayDecayedType(FromType); 1790 1791 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1792 // This conversion is deprecated in C++03 (D.4) 1793 SCS.DeprecatedStringLiteralToCharPtr = true; 1794 1795 // For the purpose of ranking in overload resolution 1796 // (13.3.3.1.1), this conversion is considered an 1797 // array-to-pointer conversion followed by a qualification 1798 // conversion (4.4). (C++ 4.2p2) 1799 SCS.Second = ICK_Identity; 1800 SCS.Third = ICK_Qualification; 1801 SCS.QualificationIncludesObjCLifetime = false; 1802 SCS.setAllToTypes(FromType); 1803 return true; 1804 } 1805 } else if (FromType->isFunctionType() && argIsLValue) { 1806 // Function-to-pointer conversion (C++ 4.3). 1807 SCS.First = ICK_Function_To_Pointer; 1808 1809 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1810 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1811 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1812 return false; 1813 1814 // An lvalue of function type T can be converted to an rvalue of 1815 // type "pointer to T." The result is a pointer to the 1816 // function. (C++ 4.3p1). 1817 FromType = S.Context.getPointerType(FromType); 1818 } else { 1819 // We don't require any conversions for the first step. 1820 SCS.First = ICK_Identity; 1821 } 1822 SCS.setToType(0, FromType); 1823 1824 // The second conversion can be an integral promotion, floating 1825 // point promotion, integral conversion, floating point conversion, 1826 // floating-integral conversion, pointer conversion, 1827 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1828 // For overloading in C, this can also be a "compatible-type" 1829 // conversion. 1830 bool IncompatibleObjC = false; 1831 ImplicitConversionKind SecondICK = ICK_Identity; 1832 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1833 // The unqualified versions of the types are the same: there's no 1834 // conversion to do. 1835 SCS.Second = ICK_Identity; 1836 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1837 // Integral promotion (C++ 4.5). 1838 SCS.Second = ICK_Integral_Promotion; 1839 FromType = ToType.getUnqualifiedType(); 1840 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1841 // Floating point promotion (C++ 4.6). 1842 SCS.Second = ICK_Floating_Promotion; 1843 FromType = ToType.getUnqualifiedType(); 1844 } else if (S.IsComplexPromotion(FromType, ToType)) { 1845 // Complex promotion (Clang extension) 1846 SCS.Second = ICK_Complex_Promotion; 1847 FromType = ToType.getUnqualifiedType(); 1848 } else if (ToType->isBooleanType() && 1849 (FromType->isArithmeticType() || 1850 FromType->isAnyPointerType() || 1851 FromType->isBlockPointerType() || 1852 FromType->isMemberPointerType())) { 1853 // Boolean conversions (C++ 4.12). 1854 SCS.Second = ICK_Boolean_Conversion; 1855 FromType = S.Context.BoolTy; 1856 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1857 ToType->isIntegralType(S.Context)) { 1858 // Integral conversions (C++ 4.7). 1859 SCS.Second = ICK_Integral_Conversion; 1860 FromType = ToType.getUnqualifiedType(); 1861 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1862 // Complex conversions (C99 6.3.1.6) 1863 SCS.Second = ICK_Complex_Conversion; 1864 FromType = ToType.getUnqualifiedType(); 1865 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1866 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1867 // Complex-real conversions (C99 6.3.1.7) 1868 SCS.Second = ICK_Complex_Real; 1869 FromType = ToType.getUnqualifiedType(); 1870 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1871 // FIXME: disable conversions between long double, __ibm128 and __float128 1872 // if their representation is different until there is back end support 1873 // We of course allow this conversion if long double is really double. 1874 1875 // Conversions between bfloat and other floats are not permitted. 1876 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1877 return false; 1878 1879 // Conversions between IEEE-quad and IBM-extended semantics are not 1880 // permitted. 1881 const llvm::fltSemantics &FromSem = 1882 S.Context.getFloatTypeSemantics(FromType); 1883 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 1884 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 1885 &ToSem == &llvm::APFloat::IEEEquad()) || 1886 (&FromSem == &llvm::APFloat::IEEEquad() && 1887 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 1888 return false; 1889 1890 // Floating point conversions (C++ 4.8). 1891 SCS.Second = ICK_Floating_Conversion; 1892 FromType = ToType.getUnqualifiedType(); 1893 } else if ((FromType->isRealFloatingType() && 1894 ToType->isIntegralType(S.Context)) || 1895 (FromType->isIntegralOrUnscopedEnumerationType() && 1896 ToType->isRealFloatingType())) { 1897 // Conversions between bfloat and int are not permitted. 1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1899 return false; 1900 1901 // Floating-integral conversions (C++ 4.9). 1902 SCS.Second = ICK_Floating_Integral; 1903 FromType = ToType.getUnqualifiedType(); 1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1905 SCS.Second = ICK_Block_Pointer_Conversion; 1906 } else if (AllowObjCWritebackConversion && 1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1908 SCS.Second = ICK_Writeback_Conversion; 1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1910 FromType, IncompatibleObjC)) { 1911 // Pointer conversions (C++ 4.10). 1912 SCS.Second = ICK_Pointer_Conversion; 1913 SCS.IncompatibleObjC = IncompatibleObjC; 1914 FromType = FromType.getUnqualifiedType(); 1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1916 InOverloadResolution, FromType)) { 1917 // Pointer to member conversions (4.11). 1918 SCS.Second = ICK_Pointer_Member; 1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, 1920 InOverloadResolution)) { 1921 SCS.Second = SecondICK; 1922 FromType = ToType.getUnqualifiedType(); 1923 } else if (!S.getLangOpts().CPlusPlus && 1924 S.Context.typesAreCompatible(ToType, FromType)) { 1925 // Compatible conversions (Clang extension for C function overloading) 1926 SCS.Second = ICK_Compatible_Conversion; 1927 FromType = ToType.getUnqualifiedType(); 1928 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1929 InOverloadResolution, 1930 SCS, CStyle)) { 1931 SCS.Second = ICK_TransparentUnionConversion; 1932 FromType = ToType; 1933 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1934 CStyle)) { 1935 // tryAtomicConversion has updated the standard conversion sequence 1936 // appropriately. 1937 return true; 1938 } else if (ToType->isEventT() && 1939 From->isIntegerConstantExpr(S.getASTContext()) && 1940 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1941 SCS.Second = ICK_Zero_Event_Conversion; 1942 FromType = ToType; 1943 } else if (ToType->isQueueT() && 1944 From->isIntegerConstantExpr(S.getASTContext()) && 1945 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1946 SCS.Second = ICK_Zero_Queue_Conversion; 1947 FromType = ToType; 1948 } else if (ToType->isSamplerT() && 1949 From->isIntegerConstantExpr(S.getASTContext())) { 1950 SCS.Second = ICK_Compatible_Conversion; 1951 FromType = ToType; 1952 } else { 1953 // No second conversion required. 1954 SCS.Second = ICK_Identity; 1955 } 1956 SCS.setToType(1, FromType); 1957 1958 // The third conversion can be a function pointer conversion or a 1959 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1960 bool ObjCLifetimeConversion; 1961 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1962 // Function pointer conversions (removing 'noexcept') including removal of 1963 // 'noreturn' (Clang extension). 1964 SCS.Third = ICK_Function_Conversion; 1965 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1966 ObjCLifetimeConversion)) { 1967 SCS.Third = ICK_Qualification; 1968 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1969 FromType = ToType; 1970 } else { 1971 // No conversion required 1972 SCS.Third = ICK_Identity; 1973 } 1974 1975 // C++ [over.best.ics]p6: 1976 // [...] Any difference in top-level cv-qualification is 1977 // subsumed by the initialization itself and does not constitute 1978 // a conversion. [...] 1979 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1980 QualType CanonTo = S.Context.getCanonicalType(ToType); 1981 if (CanonFrom.getLocalUnqualifiedType() 1982 == CanonTo.getLocalUnqualifiedType() && 1983 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1984 FromType = ToType; 1985 CanonFrom = CanonTo; 1986 } 1987 1988 SCS.setToType(2, FromType); 1989 1990 if (CanonFrom == CanonTo) 1991 return true; 1992 1993 // If we have not converted the argument type to the parameter type, 1994 // this is a bad conversion sequence, unless we're resolving an overload in C. 1995 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1996 return false; 1997 1998 ExprResult ER = ExprResult{From}; 1999 Sema::AssignConvertType Conv = 2000 S.CheckSingleAssignmentConstraints(ToType, ER, 2001 /*Diagnose=*/false, 2002 /*DiagnoseCFAudited=*/false, 2003 /*ConvertRHS=*/false); 2004 ImplicitConversionKind SecondConv; 2005 switch (Conv) { 2006 case Sema::Compatible: 2007 SecondConv = ICK_C_Only_Conversion; 2008 break; 2009 // For our purposes, discarding qualifiers is just as bad as using an 2010 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2011 // qualifiers, as well. 2012 case Sema::CompatiblePointerDiscardsQualifiers: 2013 case Sema::IncompatiblePointer: 2014 case Sema::IncompatiblePointerSign: 2015 SecondConv = ICK_Incompatible_Pointer_Conversion; 2016 break; 2017 default: 2018 return false; 2019 } 2020 2021 // First can only be an lvalue conversion, so we pretend that this was the 2022 // second conversion. First should already be valid from earlier in the 2023 // function. 2024 SCS.Second = SecondConv; 2025 SCS.setToType(1, ToType); 2026 2027 // Third is Identity, because Second should rank us worse than any other 2028 // conversion. This could also be ICK_Qualification, but it's simpler to just 2029 // lump everything in with the second conversion, and we don't gain anything 2030 // from making this ICK_Qualification. 2031 SCS.Third = ICK_Identity; 2032 SCS.setToType(2, ToType); 2033 return true; 2034 } 2035 2036 static bool 2037 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2038 QualType &ToType, 2039 bool InOverloadResolution, 2040 StandardConversionSequence &SCS, 2041 bool CStyle) { 2042 2043 const RecordType *UT = ToType->getAsUnionType(); 2044 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2045 return false; 2046 // The field to initialize within the transparent union. 2047 RecordDecl *UD = UT->getDecl(); 2048 // It's compatible if the expression matches any of the fields. 2049 for (const auto *it : UD->fields()) { 2050 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2051 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2052 ToType = it->getType(); 2053 return true; 2054 } 2055 } 2056 return false; 2057 } 2058 2059 /// IsIntegralPromotion - Determines whether the conversion from the 2060 /// expression From (whose potentially-adjusted type is FromType) to 2061 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2062 /// sets PromotedType to the promoted type. 2063 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2064 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2065 // All integers are built-in. 2066 if (!To) { 2067 return false; 2068 } 2069 2070 // An rvalue of type char, signed char, unsigned char, short int, or 2071 // unsigned short int can be converted to an rvalue of type int if 2072 // int can represent all the values of the source type; otherwise, 2073 // the source rvalue can be converted to an rvalue of type unsigned 2074 // int (C++ 4.5p1). 2075 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2076 !FromType->isEnumeralType()) { 2077 if (// We can promote any signed, promotable integer type to an int 2078 (FromType->isSignedIntegerType() || 2079 // We can promote any unsigned integer type whose size is 2080 // less than int to an int. 2081 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2082 return To->getKind() == BuiltinType::Int; 2083 } 2084 2085 return To->getKind() == BuiltinType::UInt; 2086 } 2087 2088 // C++11 [conv.prom]p3: 2089 // A prvalue of an unscoped enumeration type whose underlying type is not 2090 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2091 // following types that can represent all the values of the enumeration 2092 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2093 // unsigned int, long int, unsigned long int, long long int, or unsigned 2094 // long long int. If none of the types in that list can represent all the 2095 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2096 // type can be converted to an rvalue a prvalue of the extended integer type 2097 // with lowest integer conversion rank (4.13) greater than the rank of long 2098 // long in which all the values of the enumeration can be represented. If 2099 // there are two such extended types, the signed one is chosen. 2100 // C++11 [conv.prom]p4: 2101 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2102 // can be converted to a prvalue of its underlying type. Moreover, if 2103 // integral promotion can be applied to its underlying type, a prvalue of an 2104 // unscoped enumeration type whose underlying type is fixed can also be 2105 // converted to a prvalue of the promoted underlying type. 2106 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2107 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2108 // provided for a scoped enumeration. 2109 if (FromEnumType->getDecl()->isScoped()) 2110 return false; 2111 2112 // We can perform an integral promotion to the underlying type of the enum, 2113 // even if that's not the promoted type. Note that the check for promoting 2114 // the underlying type is based on the type alone, and does not consider 2115 // the bitfield-ness of the actual source expression. 2116 if (FromEnumType->getDecl()->isFixed()) { 2117 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2118 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2119 IsIntegralPromotion(nullptr, Underlying, ToType); 2120 } 2121 2122 // We have already pre-calculated the promotion type, so this is trivial. 2123 if (ToType->isIntegerType() && 2124 isCompleteType(From->getBeginLoc(), FromType)) 2125 return Context.hasSameUnqualifiedType( 2126 ToType, FromEnumType->getDecl()->getPromotionType()); 2127 2128 // C++ [conv.prom]p5: 2129 // If the bit-field has an enumerated type, it is treated as any other 2130 // value of that type for promotion purposes. 2131 // 2132 // ... so do not fall through into the bit-field checks below in C++. 2133 if (getLangOpts().CPlusPlus) 2134 return false; 2135 } 2136 2137 // C++0x [conv.prom]p2: 2138 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2139 // to an rvalue a prvalue of the first of the following types that can 2140 // represent all the values of its underlying type: int, unsigned int, 2141 // long int, unsigned long int, long long int, or unsigned long long int. 2142 // If none of the types in that list can represent all the values of its 2143 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2144 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2145 // type. 2146 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2147 ToType->isIntegerType()) { 2148 // Determine whether the type we're converting from is signed or 2149 // unsigned. 2150 bool FromIsSigned = FromType->isSignedIntegerType(); 2151 uint64_t FromSize = Context.getTypeSize(FromType); 2152 2153 // The types we'll try to promote to, in the appropriate 2154 // order. Try each of these types. 2155 QualType PromoteTypes[6] = { 2156 Context.IntTy, Context.UnsignedIntTy, 2157 Context.LongTy, Context.UnsignedLongTy , 2158 Context.LongLongTy, Context.UnsignedLongLongTy 2159 }; 2160 for (int Idx = 0; Idx < 6; ++Idx) { 2161 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2162 if (FromSize < ToSize || 2163 (FromSize == ToSize && 2164 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2165 // We found the type that we can promote to. If this is the 2166 // type we wanted, we have a promotion. Otherwise, no 2167 // promotion. 2168 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2169 } 2170 } 2171 } 2172 2173 // An rvalue for an integral bit-field (9.6) can be converted to an 2174 // rvalue of type int if int can represent all the values of the 2175 // bit-field; otherwise, it can be converted to unsigned int if 2176 // unsigned int can represent all the values of the bit-field. If 2177 // the bit-field is larger yet, no integral promotion applies to 2178 // it. If the bit-field has an enumerated type, it is treated as any 2179 // other value of that type for promotion purposes (C++ 4.5p3). 2180 // FIXME: We should delay checking of bit-fields until we actually perform the 2181 // conversion. 2182 // 2183 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2184 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2185 // bit-fields and those whose underlying type is larger than int) for GCC 2186 // compatibility. 2187 if (From) { 2188 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2189 Optional<llvm::APSInt> BitWidth; 2190 if (FromType->isIntegralType(Context) && 2191 (BitWidth = 2192 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2193 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2194 ToSize = Context.getTypeSize(ToType); 2195 2196 // Are we promoting to an int from a bitfield that fits in an int? 2197 if (*BitWidth < ToSize || 2198 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2199 return To->getKind() == BuiltinType::Int; 2200 } 2201 2202 // Are we promoting to an unsigned int from an unsigned bitfield 2203 // that fits into an unsigned int? 2204 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2205 return To->getKind() == BuiltinType::UInt; 2206 } 2207 2208 return false; 2209 } 2210 } 2211 } 2212 2213 // An rvalue of type bool can be converted to an rvalue of type int, 2214 // with false becoming zero and true becoming one (C++ 4.5p4). 2215 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2216 return true; 2217 } 2218 2219 return false; 2220 } 2221 2222 /// IsFloatingPointPromotion - Determines whether the conversion from 2223 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2224 /// returns true and sets PromotedType to the promoted type. 2225 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2226 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2227 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2228 /// An rvalue of type float can be converted to an rvalue of type 2229 /// double. (C++ 4.6p1). 2230 if (FromBuiltin->getKind() == BuiltinType::Float && 2231 ToBuiltin->getKind() == BuiltinType::Double) 2232 return true; 2233 2234 // C99 6.3.1.5p1: 2235 // When a float is promoted to double or long double, or a 2236 // double is promoted to long double [...]. 2237 if (!getLangOpts().CPlusPlus && 2238 (FromBuiltin->getKind() == BuiltinType::Float || 2239 FromBuiltin->getKind() == BuiltinType::Double) && 2240 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2241 ToBuiltin->getKind() == BuiltinType::Float128 || 2242 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2243 return true; 2244 2245 // Half can be promoted to float. 2246 if (!getLangOpts().NativeHalfType && 2247 FromBuiltin->getKind() == BuiltinType::Half && 2248 ToBuiltin->getKind() == BuiltinType::Float) 2249 return true; 2250 } 2251 2252 return false; 2253 } 2254 2255 /// Determine if a conversion is a complex promotion. 2256 /// 2257 /// A complex promotion is defined as a complex -> complex conversion 2258 /// where the conversion between the underlying real types is a 2259 /// floating-point or integral promotion. 2260 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2261 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2262 if (!FromComplex) 2263 return false; 2264 2265 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2266 if (!ToComplex) 2267 return false; 2268 2269 return IsFloatingPointPromotion(FromComplex->getElementType(), 2270 ToComplex->getElementType()) || 2271 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2272 ToComplex->getElementType()); 2273 } 2274 2275 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2276 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2277 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2278 /// if non-empty, will be a pointer to ToType that may or may not have 2279 /// the right set of qualifiers on its pointee. 2280 /// 2281 static QualType 2282 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2283 QualType ToPointee, QualType ToType, 2284 ASTContext &Context, 2285 bool StripObjCLifetime = false) { 2286 assert((FromPtr->getTypeClass() == Type::Pointer || 2287 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2288 "Invalid similarly-qualified pointer type"); 2289 2290 /// Conversions to 'id' subsume cv-qualifier conversions. 2291 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2292 return ToType.getUnqualifiedType(); 2293 2294 QualType CanonFromPointee 2295 = Context.getCanonicalType(FromPtr->getPointeeType()); 2296 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2297 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2298 2299 if (StripObjCLifetime) 2300 Quals.removeObjCLifetime(); 2301 2302 // Exact qualifier match -> return the pointer type we're converting to. 2303 if (CanonToPointee.getLocalQualifiers() == Quals) { 2304 // ToType is exactly what we need. Return it. 2305 if (!ToType.isNull()) 2306 return ToType.getUnqualifiedType(); 2307 2308 // Build a pointer to ToPointee. It has the right qualifiers 2309 // already. 2310 if (isa<ObjCObjectPointerType>(ToType)) 2311 return Context.getObjCObjectPointerType(ToPointee); 2312 return Context.getPointerType(ToPointee); 2313 } 2314 2315 // Just build a canonical type that has the right qualifiers. 2316 QualType QualifiedCanonToPointee 2317 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2318 2319 if (isa<ObjCObjectPointerType>(ToType)) 2320 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2321 return Context.getPointerType(QualifiedCanonToPointee); 2322 } 2323 2324 static bool isNullPointerConstantForConversion(Expr *Expr, 2325 bool InOverloadResolution, 2326 ASTContext &Context) { 2327 // Handle value-dependent integral null pointer constants correctly. 2328 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2329 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2330 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2331 return !InOverloadResolution; 2332 2333 return Expr->isNullPointerConstant(Context, 2334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2335 : Expr::NPC_ValueDependentIsNull); 2336 } 2337 2338 /// IsPointerConversion - Determines whether the conversion of the 2339 /// expression From, which has the (possibly adjusted) type FromType, 2340 /// can be converted to the type ToType via a pointer conversion (C++ 2341 /// 4.10). If so, returns true and places the converted type (that 2342 /// might differ from ToType in its cv-qualifiers at some level) into 2343 /// ConvertedType. 2344 /// 2345 /// This routine also supports conversions to and from block pointers 2346 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2347 /// pointers to interfaces. FIXME: Once we've determined the 2348 /// appropriate overloading rules for Objective-C, we may want to 2349 /// split the Objective-C checks into a different routine; however, 2350 /// GCC seems to consider all of these conversions to be pointer 2351 /// conversions, so for now they live here. IncompatibleObjC will be 2352 /// set if the conversion is an allowed Objective-C conversion that 2353 /// should result in a warning. 2354 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2355 bool InOverloadResolution, 2356 QualType& ConvertedType, 2357 bool &IncompatibleObjC) { 2358 IncompatibleObjC = false; 2359 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2360 IncompatibleObjC)) 2361 return true; 2362 2363 // Conversion from a null pointer constant to any Objective-C pointer type. 2364 if (ToType->isObjCObjectPointerType() && 2365 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2366 ConvertedType = ToType; 2367 return true; 2368 } 2369 2370 // Blocks: Block pointers can be converted to void*. 2371 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2372 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2373 ConvertedType = ToType; 2374 return true; 2375 } 2376 // Blocks: A null pointer constant can be converted to a block 2377 // pointer type. 2378 if (ToType->isBlockPointerType() && 2379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2380 ConvertedType = ToType; 2381 return true; 2382 } 2383 2384 // If the left-hand-side is nullptr_t, the right side can be a null 2385 // pointer constant. 2386 if (ToType->isNullPtrType() && 2387 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2388 ConvertedType = ToType; 2389 return true; 2390 } 2391 2392 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2393 if (!ToTypePtr) 2394 return false; 2395 2396 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2397 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2398 ConvertedType = ToType; 2399 return true; 2400 } 2401 2402 // Beyond this point, both types need to be pointers 2403 // , including objective-c pointers. 2404 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2405 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2406 !getLangOpts().ObjCAutoRefCount) { 2407 ConvertedType = BuildSimilarlyQualifiedPointerType( 2408 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2409 Context); 2410 return true; 2411 } 2412 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2413 if (!FromTypePtr) 2414 return false; 2415 2416 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2417 2418 // If the unqualified pointee types are the same, this can't be a 2419 // pointer conversion, so don't do all of the work below. 2420 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2421 return false; 2422 2423 // An rvalue of type "pointer to cv T," where T is an object type, 2424 // can be converted to an rvalue of type "pointer to cv void" (C++ 2425 // 4.10p2). 2426 if (FromPointeeType->isIncompleteOrObjectType() && 2427 ToPointeeType->isVoidType()) { 2428 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2429 ToPointeeType, 2430 ToType, Context, 2431 /*StripObjCLifetime=*/true); 2432 return true; 2433 } 2434 2435 // MSVC allows implicit function to void* type conversion. 2436 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2437 ToPointeeType->isVoidType()) { 2438 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2439 ToPointeeType, 2440 ToType, Context); 2441 return true; 2442 } 2443 2444 // When we're overloading in C, we allow a special kind of pointer 2445 // conversion for compatible-but-not-identical pointee types. 2446 if (!getLangOpts().CPlusPlus && 2447 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2449 ToPointeeType, 2450 ToType, Context); 2451 return true; 2452 } 2453 2454 // C++ [conv.ptr]p3: 2455 // 2456 // An rvalue of type "pointer to cv D," where D is a class type, 2457 // can be converted to an rvalue of type "pointer to cv B," where 2458 // B is a base class (clause 10) of D. If B is an inaccessible 2459 // (clause 11) or ambiguous (10.2) base class of D, a program that 2460 // necessitates this conversion is ill-formed. The result of the 2461 // conversion is a pointer to the base class sub-object of the 2462 // derived class object. The null pointer value is converted to 2463 // the null pointer value of the destination type. 2464 // 2465 // Note that we do not check for ambiguity or inaccessibility 2466 // here. That is handled by CheckPointerConversion. 2467 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2468 ToPointeeType->isRecordType() && 2469 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2470 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2471 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2472 ToPointeeType, 2473 ToType, Context); 2474 return true; 2475 } 2476 2477 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2478 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2479 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2480 ToPointeeType, 2481 ToType, Context); 2482 return true; 2483 } 2484 2485 return false; 2486 } 2487 2488 /// Adopt the given qualifiers for the given type. 2489 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2490 Qualifiers TQs = T.getQualifiers(); 2491 2492 // Check whether qualifiers already match. 2493 if (TQs == Qs) 2494 return T; 2495 2496 if (Qs.compatiblyIncludes(TQs)) 2497 return Context.getQualifiedType(T, Qs); 2498 2499 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2500 } 2501 2502 /// isObjCPointerConversion - Determines whether this is an 2503 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2504 /// with the same arguments and return values. 2505 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2506 QualType& ConvertedType, 2507 bool &IncompatibleObjC) { 2508 if (!getLangOpts().ObjC) 2509 return false; 2510 2511 // The set of qualifiers on the type we're converting from. 2512 Qualifiers FromQualifiers = FromType.getQualifiers(); 2513 2514 // First, we handle all conversions on ObjC object pointer types. 2515 const ObjCObjectPointerType* ToObjCPtr = 2516 ToType->getAs<ObjCObjectPointerType>(); 2517 const ObjCObjectPointerType *FromObjCPtr = 2518 FromType->getAs<ObjCObjectPointerType>(); 2519 2520 if (ToObjCPtr && FromObjCPtr) { 2521 // If the pointee types are the same (ignoring qualifications), 2522 // then this is not a pointer conversion. 2523 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2524 FromObjCPtr->getPointeeType())) 2525 return false; 2526 2527 // Conversion between Objective-C pointers. 2528 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2529 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2530 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2531 if (getLangOpts().CPlusPlus && LHS && RHS && 2532 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2533 FromObjCPtr->getPointeeType())) 2534 return false; 2535 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2536 ToObjCPtr->getPointeeType(), 2537 ToType, Context); 2538 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2539 return true; 2540 } 2541 2542 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2543 // Okay: this is some kind of implicit downcast of Objective-C 2544 // interfaces, which is permitted. However, we're going to 2545 // complain about it. 2546 IncompatibleObjC = true; 2547 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2548 ToObjCPtr->getPointeeType(), 2549 ToType, Context); 2550 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2551 return true; 2552 } 2553 } 2554 // Beyond this point, both types need to be C pointers or block pointers. 2555 QualType ToPointeeType; 2556 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2557 ToPointeeType = ToCPtr->getPointeeType(); 2558 else if (const BlockPointerType *ToBlockPtr = 2559 ToType->getAs<BlockPointerType>()) { 2560 // Objective C++: We're able to convert from a pointer to any object 2561 // to a block pointer type. 2562 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2563 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2564 return true; 2565 } 2566 ToPointeeType = ToBlockPtr->getPointeeType(); 2567 } 2568 else if (FromType->getAs<BlockPointerType>() && 2569 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2570 // Objective C++: We're able to convert from a block pointer type to a 2571 // pointer to any object. 2572 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2573 return true; 2574 } 2575 else 2576 return false; 2577 2578 QualType FromPointeeType; 2579 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2580 FromPointeeType = FromCPtr->getPointeeType(); 2581 else if (const BlockPointerType *FromBlockPtr = 2582 FromType->getAs<BlockPointerType>()) 2583 FromPointeeType = FromBlockPtr->getPointeeType(); 2584 else 2585 return false; 2586 2587 // If we have pointers to pointers, recursively check whether this 2588 // is an Objective-C conversion. 2589 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2590 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2591 IncompatibleObjC)) { 2592 // We always complain about this conversion. 2593 IncompatibleObjC = true; 2594 ConvertedType = Context.getPointerType(ConvertedType); 2595 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2596 return true; 2597 } 2598 // Allow conversion of pointee being objective-c pointer to another one; 2599 // as in I* to id. 2600 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2601 ToPointeeType->getAs<ObjCObjectPointerType>() && 2602 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2603 IncompatibleObjC)) { 2604 2605 ConvertedType = Context.getPointerType(ConvertedType); 2606 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2607 return true; 2608 } 2609 2610 // If we have pointers to functions or blocks, check whether the only 2611 // differences in the argument and result types are in Objective-C 2612 // pointer conversions. If so, we permit the conversion (but 2613 // complain about it). 2614 const FunctionProtoType *FromFunctionType 2615 = FromPointeeType->getAs<FunctionProtoType>(); 2616 const FunctionProtoType *ToFunctionType 2617 = ToPointeeType->getAs<FunctionProtoType>(); 2618 if (FromFunctionType && ToFunctionType) { 2619 // If the function types are exactly the same, this isn't an 2620 // Objective-C pointer conversion. 2621 if (Context.getCanonicalType(FromPointeeType) 2622 == Context.getCanonicalType(ToPointeeType)) 2623 return false; 2624 2625 // Perform the quick checks that will tell us whether these 2626 // function types are obviously different. 2627 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2628 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2629 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2630 return false; 2631 2632 bool HasObjCConversion = false; 2633 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2634 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2635 // Okay, the types match exactly. Nothing to do. 2636 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2637 ToFunctionType->getReturnType(), 2638 ConvertedType, IncompatibleObjC)) { 2639 // Okay, we have an Objective-C pointer conversion. 2640 HasObjCConversion = true; 2641 } else { 2642 // Function types are too different. Abort. 2643 return false; 2644 } 2645 2646 // Check argument types. 2647 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2648 ArgIdx != NumArgs; ++ArgIdx) { 2649 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2650 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2651 if (Context.getCanonicalType(FromArgType) 2652 == Context.getCanonicalType(ToArgType)) { 2653 // Okay, the types match exactly. Nothing to do. 2654 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2655 ConvertedType, IncompatibleObjC)) { 2656 // Okay, we have an Objective-C pointer conversion. 2657 HasObjCConversion = true; 2658 } else { 2659 // Argument types are too different. Abort. 2660 return false; 2661 } 2662 } 2663 2664 if (HasObjCConversion) { 2665 // We had an Objective-C conversion. Allow this pointer 2666 // conversion, but complain about it. 2667 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2668 IncompatibleObjC = true; 2669 return true; 2670 } 2671 } 2672 2673 return false; 2674 } 2675 2676 /// Determine whether this is an Objective-C writeback conversion, 2677 /// used for parameter passing when performing automatic reference counting. 2678 /// 2679 /// \param FromType The type we're converting form. 2680 /// 2681 /// \param ToType The type we're converting to. 2682 /// 2683 /// \param ConvertedType The type that will be produced after applying 2684 /// this conversion. 2685 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2686 QualType &ConvertedType) { 2687 if (!getLangOpts().ObjCAutoRefCount || 2688 Context.hasSameUnqualifiedType(FromType, ToType)) 2689 return false; 2690 2691 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2692 QualType ToPointee; 2693 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2694 ToPointee = ToPointer->getPointeeType(); 2695 else 2696 return false; 2697 2698 Qualifiers ToQuals = ToPointee.getQualifiers(); 2699 if (!ToPointee->isObjCLifetimeType() || 2700 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2701 !ToQuals.withoutObjCLifetime().empty()) 2702 return false; 2703 2704 // Argument must be a pointer to __strong to __weak. 2705 QualType FromPointee; 2706 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2707 FromPointee = FromPointer->getPointeeType(); 2708 else 2709 return false; 2710 2711 Qualifiers FromQuals = FromPointee.getQualifiers(); 2712 if (!FromPointee->isObjCLifetimeType() || 2713 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2714 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2715 return false; 2716 2717 // Make sure that we have compatible qualifiers. 2718 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2719 if (!ToQuals.compatiblyIncludes(FromQuals)) 2720 return false; 2721 2722 // Remove qualifiers from the pointee type we're converting from; they 2723 // aren't used in the compatibility check belong, and we'll be adding back 2724 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2725 FromPointee = FromPointee.getUnqualifiedType(); 2726 2727 // The unqualified form of the pointee types must be compatible. 2728 ToPointee = ToPointee.getUnqualifiedType(); 2729 bool IncompatibleObjC; 2730 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2731 FromPointee = ToPointee; 2732 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2733 IncompatibleObjC)) 2734 return false; 2735 2736 /// Construct the type we're converting to, which is a pointer to 2737 /// __autoreleasing pointee. 2738 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2739 ConvertedType = Context.getPointerType(FromPointee); 2740 return true; 2741 } 2742 2743 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2744 QualType& ConvertedType) { 2745 QualType ToPointeeType; 2746 if (const BlockPointerType *ToBlockPtr = 2747 ToType->getAs<BlockPointerType>()) 2748 ToPointeeType = ToBlockPtr->getPointeeType(); 2749 else 2750 return false; 2751 2752 QualType FromPointeeType; 2753 if (const BlockPointerType *FromBlockPtr = 2754 FromType->getAs<BlockPointerType>()) 2755 FromPointeeType = FromBlockPtr->getPointeeType(); 2756 else 2757 return false; 2758 // We have pointer to blocks, check whether the only 2759 // differences in the argument and result types are in Objective-C 2760 // pointer conversions. If so, we permit the conversion. 2761 2762 const FunctionProtoType *FromFunctionType 2763 = FromPointeeType->getAs<FunctionProtoType>(); 2764 const FunctionProtoType *ToFunctionType 2765 = ToPointeeType->getAs<FunctionProtoType>(); 2766 2767 if (!FromFunctionType || !ToFunctionType) 2768 return false; 2769 2770 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2771 return true; 2772 2773 // Perform the quick checks that will tell us whether these 2774 // function types are obviously different. 2775 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2776 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2777 return false; 2778 2779 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2780 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2781 if (FromEInfo != ToEInfo) 2782 return false; 2783 2784 bool IncompatibleObjC = false; 2785 if (Context.hasSameType(FromFunctionType->getReturnType(), 2786 ToFunctionType->getReturnType())) { 2787 // Okay, the types match exactly. Nothing to do. 2788 } else { 2789 QualType RHS = FromFunctionType->getReturnType(); 2790 QualType LHS = ToFunctionType->getReturnType(); 2791 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2792 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2793 LHS = LHS.getUnqualifiedType(); 2794 2795 if (Context.hasSameType(RHS,LHS)) { 2796 // OK exact match. 2797 } else if (isObjCPointerConversion(RHS, LHS, 2798 ConvertedType, IncompatibleObjC)) { 2799 if (IncompatibleObjC) 2800 return false; 2801 // Okay, we have an Objective-C pointer conversion. 2802 } 2803 else 2804 return false; 2805 } 2806 2807 // Check argument types. 2808 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2809 ArgIdx != NumArgs; ++ArgIdx) { 2810 IncompatibleObjC = false; 2811 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2812 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2813 if (Context.hasSameType(FromArgType, ToArgType)) { 2814 // Okay, the types match exactly. Nothing to do. 2815 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2816 ConvertedType, IncompatibleObjC)) { 2817 if (IncompatibleObjC) 2818 return false; 2819 // Okay, we have an Objective-C pointer conversion. 2820 } else 2821 // Argument types are too different. Abort. 2822 return false; 2823 } 2824 2825 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2826 bool CanUseToFPT, CanUseFromFPT; 2827 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2828 CanUseToFPT, CanUseFromFPT, 2829 NewParamInfos)) 2830 return false; 2831 2832 ConvertedType = ToType; 2833 return true; 2834 } 2835 2836 enum { 2837 ft_default, 2838 ft_different_class, 2839 ft_parameter_arity, 2840 ft_parameter_mismatch, 2841 ft_return_type, 2842 ft_qualifer_mismatch, 2843 ft_noexcept 2844 }; 2845 2846 /// Attempts to get the FunctionProtoType from a Type. Handles 2847 /// MemberFunctionPointers properly. 2848 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2849 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2850 return FPT; 2851 2852 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2853 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2854 2855 return nullptr; 2856 } 2857 2858 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2859 /// function types. Catches different number of parameter, mismatch in 2860 /// parameter types, and different return types. 2861 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2862 QualType FromType, QualType ToType) { 2863 // If either type is not valid, include no extra info. 2864 if (FromType.isNull() || ToType.isNull()) { 2865 PDiag << ft_default; 2866 return; 2867 } 2868 2869 // Get the function type from the pointers. 2870 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2871 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2872 *ToMember = ToType->castAs<MemberPointerType>(); 2873 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2874 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2875 << QualType(FromMember->getClass(), 0); 2876 return; 2877 } 2878 FromType = FromMember->getPointeeType(); 2879 ToType = ToMember->getPointeeType(); 2880 } 2881 2882 if (FromType->isPointerType()) 2883 FromType = FromType->getPointeeType(); 2884 if (ToType->isPointerType()) 2885 ToType = ToType->getPointeeType(); 2886 2887 // Remove references. 2888 FromType = FromType.getNonReferenceType(); 2889 ToType = ToType.getNonReferenceType(); 2890 2891 // Don't print extra info for non-specialized template functions. 2892 if (FromType->isInstantiationDependentType() && 2893 !FromType->getAs<TemplateSpecializationType>()) { 2894 PDiag << ft_default; 2895 return; 2896 } 2897 2898 // No extra info for same types. 2899 if (Context.hasSameType(FromType, ToType)) { 2900 PDiag << ft_default; 2901 return; 2902 } 2903 2904 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2905 *ToFunction = tryGetFunctionProtoType(ToType); 2906 2907 // Both types need to be function types. 2908 if (!FromFunction || !ToFunction) { 2909 PDiag << ft_default; 2910 return; 2911 } 2912 2913 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2914 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2915 << FromFunction->getNumParams(); 2916 return; 2917 } 2918 2919 // Handle different parameter types. 2920 unsigned ArgPos; 2921 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2922 PDiag << ft_parameter_mismatch << ArgPos + 1 2923 << ToFunction->getParamType(ArgPos) 2924 << FromFunction->getParamType(ArgPos); 2925 return; 2926 } 2927 2928 // Handle different return type. 2929 if (!Context.hasSameType(FromFunction->getReturnType(), 2930 ToFunction->getReturnType())) { 2931 PDiag << ft_return_type << ToFunction->getReturnType() 2932 << FromFunction->getReturnType(); 2933 return; 2934 } 2935 2936 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2937 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2938 << FromFunction->getMethodQuals(); 2939 return; 2940 } 2941 2942 // Handle exception specification differences on canonical type (in C++17 2943 // onwards). 2944 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2945 ->isNothrow() != 2946 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2947 ->isNothrow()) { 2948 PDiag << ft_noexcept; 2949 return; 2950 } 2951 2952 // Unable to find a difference, so add no extra info. 2953 PDiag << ft_default; 2954 } 2955 2956 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2957 /// for equality of their parameter types. Caller has already checked that 2958 /// they have same number of parameters. If the parameters are different, 2959 /// ArgPos will have the parameter index of the first different parameter. 2960 /// If `Reversed` is true, the parameters of `NewType` will be compared in 2961 /// reverse order. That's useful if one of the functions is being used as a C++20 2962 /// synthesized operator overload with a reversed parameter order. 2963 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2964 const FunctionProtoType *NewType, 2965 unsigned *ArgPos, bool Reversed) { 2966 assert(OldType->getNumParams() == NewType->getNumParams() && 2967 "Can't compare parameters of functions with different number of " 2968 "parameters!"); 2969 for (size_t I = 0; I < OldType->getNumParams(); I++) { 2970 // Reverse iterate over the parameters of `OldType` if `Reversed` is true. 2971 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I; 2972 2973 // Ignore address spaces in pointee type. This is to disallow overloading 2974 // on __ptr32/__ptr64 address spaces. 2975 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType()); 2976 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType()); 2977 2978 if (!Context.hasSameType(Old, New)) { 2979 if (ArgPos) 2980 *ArgPos = I; 2981 return false; 2982 } 2983 } 2984 return true; 2985 } 2986 2987 /// CheckPointerConversion - Check the pointer conversion from the 2988 /// expression From to the type ToType. This routine checks for 2989 /// ambiguous or inaccessible derived-to-base pointer 2990 /// conversions for which IsPointerConversion has already returned 2991 /// true. It returns true and produces a diagnostic if there was an 2992 /// error, or returns false otherwise. 2993 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2994 CastKind &Kind, 2995 CXXCastPath& BasePath, 2996 bool IgnoreBaseAccess, 2997 bool Diagnose) { 2998 QualType FromType = From->getType(); 2999 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3000 3001 Kind = CK_BitCast; 3002 3003 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3004 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3005 Expr::NPCK_ZeroExpression) { 3006 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3007 DiagRuntimeBehavior(From->getExprLoc(), From, 3008 PDiag(diag::warn_impcast_bool_to_null_pointer) 3009 << ToType << From->getSourceRange()); 3010 else if (!isUnevaluatedContext()) 3011 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3012 << ToType << From->getSourceRange(); 3013 } 3014 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3015 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3016 QualType FromPointeeType = FromPtrType->getPointeeType(), 3017 ToPointeeType = ToPtrType->getPointeeType(); 3018 3019 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3020 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3021 // We must have a derived-to-base conversion. Check an 3022 // ambiguous or inaccessible conversion. 3023 unsigned InaccessibleID = 0; 3024 unsigned AmbiguousID = 0; 3025 if (Diagnose) { 3026 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3027 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3028 } 3029 if (CheckDerivedToBaseConversion( 3030 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3031 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3032 &BasePath, IgnoreBaseAccess)) 3033 return true; 3034 3035 // The conversion was successful. 3036 Kind = CK_DerivedToBase; 3037 } 3038 3039 if (Diagnose && !IsCStyleOrFunctionalCast && 3040 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3041 assert(getLangOpts().MSVCCompat && 3042 "this should only be possible with MSVCCompat!"); 3043 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3044 << From->getSourceRange(); 3045 } 3046 } 3047 } else if (const ObjCObjectPointerType *ToPtrType = 3048 ToType->getAs<ObjCObjectPointerType>()) { 3049 if (const ObjCObjectPointerType *FromPtrType = 3050 FromType->getAs<ObjCObjectPointerType>()) { 3051 // Objective-C++ conversions are always okay. 3052 // FIXME: We should have a different class of conversions for the 3053 // Objective-C++ implicit conversions. 3054 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3055 return false; 3056 } else if (FromType->isBlockPointerType()) { 3057 Kind = CK_BlockPointerToObjCPointerCast; 3058 } else { 3059 Kind = CK_CPointerToObjCPointerCast; 3060 } 3061 } else if (ToType->isBlockPointerType()) { 3062 if (!FromType->isBlockPointerType()) 3063 Kind = CK_AnyPointerToBlockPointerCast; 3064 } 3065 3066 // We shouldn't fall into this case unless it's valid for other 3067 // reasons. 3068 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3069 Kind = CK_NullToPointer; 3070 3071 return false; 3072 } 3073 3074 /// IsMemberPointerConversion - Determines whether the conversion of the 3075 /// expression From, which has the (possibly adjusted) type FromType, can be 3076 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3077 /// If so, returns true and places the converted type (that might differ from 3078 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3079 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3080 QualType ToType, 3081 bool InOverloadResolution, 3082 QualType &ConvertedType) { 3083 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3084 if (!ToTypePtr) 3085 return false; 3086 3087 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3088 if (From->isNullPointerConstant(Context, 3089 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3090 : Expr::NPC_ValueDependentIsNull)) { 3091 ConvertedType = ToType; 3092 return true; 3093 } 3094 3095 // Otherwise, both types have to be member pointers. 3096 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3097 if (!FromTypePtr) 3098 return false; 3099 3100 // A pointer to member of B can be converted to a pointer to member of D, 3101 // where D is derived from B (C++ 4.11p2). 3102 QualType FromClass(FromTypePtr->getClass(), 0); 3103 QualType ToClass(ToTypePtr->getClass(), 0); 3104 3105 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3106 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3107 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3108 ToClass.getTypePtr()); 3109 return true; 3110 } 3111 3112 return false; 3113 } 3114 3115 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3116 /// expression From to the type ToType. This routine checks for ambiguous or 3117 /// virtual or inaccessible base-to-derived member pointer conversions 3118 /// for which IsMemberPointerConversion has already returned true. It returns 3119 /// true and produces a diagnostic if there was an error, or returns false 3120 /// otherwise. 3121 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3122 CastKind &Kind, 3123 CXXCastPath &BasePath, 3124 bool IgnoreBaseAccess) { 3125 QualType FromType = From->getType(); 3126 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3127 if (!FromPtrType) { 3128 // This must be a null pointer to member pointer conversion 3129 assert(From->isNullPointerConstant(Context, 3130 Expr::NPC_ValueDependentIsNull) && 3131 "Expr must be null pointer constant!"); 3132 Kind = CK_NullToMemberPointer; 3133 return false; 3134 } 3135 3136 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3137 assert(ToPtrType && "No member pointer cast has a target type " 3138 "that is not a member pointer."); 3139 3140 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3141 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3142 3143 // FIXME: What about dependent types? 3144 assert(FromClass->isRecordType() && "Pointer into non-class."); 3145 assert(ToClass->isRecordType() && "Pointer into non-class."); 3146 3147 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3148 /*DetectVirtual=*/true); 3149 bool DerivationOkay = 3150 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3151 assert(DerivationOkay && 3152 "Should not have been called if derivation isn't OK."); 3153 (void)DerivationOkay; 3154 3155 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3156 getUnqualifiedType())) { 3157 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3158 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3159 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3160 return true; 3161 } 3162 3163 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3164 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3165 << FromClass << ToClass << QualType(VBase, 0) 3166 << From->getSourceRange(); 3167 return true; 3168 } 3169 3170 if (!IgnoreBaseAccess) 3171 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3172 Paths.front(), 3173 diag::err_downcast_from_inaccessible_base); 3174 3175 // Must be a base to derived member conversion. 3176 BuildBasePathArray(Paths, BasePath); 3177 Kind = CK_BaseToDerivedMemberPointer; 3178 return false; 3179 } 3180 3181 /// Determine whether the lifetime conversion between the two given 3182 /// qualifiers sets is nontrivial. 3183 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3184 Qualifiers ToQuals) { 3185 // Converting anything to const __unsafe_unretained is trivial. 3186 if (ToQuals.hasConst() && 3187 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3188 return false; 3189 3190 return true; 3191 } 3192 3193 /// Perform a single iteration of the loop for checking if a qualification 3194 /// conversion is valid. 3195 /// 3196 /// Specifically, check whether any change between the qualifiers of \p 3197 /// FromType and \p ToType is permissible, given knowledge about whether every 3198 /// outer layer is const-qualified. 3199 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3200 bool CStyle, bool IsTopLevel, 3201 bool &PreviousToQualsIncludeConst, 3202 bool &ObjCLifetimeConversion) { 3203 Qualifiers FromQuals = FromType.getQualifiers(); 3204 Qualifiers ToQuals = ToType.getQualifiers(); 3205 3206 // Ignore __unaligned qualifier. 3207 FromQuals.removeUnaligned(); 3208 3209 // Objective-C ARC: 3210 // Check Objective-C lifetime conversions. 3211 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3212 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3213 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3214 ObjCLifetimeConversion = true; 3215 FromQuals.removeObjCLifetime(); 3216 ToQuals.removeObjCLifetime(); 3217 } else { 3218 // Qualification conversions cannot cast between different 3219 // Objective-C lifetime qualifiers. 3220 return false; 3221 } 3222 } 3223 3224 // Allow addition/removal of GC attributes but not changing GC attributes. 3225 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3226 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3227 FromQuals.removeObjCGCAttr(); 3228 ToQuals.removeObjCGCAttr(); 3229 } 3230 3231 // -- for every j > 0, if const is in cv 1,j then const is in cv 3232 // 2,j, and similarly for volatile. 3233 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3234 return false; 3235 3236 // If address spaces mismatch: 3237 // - in top level it is only valid to convert to addr space that is a 3238 // superset in all cases apart from C-style casts where we allow 3239 // conversions between overlapping address spaces. 3240 // - in non-top levels it is not a valid conversion. 3241 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3242 (!IsTopLevel || 3243 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3244 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3245 return false; 3246 3247 // -- if the cv 1,j and cv 2,j are different, then const is in 3248 // every cv for 0 < k < j. 3249 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3250 !PreviousToQualsIncludeConst) 3251 return false; 3252 3253 // The following wording is from C++20, where the result of the conversion 3254 // is T3, not T2. 3255 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3256 // "array of unknown bound of" 3257 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3258 return false; 3259 3260 // -- if the resulting P3,i is different from P1,i [...], then const is 3261 // added to every cv 3_k for 0 < k < i. 3262 if (!CStyle && FromType->isConstantArrayType() && 3263 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3264 return false; 3265 3266 // Keep track of whether all prior cv-qualifiers in the "to" type 3267 // include const. 3268 PreviousToQualsIncludeConst = 3269 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3270 return true; 3271 } 3272 3273 /// IsQualificationConversion - Determines whether the conversion from 3274 /// an rvalue of type FromType to ToType is a qualification conversion 3275 /// (C++ 4.4). 3276 /// 3277 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3278 /// when the qualification conversion involves a change in the Objective-C 3279 /// object lifetime. 3280 bool 3281 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3282 bool CStyle, bool &ObjCLifetimeConversion) { 3283 FromType = Context.getCanonicalType(FromType); 3284 ToType = Context.getCanonicalType(ToType); 3285 ObjCLifetimeConversion = false; 3286 3287 // If FromType and ToType are the same type, this is not a 3288 // qualification conversion. 3289 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3290 return false; 3291 3292 // (C++ 4.4p4): 3293 // A conversion can add cv-qualifiers at levels other than the first 3294 // in multi-level pointers, subject to the following rules: [...] 3295 bool PreviousToQualsIncludeConst = true; 3296 bool UnwrappedAnyPointer = false; 3297 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3298 if (!isQualificationConversionStep( 3299 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3300 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3301 return false; 3302 UnwrappedAnyPointer = true; 3303 } 3304 3305 // We are left with FromType and ToType being the pointee types 3306 // after unwrapping the original FromType and ToType the same number 3307 // of times. If we unwrapped any pointers, and if FromType and 3308 // ToType have the same unqualified type (since we checked 3309 // qualifiers above), then this is a qualification conversion. 3310 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3311 } 3312 3313 /// - Determine whether this is a conversion from a scalar type to an 3314 /// atomic type. 3315 /// 3316 /// If successful, updates \c SCS's second and third steps in the conversion 3317 /// sequence to finish the conversion. 3318 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3319 bool InOverloadResolution, 3320 StandardConversionSequence &SCS, 3321 bool CStyle) { 3322 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3323 if (!ToAtomic) 3324 return false; 3325 3326 StandardConversionSequence InnerSCS; 3327 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3328 InOverloadResolution, InnerSCS, 3329 CStyle, /*AllowObjCWritebackConversion=*/false)) 3330 return false; 3331 3332 SCS.Second = InnerSCS.Second; 3333 SCS.setToType(1, InnerSCS.getToType(1)); 3334 SCS.Third = InnerSCS.Third; 3335 SCS.QualificationIncludesObjCLifetime 3336 = InnerSCS.QualificationIncludesObjCLifetime; 3337 SCS.setToType(2, InnerSCS.getToType(2)); 3338 return true; 3339 } 3340 3341 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3342 CXXConstructorDecl *Constructor, 3343 QualType Type) { 3344 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3345 if (CtorType->getNumParams() > 0) { 3346 QualType FirstArg = CtorType->getParamType(0); 3347 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3348 return true; 3349 } 3350 return false; 3351 } 3352 3353 static OverloadingResult 3354 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3355 CXXRecordDecl *To, 3356 UserDefinedConversionSequence &User, 3357 OverloadCandidateSet &CandidateSet, 3358 bool AllowExplicit) { 3359 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3360 for (auto *D : S.LookupConstructors(To)) { 3361 auto Info = getConstructorInfo(D); 3362 if (!Info) 3363 continue; 3364 3365 bool Usable = !Info.Constructor->isInvalidDecl() && 3366 S.isInitListConstructor(Info.Constructor); 3367 if (Usable) { 3368 bool SuppressUserConversions = false; 3369 if (Info.ConstructorTmpl) 3370 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3371 /*ExplicitArgs*/ nullptr, From, 3372 CandidateSet, SuppressUserConversions, 3373 /*PartialOverloading*/ false, 3374 AllowExplicit); 3375 else 3376 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3377 CandidateSet, SuppressUserConversions, 3378 /*PartialOverloading*/ false, AllowExplicit); 3379 } 3380 } 3381 3382 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3383 3384 OverloadCandidateSet::iterator Best; 3385 switch (auto Result = 3386 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3387 case OR_Deleted: 3388 case OR_Success: { 3389 // Record the standard conversion we used and the conversion function. 3390 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3391 QualType ThisType = Constructor->getThisType(); 3392 // Initializer lists don't have conversions as such. 3393 User.Before.setAsIdentityConversion(); 3394 User.HadMultipleCandidates = HadMultipleCandidates; 3395 User.ConversionFunction = Constructor; 3396 User.FoundConversionFunction = Best->FoundDecl; 3397 User.After.setAsIdentityConversion(); 3398 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3399 User.After.setAllToTypes(ToType); 3400 return Result; 3401 } 3402 3403 case OR_No_Viable_Function: 3404 return OR_No_Viable_Function; 3405 case OR_Ambiguous: 3406 return OR_Ambiguous; 3407 } 3408 3409 llvm_unreachable("Invalid OverloadResult!"); 3410 } 3411 3412 /// Determines whether there is a user-defined conversion sequence 3413 /// (C++ [over.ics.user]) that converts expression From to the type 3414 /// ToType. If such a conversion exists, User will contain the 3415 /// user-defined conversion sequence that performs such a conversion 3416 /// and this routine will return true. Otherwise, this routine returns 3417 /// false and User is unspecified. 3418 /// 3419 /// \param AllowExplicit true if the conversion should consider C++0x 3420 /// "explicit" conversion functions as well as non-explicit conversion 3421 /// functions (C++0x [class.conv.fct]p2). 3422 /// 3423 /// \param AllowObjCConversionOnExplicit true if the conversion should 3424 /// allow an extra Objective-C pointer conversion on uses of explicit 3425 /// constructors. Requires \c AllowExplicit to also be set. 3426 static OverloadingResult 3427 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3428 UserDefinedConversionSequence &User, 3429 OverloadCandidateSet &CandidateSet, 3430 AllowedExplicit AllowExplicit, 3431 bool AllowObjCConversionOnExplicit) { 3432 assert(AllowExplicit != AllowedExplicit::None || 3433 !AllowObjCConversionOnExplicit); 3434 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3435 3436 // Whether we will only visit constructors. 3437 bool ConstructorsOnly = false; 3438 3439 // If the type we are conversion to is a class type, enumerate its 3440 // constructors. 3441 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3442 // C++ [over.match.ctor]p1: 3443 // When objects of class type are direct-initialized (8.5), or 3444 // copy-initialized from an expression of the same or a 3445 // derived class type (8.5), overload resolution selects the 3446 // constructor. [...] For copy-initialization, the candidate 3447 // functions are all the converting constructors (12.3.1) of 3448 // that class. The argument list is the expression-list within 3449 // the parentheses of the initializer. 3450 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3451 (From->getType()->getAs<RecordType>() && 3452 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3453 ConstructorsOnly = true; 3454 3455 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3456 // We're not going to find any constructors. 3457 } else if (CXXRecordDecl *ToRecordDecl 3458 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3459 3460 Expr **Args = &From; 3461 unsigned NumArgs = 1; 3462 bool ListInitializing = false; 3463 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3464 // But first, see if there is an init-list-constructor that will work. 3465 OverloadingResult Result = IsInitializerListConstructorConversion( 3466 S, From, ToType, ToRecordDecl, User, CandidateSet, 3467 AllowExplicit == AllowedExplicit::All); 3468 if (Result != OR_No_Viable_Function) 3469 return Result; 3470 // Never mind. 3471 CandidateSet.clear( 3472 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3473 3474 // If we're list-initializing, we pass the individual elements as 3475 // arguments, not the entire list. 3476 Args = InitList->getInits(); 3477 NumArgs = InitList->getNumInits(); 3478 ListInitializing = true; 3479 } 3480 3481 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3482 auto Info = getConstructorInfo(D); 3483 if (!Info) 3484 continue; 3485 3486 bool Usable = !Info.Constructor->isInvalidDecl(); 3487 if (!ListInitializing) 3488 Usable = Usable && Info.Constructor->isConvertingConstructor( 3489 /*AllowExplicit*/ true); 3490 if (Usable) { 3491 bool SuppressUserConversions = !ConstructorsOnly; 3492 // C++20 [over.best.ics.general]/4.5: 3493 // if the target is the first parameter of a constructor [of class 3494 // X] and the constructor [...] is a candidate by [...] the second 3495 // phase of [over.match.list] when the initializer list has exactly 3496 // one element that is itself an initializer list, [...] and the 3497 // conversion is to X or reference to cv X, user-defined conversion 3498 // sequences are not cnosidered. 3499 if (SuppressUserConversions && ListInitializing) { 3500 SuppressUserConversions = 3501 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3502 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3503 ToType); 3504 } 3505 if (Info.ConstructorTmpl) 3506 S.AddTemplateOverloadCandidate( 3507 Info.ConstructorTmpl, Info.FoundDecl, 3508 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3509 CandidateSet, SuppressUserConversions, 3510 /*PartialOverloading*/ false, 3511 AllowExplicit == AllowedExplicit::All); 3512 else 3513 // Allow one user-defined conversion when user specifies a 3514 // From->ToType conversion via an static cast (c-style, etc). 3515 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3516 llvm::makeArrayRef(Args, NumArgs), 3517 CandidateSet, SuppressUserConversions, 3518 /*PartialOverloading*/ false, 3519 AllowExplicit == AllowedExplicit::All); 3520 } 3521 } 3522 } 3523 } 3524 3525 // Enumerate conversion functions, if we're allowed to. 3526 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3527 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3528 // No conversion functions from incomplete types. 3529 } else if (const RecordType *FromRecordType = 3530 From->getType()->getAs<RecordType>()) { 3531 if (CXXRecordDecl *FromRecordDecl 3532 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3533 // Add all of the conversion functions as candidates. 3534 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3535 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3536 DeclAccessPair FoundDecl = I.getPair(); 3537 NamedDecl *D = FoundDecl.getDecl(); 3538 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3539 if (isa<UsingShadowDecl>(D)) 3540 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3541 3542 CXXConversionDecl *Conv; 3543 FunctionTemplateDecl *ConvTemplate; 3544 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3545 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3546 else 3547 Conv = cast<CXXConversionDecl>(D); 3548 3549 if (ConvTemplate) 3550 S.AddTemplateConversionCandidate( 3551 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3552 CandidateSet, AllowObjCConversionOnExplicit, 3553 AllowExplicit != AllowedExplicit::None); 3554 else 3555 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3556 CandidateSet, AllowObjCConversionOnExplicit, 3557 AllowExplicit != AllowedExplicit::None); 3558 } 3559 } 3560 } 3561 3562 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3563 3564 OverloadCandidateSet::iterator Best; 3565 switch (auto Result = 3566 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3567 case OR_Success: 3568 case OR_Deleted: 3569 // Record the standard conversion we used and the conversion function. 3570 if (CXXConstructorDecl *Constructor 3571 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3572 // C++ [over.ics.user]p1: 3573 // If the user-defined conversion is specified by a 3574 // constructor (12.3.1), the initial standard conversion 3575 // sequence converts the source type to the type required by 3576 // the argument of the constructor. 3577 // 3578 QualType ThisType = Constructor->getThisType(); 3579 if (isa<InitListExpr>(From)) { 3580 // Initializer lists don't have conversions as such. 3581 User.Before.setAsIdentityConversion(); 3582 } else { 3583 if (Best->Conversions[0].isEllipsis()) 3584 User.EllipsisConversion = true; 3585 else { 3586 User.Before = Best->Conversions[0].Standard; 3587 User.EllipsisConversion = false; 3588 } 3589 } 3590 User.HadMultipleCandidates = HadMultipleCandidates; 3591 User.ConversionFunction = Constructor; 3592 User.FoundConversionFunction = Best->FoundDecl; 3593 User.After.setAsIdentityConversion(); 3594 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3595 User.After.setAllToTypes(ToType); 3596 return Result; 3597 } 3598 if (CXXConversionDecl *Conversion 3599 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3600 // C++ [over.ics.user]p1: 3601 // 3602 // [...] If the user-defined conversion is specified by a 3603 // conversion function (12.3.2), the initial standard 3604 // conversion sequence converts the source type to the 3605 // implicit object parameter of the conversion function. 3606 User.Before = Best->Conversions[0].Standard; 3607 User.HadMultipleCandidates = HadMultipleCandidates; 3608 User.ConversionFunction = Conversion; 3609 User.FoundConversionFunction = Best->FoundDecl; 3610 User.EllipsisConversion = false; 3611 3612 // C++ [over.ics.user]p2: 3613 // The second standard conversion sequence converts the 3614 // result of the user-defined conversion to the target type 3615 // for the sequence. Since an implicit conversion sequence 3616 // is an initialization, the special rules for 3617 // initialization by user-defined conversion apply when 3618 // selecting the best user-defined conversion for a 3619 // user-defined conversion sequence (see 13.3.3 and 3620 // 13.3.3.1). 3621 User.After = Best->FinalConversion; 3622 return Result; 3623 } 3624 llvm_unreachable("Not a constructor or conversion function?"); 3625 3626 case OR_No_Viable_Function: 3627 return OR_No_Viable_Function; 3628 3629 case OR_Ambiguous: 3630 return OR_Ambiguous; 3631 } 3632 3633 llvm_unreachable("Invalid OverloadResult!"); 3634 } 3635 3636 bool 3637 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3638 ImplicitConversionSequence ICS; 3639 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3640 OverloadCandidateSet::CSK_Normal); 3641 OverloadingResult OvResult = 3642 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3643 CandidateSet, AllowedExplicit::None, false); 3644 3645 if (!(OvResult == OR_Ambiguous || 3646 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3647 return false; 3648 3649 auto Cands = CandidateSet.CompleteCandidates( 3650 *this, 3651 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3652 From); 3653 if (OvResult == OR_Ambiguous) 3654 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3655 << From->getType() << ToType << From->getSourceRange(); 3656 else { // OR_No_Viable_Function && !CandidateSet.empty() 3657 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3658 diag::err_typecheck_nonviable_condition_incomplete, 3659 From->getType(), From->getSourceRange())) 3660 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3661 << false << From->getType() << From->getSourceRange() << ToType; 3662 } 3663 3664 CandidateSet.NoteCandidates( 3665 *this, From, Cands); 3666 return true; 3667 } 3668 3669 // Helper for compareConversionFunctions that gets the FunctionType that the 3670 // conversion-operator return value 'points' to, or nullptr. 3671 static const FunctionType * 3672 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3673 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3674 const PointerType *RetPtrTy = 3675 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3676 3677 if (!RetPtrTy) 3678 return nullptr; 3679 3680 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3681 } 3682 3683 /// Compare the user-defined conversion functions or constructors 3684 /// of two user-defined conversion sequences to determine whether any ordering 3685 /// is possible. 3686 static ImplicitConversionSequence::CompareKind 3687 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3688 FunctionDecl *Function2) { 3689 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3690 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3691 if (!Conv1 || !Conv2) 3692 return ImplicitConversionSequence::Indistinguishable; 3693 3694 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3695 return ImplicitConversionSequence::Indistinguishable; 3696 3697 // Objective-C++: 3698 // If both conversion functions are implicitly-declared conversions from 3699 // a lambda closure type to a function pointer and a block pointer, 3700 // respectively, always prefer the conversion to a function pointer, 3701 // because the function pointer is more lightweight and is more likely 3702 // to keep code working. 3703 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3704 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3705 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3706 if (Block1 != Block2) 3707 return Block1 ? ImplicitConversionSequence::Worse 3708 : ImplicitConversionSequence::Better; 3709 } 3710 3711 // In order to support multiple calling conventions for the lambda conversion 3712 // operator (such as when the free and member function calling convention is 3713 // different), prefer the 'free' mechanism, followed by the calling-convention 3714 // of operator(). The latter is in place to support the MSVC-like solution of 3715 // defining ALL of the possible conversions in regards to calling-convention. 3716 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3717 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3718 3719 if (Conv1FuncRet && Conv2FuncRet && 3720 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3721 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3722 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3723 3724 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3725 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 3726 3727 CallingConv CallOpCC = 3728 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3729 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3730 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3731 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3732 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3733 3734 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3735 for (CallingConv CC : PrefOrder) { 3736 if (Conv1CC == CC) 3737 return ImplicitConversionSequence::Better; 3738 if (Conv2CC == CC) 3739 return ImplicitConversionSequence::Worse; 3740 } 3741 } 3742 3743 return ImplicitConversionSequence::Indistinguishable; 3744 } 3745 3746 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3747 const ImplicitConversionSequence &ICS) { 3748 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3749 (ICS.isUserDefined() && 3750 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3751 } 3752 3753 /// CompareImplicitConversionSequences - Compare two implicit 3754 /// conversion sequences to determine whether one is better than the 3755 /// other or if they are indistinguishable (C++ 13.3.3.2). 3756 static ImplicitConversionSequence::CompareKind 3757 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3758 const ImplicitConversionSequence& ICS1, 3759 const ImplicitConversionSequence& ICS2) 3760 { 3761 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3762 // conversion sequences (as defined in 13.3.3.1) 3763 // -- a standard conversion sequence (13.3.3.1.1) is a better 3764 // conversion sequence than a user-defined conversion sequence or 3765 // an ellipsis conversion sequence, and 3766 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3767 // conversion sequence than an ellipsis conversion sequence 3768 // (13.3.3.1.3). 3769 // 3770 // C++0x [over.best.ics]p10: 3771 // For the purpose of ranking implicit conversion sequences as 3772 // described in 13.3.3.2, the ambiguous conversion sequence is 3773 // treated as a user-defined sequence that is indistinguishable 3774 // from any other user-defined conversion sequence. 3775 3776 // String literal to 'char *' conversion has been deprecated in C++03. It has 3777 // been removed from C++11. We still accept this conversion, if it happens at 3778 // the best viable function. Otherwise, this conversion is considered worse 3779 // than ellipsis conversion. Consider this as an extension; this is not in the 3780 // standard. For example: 3781 // 3782 // int &f(...); // #1 3783 // void f(char*); // #2 3784 // void g() { int &r = f("foo"); } 3785 // 3786 // In C++03, we pick #2 as the best viable function. 3787 // In C++11, we pick #1 as the best viable function, because ellipsis 3788 // conversion is better than string-literal to char* conversion (since there 3789 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3790 // convert arguments, #2 would be the best viable function in C++11. 3791 // If the best viable function has this conversion, a warning will be issued 3792 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3793 3794 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3795 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3796 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 3797 // Ill-formedness must not differ 3798 ICS1.isBad() == ICS2.isBad()) 3799 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3800 ? ImplicitConversionSequence::Worse 3801 : ImplicitConversionSequence::Better; 3802 3803 if (ICS1.getKindRank() < ICS2.getKindRank()) 3804 return ImplicitConversionSequence::Better; 3805 if (ICS2.getKindRank() < ICS1.getKindRank()) 3806 return ImplicitConversionSequence::Worse; 3807 3808 // The following checks require both conversion sequences to be of 3809 // the same kind. 3810 if (ICS1.getKind() != ICS2.getKind()) 3811 return ImplicitConversionSequence::Indistinguishable; 3812 3813 ImplicitConversionSequence::CompareKind Result = 3814 ImplicitConversionSequence::Indistinguishable; 3815 3816 // Two implicit conversion sequences of the same form are 3817 // indistinguishable conversion sequences unless one of the 3818 // following rules apply: (C++ 13.3.3.2p3): 3819 3820 // List-initialization sequence L1 is a better conversion sequence than 3821 // list-initialization sequence L2 if: 3822 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3823 // if not that, 3824 // — L1 and L2 convert to arrays of the same element type, and either the 3825 // number of elements n_1 initialized by L1 is less than the number of 3826 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 3827 // an array of unknown bound and L1 does not, 3828 // even if one of the other rules in this paragraph would otherwise apply. 3829 if (!ICS1.isBad()) { 3830 bool StdInit1 = false, StdInit2 = false; 3831 if (ICS1.hasInitializerListContainerType()) 3832 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 3833 nullptr); 3834 if (ICS2.hasInitializerListContainerType()) 3835 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 3836 nullptr); 3837 if (StdInit1 != StdInit2) 3838 return StdInit1 ? ImplicitConversionSequence::Better 3839 : ImplicitConversionSequence::Worse; 3840 3841 if (ICS1.hasInitializerListContainerType() && 3842 ICS2.hasInitializerListContainerType()) 3843 if (auto *CAT1 = S.Context.getAsConstantArrayType( 3844 ICS1.getInitializerListContainerType())) 3845 if (auto *CAT2 = S.Context.getAsConstantArrayType( 3846 ICS2.getInitializerListContainerType())) { 3847 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 3848 CAT2->getElementType())) { 3849 // Both to arrays of the same element type 3850 if (CAT1->getSize() != CAT2->getSize()) 3851 // Different sized, the smaller wins 3852 return CAT1->getSize().ult(CAT2->getSize()) 3853 ? ImplicitConversionSequence::Better 3854 : ImplicitConversionSequence::Worse; 3855 if (ICS1.isInitializerListOfIncompleteArray() != 3856 ICS2.isInitializerListOfIncompleteArray()) 3857 // One is incomplete, it loses 3858 return ICS2.isInitializerListOfIncompleteArray() 3859 ? ImplicitConversionSequence::Better 3860 : ImplicitConversionSequence::Worse; 3861 } 3862 } 3863 } 3864 3865 if (ICS1.isStandard()) 3866 // Standard conversion sequence S1 is a better conversion sequence than 3867 // standard conversion sequence S2 if [...] 3868 Result = CompareStandardConversionSequences(S, Loc, 3869 ICS1.Standard, ICS2.Standard); 3870 else if (ICS1.isUserDefined()) { 3871 // User-defined conversion sequence U1 is a better conversion 3872 // sequence than another user-defined conversion sequence U2 if 3873 // they contain the same user-defined conversion function or 3874 // constructor and if the second standard conversion sequence of 3875 // U1 is better than the second standard conversion sequence of 3876 // U2 (C++ 13.3.3.2p3). 3877 if (ICS1.UserDefined.ConversionFunction == 3878 ICS2.UserDefined.ConversionFunction) 3879 Result = CompareStandardConversionSequences(S, Loc, 3880 ICS1.UserDefined.After, 3881 ICS2.UserDefined.After); 3882 else 3883 Result = compareConversionFunctions(S, 3884 ICS1.UserDefined.ConversionFunction, 3885 ICS2.UserDefined.ConversionFunction); 3886 } 3887 3888 return Result; 3889 } 3890 3891 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3892 // determine if one is a proper subset of the other. 3893 static ImplicitConversionSequence::CompareKind 3894 compareStandardConversionSubsets(ASTContext &Context, 3895 const StandardConversionSequence& SCS1, 3896 const StandardConversionSequence& SCS2) { 3897 ImplicitConversionSequence::CompareKind Result 3898 = ImplicitConversionSequence::Indistinguishable; 3899 3900 // the identity conversion sequence is considered to be a subsequence of 3901 // any non-identity conversion sequence 3902 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3903 return ImplicitConversionSequence::Better; 3904 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3905 return ImplicitConversionSequence::Worse; 3906 3907 if (SCS1.Second != SCS2.Second) { 3908 if (SCS1.Second == ICK_Identity) 3909 Result = ImplicitConversionSequence::Better; 3910 else if (SCS2.Second == ICK_Identity) 3911 Result = ImplicitConversionSequence::Worse; 3912 else 3913 return ImplicitConversionSequence::Indistinguishable; 3914 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3915 return ImplicitConversionSequence::Indistinguishable; 3916 3917 if (SCS1.Third == SCS2.Third) { 3918 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3919 : ImplicitConversionSequence::Indistinguishable; 3920 } 3921 3922 if (SCS1.Third == ICK_Identity) 3923 return Result == ImplicitConversionSequence::Worse 3924 ? ImplicitConversionSequence::Indistinguishable 3925 : ImplicitConversionSequence::Better; 3926 3927 if (SCS2.Third == ICK_Identity) 3928 return Result == ImplicitConversionSequence::Better 3929 ? ImplicitConversionSequence::Indistinguishable 3930 : ImplicitConversionSequence::Worse; 3931 3932 return ImplicitConversionSequence::Indistinguishable; 3933 } 3934 3935 /// Determine whether one of the given reference bindings is better 3936 /// than the other based on what kind of bindings they are. 3937 static bool 3938 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3939 const StandardConversionSequence &SCS2) { 3940 // C++0x [over.ics.rank]p3b4: 3941 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3942 // implicit object parameter of a non-static member function declared 3943 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3944 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3945 // lvalue reference to a function lvalue and S2 binds an rvalue 3946 // reference*. 3947 // 3948 // FIXME: Rvalue references. We're going rogue with the above edits, 3949 // because the semantics in the current C++0x working paper (N3225 at the 3950 // time of this writing) break the standard definition of std::forward 3951 // and std::reference_wrapper when dealing with references to functions. 3952 // Proposed wording changes submitted to CWG for consideration. 3953 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3954 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3955 return false; 3956 3957 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3958 SCS2.IsLvalueReference) || 3959 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3960 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3961 } 3962 3963 enum class FixedEnumPromotion { 3964 None, 3965 ToUnderlyingType, 3966 ToPromotedUnderlyingType 3967 }; 3968 3969 /// Returns kind of fixed enum promotion the \a SCS uses. 3970 static FixedEnumPromotion 3971 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3972 3973 if (SCS.Second != ICK_Integral_Promotion) 3974 return FixedEnumPromotion::None; 3975 3976 QualType FromType = SCS.getFromType(); 3977 if (!FromType->isEnumeralType()) 3978 return FixedEnumPromotion::None; 3979 3980 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 3981 if (!Enum->isFixed()) 3982 return FixedEnumPromotion::None; 3983 3984 QualType UnderlyingType = Enum->getIntegerType(); 3985 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3986 return FixedEnumPromotion::ToUnderlyingType; 3987 3988 return FixedEnumPromotion::ToPromotedUnderlyingType; 3989 } 3990 3991 /// CompareStandardConversionSequences - Compare two standard 3992 /// conversion sequences to determine whether one is better than the 3993 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3994 static ImplicitConversionSequence::CompareKind 3995 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3996 const StandardConversionSequence& SCS1, 3997 const StandardConversionSequence& SCS2) 3998 { 3999 // Standard conversion sequence S1 is a better conversion sequence 4000 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 4001 4002 // -- S1 is a proper subsequence of S2 (comparing the conversion 4003 // sequences in the canonical form defined by 13.3.3.1.1, 4004 // excluding any Lvalue Transformation; the identity conversion 4005 // sequence is considered to be a subsequence of any 4006 // non-identity conversion sequence) or, if not that, 4007 if (ImplicitConversionSequence::CompareKind CK 4008 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4009 return CK; 4010 4011 // -- the rank of S1 is better than the rank of S2 (by the rules 4012 // defined below), or, if not that, 4013 ImplicitConversionRank Rank1 = SCS1.getRank(); 4014 ImplicitConversionRank Rank2 = SCS2.getRank(); 4015 if (Rank1 < Rank2) 4016 return ImplicitConversionSequence::Better; 4017 else if (Rank2 < Rank1) 4018 return ImplicitConversionSequence::Worse; 4019 4020 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4021 // are indistinguishable unless one of the following rules 4022 // applies: 4023 4024 // A conversion that is not a conversion of a pointer, or 4025 // pointer to member, to bool is better than another conversion 4026 // that is such a conversion. 4027 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4028 return SCS2.isPointerConversionToBool() 4029 ? ImplicitConversionSequence::Better 4030 : ImplicitConversionSequence::Worse; 4031 4032 // C++14 [over.ics.rank]p4b2: 4033 // This is retroactively applied to C++11 by CWG 1601. 4034 // 4035 // A conversion that promotes an enumeration whose underlying type is fixed 4036 // to its underlying type is better than one that promotes to the promoted 4037 // underlying type, if the two are different. 4038 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4039 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4040 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4041 FEP1 != FEP2) 4042 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4043 ? ImplicitConversionSequence::Better 4044 : ImplicitConversionSequence::Worse; 4045 4046 // C++ [over.ics.rank]p4b2: 4047 // 4048 // If class B is derived directly or indirectly from class A, 4049 // conversion of B* to A* is better than conversion of B* to 4050 // void*, and conversion of A* to void* is better than conversion 4051 // of B* to void*. 4052 bool SCS1ConvertsToVoid 4053 = SCS1.isPointerConversionToVoidPointer(S.Context); 4054 bool SCS2ConvertsToVoid 4055 = SCS2.isPointerConversionToVoidPointer(S.Context); 4056 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4057 // Exactly one of the conversion sequences is a conversion to 4058 // a void pointer; it's the worse conversion. 4059 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4060 : ImplicitConversionSequence::Worse; 4061 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4062 // Neither conversion sequence converts to a void pointer; compare 4063 // their derived-to-base conversions. 4064 if (ImplicitConversionSequence::CompareKind DerivedCK 4065 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4066 return DerivedCK; 4067 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4068 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4069 // Both conversion sequences are conversions to void 4070 // pointers. Compare the source types to determine if there's an 4071 // inheritance relationship in their sources. 4072 QualType FromType1 = SCS1.getFromType(); 4073 QualType FromType2 = SCS2.getFromType(); 4074 4075 // Adjust the types we're converting from via the array-to-pointer 4076 // conversion, if we need to. 4077 if (SCS1.First == ICK_Array_To_Pointer) 4078 FromType1 = S.Context.getArrayDecayedType(FromType1); 4079 if (SCS2.First == ICK_Array_To_Pointer) 4080 FromType2 = S.Context.getArrayDecayedType(FromType2); 4081 4082 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4083 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4084 4085 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4086 return ImplicitConversionSequence::Better; 4087 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4088 return ImplicitConversionSequence::Worse; 4089 4090 // Objective-C++: If one interface is more specific than the 4091 // other, it is the better one. 4092 const ObjCObjectPointerType* FromObjCPtr1 4093 = FromType1->getAs<ObjCObjectPointerType>(); 4094 const ObjCObjectPointerType* FromObjCPtr2 4095 = FromType2->getAs<ObjCObjectPointerType>(); 4096 if (FromObjCPtr1 && FromObjCPtr2) { 4097 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4098 FromObjCPtr2); 4099 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4100 FromObjCPtr1); 4101 if (AssignLeft != AssignRight) { 4102 return AssignLeft? ImplicitConversionSequence::Better 4103 : ImplicitConversionSequence::Worse; 4104 } 4105 } 4106 } 4107 4108 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4109 // Check for a better reference binding based on the kind of bindings. 4110 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4111 return ImplicitConversionSequence::Better; 4112 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4113 return ImplicitConversionSequence::Worse; 4114 } 4115 4116 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4117 // bullet 3). 4118 if (ImplicitConversionSequence::CompareKind QualCK 4119 = CompareQualificationConversions(S, SCS1, SCS2)) 4120 return QualCK; 4121 4122 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4123 // C++ [over.ics.rank]p3b4: 4124 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4125 // which the references refer are the same type except for 4126 // top-level cv-qualifiers, and the type to which the reference 4127 // initialized by S2 refers is more cv-qualified than the type 4128 // to which the reference initialized by S1 refers. 4129 QualType T1 = SCS1.getToType(2); 4130 QualType T2 = SCS2.getToType(2); 4131 T1 = S.Context.getCanonicalType(T1); 4132 T2 = S.Context.getCanonicalType(T2); 4133 Qualifiers T1Quals, T2Quals; 4134 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4135 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4136 if (UnqualT1 == UnqualT2) { 4137 // Objective-C++ ARC: If the references refer to objects with different 4138 // lifetimes, prefer bindings that don't change lifetime. 4139 if (SCS1.ObjCLifetimeConversionBinding != 4140 SCS2.ObjCLifetimeConversionBinding) { 4141 return SCS1.ObjCLifetimeConversionBinding 4142 ? ImplicitConversionSequence::Worse 4143 : ImplicitConversionSequence::Better; 4144 } 4145 4146 // If the type is an array type, promote the element qualifiers to the 4147 // type for comparison. 4148 if (isa<ArrayType>(T1) && T1Quals) 4149 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4150 if (isa<ArrayType>(T2) && T2Quals) 4151 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4152 if (T2.isMoreQualifiedThan(T1)) 4153 return ImplicitConversionSequence::Better; 4154 if (T1.isMoreQualifiedThan(T2)) 4155 return ImplicitConversionSequence::Worse; 4156 } 4157 } 4158 4159 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4160 // floating-to-integral conversion if the integral conversion 4161 // is between types of the same size. 4162 // For example: 4163 // void f(float); 4164 // void f(int); 4165 // int main { 4166 // long a; 4167 // f(a); 4168 // } 4169 // Here, MSVC will call f(int) instead of generating a compile error 4170 // as clang will do in standard mode. 4171 if (S.getLangOpts().MSVCCompat && 4172 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4173 SCS1.Second == ICK_Integral_Conversion && 4174 SCS2.Second == ICK_Floating_Integral && 4175 S.Context.getTypeSize(SCS1.getFromType()) == 4176 S.Context.getTypeSize(SCS1.getToType(2))) 4177 return ImplicitConversionSequence::Better; 4178 4179 // Prefer a compatible vector conversion over a lax vector conversion 4180 // For example: 4181 // 4182 // typedef float __v4sf __attribute__((__vector_size__(16))); 4183 // void f(vector float); 4184 // void f(vector signed int); 4185 // int main() { 4186 // __v4sf a; 4187 // f(a); 4188 // } 4189 // Here, we'd like to choose f(vector float) and not 4190 // report an ambiguous call error 4191 if (SCS1.Second == ICK_Vector_Conversion && 4192 SCS2.Second == ICK_Vector_Conversion) { 4193 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4194 SCS1.getFromType(), SCS1.getToType(2)); 4195 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4196 SCS2.getFromType(), SCS2.getToType(2)); 4197 4198 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4199 return SCS1IsCompatibleVectorConversion 4200 ? ImplicitConversionSequence::Better 4201 : ImplicitConversionSequence::Worse; 4202 } 4203 4204 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4205 SCS2.Second == ICK_SVE_Vector_Conversion) { 4206 bool SCS1IsCompatibleSVEVectorConversion = 4207 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4208 bool SCS2IsCompatibleSVEVectorConversion = 4209 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4210 4211 if (SCS1IsCompatibleSVEVectorConversion != 4212 SCS2IsCompatibleSVEVectorConversion) 4213 return SCS1IsCompatibleSVEVectorConversion 4214 ? ImplicitConversionSequence::Better 4215 : ImplicitConversionSequence::Worse; 4216 } 4217 4218 return ImplicitConversionSequence::Indistinguishable; 4219 } 4220 4221 /// CompareQualificationConversions - Compares two standard conversion 4222 /// sequences to determine whether they can be ranked based on their 4223 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4224 static ImplicitConversionSequence::CompareKind 4225 CompareQualificationConversions(Sema &S, 4226 const StandardConversionSequence& SCS1, 4227 const StandardConversionSequence& SCS2) { 4228 // C++ [over.ics.rank]p3: 4229 // -- S1 and S2 differ only in their qualification conversion and 4230 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4231 // [C++98] 4232 // [...] and the cv-qualification signature of type T1 is a proper subset 4233 // of the cv-qualification signature of type T2, and S1 is not the 4234 // deprecated string literal array-to-pointer conversion (4.2). 4235 // [C++2a] 4236 // [...] where T1 can be converted to T2 by a qualification conversion. 4237 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4238 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4239 return ImplicitConversionSequence::Indistinguishable; 4240 4241 // FIXME: the example in the standard doesn't use a qualification 4242 // conversion (!) 4243 QualType T1 = SCS1.getToType(2); 4244 QualType T2 = SCS2.getToType(2); 4245 T1 = S.Context.getCanonicalType(T1); 4246 T2 = S.Context.getCanonicalType(T2); 4247 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4248 Qualifiers T1Quals, T2Quals; 4249 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4250 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4251 4252 // If the types are the same, we won't learn anything by unwrapping 4253 // them. 4254 if (UnqualT1 == UnqualT2) 4255 return ImplicitConversionSequence::Indistinguishable; 4256 4257 // Don't ever prefer a standard conversion sequence that uses the deprecated 4258 // string literal array to pointer conversion. 4259 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4260 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4261 4262 // Objective-C++ ARC: 4263 // Prefer qualification conversions not involving a change in lifetime 4264 // to qualification conversions that do change lifetime. 4265 if (SCS1.QualificationIncludesObjCLifetime && 4266 !SCS2.QualificationIncludesObjCLifetime) 4267 CanPick1 = false; 4268 if (SCS2.QualificationIncludesObjCLifetime && 4269 !SCS1.QualificationIncludesObjCLifetime) 4270 CanPick2 = false; 4271 4272 bool ObjCLifetimeConversion; 4273 if (CanPick1 && 4274 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4275 CanPick1 = false; 4276 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4277 // directions, so we can't short-cut this second check in general. 4278 if (CanPick2 && 4279 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4280 CanPick2 = false; 4281 4282 if (CanPick1 != CanPick2) 4283 return CanPick1 ? ImplicitConversionSequence::Better 4284 : ImplicitConversionSequence::Worse; 4285 return ImplicitConversionSequence::Indistinguishable; 4286 } 4287 4288 /// CompareDerivedToBaseConversions - Compares two standard conversion 4289 /// sequences to determine whether they can be ranked based on their 4290 /// various kinds of derived-to-base conversions (C++ 4291 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4292 /// conversions between Objective-C interface types. 4293 static ImplicitConversionSequence::CompareKind 4294 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4295 const StandardConversionSequence& SCS1, 4296 const StandardConversionSequence& SCS2) { 4297 QualType FromType1 = SCS1.getFromType(); 4298 QualType ToType1 = SCS1.getToType(1); 4299 QualType FromType2 = SCS2.getFromType(); 4300 QualType ToType2 = SCS2.getToType(1); 4301 4302 // Adjust the types we're converting from via the array-to-pointer 4303 // conversion, if we need to. 4304 if (SCS1.First == ICK_Array_To_Pointer) 4305 FromType1 = S.Context.getArrayDecayedType(FromType1); 4306 if (SCS2.First == ICK_Array_To_Pointer) 4307 FromType2 = S.Context.getArrayDecayedType(FromType2); 4308 4309 // Canonicalize all of the types. 4310 FromType1 = S.Context.getCanonicalType(FromType1); 4311 ToType1 = S.Context.getCanonicalType(ToType1); 4312 FromType2 = S.Context.getCanonicalType(FromType2); 4313 ToType2 = S.Context.getCanonicalType(ToType2); 4314 4315 // C++ [over.ics.rank]p4b3: 4316 // 4317 // If class B is derived directly or indirectly from class A and 4318 // class C is derived directly or indirectly from B, 4319 // 4320 // Compare based on pointer conversions. 4321 if (SCS1.Second == ICK_Pointer_Conversion && 4322 SCS2.Second == ICK_Pointer_Conversion && 4323 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4324 FromType1->isPointerType() && FromType2->isPointerType() && 4325 ToType1->isPointerType() && ToType2->isPointerType()) { 4326 QualType FromPointee1 = 4327 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4328 QualType ToPointee1 = 4329 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4330 QualType FromPointee2 = 4331 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4332 QualType ToPointee2 = 4333 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4334 4335 // -- conversion of C* to B* is better than conversion of C* to A*, 4336 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4337 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4338 return ImplicitConversionSequence::Better; 4339 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4340 return ImplicitConversionSequence::Worse; 4341 } 4342 4343 // -- conversion of B* to A* is better than conversion of C* to A*, 4344 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4345 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4346 return ImplicitConversionSequence::Better; 4347 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4348 return ImplicitConversionSequence::Worse; 4349 } 4350 } else if (SCS1.Second == ICK_Pointer_Conversion && 4351 SCS2.Second == ICK_Pointer_Conversion) { 4352 const ObjCObjectPointerType *FromPtr1 4353 = FromType1->getAs<ObjCObjectPointerType>(); 4354 const ObjCObjectPointerType *FromPtr2 4355 = FromType2->getAs<ObjCObjectPointerType>(); 4356 const ObjCObjectPointerType *ToPtr1 4357 = ToType1->getAs<ObjCObjectPointerType>(); 4358 const ObjCObjectPointerType *ToPtr2 4359 = ToType2->getAs<ObjCObjectPointerType>(); 4360 4361 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4362 // Apply the same conversion ranking rules for Objective-C pointer types 4363 // that we do for C++ pointers to class types. However, we employ the 4364 // Objective-C pseudo-subtyping relationship used for assignment of 4365 // Objective-C pointer types. 4366 bool FromAssignLeft 4367 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4368 bool FromAssignRight 4369 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4370 bool ToAssignLeft 4371 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4372 bool ToAssignRight 4373 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4374 4375 // A conversion to an a non-id object pointer type or qualified 'id' 4376 // type is better than a conversion to 'id'. 4377 if (ToPtr1->isObjCIdType() && 4378 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4379 return ImplicitConversionSequence::Worse; 4380 if (ToPtr2->isObjCIdType() && 4381 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4382 return ImplicitConversionSequence::Better; 4383 4384 // A conversion to a non-id object pointer type is better than a 4385 // conversion to a qualified 'id' type 4386 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4387 return ImplicitConversionSequence::Worse; 4388 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4389 return ImplicitConversionSequence::Better; 4390 4391 // A conversion to an a non-Class object pointer type or qualified 'Class' 4392 // type is better than a conversion to 'Class'. 4393 if (ToPtr1->isObjCClassType() && 4394 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4395 return ImplicitConversionSequence::Worse; 4396 if (ToPtr2->isObjCClassType() && 4397 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4398 return ImplicitConversionSequence::Better; 4399 4400 // A conversion to a non-Class object pointer type is better than a 4401 // conversion to a qualified 'Class' type. 4402 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4403 return ImplicitConversionSequence::Worse; 4404 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4405 return ImplicitConversionSequence::Better; 4406 4407 // -- "conversion of C* to B* is better than conversion of C* to A*," 4408 if (S.Context.hasSameType(FromType1, FromType2) && 4409 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4410 (ToAssignLeft != ToAssignRight)) { 4411 if (FromPtr1->isSpecialized()) { 4412 // "conversion of B<A> * to B * is better than conversion of B * to 4413 // C *. 4414 bool IsFirstSame = 4415 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4416 bool IsSecondSame = 4417 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4418 if (IsFirstSame) { 4419 if (!IsSecondSame) 4420 return ImplicitConversionSequence::Better; 4421 } else if (IsSecondSame) 4422 return ImplicitConversionSequence::Worse; 4423 } 4424 return ToAssignLeft? ImplicitConversionSequence::Worse 4425 : ImplicitConversionSequence::Better; 4426 } 4427 4428 // -- "conversion of B* to A* is better than conversion of C* to A*," 4429 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4430 (FromAssignLeft != FromAssignRight)) 4431 return FromAssignLeft? ImplicitConversionSequence::Better 4432 : ImplicitConversionSequence::Worse; 4433 } 4434 } 4435 4436 // Ranking of member-pointer types. 4437 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4438 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4439 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4440 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4441 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4442 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4443 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4444 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4445 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4446 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4447 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4448 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4449 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4450 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4451 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4452 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4453 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4454 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4455 return ImplicitConversionSequence::Worse; 4456 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4457 return ImplicitConversionSequence::Better; 4458 } 4459 // conversion of B::* to C::* is better than conversion of A::* to C::* 4460 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4461 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4462 return ImplicitConversionSequence::Better; 4463 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4464 return ImplicitConversionSequence::Worse; 4465 } 4466 } 4467 4468 if (SCS1.Second == ICK_Derived_To_Base) { 4469 // -- conversion of C to B is better than conversion of C to A, 4470 // -- binding of an expression of type C to a reference of type 4471 // B& is better than binding an expression of type C to a 4472 // reference of type A&, 4473 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4474 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4475 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4476 return ImplicitConversionSequence::Better; 4477 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4478 return ImplicitConversionSequence::Worse; 4479 } 4480 4481 // -- conversion of B to A is better than conversion of C to A. 4482 // -- binding of an expression of type B to a reference of type 4483 // A& is better than binding an expression of type C to a 4484 // reference of type A&, 4485 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4486 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4487 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4488 return ImplicitConversionSequence::Better; 4489 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4490 return ImplicitConversionSequence::Worse; 4491 } 4492 } 4493 4494 return ImplicitConversionSequence::Indistinguishable; 4495 } 4496 4497 /// Determine whether the given type is valid, e.g., it is not an invalid 4498 /// C++ class. 4499 static bool isTypeValid(QualType T) { 4500 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4501 return !Record->isInvalidDecl(); 4502 4503 return true; 4504 } 4505 4506 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4507 if (!T.getQualifiers().hasUnaligned()) 4508 return T; 4509 4510 Qualifiers Q; 4511 T = Ctx.getUnqualifiedArrayType(T, Q); 4512 Q.removeUnaligned(); 4513 return Ctx.getQualifiedType(T, Q); 4514 } 4515 4516 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4517 /// determine whether they are reference-compatible, 4518 /// reference-related, or incompatible, for use in C++ initialization by 4519 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4520 /// type, and the first type (T1) is the pointee type of the reference 4521 /// type being initialized. 4522 Sema::ReferenceCompareResult 4523 Sema::CompareReferenceRelationship(SourceLocation Loc, 4524 QualType OrigT1, QualType OrigT2, 4525 ReferenceConversions *ConvOut) { 4526 assert(!OrigT1->isReferenceType() && 4527 "T1 must be the pointee type of the reference type"); 4528 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4529 4530 QualType T1 = Context.getCanonicalType(OrigT1); 4531 QualType T2 = Context.getCanonicalType(OrigT2); 4532 Qualifiers T1Quals, T2Quals; 4533 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4534 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4535 4536 ReferenceConversions ConvTmp; 4537 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4538 Conv = ReferenceConversions(); 4539 4540 // C++2a [dcl.init.ref]p4: 4541 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4542 // reference-related to "cv2 T2" if T1 is similar to T2, or 4543 // T1 is a base class of T2. 4544 // "cv1 T1" is reference-compatible with "cv2 T2" if 4545 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4546 // "pointer to cv1 T1" via a standard conversion sequence. 4547 4548 // Check for standard conversions we can apply to pointers: derived-to-base 4549 // conversions, ObjC pointer conversions, and function pointer conversions. 4550 // (Qualification conversions are checked last.) 4551 QualType ConvertedT2; 4552 if (UnqualT1 == UnqualT2) { 4553 // Nothing to do. 4554 } else if (isCompleteType(Loc, OrigT2) && 4555 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4556 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4557 Conv |= ReferenceConversions::DerivedToBase; 4558 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4559 UnqualT2->isObjCObjectOrInterfaceType() && 4560 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4561 Conv |= ReferenceConversions::ObjC; 4562 else if (UnqualT2->isFunctionType() && 4563 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4564 Conv |= ReferenceConversions::Function; 4565 // No need to check qualifiers; function types don't have them. 4566 return Ref_Compatible; 4567 } 4568 bool ConvertedReferent = Conv != 0; 4569 4570 // We can have a qualification conversion. Compute whether the types are 4571 // similar at the same time. 4572 bool PreviousToQualsIncludeConst = true; 4573 bool TopLevel = true; 4574 do { 4575 if (T1 == T2) 4576 break; 4577 4578 // We will need a qualification conversion. 4579 Conv |= ReferenceConversions::Qualification; 4580 4581 // Track whether we performed a qualification conversion anywhere other 4582 // than the top level. This matters for ranking reference bindings in 4583 // overload resolution. 4584 if (!TopLevel) 4585 Conv |= ReferenceConversions::NestedQualification; 4586 4587 // MS compiler ignores __unaligned qualifier for references; do the same. 4588 T1 = withoutUnaligned(Context, T1); 4589 T2 = withoutUnaligned(Context, T2); 4590 4591 // If we find a qualifier mismatch, the types are not reference-compatible, 4592 // but are still be reference-related if they're similar. 4593 bool ObjCLifetimeConversion = false; 4594 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4595 PreviousToQualsIncludeConst, 4596 ObjCLifetimeConversion)) 4597 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4598 ? Ref_Related 4599 : Ref_Incompatible; 4600 4601 // FIXME: Should we track this for any level other than the first? 4602 if (ObjCLifetimeConversion) 4603 Conv |= ReferenceConversions::ObjCLifetime; 4604 4605 TopLevel = false; 4606 } while (Context.UnwrapSimilarTypes(T1, T2)); 4607 4608 // At this point, if the types are reference-related, we must either have the 4609 // same inner type (ignoring qualifiers), or must have already worked out how 4610 // to convert the referent. 4611 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4612 ? Ref_Compatible 4613 : Ref_Incompatible; 4614 } 4615 4616 /// Look for a user-defined conversion to a value reference-compatible 4617 /// with DeclType. Return true if something definite is found. 4618 static bool 4619 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4620 QualType DeclType, SourceLocation DeclLoc, 4621 Expr *Init, QualType T2, bool AllowRvalues, 4622 bool AllowExplicit) { 4623 assert(T2->isRecordType() && "Can only find conversions of record types."); 4624 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4625 4626 OverloadCandidateSet CandidateSet( 4627 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4628 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4629 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4630 NamedDecl *D = *I; 4631 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4632 if (isa<UsingShadowDecl>(D)) 4633 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4634 4635 FunctionTemplateDecl *ConvTemplate 4636 = dyn_cast<FunctionTemplateDecl>(D); 4637 CXXConversionDecl *Conv; 4638 if (ConvTemplate) 4639 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4640 else 4641 Conv = cast<CXXConversionDecl>(D); 4642 4643 if (AllowRvalues) { 4644 // If we are initializing an rvalue reference, don't permit conversion 4645 // functions that return lvalues. 4646 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4647 const ReferenceType *RefType 4648 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4649 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4650 continue; 4651 } 4652 4653 if (!ConvTemplate && 4654 S.CompareReferenceRelationship( 4655 DeclLoc, 4656 Conv->getConversionType() 4657 .getNonReferenceType() 4658 .getUnqualifiedType(), 4659 DeclType.getNonReferenceType().getUnqualifiedType()) == 4660 Sema::Ref_Incompatible) 4661 continue; 4662 } else { 4663 // If the conversion function doesn't return a reference type, 4664 // it can't be considered for this conversion. An rvalue reference 4665 // is only acceptable if its referencee is a function type. 4666 4667 const ReferenceType *RefType = 4668 Conv->getConversionType()->getAs<ReferenceType>(); 4669 if (!RefType || 4670 (!RefType->isLValueReferenceType() && 4671 !RefType->getPointeeType()->isFunctionType())) 4672 continue; 4673 } 4674 4675 if (ConvTemplate) 4676 S.AddTemplateConversionCandidate( 4677 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4678 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4679 else 4680 S.AddConversionCandidate( 4681 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4682 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4683 } 4684 4685 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4686 4687 OverloadCandidateSet::iterator Best; 4688 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4689 case OR_Success: 4690 // C++ [over.ics.ref]p1: 4691 // 4692 // [...] If the parameter binds directly to the result of 4693 // applying a conversion function to the argument 4694 // expression, the implicit conversion sequence is a 4695 // user-defined conversion sequence (13.3.3.1.2), with the 4696 // second standard conversion sequence either an identity 4697 // conversion or, if the conversion function returns an 4698 // entity of a type that is a derived class of the parameter 4699 // type, a derived-to-base Conversion. 4700 if (!Best->FinalConversion.DirectBinding) 4701 return false; 4702 4703 ICS.setUserDefined(); 4704 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4705 ICS.UserDefined.After = Best->FinalConversion; 4706 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4707 ICS.UserDefined.ConversionFunction = Best->Function; 4708 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4709 ICS.UserDefined.EllipsisConversion = false; 4710 assert(ICS.UserDefined.After.ReferenceBinding && 4711 ICS.UserDefined.After.DirectBinding && 4712 "Expected a direct reference binding!"); 4713 return true; 4714 4715 case OR_Ambiguous: 4716 ICS.setAmbiguous(); 4717 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4718 Cand != CandidateSet.end(); ++Cand) 4719 if (Cand->Best) 4720 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4721 return true; 4722 4723 case OR_No_Viable_Function: 4724 case OR_Deleted: 4725 // There was no suitable conversion, or we found a deleted 4726 // conversion; continue with other checks. 4727 return false; 4728 } 4729 4730 llvm_unreachable("Invalid OverloadResult!"); 4731 } 4732 4733 /// Compute an implicit conversion sequence for reference 4734 /// initialization. 4735 static ImplicitConversionSequence 4736 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4737 SourceLocation DeclLoc, 4738 bool SuppressUserConversions, 4739 bool AllowExplicit) { 4740 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4741 4742 // Most paths end in a failed conversion. 4743 ImplicitConversionSequence ICS; 4744 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4745 4746 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4747 QualType T2 = Init->getType(); 4748 4749 // If the initializer is the address of an overloaded function, try 4750 // to resolve the overloaded function. If all goes well, T2 is the 4751 // type of the resulting function. 4752 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4753 DeclAccessPair Found; 4754 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4755 false, Found)) 4756 T2 = Fn->getType(); 4757 } 4758 4759 // Compute some basic properties of the types and the initializer. 4760 bool isRValRef = DeclType->isRValueReferenceType(); 4761 Expr::Classification InitCategory = Init->Classify(S.Context); 4762 4763 Sema::ReferenceConversions RefConv; 4764 Sema::ReferenceCompareResult RefRelationship = 4765 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4766 4767 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4768 ICS.setStandard(); 4769 ICS.Standard.First = ICK_Identity; 4770 // FIXME: A reference binding can be a function conversion too. We should 4771 // consider that when ordering reference-to-function bindings. 4772 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4773 ? ICK_Derived_To_Base 4774 : (RefConv & Sema::ReferenceConversions::ObjC) 4775 ? ICK_Compatible_Conversion 4776 : ICK_Identity; 4777 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4778 // a reference binding that performs a non-top-level qualification 4779 // conversion as a qualification conversion, not as an identity conversion. 4780 ICS.Standard.Third = (RefConv & 4781 Sema::ReferenceConversions::NestedQualification) 4782 ? ICK_Qualification 4783 : ICK_Identity; 4784 ICS.Standard.setFromType(T2); 4785 ICS.Standard.setToType(0, T2); 4786 ICS.Standard.setToType(1, T1); 4787 ICS.Standard.setToType(2, T1); 4788 ICS.Standard.ReferenceBinding = true; 4789 ICS.Standard.DirectBinding = BindsDirectly; 4790 ICS.Standard.IsLvalueReference = !isRValRef; 4791 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4792 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4793 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4794 ICS.Standard.ObjCLifetimeConversionBinding = 4795 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4796 ICS.Standard.CopyConstructor = nullptr; 4797 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4798 }; 4799 4800 // C++0x [dcl.init.ref]p5: 4801 // A reference to type "cv1 T1" is initialized by an expression 4802 // of type "cv2 T2" as follows: 4803 4804 // -- If reference is an lvalue reference and the initializer expression 4805 if (!isRValRef) { 4806 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4807 // reference-compatible with "cv2 T2," or 4808 // 4809 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4810 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4811 // C++ [over.ics.ref]p1: 4812 // When a parameter of reference type binds directly (8.5.3) 4813 // to an argument expression, the implicit conversion sequence 4814 // is the identity conversion, unless the argument expression 4815 // has a type that is a derived class of the parameter type, 4816 // in which case the implicit conversion sequence is a 4817 // derived-to-base Conversion (13.3.3.1). 4818 SetAsReferenceBinding(/*BindsDirectly=*/true); 4819 4820 // Nothing more to do: the inaccessibility/ambiguity check for 4821 // derived-to-base conversions is suppressed when we're 4822 // computing the implicit conversion sequence (C++ 4823 // [over.best.ics]p2). 4824 return ICS; 4825 } 4826 4827 // -- has a class type (i.e., T2 is a class type), where T1 is 4828 // not reference-related to T2, and can be implicitly 4829 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4830 // is reference-compatible with "cv3 T3" 92) (this 4831 // conversion is selected by enumerating the applicable 4832 // conversion functions (13.3.1.6) and choosing the best 4833 // one through overload resolution (13.3)), 4834 if (!SuppressUserConversions && T2->isRecordType() && 4835 S.isCompleteType(DeclLoc, T2) && 4836 RefRelationship == Sema::Ref_Incompatible) { 4837 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4838 Init, T2, /*AllowRvalues=*/false, 4839 AllowExplicit)) 4840 return ICS; 4841 } 4842 } 4843 4844 // -- Otherwise, the reference shall be an lvalue reference to a 4845 // non-volatile const type (i.e., cv1 shall be const), or the reference 4846 // shall be an rvalue reference. 4847 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4848 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4849 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4850 return ICS; 4851 } 4852 4853 // -- If the initializer expression 4854 // 4855 // -- is an xvalue, class prvalue, array prvalue or function 4856 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4857 if (RefRelationship == Sema::Ref_Compatible && 4858 (InitCategory.isXValue() || 4859 (InitCategory.isPRValue() && 4860 (T2->isRecordType() || T2->isArrayType())) || 4861 (InitCategory.isLValue() && T2->isFunctionType()))) { 4862 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4863 // binding unless we're binding to a class prvalue. 4864 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4865 // allow the use of rvalue references in C++98/03 for the benefit of 4866 // standard library implementors; therefore, we need the xvalue check here. 4867 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4868 !(InitCategory.isPRValue() || T2->isRecordType())); 4869 return ICS; 4870 } 4871 4872 // -- has a class type (i.e., T2 is a class type), where T1 is not 4873 // reference-related to T2, and can be implicitly converted to 4874 // an xvalue, class prvalue, or function lvalue of type 4875 // "cv3 T3", where "cv1 T1" is reference-compatible with 4876 // "cv3 T3", 4877 // 4878 // then the reference is bound to the value of the initializer 4879 // expression in the first case and to the result of the conversion 4880 // in the second case (or, in either case, to an appropriate base 4881 // class subobject). 4882 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4883 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4884 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4885 Init, T2, /*AllowRvalues=*/true, 4886 AllowExplicit)) { 4887 // In the second case, if the reference is an rvalue reference 4888 // and the second standard conversion sequence of the 4889 // user-defined conversion sequence includes an lvalue-to-rvalue 4890 // conversion, the program is ill-formed. 4891 if (ICS.isUserDefined() && isRValRef && 4892 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4893 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4894 4895 return ICS; 4896 } 4897 4898 // A temporary of function type cannot be created; don't even try. 4899 if (T1->isFunctionType()) 4900 return ICS; 4901 4902 // -- Otherwise, a temporary of type "cv1 T1" is created and 4903 // initialized from the initializer expression using the 4904 // rules for a non-reference copy initialization (8.5). The 4905 // reference is then bound to the temporary. If T1 is 4906 // reference-related to T2, cv1 must be the same 4907 // cv-qualification as, or greater cv-qualification than, 4908 // cv2; otherwise, the program is ill-formed. 4909 if (RefRelationship == Sema::Ref_Related) { 4910 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4911 // we would be reference-compatible or reference-compatible with 4912 // added qualification. But that wasn't the case, so the reference 4913 // initialization fails. 4914 // 4915 // Note that we only want to check address spaces and cvr-qualifiers here. 4916 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4917 Qualifiers T1Quals = T1.getQualifiers(); 4918 Qualifiers T2Quals = T2.getQualifiers(); 4919 T1Quals.removeObjCGCAttr(); 4920 T1Quals.removeObjCLifetime(); 4921 T2Quals.removeObjCGCAttr(); 4922 T2Quals.removeObjCLifetime(); 4923 // MS compiler ignores __unaligned qualifier for references; do the same. 4924 T1Quals.removeUnaligned(); 4925 T2Quals.removeUnaligned(); 4926 if (!T1Quals.compatiblyIncludes(T2Quals)) 4927 return ICS; 4928 } 4929 4930 // If at least one of the types is a class type, the types are not 4931 // related, and we aren't allowed any user conversions, the 4932 // reference binding fails. This case is important for breaking 4933 // recursion, since TryImplicitConversion below will attempt to 4934 // create a temporary through the use of a copy constructor. 4935 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4936 (T1->isRecordType() || T2->isRecordType())) 4937 return ICS; 4938 4939 // If T1 is reference-related to T2 and the reference is an rvalue 4940 // reference, the initializer expression shall not be an lvalue. 4941 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4942 Init->Classify(S.Context).isLValue()) { 4943 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4944 return ICS; 4945 } 4946 4947 // C++ [over.ics.ref]p2: 4948 // When a parameter of reference type is not bound directly to 4949 // an argument expression, the conversion sequence is the one 4950 // required to convert the argument expression to the 4951 // underlying type of the reference according to 4952 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4953 // to copy-initializing a temporary of the underlying type with 4954 // the argument expression. Any difference in top-level 4955 // cv-qualification is subsumed by the initialization itself 4956 // and does not constitute a conversion. 4957 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4958 AllowedExplicit::None, 4959 /*InOverloadResolution=*/false, 4960 /*CStyle=*/false, 4961 /*AllowObjCWritebackConversion=*/false, 4962 /*AllowObjCConversionOnExplicit=*/false); 4963 4964 // Of course, that's still a reference binding. 4965 if (ICS.isStandard()) { 4966 ICS.Standard.ReferenceBinding = true; 4967 ICS.Standard.IsLvalueReference = !isRValRef; 4968 ICS.Standard.BindsToFunctionLvalue = false; 4969 ICS.Standard.BindsToRvalue = true; 4970 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4971 ICS.Standard.ObjCLifetimeConversionBinding = false; 4972 } else if (ICS.isUserDefined()) { 4973 const ReferenceType *LValRefType = 4974 ICS.UserDefined.ConversionFunction->getReturnType() 4975 ->getAs<LValueReferenceType>(); 4976 4977 // C++ [over.ics.ref]p3: 4978 // Except for an implicit object parameter, for which see 13.3.1, a 4979 // standard conversion sequence cannot be formed if it requires [...] 4980 // binding an rvalue reference to an lvalue other than a function 4981 // lvalue. 4982 // Note that the function case is not possible here. 4983 if (isRValRef && LValRefType) { 4984 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4985 return ICS; 4986 } 4987 4988 ICS.UserDefined.After.ReferenceBinding = true; 4989 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4990 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4991 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4992 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4993 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4994 } 4995 4996 return ICS; 4997 } 4998 4999 static ImplicitConversionSequence 5000 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5001 bool SuppressUserConversions, 5002 bool InOverloadResolution, 5003 bool AllowObjCWritebackConversion, 5004 bool AllowExplicit = false); 5005 5006 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5007 /// initializer list From. 5008 static ImplicitConversionSequence 5009 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5010 bool SuppressUserConversions, 5011 bool InOverloadResolution, 5012 bool AllowObjCWritebackConversion) { 5013 // C++11 [over.ics.list]p1: 5014 // When an argument is an initializer list, it is not an expression and 5015 // special rules apply for converting it to a parameter type. 5016 5017 ImplicitConversionSequence Result; 5018 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5019 5020 // We need a complete type for what follows. With one C++20 exception, 5021 // incomplete types can never be initialized from init lists. 5022 QualType InitTy = ToType; 5023 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5024 if (AT && S.getLangOpts().CPlusPlus20) 5025 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5026 // C++20 allows list initialization of an incomplete array type. 5027 InitTy = IAT->getElementType(); 5028 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5029 return Result; 5030 5031 // Per DR1467: 5032 // If the parameter type is a class X and the initializer list has a single 5033 // element of type cv U, where U is X or a class derived from X, the 5034 // implicit conversion sequence is the one required to convert the element 5035 // to the parameter type. 5036 // 5037 // Otherwise, if the parameter type is a character array [... ] 5038 // and the initializer list has a single element that is an 5039 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5040 // implicit conversion sequence is the identity conversion. 5041 if (From->getNumInits() == 1) { 5042 if (ToType->isRecordType()) { 5043 QualType InitType = From->getInit(0)->getType(); 5044 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5045 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5046 return TryCopyInitialization(S, From->getInit(0), ToType, 5047 SuppressUserConversions, 5048 InOverloadResolution, 5049 AllowObjCWritebackConversion); 5050 } 5051 5052 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5053 InitializedEntity Entity = 5054 InitializedEntity::InitializeParameter(S.Context, ToType, 5055 /*Consumed=*/false); 5056 if (S.CanPerformCopyInitialization(Entity, From)) { 5057 Result.setStandard(); 5058 Result.Standard.setAsIdentityConversion(); 5059 Result.Standard.setFromType(ToType); 5060 Result.Standard.setAllToTypes(ToType); 5061 return Result; 5062 } 5063 } 5064 } 5065 5066 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5067 // C++11 [over.ics.list]p2: 5068 // If the parameter type is std::initializer_list<X> or "array of X" and 5069 // all the elements can be implicitly converted to X, the implicit 5070 // conversion sequence is the worst conversion necessary to convert an 5071 // element of the list to X. 5072 // 5073 // C++14 [over.ics.list]p3: 5074 // Otherwise, if the parameter type is "array of N X", if the initializer 5075 // list has exactly N elements or if it has fewer than N elements and X is 5076 // default-constructible, and if all the elements of the initializer list 5077 // can be implicitly converted to X, the implicit conversion sequence is 5078 // the worst conversion necessary to convert an element of the list to X. 5079 if (AT || S.isStdInitializerList(ToType, &InitTy)) { 5080 unsigned e = From->getNumInits(); 5081 ImplicitConversionSequence DfltElt; 5082 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5083 QualType()); 5084 QualType ContTy = ToType; 5085 bool IsUnbounded = false; 5086 if (AT) { 5087 InitTy = AT->getElementType(); 5088 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5089 if (CT->getSize().ult(e)) { 5090 // Too many inits, fatally bad 5091 Result.setBad(BadConversionSequence::too_many_initializers, From, 5092 ToType); 5093 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5094 return Result; 5095 } 5096 if (CT->getSize().ugt(e)) { 5097 // Need an init from empty {}, is there one? 5098 InitListExpr EmptyList(S.Context, From->getEndLoc(), None, 5099 From->getEndLoc()); 5100 EmptyList.setType(S.Context.VoidTy); 5101 DfltElt = TryListConversion( 5102 S, &EmptyList, InitTy, SuppressUserConversions, 5103 InOverloadResolution, AllowObjCWritebackConversion); 5104 if (DfltElt.isBad()) { 5105 // No {} init, fatally bad 5106 Result.setBad(BadConversionSequence::too_few_initializers, From, 5107 ToType); 5108 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5109 return Result; 5110 } 5111 } 5112 } else { 5113 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5114 IsUnbounded = true; 5115 if (!e) { 5116 // Cannot convert to zero-sized. 5117 Result.setBad(BadConversionSequence::too_few_initializers, From, 5118 ToType); 5119 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5120 return Result; 5121 } 5122 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5123 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5124 ArrayType::Normal, 0); 5125 } 5126 } 5127 5128 Result.setStandard(); 5129 Result.Standard.setAsIdentityConversion(); 5130 Result.Standard.setFromType(InitTy); 5131 Result.Standard.setAllToTypes(InitTy); 5132 for (unsigned i = 0; i < e; ++i) { 5133 Expr *Init = From->getInit(i); 5134 ImplicitConversionSequence ICS = TryCopyInitialization( 5135 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5136 AllowObjCWritebackConversion); 5137 5138 // Keep the worse conversion seen so far. 5139 // FIXME: Sequences are not totally ordered, so 'worse' can be 5140 // ambiguous. CWG has been informed. 5141 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5142 Result) == 5143 ImplicitConversionSequence::Worse) { 5144 Result = ICS; 5145 // Bail as soon as we find something unconvertible. 5146 if (Result.isBad()) { 5147 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5148 return Result; 5149 } 5150 } 5151 } 5152 5153 // If we needed any implicit {} initialization, compare that now. 5154 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5155 // has been informed that this might not be the best thing. 5156 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5157 S, From->getEndLoc(), DfltElt, Result) == 5158 ImplicitConversionSequence::Worse) 5159 Result = DfltElt; 5160 // Record the type being initialized so that we may compare sequences 5161 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5162 return Result; 5163 } 5164 5165 // C++14 [over.ics.list]p4: 5166 // C++11 [over.ics.list]p3: 5167 // Otherwise, if the parameter is a non-aggregate class X and overload 5168 // resolution chooses a single best constructor [...] the implicit 5169 // conversion sequence is a user-defined conversion sequence. If multiple 5170 // constructors are viable but none is better than the others, the 5171 // implicit conversion sequence is a user-defined conversion sequence. 5172 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5173 // This function can deal with initializer lists. 5174 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5175 AllowedExplicit::None, 5176 InOverloadResolution, /*CStyle=*/false, 5177 AllowObjCWritebackConversion, 5178 /*AllowObjCConversionOnExplicit=*/false); 5179 } 5180 5181 // C++14 [over.ics.list]p5: 5182 // C++11 [over.ics.list]p4: 5183 // Otherwise, if the parameter has an aggregate type which can be 5184 // initialized from the initializer list [...] the implicit conversion 5185 // sequence is a user-defined conversion sequence. 5186 if (ToType->isAggregateType()) { 5187 // Type is an aggregate, argument is an init list. At this point it comes 5188 // down to checking whether the initialization works. 5189 // FIXME: Find out whether this parameter is consumed or not. 5190 InitializedEntity Entity = 5191 InitializedEntity::InitializeParameter(S.Context, ToType, 5192 /*Consumed=*/false); 5193 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5194 From)) { 5195 Result.setUserDefined(); 5196 Result.UserDefined.Before.setAsIdentityConversion(); 5197 // Initializer lists don't have a type. 5198 Result.UserDefined.Before.setFromType(QualType()); 5199 Result.UserDefined.Before.setAllToTypes(QualType()); 5200 5201 Result.UserDefined.After.setAsIdentityConversion(); 5202 Result.UserDefined.After.setFromType(ToType); 5203 Result.UserDefined.After.setAllToTypes(ToType); 5204 Result.UserDefined.ConversionFunction = nullptr; 5205 } 5206 return Result; 5207 } 5208 5209 // C++14 [over.ics.list]p6: 5210 // C++11 [over.ics.list]p5: 5211 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5212 if (ToType->isReferenceType()) { 5213 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5214 // mention initializer lists in any way. So we go by what list- 5215 // initialization would do and try to extrapolate from that. 5216 5217 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5218 5219 // If the initializer list has a single element that is reference-related 5220 // to the parameter type, we initialize the reference from that. 5221 if (From->getNumInits() == 1) { 5222 Expr *Init = From->getInit(0); 5223 5224 QualType T2 = Init->getType(); 5225 5226 // If the initializer is the address of an overloaded function, try 5227 // to resolve the overloaded function. If all goes well, T2 is the 5228 // type of the resulting function. 5229 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5230 DeclAccessPair Found; 5231 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5232 Init, ToType, false, Found)) 5233 T2 = Fn->getType(); 5234 } 5235 5236 // Compute some basic properties of the types and the initializer. 5237 Sema::ReferenceCompareResult RefRelationship = 5238 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5239 5240 if (RefRelationship >= Sema::Ref_Related) { 5241 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5242 SuppressUserConversions, 5243 /*AllowExplicit=*/false); 5244 } 5245 } 5246 5247 // Otherwise, we bind the reference to a temporary created from the 5248 // initializer list. 5249 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5250 InOverloadResolution, 5251 AllowObjCWritebackConversion); 5252 if (Result.isFailure()) 5253 return Result; 5254 assert(!Result.isEllipsis() && 5255 "Sub-initialization cannot result in ellipsis conversion."); 5256 5257 // Can we even bind to a temporary? 5258 if (ToType->isRValueReferenceType() || 5259 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5260 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5261 Result.UserDefined.After; 5262 SCS.ReferenceBinding = true; 5263 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5264 SCS.BindsToRvalue = true; 5265 SCS.BindsToFunctionLvalue = false; 5266 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5267 SCS.ObjCLifetimeConversionBinding = false; 5268 } else 5269 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5270 From, ToType); 5271 return Result; 5272 } 5273 5274 // C++14 [over.ics.list]p7: 5275 // C++11 [over.ics.list]p6: 5276 // Otherwise, if the parameter type is not a class: 5277 if (!ToType->isRecordType()) { 5278 // - if the initializer list has one element that is not itself an 5279 // initializer list, the implicit conversion sequence is the one 5280 // required to convert the element to the parameter type. 5281 unsigned NumInits = From->getNumInits(); 5282 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5283 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5284 SuppressUserConversions, 5285 InOverloadResolution, 5286 AllowObjCWritebackConversion); 5287 // - if the initializer list has no elements, the implicit conversion 5288 // sequence is the identity conversion. 5289 else if (NumInits == 0) { 5290 Result.setStandard(); 5291 Result.Standard.setAsIdentityConversion(); 5292 Result.Standard.setFromType(ToType); 5293 Result.Standard.setAllToTypes(ToType); 5294 } 5295 return Result; 5296 } 5297 5298 // C++14 [over.ics.list]p8: 5299 // C++11 [over.ics.list]p7: 5300 // In all cases other than those enumerated above, no conversion is possible 5301 return Result; 5302 } 5303 5304 /// TryCopyInitialization - Try to copy-initialize a value of type 5305 /// ToType from the expression From. Return the implicit conversion 5306 /// sequence required to pass this argument, which may be a bad 5307 /// conversion sequence (meaning that the argument cannot be passed to 5308 /// a parameter of this type). If @p SuppressUserConversions, then we 5309 /// do not permit any user-defined conversion sequences. 5310 static ImplicitConversionSequence 5311 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5312 bool SuppressUserConversions, 5313 bool InOverloadResolution, 5314 bool AllowObjCWritebackConversion, 5315 bool AllowExplicit) { 5316 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5317 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5318 InOverloadResolution,AllowObjCWritebackConversion); 5319 5320 if (ToType->isReferenceType()) 5321 return TryReferenceInit(S, From, ToType, 5322 /*FIXME:*/ From->getBeginLoc(), 5323 SuppressUserConversions, AllowExplicit); 5324 5325 return TryImplicitConversion(S, From, ToType, 5326 SuppressUserConversions, 5327 AllowedExplicit::None, 5328 InOverloadResolution, 5329 /*CStyle=*/false, 5330 AllowObjCWritebackConversion, 5331 /*AllowObjCConversionOnExplicit=*/false); 5332 } 5333 5334 static bool TryCopyInitialization(const CanQualType FromQTy, 5335 const CanQualType ToQTy, 5336 Sema &S, 5337 SourceLocation Loc, 5338 ExprValueKind FromVK) { 5339 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5340 ImplicitConversionSequence ICS = 5341 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5342 5343 return !ICS.isBad(); 5344 } 5345 5346 /// TryObjectArgumentInitialization - Try to initialize the object 5347 /// parameter of the given member function (@c Method) from the 5348 /// expression @p From. 5349 static ImplicitConversionSequence 5350 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5351 Expr::Classification FromClassification, 5352 CXXMethodDecl *Method, 5353 CXXRecordDecl *ActingContext) { 5354 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5355 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5356 // const volatile object. 5357 Qualifiers Quals = Method->getMethodQualifiers(); 5358 if (isa<CXXDestructorDecl>(Method)) { 5359 Quals.addConst(); 5360 Quals.addVolatile(); 5361 } 5362 5363 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5364 5365 // Set up the conversion sequence as a "bad" conversion, to allow us 5366 // to exit early. 5367 ImplicitConversionSequence ICS; 5368 5369 // We need to have an object of class type. 5370 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5371 FromType = PT->getPointeeType(); 5372 5373 // When we had a pointer, it's implicitly dereferenced, so we 5374 // better have an lvalue. 5375 assert(FromClassification.isLValue()); 5376 } 5377 5378 assert(FromType->isRecordType()); 5379 5380 // C++0x [over.match.funcs]p4: 5381 // For non-static member functions, the type of the implicit object 5382 // parameter is 5383 // 5384 // - "lvalue reference to cv X" for functions declared without a 5385 // ref-qualifier or with the & ref-qualifier 5386 // - "rvalue reference to cv X" for functions declared with the && 5387 // ref-qualifier 5388 // 5389 // where X is the class of which the function is a member and cv is the 5390 // cv-qualification on the member function declaration. 5391 // 5392 // However, when finding an implicit conversion sequence for the argument, we 5393 // are not allowed to perform user-defined conversions 5394 // (C++ [over.match.funcs]p5). We perform a simplified version of 5395 // reference binding here, that allows class rvalues to bind to 5396 // non-constant references. 5397 5398 // First check the qualifiers. 5399 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5400 if (ImplicitParamType.getCVRQualifiers() 5401 != FromTypeCanon.getLocalCVRQualifiers() && 5402 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5403 ICS.setBad(BadConversionSequence::bad_qualifiers, 5404 FromType, ImplicitParamType); 5405 return ICS; 5406 } 5407 5408 if (FromTypeCanon.hasAddressSpace()) { 5409 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5410 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5411 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5412 ICS.setBad(BadConversionSequence::bad_qualifiers, 5413 FromType, ImplicitParamType); 5414 return ICS; 5415 } 5416 } 5417 5418 // Check that we have either the same type or a derived type. It 5419 // affects the conversion rank. 5420 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5421 ImplicitConversionKind SecondKind; 5422 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5423 SecondKind = ICK_Identity; 5424 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5425 SecondKind = ICK_Derived_To_Base; 5426 else { 5427 ICS.setBad(BadConversionSequence::unrelated_class, 5428 FromType, ImplicitParamType); 5429 return ICS; 5430 } 5431 5432 // Check the ref-qualifier. 5433 switch (Method->getRefQualifier()) { 5434 case RQ_None: 5435 // Do nothing; we don't care about lvalueness or rvalueness. 5436 break; 5437 5438 case RQ_LValue: 5439 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5440 // non-const lvalue reference cannot bind to an rvalue 5441 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5442 ImplicitParamType); 5443 return ICS; 5444 } 5445 break; 5446 5447 case RQ_RValue: 5448 if (!FromClassification.isRValue()) { 5449 // rvalue reference cannot bind to an lvalue 5450 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5451 ImplicitParamType); 5452 return ICS; 5453 } 5454 break; 5455 } 5456 5457 // Success. Mark this as a reference binding. 5458 ICS.setStandard(); 5459 ICS.Standard.setAsIdentityConversion(); 5460 ICS.Standard.Second = SecondKind; 5461 ICS.Standard.setFromType(FromType); 5462 ICS.Standard.setAllToTypes(ImplicitParamType); 5463 ICS.Standard.ReferenceBinding = true; 5464 ICS.Standard.DirectBinding = true; 5465 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5466 ICS.Standard.BindsToFunctionLvalue = false; 5467 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5468 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5469 = (Method->getRefQualifier() == RQ_None); 5470 return ICS; 5471 } 5472 5473 /// PerformObjectArgumentInitialization - Perform initialization of 5474 /// the implicit object parameter for the given Method with the given 5475 /// expression. 5476 ExprResult 5477 Sema::PerformObjectArgumentInitialization(Expr *From, 5478 NestedNameSpecifier *Qualifier, 5479 NamedDecl *FoundDecl, 5480 CXXMethodDecl *Method) { 5481 QualType FromRecordType, DestType; 5482 QualType ImplicitParamRecordType = 5483 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5484 5485 Expr::Classification FromClassification; 5486 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5487 FromRecordType = PT->getPointeeType(); 5488 DestType = Method->getThisType(); 5489 FromClassification = Expr::Classification::makeSimpleLValue(); 5490 } else { 5491 FromRecordType = From->getType(); 5492 DestType = ImplicitParamRecordType; 5493 FromClassification = From->Classify(Context); 5494 5495 // When performing member access on a prvalue, materialize a temporary. 5496 if (From->isPRValue()) { 5497 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5498 Method->getRefQualifier() != 5499 RefQualifierKind::RQ_RValue); 5500 } 5501 } 5502 5503 // Note that we always use the true parent context when performing 5504 // the actual argument initialization. 5505 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5506 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5507 Method->getParent()); 5508 if (ICS.isBad()) { 5509 switch (ICS.Bad.Kind) { 5510 case BadConversionSequence::bad_qualifiers: { 5511 Qualifiers FromQs = FromRecordType.getQualifiers(); 5512 Qualifiers ToQs = DestType.getQualifiers(); 5513 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5514 if (CVR) { 5515 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5516 << Method->getDeclName() << FromRecordType << (CVR - 1) 5517 << From->getSourceRange(); 5518 Diag(Method->getLocation(), diag::note_previous_decl) 5519 << Method->getDeclName(); 5520 return ExprError(); 5521 } 5522 break; 5523 } 5524 5525 case BadConversionSequence::lvalue_ref_to_rvalue: 5526 case BadConversionSequence::rvalue_ref_to_lvalue: { 5527 bool IsRValueQualified = 5528 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5529 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5530 << Method->getDeclName() << FromClassification.isRValue() 5531 << IsRValueQualified; 5532 Diag(Method->getLocation(), diag::note_previous_decl) 5533 << Method->getDeclName(); 5534 return ExprError(); 5535 } 5536 5537 case BadConversionSequence::no_conversion: 5538 case BadConversionSequence::unrelated_class: 5539 break; 5540 5541 case BadConversionSequence::too_few_initializers: 5542 case BadConversionSequence::too_many_initializers: 5543 llvm_unreachable("Lists are not objects"); 5544 } 5545 5546 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5547 << ImplicitParamRecordType << FromRecordType 5548 << From->getSourceRange(); 5549 } 5550 5551 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5552 ExprResult FromRes = 5553 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5554 if (FromRes.isInvalid()) 5555 return ExprError(); 5556 From = FromRes.get(); 5557 } 5558 5559 if (!Context.hasSameType(From->getType(), DestType)) { 5560 CastKind CK; 5561 QualType PteeTy = DestType->getPointeeType(); 5562 LangAS DestAS = 5563 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5564 if (FromRecordType.getAddressSpace() != DestAS) 5565 CK = CK_AddressSpaceConversion; 5566 else 5567 CK = CK_NoOp; 5568 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5569 } 5570 return From; 5571 } 5572 5573 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5574 /// expression From to bool (C++0x [conv]p3). 5575 static ImplicitConversionSequence 5576 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5577 // C++ [dcl.init]/17.8: 5578 // - Otherwise, if the initialization is direct-initialization, the source 5579 // type is std::nullptr_t, and the destination type is bool, the initial 5580 // value of the object being initialized is false. 5581 if (From->getType()->isNullPtrType()) 5582 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5583 S.Context.BoolTy, 5584 From->isGLValue()); 5585 5586 // All other direct-initialization of bool is equivalent to an implicit 5587 // conversion to bool in which explicit conversions are permitted. 5588 return TryImplicitConversion(S, From, S.Context.BoolTy, 5589 /*SuppressUserConversions=*/false, 5590 AllowedExplicit::Conversions, 5591 /*InOverloadResolution=*/false, 5592 /*CStyle=*/false, 5593 /*AllowObjCWritebackConversion=*/false, 5594 /*AllowObjCConversionOnExplicit=*/false); 5595 } 5596 5597 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5598 /// of the expression From to bool (C++0x [conv]p3). 5599 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5600 if (checkPlaceholderForOverload(*this, From)) 5601 return ExprError(); 5602 5603 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5604 if (!ICS.isBad()) 5605 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5606 5607 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5608 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5609 << From->getType() << From->getSourceRange(); 5610 return ExprError(); 5611 } 5612 5613 /// Check that the specified conversion is permitted in a converted constant 5614 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5615 /// is acceptable. 5616 static bool CheckConvertedConstantConversions(Sema &S, 5617 StandardConversionSequence &SCS) { 5618 // Since we know that the target type is an integral or unscoped enumeration 5619 // type, most conversion kinds are impossible. All possible First and Third 5620 // conversions are fine. 5621 switch (SCS.Second) { 5622 case ICK_Identity: 5623 case ICK_Integral_Promotion: 5624 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5625 case ICK_Zero_Queue_Conversion: 5626 return true; 5627 5628 case ICK_Boolean_Conversion: 5629 // Conversion from an integral or unscoped enumeration type to bool is 5630 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5631 // conversion, so we allow it in a converted constant expression. 5632 // 5633 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5634 // a lot of popular code. We should at least add a warning for this 5635 // (non-conforming) extension. 5636 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5637 SCS.getToType(2)->isBooleanType(); 5638 5639 case ICK_Pointer_Conversion: 5640 case ICK_Pointer_Member: 5641 // C++1z: null pointer conversions and null member pointer conversions are 5642 // only permitted if the source type is std::nullptr_t. 5643 return SCS.getFromType()->isNullPtrType(); 5644 5645 case ICK_Floating_Promotion: 5646 case ICK_Complex_Promotion: 5647 case ICK_Floating_Conversion: 5648 case ICK_Complex_Conversion: 5649 case ICK_Floating_Integral: 5650 case ICK_Compatible_Conversion: 5651 case ICK_Derived_To_Base: 5652 case ICK_Vector_Conversion: 5653 case ICK_SVE_Vector_Conversion: 5654 case ICK_Vector_Splat: 5655 case ICK_Complex_Real: 5656 case ICK_Block_Pointer_Conversion: 5657 case ICK_TransparentUnionConversion: 5658 case ICK_Writeback_Conversion: 5659 case ICK_Zero_Event_Conversion: 5660 case ICK_C_Only_Conversion: 5661 case ICK_Incompatible_Pointer_Conversion: 5662 return false; 5663 5664 case ICK_Lvalue_To_Rvalue: 5665 case ICK_Array_To_Pointer: 5666 case ICK_Function_To_Pointer: 5667 llvm_unreachable("found a first conversion kind in Second"); 5668 5669 case ICK_Function_Conversion: 5670 case ICK_Qualification: 5671 llvm_unreachable("found a third conversion kind in Second"); 5672 5673 case ICK_Num_Conversion_Kinds: 5674 break; 5675 } 5676 5677 llvm_unreachable("unknown conversion kind"); 5678 } 5679 5680 /// CheckConvertedConstantExpression - Check that the expression From is a 5681 /// converted constant expression of type T, perform the conversion and produce 5682 /// the converted expression, per C++11 [expr.const]p3. 5683 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5684 QualType T, APValue &Value, 5685 Sema::CCEKind CCE, 5686 bool RequireInt, 5687 NamedDecl *Dest) { 5688 assert(S.getLangOpts().CPlusPlus11 && 5689 "converted constant expression outside C++11"); 5690 5691 if (checkPlaceholderForOverload(S, From)) 5692 return ExprError(); 5693 5694 // C++1z [expr.const]p3: 5695 // A converted constant expression of type T is an expression, 5696 // implicitly converted to type T, where the converted 5697 // expression is a constant expression and the implicit conversion 5698 // sequence contains only [... list of conversions ...]. 5699 ImplicitConversionSequence ICS = 5700 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 5701 ? TryContextuallyConvertToBool(S, From) 5702 : TryCopyInitialization(S, From, T, 5703 /*SuppressUserConversions=*/false, 5704 /*InOverloadResolution=*/false, 5705 /*AllowObjCWritebackConversion=*/false, 5706 /*AllowExplicit=*/false); 5707 StandardConversionSequence *SCS = nullptr; 5708 switch (ICS.getKind()) { 5709 case ImplicitConversionSequence::StandardConversion: 5710 SCS = &ICS.Standard; 5711 break; 5712 case ImplicitConversionSequence::UserDefinedConversion: 5713 if (T->isRecordType()) 5714 SCS = &ICS.UserDefined.Before; 5715 else 5716 SCS = &ICS.UserDefined.After; 5717 break; 5718 case ImplicitConversionSequence::AmbiguousConversion: 5719 case ImplicitConversionSequence::BadConversion: 5720 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5721 return S.Diag(From->getBeginLoc(), 5722 diag::err_typecheck_converted_constant_expression) 5723 << From->getType() << From->getSourceRange() << T; 5724 return ExprError(); 5725 5726 case ImplicitConversionSequence::EllipsisConversion: 5727 llvm_unreachable("ellipsis conversion in converted constant expression"); 5728 } 5729 5730 // Check that we would only use permitted conversions. 5731 if (!CheckConvertedConstantConversions(S, *SCS)) { 5732 return S.Diag(From->getBeginLoc(), 5733 diag::err_typecheck_converted_constant_expression_disallowed) 5734 << From->getType() << From->getSourceRange() << T; 5735 } 5736 // [...] and where the reference binding (if any) binds directly. 5737 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5738 return S.Diag(From->getBeginLoc(), 5739 diag::err_typecheck_converted_constant_expression_indirect) 5740 << From->getType() << From->getSourceRange() << T; 5741 } 5742 5743 // Usually we can simply apply the ImplicitConversionSequence we formed 5744 // earlier, but that's not guaranteed to work when initializing an object of 5745 // class type. 5746 ExprResult Result; 5747 if (T->isRecordType()) { 5748 assert(CCE == Sema::CCEK_TemplateArg && 5749 "unexpected class type converted constant expr"); 5750 Result = S.PerformCopyInitialization( 5751 InitializedEntity::InitializeTemplateParameter( 5752 T, cast<NonTypeTemplateParmDecl>(Dest)), 5753 SourceLocation(), From); 5754 } else { 5755 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5756 } 5757 if (Result.isInvalid()) 5758 return Result; 5759 5760 // C++2a [intro.execution]p5: 5761 // A full-expression is [...] a constant-expression [...] 5762 Result = 5763 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5764 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5765 if (Result.isInvalid()) 5766 return Result; 5767 5768 // Check for a narrowing implicit conversion. 5769 bool ReturnPreNarrowingValue = false; 5770 APValue PreNarrowingValue; 5771 QualType PreNarrowingType; 5772 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5773 PreNarrowingType)) { 5774 case NK_Dependent_Narrowing: 5775 // Implicit conversion to a narrower type, but the expression is 5776 // value-dependent so we can't tell whether it's actually narrowing. 5777 case NK_Variable_Narrowing: 5778 // Implicit conversion to a narrower type, and the value is not a constant 5779 // expression. We'll diagnose this in a moment. 5780 case NK_Not_Narrowing: 5781 break; 5782 5783 case NK_Constant_Narrowing: 5784 if (CCE == Sema::CCEK_ArrayBound && 5785 PreNarrowingType->isIntegralOrEnumerationType() && 5786 PreNarrowingValue.isInt()) { 5787 // Don't diagnose array bound narrowing here; we produce more precise 5788 // errors by allowing the un-narrowed value through. 5789 ReturnPreNarrowingValue = true; 5790 break; 5791 } 5792 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5793 << CCE << /*Constant*/ 1 5794 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5795 break; 5796 5797 case NK_Type_Narrowing: 5798 // FIXME: It would be better to diagnose that the expression is not a 5799 // constant expression. 5800 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5801 << CCE << /*Constant*/ 0 << From->getType() << T; 5802 break; 5803 } 5804 5805 if (Result.get()->isValueDependent()) { 5806 Value = APValue(); 5807 return Result; 5808 } 5809 5810 // Check the expression is a constant expression. 5811 SmallVector<PartialDiagnosticAt, 8> Notes; 5812 Expr::EvalResult Eval; 5813 Eval.Diag = &Notes; 5814 5815 ConstantExprKind Kind; 5816 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5817 Kind = ConstantExprKind::ClassTemplateArgument; 5818 else if (CCE == Sema::CCEK_TemplateArg) 5819 Kind = ConstantExprKind::NonClassTemplateArgument; 5820 else 5821 Kind = ConstantExprKind::Normal; 5822 5823 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5824 (RequireInt && !Eval.Val.isInt())) { 5825 // The expression can't be folded, so we can't keep it at this position in 5826 // the AST. 5827 Result = ExprError(); 5828 } else { 5829 Value = Eval.Val; 5830 5831 if (Notes.empty()) { 5832 // It's a constant expression. 5833 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5834 if (ReturnPreNarrowingValue) 5835 Value = std::move(PreNarrowingValue); 5836 return E; 5837 } 5838 } 5839 5840 // It's not a constant expression. Produce an appropriate diagnostic. 5841 if (Notes.size() == 1 && 5842 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5843 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5844 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5845 diag::note_constexpr_invalid_template_arg) { 5846 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5847 for (unsigned I = 0; I < Notes.size(); ++I) 5848 S.Diag(Notes[I].first, Notes[I].second); 5849 } else { 5850 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5851 << CCE << From->getSourceRange(); 5852 for (unsigned I = 0; I < Notes.size(); ++I) 5853 S.Diag(Notes[I].first, Notes[I].second); 5854 } 5855 return ExprError(); 5856 } 5857 5858 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5859 APValue &Value, CCEKind CCE, 5860 NamedDecl *Dest) { 5861 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5862 Dest); 5863 } 5864 5865 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5866 llvm::APSInt &Value, 5867 CCEKind CCE) { 5868 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5869 5870 APValue V; 5871 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5872 /*Dest=*/nullptr); 5873 if (!R.isInvalid() && !R.get()->isValueDependent()) 5874 Value = V.getInt(); 5875 return R; 5876 } 5877 5878 5879 /// dropPointerConversions - If the given standard conversion sequence 5880 /// involves any pointer conversions, remove them. This may change 5881 /// the result type of the conversion sequence. 5882 static void dropPointerConversion(StandardConversionSequence &SCS) { 5883 if (SCS.Second == ICK_Pointer_Conversion) { 5884 SCS.Second = ICK_Identity; 5885 SCS.Third = ICK_Identity; 5886 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5887 } 5888 } 5889 5890 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5891 /// convert the expression From to an Objective-C pointer type. 5892 static ImplicitConversionSequence 5893 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5894 // Do an implicit conversion to 'id'. 5895 QualType Ty = S.Context.getObjCIdType(); 5896 ImplicitConversionSequence ICS 5897 = TryImplicitConversion(S, From, Ty, 5898 // FIXME: Are these flags correct? 5899 /*SuppressUserConversions=*/false, 5900 AllowedExplicit::Conversions, 5901 /*InOverloadResolution=*/false, 5902 /*CStyle=*/false, 5903 /*AllowObjCWritebackConversion=*/false, 5904 /*AllowObjCConversionOnExplicit=*/true); 5905 5906 // Strip off any final conversions to 'id'. 5907 switch (ICS.getKind()) { 5908 case ImplicitConversionSequence::BadConversion: 5909 case ImplicitConversionSequence::AmbiguousConversion: 5910 case ImplicitConversionSequence::EllipsisConversion: 5911 break; 5912 5913 case ImplicitConversionSequence::UserDefinedConversion: 5914 dropPointerConversion(ICS.UserDefined.After); 5915 break; 5916 5917 case ImplicitConversionSequence::StandardConversion: 5918 dropPointerConversion(ICS.Standard); 5919 break; 5920 } 5921 5922 return ICS; 5923 } 5924 5925 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5926 /// conversion of the expression From to an Objective-C pointer type. 5927 /// Returns a valid but null ExprResult if no conversion sequence exists. 5928 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5929 if (checkPlaceholderForOverload(*this, From)) 5930 return ExprError(); 5931 5932 QualType Ty = Context.getObjCIdType(); 5933 ImplicitConversionSequence ICS = 5934 TryContextuallyConvertToObjCPointer(*this, From); 5935 if (!ICS.isBad()) 5936 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5937 return ExprResult(); 5938 } 5939 5940 /// Determine whether the provided type is an integral type, or an enumeration 5941 /// type of a permitted flavor. 5942 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5943 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5944 : T->isIntegralOrUnscopedEnumerationType(); 5945 } 5946 5947 static ExprResult 5948 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5949 Sema::ContextualImplicitConverter &Converter, 5950 QualType T, UnresolvedSetImpl &ViableConversions) { 5951 5952 if (Converter.Suppress) 5953 return ExprError(); 5954 5955 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5956 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5957 CXXConversionDecl *Conv = 5958 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5959 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5960 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5961 } 5962 return From; 5963 } 5964 5965 static bool 5966 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5967 Sema::ContextualImplicitConverter &Converter, 5968 QualType T, bool HadMultipleCandidates, 5969 UnresolvedSetImpl &ExplicitConversions) { 5970 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5971 DeclAccessPair Found = ExplicitConversions[0]; 5972 CXXConversionDecl *Conversion = 5973 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5974 5975 // The user probably meant to invoke the given explicit 5976 // conversion; use it. 5977 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5978 std::string TypeStr; 5979 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5980 5981 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5982 << FixItHint::CreateInsertion(From->getBeginLoc(), 5983 "static_cast<" + TypeStr + ">(") 5984 << FixItHint::CreateInsertion( 5985 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5986 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5987 5988 // If we aren't in a SFINAE context, build a call to the 5989 // explicit conversion function. 5990 if (SemaRef.isSFINAEContext()) 5991 return true; 5992 5993 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5994 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5995 HadMultipleCandidates); 5996 if (Result.isInvalid()) 5997 return true; 5998 // Record usage of conversion in an implicit cast. 5999 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6000 CK_UserDefinedConversion, Result.get(), 6001 nullptr, Result.get()->getValueKind(), 6002 SemaRef.CurFPFeatureOverrides()); 6003 } 6004 return false; 6005 } 6006 6007 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6008 Sema::ContextualImplicitConverter &Converter, 6009 QualType T, bool HadMultipleCandidates, 6010 DeclAccessPair &Found) { 6011 CXXConversionDecl *Conversion = 6012 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6013 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6014 6015 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6016 if (!Converter.SuppressConversion) { 6017 if (SemaRef.isSFINAEContext()) 6018 return true; 6019 6020 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6021 << From->getSourceRange(); 6022 } 6023 6024 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6025 HadMultipleCandidates); 6026 if (Result.isInvalid()) 6027 return true; 6028 // Record usage of conversion in an implicit cast. 6029 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6030 CK_UserDefinedConversion, Result.get(), 6031 nullptr, Result.get()->getValueKind(), 6032 SemaRef.CurFPFeatureOverrides()); 6033 return false; 6034 } 6035 6036 static ExprResult finishContextualImplicitConversion( 6037 Sema &SemaRef, SourceLocation Loc, Expr *From, 6038 Sema::ContextualImplicitConverter &Converter) { 6039 if (!Converter.match(From->getType()) && !Converter.Suppress) 6040 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6041 << From->getSourceRange(); 6042 6043 return SemaRef.DefaultLvalueConversion(From); 6044 } 6045 6046 static void 6047 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6048 UnresolvedSetImpl &ViableConversions, 6049 OverloadCandidateSet &CandidateSet) { 6050 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6051 DeclAccessPair FoundDecl = ViableConversions[I]; 6052 NamedDecl *D = FoundDecl.getDecl(); 6053 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6054 if (isa<UsingShadowDecl>(D)) 6055 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6056 6057 CXXConversionDecl *Conv; 6058 FunctionTemplateDecl *ConvTemplate; 6059 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6060 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6061 else 6062 Conv = cast<CXXConversionDecl>(D); 6063 6064 if (ConvTemplate) 6065 SemaRef.AddTemplateConversionCandidate( 6066 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6067 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6068 else 6069 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6070 ToType, CandidateSet, 6071 /*AllowObjCConversionOnExplicit=*/false, 6072 /*AllowExplicit*/ true); 6073 } 6074 } 6075 6076 /// Attempt to convert the given expression to a type which is accepted 6077 /// by the given converter. 6078 /// 6079 /// This routine will attempt to convert an expression of class type to a 6080 /// type accepted by the specified converter. In C++11 and before, the class 6081 /// must have a single non-explicit conversion function converting to a matching 6082 /// type. In C++1y, there can be multiple such conversion functions, but only 6083 /// one target type. 6084 /// 6085 /// \param Loc The source location of the construct that requires the 6086 /// conversion. 6087 /// 6088 /// \param From The expression we're converting from. 6089 /// 6090 /// \param Converter Used to control and diagnose the conversion process. 6091 /// 6092 /// \returns The expression, converted to an integral or enumeration type if 6093 /// successful. 6094 ExprResult Sema::PerformContextualImplicitConversion( 6095 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6096 // We can't perform any more checking for type-dependent expressions. 6097 if (From->isTypeDependent()) 6098 return From; 6099 6100 // Process placeholders immediately. 6101 if (From->hasPlaceholderType()) { 6102 ExprResult result = CheckPlaceholderExpr(From); 6103 if (result.isInvalid()) 6104 return result; 6105 From = result.get(); 6106 } 6107 6108 // If the expression already has a matching type, we're golden. 6109 QualType T = From->getType(); 6110 if (Converter.match(T)) 6111 return DefaultLvalueConversion(From); 6112 6113 // FIXME: Check for missing '()' if T is a function type? 6114 6115 // We can only perform contextual implicit conversions on objects of class 6116 // type. 6117 const RecordType *RecordTy = T->getAs<RecordType>(); 6118 if (!RecordTy || !getLangOpts().CPlusPlus) { 6119 if (!Converter.Suppress) 6120 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6121 return From; 6122 } 6123 6124 // We must have a complete class type. 6125 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6126 ContextualImplicitConverter &Converter; 6127 Expr *From; 6128 6129 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6130 : Converter(Converter), From(From) {} 6131 6132 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6133 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6134 } 6135 } IncompleteDiagnoser(Converter, From); 6136 6137 if (Converter.Suppress ? !isCompleteType(Loc, T) 6138 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6139 return From; 6140 6141 // Look for a conversion to an integral or enumeration type. 6142 UnresolvedSet<4> 6143 ViableConversions; // These are *potentially* viable in C++1y. 6144 UnresolvedSet<4> ExplicitConversions; 6145 const auto &Conversions = 6146 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6147 6148 bool HadMultipleCandidates = 6149 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6150 6151 // To check that there is only one target type, in C++1y: 6152 QualType ToType; 6153 bool HasUniqueTargetType = true; 6154 6155 // Collect explicit or viable (potentially in C++1y) conversions. 6156 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6157 NamedDecl *D = (*I)->getUnderlyingDecl(); 6158 CXXConversionDecl *Conversion; 6159 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6160 if (ConvTemplate) { 6161 if (getLangOpts().CPlusPlus14) 6162 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6163 else 6164 continue; // C++11 does not consider conversion operator templates(?). 6165 } else 6166 Conversion = cast<CXXConversionDecl>(D); 6167 6168 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6169 "Conversion operator templates are considered potentially " 6170 "viable in C++1y"); 6171 6172 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6173 if (Converter.match(CurToType) || ConvTemplate) { 6174 6175 if (Conversion->isExplicit()) { 6176 // FIXME: For C++1y, do we need this restriction? 6177 // cf. diagnoseNoViableConversion() 6178 if (!ConvTemplate) 6179 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6180 } else { 6181 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6182 if (ToType.isNull()) 6183 ToType = CurToType.getUnqualifiedType(); 6184 else if (HasUniqueTargetType && 6185 (CurToType.getUnqualifiedType() != ToType)) 6186 HasUniqueTargetType = false; 6187 } 6188 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6189 } 6190 } 6191 } 6192 6193 if (getLangOpts().CPlusPlus14) { 6194 // C++1y [conv]p6: 6195 // ... An expression e of class type E appearing in such a context 6196 // is said to be contextually implicitly converted to a specified 6197 // type T and is well-formed if and only if e can be implicitly 6198 // converted to a type T that is determined as follows: E is searched 6199 // for conversion functions whose return type is cv T or reference to 6200 // cv T such that T is allowed by the context. There shall be 6201 // exactly one such T. 6202 6203 // If no unique T is found: 6204 if (ToType.isNull()) { 6205 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6206 HadMultipleCandidates, 6207 ExplicitConversions)) 6208 return ExprError(); 6209 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6210 } 6211 6212 // If more than one unique Ts are found: 6213 if (!HasUniqueTargetType) 6214 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6215 ViableConversions); 6216 6217 // If one unique T is found: 6218 // First, build a candidate set from the previously recorded 6219 // potentially viable conversions. 6220 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6221 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6222 CandidateSet); 6223 6224 // Then, perform overload resolution over the candidate set. 6225 OverloadCandidateSet::iterator Best; 6226 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6227 case OR_Success: { 6228 // Apply this conversion. 6229 DeclAccessPair Found = 6230 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6231 if (recordConversion(*this, Loc, From, Converter, T, 6232 HadMultipleCandidates, Found)) 6233 return ExprError(); 6234 break; 6235 } 6236 case OR_Ambiguous: 6237 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6238 ViableConversions); 6239 case OR_No_Viable_Function: 6240 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6241 HadMultipleCandidates, 6242 ExplicitConversions)) 6243 return ExprError(); 6244 LLVM_FALLTHROUGH; 6245 case OR_Deleted: 6246 // We'll complain below about a non-integral condition type. 6247 break; 6248 } 6249 } else { 6250 switch (ViableConversions.size()) { 6251 case 0: { 6252 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6253 HadMultipleCandidates, 6254 ExplicitConversions)) 6255 return ExprError(); 6256 6257 // We'll complain below about a non-integral condition type. 6258 break; 6259 } 6260 case 1: { 6261 // Apply this conversion. 6262 DeclAccessPair Found = ViableConversions[0]; 6263 if (recordConversion(*this, Loc, From, Converter, T, 6264 HadMultipleCandidates, Found)) 6265 return ExprError(); 6266 break; 6267 } 6268 default: 6269 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6270 ViableConversions); 6271 } 6272 } 6273 6274 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6275 } 6276 6277 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6278 /// an acceptable non-member overloaded operator for a call whose 6279 /// arguments have types T1 (and, if non-empty, T2). This routine 6280 /// implements the check in C++ [over.match.oper]p3b2 concerning 6281 /// enumeration types. 6282 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6283 FunctionDecl *Fn, 6284 ArrayRef<Expr *> Args) { 6285 QualType T1 = Args[0]->getType(); 6286 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6287 6288 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6289 return true; 6290 6291 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6292 return true; 6293 6294 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6295 if (Proto->getNumParams() < 1) 6296 return false; 6297 6298 if (T1->isEnumeralType()) { 6299 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6300 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6301 return true; 6302 } 6303 6304 if (Proto->getNumParams() < 2) 6305 return false; 6306 6307 if (!T2.isNull() && T2->isEnumeralType()) { 6308 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6309 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6310 return true; 6311 } 6312 6313 return false; 6314 } 6315 6316 /// AddOverloadCandidate - Adds the given function to the set of 6317 /// candidate functions, using the given function call arguments. If 6318 /// @p SuppressUserConversions, then don't allow user-defined 6319 /// conversions via constructors or conversion operators. 6320 /// 6321 /// \param PartialOverloading true if we are performing "partial" overloading 6322 /// based on an incomplete set of function arguments. This feature is used by 6323 /// code completion. 6324 void Sema::AddOverloadCandidate( 6325 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6326 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6327 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6328 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6329 OverloadCandidateParamOrder PO) { 6330 const FunctionProtoType *Proto 6331 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6332 assert(Proto && "Functions without a prototype cannot be overloaded"); 6333 assert(!Function->getDescribedFunctionTemplate() && 6334 "Use AddTemplateOverloadCandidate for function templates"); 6335 6336 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6337 if (!isa<CXXConstructorDecl>(Method)) { 6338 // If we get here, it's because we're calling a member function 6339 // that is named without a member access expression (e.g., 6340 // "this->f") that was either written explicitly or created 6341 // implicitly. This can happen with a qualified call to a member 6342 // function, e.g., X::f(). We use an empty type for the implied 6343 // object argument (C++ [over.call.func]p3), and the acting context 6344 // is irrelevant. 6345 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6346 Expr::Classification::makeSimpleLValue(), Args, 6347 CandidateSet, SuppressUserConversions, 6348 PartialOverloading, EarlyConversions, PO); 6349 return; 6350 } 6351 // We treat a constructor like a non-member function, since its object 6352 // argument doesn't participate in overload resolution. 6353 } 6354 6355 if (!CandidateSet.isNewCandidate(Function, PO)) 6356 return; 6357 6358 // C++11 [class.copy]p11: [DR1402] 6359 // A defaulted move constructor that is defined as deleted is ignored by 6360 // overload resolution. 6361 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6362 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6363 Constructor->isMoveConstructor()) 6364 return; 6365 6366 // Overload resolution is always an unevaluated context. 6367 EnterExpressionEvaluationContext Unevaluated( 6368 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6369 6370 // C++ [over.match.oper]p3: 6371 // if no operand has a class type, only those non-member functions in the 6372 // lookup set that have a first parameter of type T1 or "reference to 6373 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6374 // is a right operand) a second parameter of type T2 or "reference to 6375 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6376 // candidate functions. 6377 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6378 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6379 return; 6380 6381 // Add this candidate 6382 OverloadCandidate &Candidate = 6383 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6384 Candidate.FoundDecl = FoundDecl; 6385 Candidate.Function = Function; 6386 Candidate.Viable = true; 6387 Candidate.RewriteKind = 6388 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6389 Candidate.IsSurrogate = false; 6390 Candidate.IsADLCandidate = IsADLCandidate; 6391 Candidate.IgnoreObjectArgument = false; 6392 Candidate.ExplicitCallArguments = Args.size(); 6393 6394 // Explicit functions are not actually candidates at all if we're not 6395 // allowing them in this context, but keep them around so we can point 6396 // to them in diagnostics. 6397 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6398 Candidate.Viable = false; 6399 Candidate.FailureKind = ovl_fail_explicit; 6400 return; 6401 } 6402 6403 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6404 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6405 Candidate.Viable = false; 6406 Candidate.FailureKind = ovl_non_default_multiversion_function; 6407 return; 6408 } 6409 6410 if (Constructor) { 6411 // C++ [class.copy]p3: 6412 // A member function template is never instantiated to perform the copy 6413 // of a class object to an object of its class type. 6414 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6415 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6416 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6417 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6418 ClassType))) { 6419 Candidate.Viable = false; 6420 Candidate.FailureKind = ovl_fail_illegal_constructor; 6421 return; 6422 } 6423 6424 // C++ [over.match.funcs]p8: (proposed DR resolution) 6425 // A constructor inherited from class type C that has a first parameter 6426 // of type "reference to P" (including such a constructor instantiated 6427 // from a template) is excluded from the set of candidate functions when 6428 // constructing an object of type cv D if the argument list has exactly 6429 // one argument and D is reference-related to P and P is reference-related 6430 // to C. 6431 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6432 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6433 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6434 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6435 QualType C = Context.getRecordType(Constructor->getParent()); 6436 QualType D = Context.getRecordType(Shadow->getParent()); 6437 SourceLocation Loc = Args.front()->getExprLoc(); 6438 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6439 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6440 Candidate.Viable = false; 6441 Candidate.FailureKind = ovl_fail_inhctor_slice; 6442 return; 6443 } 6444 } 6445 6446 // Check that the constructor is capable of constructing an object in the 6447 // destination address space. 6448 if (!Qualifiers::isAddressSpaceSupersetOf( 6449 Constructor->getMethodQualifiers().getAddressSpace(), 6450 CandidateSet.getDestAS())) { 6451 Candidate.Viable = false; 6452 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6453 } 6454 } 6455 6456 unsigned NumParams = Proto->getNumParams(); 6457 6458 // (C++ 13.3.2p2): A candidate function having fewer than m 6459 // parameters is viable only if it has an ellipsis in its parameter 6460 // list (8.3.5). 6461 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6462 !Proto->isVariadic() && 6463 shouldEnforceArgLimit(PartialOverloading, Function)) { 6464 Candidate.Viable = false; 6465 Candidate.FailureKind = ovl_fail_too_many_arguments; 6466 return; 6467 } 6468 6469 // (C++ 13.3.2p2): A candidate function having more than m parameters 6470 // is viable only if the (m+1)st parameter has a default argument 6471 // (8.3.6). For the purposes of overload resolution, the 6472 // parameter list is truncated on the right, so that there are 6473 // exactly m parameters. 6474 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6475 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6476 // Not enough arguments. 6477 Candidate.Viable = false; 6478 Candidate.FailureKind = ovl_fail_too_few_arguments; 6479 return; 6480 } 6481 6482 // (CUDA B.1): Check for invalid calls between targets. 6483 if (getLangOpts().CUDA) 6484 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) 6485 // Skip the check for callers that are implicit members, because in this 6486 // case we may not yet know what the member's target is; the target is 6487 // inferred for the member automatically, based on the bases and fields of 6488 // the class. 6489 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6490 Candidate.Viable = false; 6491 Candidate.FailureKind = ovl_fail_bad_target; 6492 return; 6493 } 6494 6495 if (Function->getTrailingRequiresClause()) { 6496 ConstraintSatisfaction Satisfaction; 6497 if (CheckFunctionConstraints(Function, Satisfaction) || 6498 !Satisfaction.IsSatisfied) { 6499 Candidate.Viable = false; 6500 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6501 return; 6502 } 6503 } 6504 6505 // Determine the implicit conversion sequences for each of the 6506 // arguments. 6507 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6508 unsigned ConvIdx = 6509 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6510 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6511 // We already formed a conversion sequence for this parameter during 6512 // template argument deduction. 6513 } else if (ArgIdx < NumParams) { 6514 // (C++ 13.3.2p3): for F to be a viable function, there shall 6515 // exist for each argument an implicit conversion sequence 6516 // (13.3.3.1) that converts that argument to the corresponding 6517 // parameter of F. 6518 QualType ParamType = Proto->getParamType(ArgIdx); 6519 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6520 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6521 /*InOverloadResolution=*/true, 6522 /*AllowObjCWritebackConversion=*/ 6523 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6524 if (Candidate.Conversions[ConvIdx].isBad()) { 6525 Candidate.Viable = false; 6526 Candidate.FailureKind = ovl_fail_bad_conversion; 6527 return; 6528 } 6529 } else { 6530 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6531 // argument for which there is no corresponding parameter is 6532 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6533 Candidate.Conversions[ConvIdx].setEllipsis(); 6534 } 6535 } 6536 6537 if (EnableIfAttr *FailedAttr = 6538 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6539 Candidate.Viable = false; 6540 Candidate.FailureKind = ovl_fail_enable_if; 6541 Candidate.DeductionFailure.Data = FailedAttr; 6542 return; 6543 } 6544 } 6545 6546 ObjCMethodDecl * 6547 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6548 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6549 if (Methods.size() <= 1) 6550 return nullptr; 6551 6552 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6553 bool Match = true; 6554 ObjCMethodDecl *Method = Methods[b]; 6555 unsigned NumNamedArgs = Sel.getNumArgs(); 6556 // Method might have more arguments than selector indicates. This is due 6557 // to addition of c-style arguments in method. 6558 if (Method->param_size() > NumNamedArgs) 6559 NumNamedArgs = Method->param_size(); 6560 if (Args.size() < NumNamedArgs) 6561 continue; 6562 6563 for (unsigned i = 0; i < NumNamedArgs; i++) { 6564 // We can't do any type-checking on a type-dependent argument. 6565 if (Args[i]->isTypeDependent()) { 6566 Match = false; 6567 break; 6568 } 6569 6570 ParmVarDecl *param = Method->parameters()[i]; 6571 Expr *argExpr = Args[i]; 6572 assert(argExpr && "SelectBestMethod(): missing expression"); 6573 6574 // Strip the unbridged-cast placeholder expression off unless it's 6575 // a consumed argument. 6576 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6577 !param->hasAttr<CFConsumedAttr>()) 6578 argExpr = stripARCUnbridgedCast(argExpr); 6579 6580 // If the parameter is __unknown_anytype, move on to the next method. 6581 if (param->getType() == Context.UnknownAnyTy) { 6582 Match = false; 6583 break; 6584 } 6585 6586 ImplicitConversionSequence ConversionState 6587 = TryCopyInitialization(*this, argExpr, param->getType(), 6588 /*SuppressUserConversions*/false, 6589 /*InOverloadResolution=*/true, 6590 /*AllowObjCWritebackConversion=*/ 6591 getLangOpts().ObjCAutoRefCount, 6592 /*AllowExplicit*/false); 6593 // This function looks for a reasonably-exact match, so we consider 6594 // incompatible pointer conversions to be a failure here. 6595 if (ConversionState.isBad() || 6596 (ConversionState.isStandard() && 6597 ConversionState.Standard.Second == 6598 ICK_Incompatible_Pointer_Conversion)) { 6599 Match = false; 6600 break; 6601 } 6602 } 6603 // Promote additional arguments to variadic methods. 6604 if (Match && Method->isVariadic()) { 6605 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6606 if (Args[i]->isTypeDependent()) { 6607 Match = false; 6608 break; 6609 } 6610 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6611 nullptr); 6612 if (Arg.isInvalid()) { 6613 Match = false; 6614 break; 6615 } 6616 } 6617 } else { 6618 // Check for extra arguments to non-variadic methods. 6619 if (Args.size() != NumNamedArgs) 6620 Match = false; 6621 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6622 // Special case when selectors have no argument. In this case, select 6623 // one with the most general result type of 'id'. 6624 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6625 QualType ReturnT = Methods[b]->getReturnType(); 6626 if (ReturnT->isObjCIdType()) 6627 return Methods[b]; 6628 } 6629 } 6630 } 6631 6632 if (Match) 6633 return Method; 6634 } 6635 return nullptr; 6636 } 6637 6638 static bool convertArgsForAvailabilityChecks( 6639 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6640 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6641 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6642 if (ThisArg) { 6643 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6644 assert(!isa<CXXConstructorDecl>(Method) && 6645 "Shouldn't have `this` for ctors!"); 6646 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6647 ExprResult R = S.PerformObjectArgumentInitialization( 6648 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6649 if (R.isInvalid()) 6650 return false; 6651 ConvertedThis = R.get(); 6652 } else { 6653 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6654 (void)MD; 6655 assert((MissingImplicitThis || MD->isStatic() || 6656 isa<CXXConstructorDecl>(MD)) && 6657 "Expected `this` for non-ctor instance methods"); 6658 } 6659 ConvertedThis = nullptr; 6660 } 6661 6662 // Ignore any variadic arguments. Converting them is pointless, since the 6663 // user can't refer to them in the function condition. 6664 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6665 6666 // Convert the arguments. 6667 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6668 ExprResult R; 6669 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6670 S.Context, Function->getParamDecl(I)), 6671 SourceLocation(), Args[I]); 6672 6673 if (R.isInvalid()) 6674 return false; 6675 6676 ConvertedArgs.push_back(R.get()); 6677 } 6678 6679 if (Trap.hasErrorOccurred()) 6680 return false; 6681 6682 // Push default arguments if needed. 6683 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6684 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6685 ParmVarDecl *P = Function->getParamDecl(i); 6686 if (!P->hasDefaultArg()) 6687 return false; 6688 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6689 if (R.isInvalid()) 6690 return false; 6691 ConvertedArgs.push_back(R.get()); 6692 } 6693 6694 if (Trap.hasErrorOccurred()) 6695 return false; 6696 } 6697 return true; 6698 } 6699 6700 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6701 SourceLocation CallLoc, 6702 ArrayRef<Expr *> Args, 6703 bool MissingImplicitThis) { 6704 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6705 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6706 return nullptr; 6707 6708 SFINAETrap Trap(*this); 6709 SmallVector<Expr *, 16> ConvertedArgs; 6710 // FIXME: We should look into making enable_if late-parsed. 6711 Expr *DiscardedThis; 6712 if (!convertArgsForAvailabilityChecks( 6713 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6714 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6715 return *EnableIfAttrs.begin(); 6716 6717 for (auto *EIA : EnableIfAttrs) { 6718 APValue Result; 6719 // FIXME: This doesn't consider value-dependent cases, because doing so is 6720 // very difficult. Ideally, we should handle them more gracefully. 6721 if (EIA->getCond()->isValueDependent() || 6722 !EIA->getCond()->EvaluateWithSubstitution( 6723 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6724 return EIA; 6725 6726 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6727 return EIA; 6728 } 6729 return nullptr; 6730 } 6731 6732 template <typename CheckFn> 6733 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6734 bool ArgDependent, SourceLocation Loc, 6735 CheckFn &&IsSuccessful) { 6736 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6737 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6738 if (ArgDependent == DIA->getArgDependent()) 6739 Attrs.push_back(DIA); 6740 } 6741 6742 // Common case: No diagnose_if attributes, so we can quit early. 6743 if (Attrs.empty()) 6744 return false; 6745 6746 auto WarningBegin = std::stable_partition( 6747 Attrs.begin(), Attrs.end(), 6748 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6749 6750 // Note that diagnose_if attributes are late-parsed, so they appear in the 6751 // correct order (unlike enable_if attributes). 6752 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6753 IsSuccessful); 6754 if (ErrAttr != WarningBegin) { 6755 const DiagnoseIfAttr *DIA = *ErrAttr; 6756 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6757 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6758 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6759 return true; 6760 } 6761 6762 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6763 if (IsSuccessful(DIA)) { 6764 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6765 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6766 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6767 } 6768 6769 return false; 6770 } 6771 6772 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6773 const Expr *ThisArg, 6774 ArrayRef<const Expr *> Args, 6775 SourceLocation Loc) { 6776 return diagnoseDiagnoseIfAttrsWith( 6777 *this, Function, /*ArgDependent=*/true, Loc, 6778 [&](const DiagnoseIfAttr *DIA) { 6779 APValue Result; 6780 // It's sane to use the same Args for any redecl of this function, since 6781 // EvaluateWithSubstitution only cares about the position of each 6782 // argument in the arg list, not the ParmVarDecl* it maps to. 6783 if (!DIA->getCond()->EvaluateWithSubstitution( 6784 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6785 return false; 6786 return Result.isInt() && Result.getInt().getBoolValue(); 6787 }); 6788 } 6789 6790 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6791 SourceLocation Loc) { 6792 return diagnoseDiagnoseIfAttrsWith( 6793 *this, ND, /*ArgDependent=*/false, Loc, 6794 [&](const DiagnoseIfAttr *DIA) { 6795 bool Result; 6796 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6797 Result; 6798 }); 6799 } 6800 6801 /// Add all of the function declarations in the given function set to 6802 /// the overload candidate set. 6803 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6804 ArrayRef<Expr *> Args, 6805 OverloadCandidateSet &CandidateSet, 6806 TemplateArgumentListInfo *ExplicitTemplateArgs, 6807 bool SuppressUserConversions, 6808 bool PartialOverloading, 6809 bool FirstArgumentIsBase) { 6810 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6811 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6812 ArrayRef<Expr *> FunctionArgs = Args; 6813 6814 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6815 FunctionDecl *FD = 6816 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6817 6818 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6819 QualType ObjectType; 6820 Expr::Classification ObjectClassification; 6821 if (Args.size() > 0) { 6822 if (Expr *E = Args[0]) { 6823 // Use the explicit base to restrict the lookup: 6824 ObjectType = E->getType(); 6825 // Pointers in the object arguments are implicitly dereferenced, so we 6826 // always classify them as l-values. 6827 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6828 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6829 else 6830 ObjectClassification = E->Classify(Context); 6831 } // .. else there is an implicit base. 6832 FunctionArgs = Args.slice(1); 6833 } 6834 if (FunTmpl) { 6835 AddMethodTemplateCandidate( 6836 FunTmpl, F.getPair(), 6837 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6838 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6839 FunctionArgs, CandidateSet, SuppressUserConversions, 6840 PartialOverloading); 6841 } else { 6842 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6843 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6844 ObjectClassification, FunctionArgs, CandidateSet, 6845 SuppressUserConversions, PartialOverloading); 6846 } 6847 } else { 6848 // This branch handles both standalone functions and static methods. 6849 6850 // Slice the first argument (which is the base) when we access 6851 // static method as non-static. 6852 if (Args.size() > 0 && 6853 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6854 !isa<CXXConstructorDecl>(FD)))) { 6855 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6856 FunctionArgs = Args.slice(1); 6857 } 6858 if (FunTmpl) { 6859 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6860 ExplicitTemplateArgs, FunctionArgs, 6861 CandidateSet, SuppressUserConversions, 6862 PartialOverloading); 6863 } else { 6864 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6865 SuppressUserConversions, PartialOverloading); 6866 } 6867 } 6868 } 6869 } 6870 6871 /// AddMethodCandidate - Adds a named decl (which is some kind of 6872 /// method) as a method candidate to the given overload set. 6873 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6874 Expr::Classification ObjectClassification, 6875 ArrayRef<Expr *> Args, 6876 OverloadCandidateSet &CandidateSet, 6877 bool SuppressUserConversions, 6878 OverloadCandidateParamOrder PO) { 6879 NamedDecl *Decl = FoundDecl.getDecl(); 6880 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6881 6882 if (isa<UsingShadowDecl>(Decl)) 6883 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6884 6885 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6886 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6887 "Expected a member function template"); 6888 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6889 /*ExplicitArgs*/ nullptr, ObjectType, 6890 ObjectClassification, Args, CandidateSet, 6891 SuppressUserConversions, false, PO); 6892 } else { 6893 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6894 ObjectType, ObjectClassification, Args, CandidateSet, 6895 SuppressUserConversions, false, None, PO); 6896 } 6897 } 6898 6899 /// AddMethodCandidate - Adds the given C++ member function to the set 6900 /// of candidate functions, using the given function call arguments 6901 /// and the object argument (@c Object). For example, in a call 6902 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6903 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6904 /// allow user-defined conversions via constructors or conversion 6905 /// operators. 6906 void 6907 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6908 CXXRecordDecl *ActingContext, QualType ObjectType, 6909 Expr::Classification ObjectClassification, 6910 ArrayRef<Expr *> Args, 6911 OverloadCandidateSet &CandidateSet, 6912 bool SuppressUserConversions, 6913 bool PartialOverloading, 6914 ConversionSequenceList EarlyConversions, 6915 OverloadCandidateParamOrder PO) { 6916 const FunctionProtoType *Proto 6917 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6918 assert(Proto && "Methods without a prototype cannot be overloaded"); 6919 assert(!isa<CXXConstructorDecl>(Method) && 6920 "Use AddOverloadCandidate for constructors"); 6921 6922 if (!CandidateSet.isNewCandidate(Method, PO)) 6923 return; 6924 6925 // C++11 [class.copy]p23: [DR1402] 6926 // A defaulted move assignment operator that is defined as deleted is 6927 // ignored by overload resolution. 6928 if (Method->isDefaulted() && Method->isDeleted() && 6929 Method->isMoveAssignmentOperator()) 6930 return; 6931 6932 // Overload resolution is always an unevaluated context. 6933 EnterExpressionEvaluationContext Unevaluated( 6934 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6935 6936 // Add this candidate 6937 OverloadCandidate &Candidate = 6938 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6939 Candidate.FoundDecl = FoundDecl; 6940 Candidate.Function = Method; 6941 Candidate.RewriteKind = 6942 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6943 Candidate.IsSurrogate = false; 6944 Candidate.IgnoreObjectArgument = false; 6945 Candidate.ExplicitCallArguments = Args.size(); 6946 6947 unsigned NumParams = Proto->getNumParams(); 6948 6949 // (C++ 13.3.2p2): A candidate function having fewer than m 6950 // parameters is viable only if it has an ellipsis in its parameter 6951 // list (8.3.5). 6952 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6953 !Proto->isVariadic() && 6954 shouldEnforceArgLimit(PartialOverloading, Method)) { 6955 Candidate.Viable = false; 6956 Candidate.FailureKind = ovl_fail_too_many_arguments; 6957 return; 6958 } 6959 6960 // (C++ 13.3.2p2): A candidate function having more than m parameters 6961 // is viable only if the (m+1)st parameter has a default argument 6962 // (8.3.6). For the purposes of overload resolution, the 6963 // parameter list is truncated on the right, so that there are 6964 // exactly m parameters. 6965 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6966 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6967 // Not enough arguments. 6968 Candidate.Viable = false; 6969 Candidate.FailureKind = ovl_fail_too_few_arguments; 6970 return; 6971 } 6972 6973 Candidate.Viable = true; 6974 6975 if (Method->isStatic() || ObjectType.isNull()) 6976 // The implicit object argument is ignored. 6977 Candidate.IgnoreObjectArgument = true; 6978 else { 6979 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6980 // Determine the implicit conversion sequence for the object 6981 // parameter. 6982 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6983 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6984 Method, ActingContext); 6985 if (Candidate.Conversions[ConvIdx].isBad()) { 6986 Candidate.Viable = false; 6987 Candidate.FailureKind = ovl_fail_bad_conversion; 6988 return; 6989 } 6990 } 6991 6992 // (CUDA B.1): Check for invalid calls between targets. 6993 if (getLangOpts().CUDA) 6994 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) 6995 if (!IsAllowedCUDACall(Caller, Method)) { 6996 Candidate.Viable = false; 6997 Candidate.FailureKind = ovl_fail_bad_target; 6998 return; 6999 } 7000 7001 if (Method->getTrailingRequiresClause()) { 7002 ConstraintSatisfaction Satisfaction; 7003 if (CheckFunctionConstraints(Method, Satisfaction) || 7004 !Satisfaction.IsSatisfied) { 7005 Candidate.Viable = false; 7006 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7007 return; 7008 } 7009 } 7010 7011 // Determine the implicit conversion sequences for each of the 7012 // arguments. 7013 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7014 unsigned ConvIdx = 7015 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7016 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7017 // We already formed a conversion sequence for this parameter during 7018 // template argument deduction. 7019 } else if (ArgIdx < NumParams) { 7020 // (C++ 13.3.2p3): for F to be a viable function, there shall 7021 // exist for each argument an implicit conversion sequence 7022 // (13.3.3.1) that converts that argument to the corresponding 7023 // parameter of F. 7024 QualType ParamType = Proto->getParamType(ArgIdx); 7025 Candidate.Conversions[ConvIdx] 7026 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7027 SuppressUserConversions, 7028 /*InOverloadResolution=*/true, 7029 /*AllowObjCWritebackConversion=*/ 7030 getLangOpts().ObjCAutoRefCount); 7031 if (Candidate.Conversions[ConvIdx].isBad()) { 7032 Candidate.Viable = false; 7033 Candidate.FailureKind = ovl_fail_bad_conversion; 7034 return; 7035 } 7036 } else { 7037 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7038 // argument for which there is no corresponding parameter is 7039 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7040 Candidate.Conversions[ConvIdx].setEllipsis(); 7041 } 7042 } 7043 7044 if (EnableIfAttr *FailedAttr = 7045 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7046 Candidate.Viable = false; 7047 Candidate.FailureKind = ovl_fail_enable_if; 7048 Candidate.DeductionFailure.Data = FailedAttr; 7049 return; 7050 } 7051 7052 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 7053 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 7054 Candidate.Viable = false; 7055 Candidate.FailureKind = ovl_non_default_multiversion_function; 7056 } 7057 } 7058 7059 /// Add a C++ member function template as a candidate to the candidate 7060 /// set, using template argument deduction to produce an appropriate member 7061 /// function template specialization. 7062 void Sema::AddMethodTemplateCandidate( 7063 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7064 CXXRecordDecl *ActingContext, 7065 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7066 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7067 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7068 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7069 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7070 return; 7071 7072 // C++ [over.match.funcs]p7: 7073 // In each case where a candidate is a function template, candidate 7074 // function template specializations are generated using template argument 7075 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7076 // candidate functions in the usual way.113) A given name can refer to one 7077 // or more function templates and also to a set of overloaded non-template 7078 // functions. In such a case, the candidate functions generated from each 7079 // function template are combined with the set of non-template candidate 7080 // functions. 7081 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7082 FunctionDecl *Specialization = nullptr; 7083 ConversionSequenceList Conversions; 7084 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7085 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7086 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7087 return CheckNonDependentConversions( 7088 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7089 SuppressUserConversions, ActingContext, ObjectType, 7090 ObjectClassification, PO); 7091 })) { 7092 OverloadCandidate &Candidate = 7093 CandidateSet.addCandidate(Conversions.size(), Conversions); 7094 Candidate.FoundDecl = FoundDecl; 7095 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7096 Candidate.Viable = false; 7097 Candidate.RewriteKind = 7098 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7099 Candidate.IsSurrogate = false; 7100 Candidate.IgnoreObjectArgument = 7101 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7102 ObjectType.isNull(); 7103 Candidate.ExplicitCallArguments = Args.size(); 7104 if (Result == TDK_NonDependentConversionFailure) 7105 Candidate.FailureKind = ovl_fail_bad_conversion; 7106 else { 7107 Candidate.FailureKind = ovl_fail_bad_deduction; 7108 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7109 Info); 7110 } 7111 return; 7112 } 7113 7114 // Add the function template specialization produced by template argument 7115 // deduction as a candidate. 7116 assert(Specialization && "Missing member function template specialization?"); 7117 assert(isa<CXXMethodDecl>(Specialization) && 7118 "Specialization is not a member function?"); 7119 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7120 ActingContext, ObjectType, ObjectClassification, Args, 7121 CandidateSet, SuppressUserConversions, PartialOverloading, 7122 Conversions, PO); 7123 } 7124 7125 /// Determine whether a given function template has a simple explicit specifier 7126 /// or a non-value-dependent explicit-specification that evaluates to true. 7127 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7128 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7129 } 7130 7131 /// Add a C++ function template specialization as a candidate 7132 /// in the candidate set, using template argument deduction to produce 7133 /// an appropriate function template specialization. 7134 void Sema::AddTemplateOverloadCandidate( 7135 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7136 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7137 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7138 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7139 OverloadCandidateParamOrder PO) { 7140 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7141 return; 7142 7143 // If the function template has a non-dependent explicit specification, 7144 // exclude it now if appropriate; we are not permitted to perform deduction 7145 // and substitution in this case. 7146 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7147 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7148 Candidate.FoundDecl = FoundDecl; 7149 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7150 Candidate.Viable = false; 7151 Candidate.FailureKind = ovl_fail_explicit; 7152 return; 7153 } 7154 7155 // C++ [over.match.funcs]p7: 7156 // In each case where a candidate is a function template, candidate 7157 // function template specializations are generated using template argument 7158 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7159 // candidate functions in the usual way.113) A given name can refer to one 7160 // or more function templates and also to a set of overloaded non-template 7161 // functions. In such a case, the candidate functions generated from each 7162 // function template are combined with the set of non-template candidate 7163 // functions. 7164 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7165 FunctionDecl *Specialization = nullptr; 7166 ConversionSequenceList Conversions; 7167 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7168 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7169 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7170 return CheckNonDependentConversions( 7171 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7172 SuppressUserConversions, nullptr, QualType(), {}, PO); 7173 })) { 7174 OverloadCandidate &Candidate = 7175 CandidateSet.addCandidate(Conversions.size(), Conversions); 7176 Candidate.FoundDecl = FoundDecl; 7177 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7178 Candidate.Viable = false; 7179 Candidate.RewriteKind = 7180 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7181 Candidate.IsSurrogate = false; 7182 Candidate.IsADLCandidate = IsADLCandidate; 7183 // Ignore the object argument if there is one, since we don't have an object 7184 // type. 7185 Candidate.IgnoreObjectArgument = 7186 isa<CXXMethodDecl>(Candidate.Function) && 7187 !isa<CXXConstructorDecl>(Candidate.Function); 7188 Candidate.ExplicitCallArguments = Args.size(); 7189 if (Result == TDK_NonDependentConversionFailure) 7190 Candidate.FailureKind = ovl_fail_bad_conversion; 7191 else { 7192 Candidate.FailureKind = ovl_fail_bad_deduction; 7193 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7194 Info); 7195 } 7196 return; 7197 } 7198 7199 // Add the function template specialization produced by template argument 7200 // deduction as a candidate. 7201 assert(Specialization && "Missing function template specialization?"); 7202 AddOverloadCandidate( 7203 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7204 PartialOverloading, AllowExplicit, 7205 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7206 } 7207 7208 /// Check that implicit conversion sequences can be formed for each argument 7209 /// whose corresponding parameter has a non-dependent type, per DR1391's 7210 /// [temp.deduct.call]p10. 7211 bool Sema::CheckNonDependentConversions( 7212 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7213 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7214 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7215 CXXRecordDecl *ActingContext, QualType ObjectType, 7216 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7217 // FIXME: The cases in which we allow explicit conversions for constructor 7218 // arguments never consider calling a constructor template. It's not clear 7219 // that is correct. 7220 const bool AllowExplicit = false; 7221 7222 auto *FD = FunctionTemplate->getTemplatedDecl(); 7223 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7224 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7225 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7226 7227 Conversions = 7228 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7229 7230 // Overload resolution is always an unevaluated context. 7231 EnterExpressionEvaluationContext Unevaluated( 7232 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7233 7234 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7235 // require that, but this check should never result in a hard error, and 7236 // overload resolution is permitted to sidestep instantiations. 7237 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7238 !ObjectType.isNull()) { 7239 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7240 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7241 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7242 Method, ActingContext); 7243 if (Conversions[ConvIdx].isBad()) 7244 return true; 7245 } 7246 7247 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7248 ++I) { 7249 QualType ParamType = ParamTypes[I]; 7250 if (!ParamType->isDependentType()) { 7251 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7252 ? 0 7253 : (ThisConversions + I); 7254 Conversions[ConvIdx] 7255 = TryCopyInitialization(*this, Args[I], ParamType, 7256 SuppressUserConversions, 7257 /*InOverloadResolution=*/true, 7258 /*AllowObjCWritebackConversion=*/ 7259 getLangOpts().ObjCAutoRefCount, 7260 AllowExplicit); 7261 if (Conversions[ConvIdx].isBad()) 7262 return true; 7263 } 7264 } 7265 7266 return false; 7267 } 7268 7269 /// Determine whether this is an allowable conversion from the result 7270 /// of an explicit conversion operator to the expected type, per C++ 7271 /// [over.match.conv]p1 and [over.match.ref]p1. 7272 /// 7273 /// \param ConvType The return type of the conversion function. 7274 /// 7275 /// \param ToType The type we are converting to. 7276 /// 7277 /// \param AllowObjCPointerConversion Allow a conversion from one 7278 /// Objective-C pointer to another. 7279 /// 7280 /// \returns true if the conversion is allowable, false otherwise. 7281 static bool isAllowableExplicitConversion(Sema &S, 7282 QualType ConvType, QualType ToType, 7283 bool AllowObjCPointerConversion) { 7284 QualType ToNonRefType = ToType.getNonReferenceType(); 7285 7286 // Easy case: the types are the same. 7287 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7288 return true; 7289 7290 // Allow qualification conversions. 7291 bool ObjCLifetimeConversion; 7292 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7293 ObjCLifetimeConversion)) 7294 return true; 7295 7296 // If we're not allowed to consider Objective-C pointer conversions, 7297 // we're done. 7298 if (!AllowObjCPointerConversion) 7299 return false; 7300 7301 // Is this an Objective-C pointer conversion? 7302 bool IncompatibleObjC = false; 7303 QualType ConvertedType; 7304 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7305 IncompatibleObjC); 7306 } 7307 7308 /// AddConversionCandidate - Add a C++ conversion function as a 7309 /// candidate in the candidate set (C++ [over.match.conv], 7310 /// C++ [over.match.copy]). From is the expression we're converting from, 7311 /// and ToType is the type that we're eventually trying to convert to 7312 /// (which may or may not be the same type as the type that the 7313 /// conversion function produces). 7314 void Sema::AddConversionCandidate( 7315 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7316 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7317 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7318 bool AllowExplicit, bool AllowResultConversion) { 7319 assert(!Conversion->getDescribedFunctionTemplate() && 7320 "Conversion function templates use AddTemplateConversionCandidate"); 7321 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7322 if (!CandidateSet.isNewCandidate(Conversion)) 7323 return; 7324 7325 // If the conversion function has an undeduced return type, trigger its 7326 // deduction now. 7327 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7328 if (DeduceReturnType(Conversion, From->getExprLoc())) 7329 return; 7330 ConvType = Conversion->getConversionType().getNonReferenceType(); 7331 } 7332 7333 // If we don't allow any conversion of the result type, ignore conversion 7334 // functions that don't convert to exactly (possibly cv-qualified) T. 7335 if (!AllowResultConversion && 7336 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7337 return; 7338 7339 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7340 // operator is only a candidate if its return type is the target type or 7341 // can be converted to the target type with a qualification conversion. 7342 // 7343 // FIXME: Include such functions in the candidate list and explain why we 7344 // can't select them. 7345 if (Conversion->isExplicit() && 7346 !isAllowableExplicitConversion(*this, ConvType, ToType, 7347 AllowObjCConversionOnExplicit)) 7348 return; 7349 7350 // Overload resolution is always an unevaluated context. 7351 EnterExpressionEvaluationContext Unevaluated( 7352 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7353 7354 // Add this candidate 7355 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7356 Candidate.FoundDecl = FoundDecl; 7357 Candidate.Function = Conversion; 7358 Candidate.IsSurrogate = false; 7359 Candidate.IgnoreObjectArgument = false; 7360 Candidate.FinalConversion.setAsIdentityConversion(); 7361 Candidate.FinalConversion.setFromType(ConvType); 7362 Candidate.FinalConversion.setAllToTypes(ToType); 7363 Candidate.Viable = true; 7364 Candidate.ExplicitCallArguments = 1; 7365 7366 // Explicit functions are not actually candidates at all if we're not 7367 // allowing them in this context, but keep them around so we can point 7368 // to them in diagnostics. 7369 if (!AllowExplicit && Conversion->isExplicit()) { 7370 Candidate.Viable = false; 7371 Candidate.FailureKind = ovl_fail_explicit; 7372 return; 7373 } 7374 7375 // C++ [over.match.funcs]p4: 7376 // For conversion functions, the function is considered to be a member of 7377 // the class of the implicit implied object argument for the purpose of 7378 // defining the type of the implicit object parameter. 7379 // 7380 // Determine the implicit conversion sequence for the implicit 7381 // object parameter. 7382 QualType ImplicitParamType = From->getType(); 7383 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7384 ImplicitParamType = FromPtrType->getPointeeType(); 7385 CXXRecordDecl *ConversionContext 7386 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7387 7388 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7389 *this, CandidateSet.getLocation(), From->getType(), 7390 From->Classify(Context), Conversion, ConversionContext); 7391 7392 if (Candidate.Conversions[0].isBad()) { 7393 Candidate.Viable = false; 7394 Candidate.FailureKind = ovl_fail_bad_conversion; 7395 return; 7396 } 7397 7398 if (Conversion->getTrailingRequiresClause()) { 7399 ConstraintSatisfaction Satisfaction; 7400 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7401 !Satisfaction.IsSatisfied) { 7402 Candidate.Viable = false; 7403 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7404 return; 7405 } 7406 } 7407 7408 // We won't go through a user-defined type conversion function to convert a 7409 // derived to base as such conversions are given Conversion Rank. They only 7410 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7411 QualType FromCanon 7412 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7413 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7414 if (FromCanon == ToCanon || 7415 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7416 Candidate.Viable = false; 7417 Candidate.FailureKind = ovl_fail_trivial_conversion; 7418 return; 7419 } 7420 7421 // To determine what the conversion from the result of calling the 7422 // conversion function to the type we're eventually trying to 7423 // convert to (ToType), we need to synthesize a call to the 7424 // conversion function and attempt copy initialization from it. This 7425 // makes sure that we get the right semantics with respect to 7426 // lvalues/rvalues and the type. Fortunately, we can allocate this 7427 // call on the stack and we don't need its arguments to be 7428 // well-formed. 7429 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7430 VK_LValue, From->getBeginLoc()); 7431 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7432 Context.getPointerType(Conversion->getType()), 7433 CK_FunctionToPointerDecay, &ConversionRef, 7434 VK_PRValue, FPOptionsOverride()); 7435 7436 QualType ConversionType = Conversion->getConversionType(); 7437 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7438 Candidate.Viable = false; 7439 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7440 return; 7441 } 7442 7443 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7444 7445 // Note that it is safe to allocate CallExpr on the stack here because 7446 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7447 // allocator). 7448 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7449 7450 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7451 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7452 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7453 7454 ImplicitConversionSequence ICS = 7455 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7456 /*SuppressUserConversions=*/true, 7457 /*InOverloadResolution=*/false, 7458 /*AllowObjCWritebackConversion=*/false); 7459 7460 switch (ICS.getKind()) { 7461 case ImplicitConversionSequence::StandardConversion: 7462 Candidate.FinalConversion = ICS.Standard; 7463 7464 // C++ [over.ics.user]p3: 7465 // If the user-defined conversion is specified by a specialization of a 7466 // conversion function template, the second standard conversion sequence 7467 // shall have exact match rank. 7468 if (Conversion->getPrimaryTemplate() && 7469 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7470 Candidate.Viable = false; 7471 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7472 return; 7473 } 7474 7475 // C++0x [dcl.init.ref]p5: 7476 // In the second case, if the reference is an rvalue reference and 7477 // the second standard conversion sequence of the user-defined 7478 // conversion sequence includes an lvalue-to-rvalue conversion, the 7479 // program is ill-formed. 7480 if (ToType->isRValueReferenceType() && 7481 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7482 Candidate.Viable = false; 7483 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7484 return; 7485 } 7486 break; 7487 7488 case ImplicitConversionSequence::BadConversion: 7489 Candidate.Viable = false; 7490 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7491 return; 7492 7493 default: 7494 llvm_unreachable( 7495 "Can only end up with a standard conversion sequence or failure"); 7496 } 7497 7498 if (EnableIfAttr *FailedAttr = 7499 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7500 Candidate.Viable = false; 7501 Candidate.FailureKind = ovl_fail_enable_if; 7502 Candidate.DeductionFailure.Data = FailedAttr; 7503 return; 7504 } 7505 7506 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7507 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7508 Candidate.Viable = false; 7509 Candidate.FailureKind = ovl_non_default_multiversion_function; 7510 } 7511 } 7512 7513 /// Adds a conversion function template specialization 7514 /// candidate to the overload set, using template argument deduction 7515 /// to deduce the template arguments of the conversion function 7516 /// template from the type that we are converting to (C++ 7517 /// [temp.deduct.conv]). 7518 void Sema::AddTemplateConversionCandidate( 7519 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7520 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7521 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7522 bool AllowExplicit, bool AllowResultConversion) { 7523 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7524 "Only conversion function templates permitted here"); 7525 7526 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7527 return; 7528 7529 // If the function template has a non-dependent explicit specification, 7530 // exclude it now if appropriate; we are not permitted to perform deduction 7531 // and substitution in this case. 7532 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7533 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7534 Candidate.FoundDecl = FoundDecl; 7535 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7536 Candidate.Viable = false; 7537 Candidate.FailureKind = ovl_fail_explicit; 7538 return; 7539 } 7540 7541 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7542 CXXConversionDecl *Specialization = nullptr; 7543 if (TemplateDeductionResult Result 7544 = DeduceTemplateArguments(FunctionTemplate, ToType, 7545 Specialization, Info)) { 7546 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7547 Candidate.FoundDecl = FoundDecl; 7548 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7549 Candidate.Viable = false; 7550 Candidate.FailureKind = ovl_fail_bad_deduction; 7551 Candidate.IsSurrogate = false; 7552 Candidate.IgnoreObjectArgument = false; 7553 Candidate.ExplicitCallArguments = 1; 7554 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7555 Info); 7556 return; 7557 } 7558 7559 // Add the conversion function template specialization produced by 7560 // template argument deduction as a candidate. 7561 assert(Specialization && "Missing function template specialization?"); 7562 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7563 CandidateSet, AllowObjCConversionOnExplicit, 7564 AllowExplicit, AllowResultConversion); 7565 } 7566 7567 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7568 /// converts the given @c Object to a function pointer via the 7569 /// conversion function @c Conversion, and then attempts to call it 7570 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7571 /// the type of function that we'll eventually be calling. 7572 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7573 DeclAccessPair FoundDecl, 7574 CXXRecordDecl *ActingContext, 7575 const FunctionProtoType *Proto, 7576 Expr *Object, 7577 ArrayRef<Expr *> Args, 7578 OverloadCandidateSet& CandidateSet) { 7579 if (!CandidateSet.isNewCandidate(Conversion)) 7580 return; 7581 7582 // Overload resolution is always an unevaluated context. 7583 EnterExpressionEvaluationContext Unevaluated( 7584 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7585 7586 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7587 Candidate.FoundDecl = FoundDecl; 7588 Candidate.Function = nullptr; 7589 Candidate.Surrogate = Conversion; 7590 Candidate.Viable = true; 7591 Candidate.IsSurrogate = true; 7592 Candidate.IgnoreObjectArgument = false; 7593 Candidate.ExplicitCallArguments = Args.size(); 7594 7595 // Determine the implicit conversion sequence for the implicit 7596 // object parameter. 7597 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7598 *this, CandidateSet.getLocation(), Object->getType(), 7599 Object->Classify(Context), Conversion, ActingContext); 7600 if (ObjectInit.isBad()) { 7601 Candidate.Viable = false; 7602 Candidate.FailureKind = ovl_fail_bad_conversion; 7603 Candidate.Conversions[0] = ObjectInit; 7604 return; 7605 } 7606 7607 // The first conversion is actually a user-defined conversion whose 7608 // first conversion is ObjectInit's standard conversion (which is 7609 // effectively a reference binding). Record it as such. 7610 Candidate.Conversions[0].setUserDefined(); 7611 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7612 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7613 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7614 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7615 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7616 Candidate.Conversions[0].UserDefined.After 7617 = Candidate.Conversions[0].UserDefined.Before; 7618 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7619 7620 // Find the 7621 unsigned NumParams = Proto->getNumParams(); 7622 7623 // (C++ 13.3.2p2): A candidate function having fewer than m 7624 // parameters is viable only if it has an ellipsis in its parameter 7625 // list (8.3.5). 7626 if (Args.size() > NumParams && !Proto->isVariadic()) { 7627 Candidate.Viable = false; 7628 Candidate.FailureKind = ovl_fail_too_many_arguments; 7629 return; 7630 } 7631 7632 // Function types don't have any default arguments, so just check if 7633 // we have enough arguments. 7634 if (Args.size() < NumParams) { 7635 // Not enough arguments. 7636 Candidate.Viable = false; 7637 Candidate.FailureKind = ovl_fail_too_few_arguments; 7638 return; 7639 } 7640 7641 // Determine the implicit conversion sequences for each of the 7642 // arguments. 7643 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7644 if (ArgIdx < NumParams) { 7645 // (C++ 13.3.2p3): for F to be a viable function, there shall 7646 // exist for each argument an implicit conversion sequence 7647 // (13.3.3.1) that converts that argument to the corresponding 7648 // parameter of F. 7649 QualType ParamType = Proto->getParamType(ArgIdx); 7650 Candidate.Conversions[ArgIdx + 1] 7651 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7652 /*SuppressUserConversions=*/false, 7653 /*InOverloadResolution=*/false, 7654 /*AllowObjCWritebackConversion=*/ 7655 getLangOpts().ObjCAutoRefCount); 7656 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7657 Candidate.Viable = false; 7658 Candidate.FailureKind = ovl_fail_bad_conversion; 7659 return; 7660 } 7661 } else { 7662 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7663 // argument for which there is no corresponding parameter is 7664 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7665 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7666 } 7667 } 7668 7669 if (EnableIfAttr *FailedAttr = 7670 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7671 Candidate.Viable = false; 7672 Candidate.FailureKind = ovl_fail_enable_if; 7673 Candidate.DeductionFailure.Data = FailedAttr; 7674 return; 7675 } 7676 } 7677 7678 /// Add all of the non-member operator function declarations in the given 7679 /// function set to the overload candidate set. 7680 void Sema::AddNonMemberOperatorCandidates( 7681 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7682 OverloadCandidateSet &CandidateSet, 7683 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7684 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7685 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7686 ArrayRef<Expr *> FunctionArgs = Args; 7687 7688 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7689 FunctionDecl *FD = 7690 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7691 7692 // Don't consider rewritten functions if we're not rewriting. 7693 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7694 continue; 7695 7696 assert(!isa<CXXMethodDecl>(FD) && 7697 "unqualified operator lookup found a member function"); 7698 7699 if (FunTmpl) { 7700 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7701 FunctionArgs, CandidateSet); 7702 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7703 AddTemplateOverloadCandidate( 7704 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7705 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7706 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7707 } else { 7708 if (ExplicitTemplateArgs) 7709 continue; 7710 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7711 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7712 AddOverloadCandidate(FD, F.getPair(), 7713 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7714 false, false, true, false, ADLCallKind::NotADL, 7715 None, OverloadCandidateParamOrder::Reversed); 7716 } 7717 } 7718 } 7719 7720 /// Add overload candidates for overloaded operators that are 7721 /// member functions. 7722 /// 7723 /// Add the overloaded operator candidates that are member functions 7724 /// for the operator Op that was used in an operator expression such 7725 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7726 /// CandidateSet will store the added overload candidates. (C++ 7727 /// [over.match.oper]). 7728 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7729 SourceLocation OpLoc, 7730 ArrayRef<Expr *> Args, 7731 OverloadCandidateSet &CandidateSet, 7732 OverloadCandidateParamOrder PO) { 7733 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7734 7735 // C++ [over.match.oper]p3: 7736 // For a unary operator @ with an operand of a type whose 7737 // cv-unqualified version is T1, and for a binary operator @ with 7738 // a left operand of a type whose cv-unqualified version is T1 and 7739 // a right operand of a type whose cv-unqualified version is T2, 7740 // three sets of candidate functions, designated member 7741 // candidates, non-member candidates and built-in candidates, are 7742 // constructed as follows: 7743 QualType T1 = Args[0]->getType(); 7744 7745 // -- If T1 is a complete class type or a class currently being 7746 // defined, the set of member candidates is the result of the 7747 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7748 // the set of member candidates is empty. 7749 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7750 // Complete the type if it can be completed. 7751 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7752 return; 7753 // If the type is neither complete nor being defined, bail out now. 7754 if (!T1Rec->getDecl()->getDefinition()) 7755 return; 7756 7757 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7758 LookupQualifiedName(Operators, T1Rec->getDecl()); 7759 Operators.suppressDiagnostics(); 7760 7761 for (LookupResult::iterator Oper = Operators.begin(), 7762 OperEnd = Operators.end(); 7763 Oper != OperEnd; 7764 ++Oper) 7765 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7766 Args[0]->Classify(Context), Args.slice(1), 7767 CandidateSet, /*SuppressUserConversion=*/false, PO); 7768 } 7769 } 7770 7771 /// AddBuiltinCandidate - Add a candidate for a built-in 7772 /// operator. ResultTy and ParamTys are the result and parameter types 7773 /// of the built-in candidate, respectively. Args and NumArgs are the 7774 /// arguments being passed to the candidate. IsAssignmentOperator 7775 /// should be true when this built-in candidate is an assignment 7776 /// operator. NumContextualBoolArguments is the number of arguments 7777 /// (at the beginning of the argument list) that will be contextually 7778 /// converted to bool. 7779 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7780 OverloadCandidateSet& CandidateSet, 7781 bool IsAssignmentOperator, 7782 unsigned NumContextualBoolArguments) { 7783 // Overload resolution is always an unevaluated context. 7784 EnterExpressionEvaluationContext Unevaluated( 7785 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7786 7787 // Add this candidate 7788 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7789 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7790 Candidate.Function = nullptr; 7791 Candidate.IsSurrogate = false; 7792 Candidate.IgnoreObjectArgument = false; 7793 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7794 7795 // Determine the implicit conversion sequences for each of the 7796 // arguments. 7797 Candidate.Viable = true; 7798 Candidate.ExplicitCallArguments = Args.size(); 7799 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7800 // C++ [over.match.oper]p4: 7801 // For the built-in assignment operators, conversions of the 7802 // left operand are restricted as follows: 7803 // -- no temporaries are introduced to hold the left operand, and 7804 // -- no user-defined conversions are applied to the left 7805 // operand to achieve a type match with the left-most 7806 // parameter of a built-in candidate. 7807 // 7808 // We block these conversions by turning off user-defined 7809 // conversions, since that is the only way that initialization of 7810 // a reference to a non-class type can occur from something that 7811 // is not of the same type. 7812 if (ArgIdx < NumContextualBoolArguments) { 7813 assert(ParamTys[ArgIdx] == Context.BoolTy && 7814 "Contextual conversion to bool requires bool type"); 7815 Candidate.Conversions[ArgIdx] 7816 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7817 } else { 7818 Candidate.Conversions[ArgIdx] 7819 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7820 ArgIdx == 0 && IsAssignmentOperator, 7821 /*InOverloadResolution=*/false, 7822 /*AllowObjCWritebackConversion=*/ 7823 getLangOpts().ObjCAutoRefCount); 7824 } 7825 if (Candidate.Conversions[ArgIdx].isBad()) { 7826 Candidate.Viable = false; 7827 Candidate.FailureKind = ovl_fail_bad_conversion; 7828 break; 7829 } 7830 } 7831 } 7832 7833 namespace { 7834 7835 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7836 /// candidate operator functions for built-in operators (C++ 7837 /// [over.built]). The types are separated into pointer types and 7838 /// enumeration types. 7839 class BuiltinCandidateTypeSet { 7840 /// TypeSet - A set of types. 7841 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7842 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7843 7844 /// PointerTypes - The set of pointer types that will be used in the 7845 /// built-in candidates. 7846 TypeSet PointerTypes; 7847 7848 /// MemberPointerTypes - The set of member pointer types that will be 7849 /// used in the built-in candidates. 7850 TypeSet MemberPointerTypes; 7851 7852 /// EnumerationTypes - The set of enumeration types that will be 7853 /// used in the built-in candidates. 7854 TypeSet EnumerationTypes; 7855 7856 /// The set of vector types that will be used in the built-in 7857 /// candidates. 7858 TypeSet VectorTypes; 7859 7860 /// The set of matrix types that will be used in the built-in 7861 /// candidates. 7862 TypeSet MatrixTypes; 7863 7864 /// A flag indicating non-record types are viable candidates 7865 bool HasNonRecordTypes; 7866 7867 /// A flag indicating whether either arithmetic or enumeration types 7868 /// were present in the candidate set. 7869 bool HasArithmeticOrEnumeralTypes; 7870 7871 /// A flag indicating whether the nullptr type was present in the 7872 /// candidate set. 7873 bool HasNullPtrType; 7874 7875 /// Sema - The semantic analysis instance where we are building the 7876 /// candidate type set. 7877 Sema &SemaRef; 7878 7879 /// Context - The AST context in which we will build the type sets. 7880 ASTContext &Context; 7881 7882 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7883 const Qualifiers &VisibleQuals); 7884 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7885 7886 public: 7887 /// iterator - Iterates through the types that are part of the set. 7888 typedef TypeSet::iterator iterator; 7889 7890 BuiltinCandidateTypeSet(Sema &SemaRef) 7891 : HasNonRecordTypes(false), 7892 HasArithmeticOrEnumeralTypes(false), 7893 HasNullPtrType(false), 7894 SemaRef(SemaRef), 7895 Context(SemaRef.Context) { } 7896 7897 void AddTypesConvertedFrom(QualType Ty, 7898 SourceLocation Loc, 7899 bool AllowUserConversions, 7900 bool AllowExplicitConversions, 7901 const Qualifiers &VisibleTypeConversionsQuals); 7902 7903 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7904 llvm::iterator_range<iterator> member_pointer_types() { 7905 return MemberPointerTypes; 7906 } 7907 llvm::iterator_range<iterator> enumeration_types() { 7908 return EnumerationTypes; 7909 } 7910 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7911 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7912 7913 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7914 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7915 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7916 bool hasNullPtrType() const { return HasNullPtrType; } 7917 }; 7918 7919 } // end anonymous namespace 7920 7921 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7922 /// the set of pointer types along with any more-qualified variants of 7923 /// that type. For example, if @p Ty is "int const *", this routine 7924 /// will add "int const *", "int const volatile *", "int const 7925 /// restrict *", and "int const volatile restrict *" to the set of 7926 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7927 /// false otherwise. 7928 /// 7929 /// FIXME: what to do about extended qualifiers? 7930 bool 7931 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7932 const Qualifiers &VisibleQuals) { 7933 7934 // Insert this type. 7935 if (!PointerTypes.insert(Ty)) 7936 return false; 7937 7938 QualType PointeeTy; 7939 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7940 bool buildObjCPtr = false; 7941 if (!PointerTy) { 7942 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7943 PointeeTy = PTy->getPointeeType(); 7944 buildObjCPtr = true; 7945 } else { 7946 PointeeTy = PointerTy->getPointeeType(); 7947 } 7948 7949 // Don't add qualified variants of arrays. For one, they're not allowed 7950 // (the qualifier would sink to the element type), and for another, the 7951 // only overload situation where it matters is subscript or pointer +- int, 7952 // and those shouldn't have qualifier variants anyway. 7953 if (PointeeTy->isArrayType()) 7954 return true; 7955 7956 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7957 bool hasVolatile = VisibleQuals.hasVolatile(); 7958 bool hasRestrict = VisibleQuals.hasRestrict(); 7959 7960 // Iterate through all strict supersets of BaseCVR. 7961 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7962 if ((CVR | BaseCVR) != CVR) continue; 7963 // Skip over volatile if no volatile found anywhere in the types. 7964 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7965 7966 // Skip over restrict if no restrict found anywhere in the types, or if 7967 // the type cannot be restrict-qualified. 7968 if ((CVR & Qualifiers::Restrict) && 7969 (!hasRestrict || 7970 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7971 continue; 7972 7973 // Build qualified pointee type. 7974 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7975 7976 // Build qualified pointer type. 7977 QualType QPointerTy; 7978 if (!buildObjCPtr) 7979 QPointerTy = Context.getPointerType(QPointeeTy); 7980 else 7981 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7982 7983 // Insert qualified pointer type. 7984 PointerTypes.insert(QPointerTy); 7985 } 7986 7987 return true; 7988 } 7989 7990 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7991 /// to the set of pointer types along with any more-qualified variants of 7992 /// that type. For example, if @p Ty is "int const *", this routine 7993 /// will add "int const *", "int const volatile *", "int const 7994 /// restrict *", and "int const volatile restrict *" to the set of 7995 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7996 /// false otherwise. 7997 /// 7998 /// FIXME: what to do about extended qualifiers? 7999 bool 8000 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 8001 QualType Ty) { 8002 // Insert this type. 8003 if (!MemberPointerTypes.insert(Ty)) 8004 return false; 8005 8006 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8007 assert(PointerTy && "type was not a member pointer type!"); 8008 8009 QualType PointeeTy = PointerTy->getPointeeType(); 8010 // Don't add qualified variants of arrays. For one, they're not allowed 8011 // (the qualifier would sink to the element type), and for another, the 8012 // only overload situation where it matters is subscript or pointer +- int, 8013 // and those shouldn't have qualifier variants anyway. 8014 if (PointeeTy->isArrayType()) 8015 return true; 8016 const Type *ClassTy = PointerTy->getClass(); 8017 8018 // Iterate through all strict supersets of the pointee type's CVR 8019 // qualifiers. 8020 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8021 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8022 if ((CVR | BaseCVR) != CVR) continue; 8023 8024 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8025 MemberPointerTypes.insert( 8026 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8027 } 8028 8029 return true; 8030 } 8031 8032 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8033 /// Ty can be implicit converted to the given set of @p Types. We're 8034 /// primarily interested in pointer types and enumeration types. We also 8035 /// take member pointer types, for the conditional operator. 8036 /// AllowUserConversions is true if we should look at the conversion 8037 /// functions of a class type, and AllowExplicitConversions if we 8038 /// should also include the explicit conversion functions of a class 8039 /// type. 8040 void 8041 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8042 SourceLocation Loc, 8043 bool AllowUserConversions, 8044 bool AllowExplicitConversions, 8045 const Qualifiers &VisibleQuals) { 8046 // Only deal with canonical types. 8047 Ty = Context.getCanonicalType(Ty); 8048 8049 // Look through reference types; they aren't part of the type of an 8050 // expression for the purposes of conversions. 8051 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8052 Ty = RefTy->getPointeeType(); 8053 8054 // If we're dealing with an array type, decay to the pointer. 8055 if (Ty->isArrayType()) 8056 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8057 8058 // Otherwise, we don't care about qualifiers on the type. 8059 Ty = Ty.getLocalUnqualifiedType(); 8060 8061 // Flag if we ever add a non-record type. 8062 const RecordType *TyRec = Ty->getAs<RecordType>(); 8063 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8064 8065 // Flag if we encounter an arithmetic type. 8066 HasArithmeticOrEnumeralTypes = 8067 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8068 8069 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8070 PointerTypes.insert(Ty); 8071 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8072 // Insert our type, and its more-qualified variants, into the set 8073 // of types. 8074 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8075 return; 8076 } else if (Ty->isMemberPointerType()) { 8077 // Member pointers are far easier, since the pointee can't be converted. 8078 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8079 return; 8080 } else if (Ty->isEnumeralType()) { 8081 HasArithmeticOrEnumeralTypes = true; 8082 EnumerationTypes.insert(Ty); 8083 } else if (Ty->isVectorType()) { 8084 // We treat vector types as arithmetic types in many contexts as an 8085 // extension. 8086 HasArithmeticOrEnumeralTypes = true; 8087 VectorTypes.insert(Ty); 8088 } else if (Ty->isMatrixType()) { 8089 // Similar to vector types, we treat vector types as arithmetic types in 8090 // many contexts as an extension. 8091 HasArithmeticOrEnumeralTypes = true; 8092 MatrixTypes.insert(Ty); 8093 } else if (Ty->isNullPtrType()) { 8094 HasNullPtrType = true; 8095 } else if (AllowUserConversions && TyRec) { 8096 // No conversion functions in incomplete types. 8097 if (!SemaRef.isCompleteType(Loc, Ty)) 8098 return; 8099 8100 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8101 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8102 if (isa<UsingShadowDecl>(D)) 8103 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8104 8105 // Skip conversion function templates; they don't tell us anything 8106 // about which builtin types we can convert to. 8107 if (isa<FunctionTemplateDecl>(D)) 8108 continue; 8109 8110 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8111 if (AllowExplicitConversions || !Conv->isExplicit()) { 8112 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8113 VisibleQuals); 8114 } 8115 } 8116 } 8117 } 8118 /// Helper function for adjusting address spaces for the pointer or reference 8119 /// operands of builtin operators depending on the argument. 8120 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8121 Expr *Arg) { 8122 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8123 } 8124 8125 /// Helper function for AddBuiltinOperatorCandidates() that adds 8126 /// the volatile- and non-volatile-qualified assignment operators for the 8127 /// given type to the candidate set. 8128 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8129 QualType T, 8130 ArrayRef<Expr *> Args, 8131 OverloadCandidateSet &CandidateSet) { 8132 QualType ParamTypes[2]; 8133 8134 // T& operator=(T&, T) 8135 ParamTypes[0] = S.Context.getLValueReferenceType( 8136 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8137 ParamTypes[1] = T; 8138 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8139 /*IsAssignmentOperator=*/true); 8140 8141 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8142 // volatile T& operator=(volatile T&, T) 8143 ParamTypes[0] = S.Context.getLValueReferenceType( 8144 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8145 Args[0])); 8146 ParamTypes[1] = T; 8147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8148 /*IsAssignmentOperator=*/true); 8149 } 8150 } 8151 8152 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8153 /// if any, found in visible type conversion functions found in ArgExpr's type. 8154 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8155 Qualifiers VRQuals; 8156 const RecordType *TyRec; 8157 if (const MemberPointerType *RHSMPType = 8158 ArgExpr->getType()->getAs<MemberPointerType>()) 8159 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8160 else 8161 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8162 if (!TyRec) { 8163 // Just to be safe, assume the worst case. 8164 VRQuals.addVolatile(); 8165 VRQuals.addRestrict(); 8166 return VRQuals; 8167 } 8168 8169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8170 if (!ClassDecl->hasDefinition()) 8171 return VRQuals; 8172 8173 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8174 if (isa<UsingShadowDecl>(D)) 8175 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8176 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8177 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8178 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8179 CanTy = ResTypeRef->getPointeeType(); 8180 // Need to go down the pointer/mempointer chain and add qualifiers 8181 // as see them. 8182 bool done = false; 8183 while (!done) { 8184 if (CanTy.isRestrictQualified()) 8185 VRQuals.addRestrict(); 8186 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8187 CanTy = ResTypePtr->getPointeeType(); 8188 else if (const MemberPointerType *ResTypeMPtr = 8189 CanTy->getAs<MemberPointerType>()) 8190 CanTy = ResTypeMPtr->getPointeeType(); 8191 else 8192 done = true; 8193 if (CanTy.isVolatileQualified()) 8194 VRQuals.addVolatile(); 8195 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8196 return VRQuals; 8197 } 8198 } 8199 } 8200 return VRQuals; 8201 } 8202 8203 // Note: We're currently only handling qualifiers that are meaningful for the 8204 // LHS of compound assignment overloading. 8205 static void forAllQualifierCombinationsImpl( 8206 QualifiersAndAtomic Available, QualifiersAndAtomic Applied, 8207 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8208 // _Atomic 8209 if (Available.hasAtomic()) { 8210 Available.removeAtomic(); 8211 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); 8212 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8213 return; 8214 } 8215 8216 // volatile 8217 if (Available.hasVolatile()) { 8218 Available.removeVolatile(); 8219 assert(!Applied.hasVolatile()); 8220 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), 8221 Callback); 8222 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8223 return; 8224 } 8225 8226 Callback(Applied); 8227 } 8228 8229 static void forAllQualifierCombinations( 8230 QualifiersAndAtomic Quals, 8231 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8232 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), 8233 Callback); 8234 } 8235 8236 static QualType makeQualifiedLValueReferenceType(QualType Base, 8237 QualifiersAndAtomic Quals, 8238 Sema &S) { 8239 if (Quals.hasAtomic()) 8240 Base = S.Context.getAtomicType(Base); 8241 if (Quals.hasVolatile()) 8242 Base = S.Context.getVolatileType(Base); 8243 return S.Context.getLValueReferenceType(Base); 8244 } 8245 8246 namespace { 8247 8248 /// Helper class to manage the addition of builtin operator overload 8249 /// candidates. It provides shared state and utility methods used throughout 8250 /// the process, as well as a helper method to add each group of builtin 8251 /// operator overloads from the standard to a candidate set. 8252 class BuiltinOperatorOverloadBuilder { 8253 // Common instance state available to all overload candidate addition methods. 8254 Sema &S; 8255 ArrayRef<Expr *> Args; 8256 QualifiersAndAtomic VisibleTypeConversionsQuals; 8257 bool HasArithmeticOrEnumeralCandidateType; 8258 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8259 OverloadCandidateSet &CandidateSet; 8260 8261 static constexpr int ArithmeticTypesCap = 24; 8262 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8263 8264 // Define some indices used to iterate over the arithmetic types in 8265 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8266 // types are that preserved by promotion (C++ [over.built]p2). 8267 unsigned FirstIntegralType, 8268 LastIntegralType; 8269 unsigned FirstPromotedIntegralType, 8270 LastPromotedIntegralType; 8271 unsigned FirstPromotedArithmeticType, 8272 LastPromotedArithmeticType; 8273 unsigned NumArithmeticTypes; 8274 8275 void InitArithmeticTypes() { 8276 // Start of promoted types. 8277 FirstPromotedArithmeticType = 0; 8278 ArithmeticTypes.push_back(S.Context.FloatTy); 8279 ArithmeticTypes.push_back(S.Context.DoubleTy); 8280 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8281 if (S.Context.getTargetInfo().hasFloat128Type()) 8282 ArithmeticTypes.push_back(S.Context.Float128Ty); 8283 if (S.Context.getTargetInfo().hasIbm128Type()) 8284 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8285 8286 // Start of integral types. 8287 FirstIntegralType = ArithmeticTypes.size(); 8288 FirstPromotedIntegralType = ArithmeticTypes.size(); 8289 ArithmeticTypes.push_back(S.Context.IntTy); 8290 ArithmeticTypes.push_back(S.Context.LongTy); 8291 ArithmeticTypes.push_back(S.Context.LongLongTy); 8292 if (S.Context.getTargetInfo().hasInt128Type() || 8293 (S.Context.getAuxTargetInfo() && 8294 S.Context.getAuxTargetInfo()->hasInt128Type())) 8295 ArithmeticTypes.push_back(S.Context.Int128Ty); 8296 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8297 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8298 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8299 if (S.Context.getTargetInfo().hasInt128Type() || 8300 (S.Context.getAuxTargetInfo() && 8301 S.Context.getAuxTargetInfo()->hasInt128Type())) 8302 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8303 LastPromotedIntegralType = ArithmeticTypes.size(); 8304 LastPromotedArithmeticType = ArithmeticTypes.size(); 8305 // End of promoted types. 8306 8307 ArithmeticTypes.push_back(S.Context.BoolTy); 8308 ArithmeticTypes.push_back(S.Context.CharTy); 8309 ArithmeticTypes.push_back(S.Context.WCharTy); 8310 if (S.Context.getLangOpts().Char8) 8311 ArithmeticTypes.push_back(S.Context.Char8Ty); 8312 ArithmeticTypes.push_back(S.Context.Char16Ty); 8313 ArithmeticTypes.push_back(S.Context.Char32Ty); 8314 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8315 ArithmeticTypes.push_back(S.Context.ShortTy); 8316 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8317 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8318 LastIntegralType = ArithmeticTypes.size(); 8319 NumArithmeticTypes = ArithmeticTypes.size(); 8320 // End of integral types. 8321 // FIXME: What about complex? What about half? 8322 8323 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8324 "Enough inline storage for all arithmetic types."); 8325 } 8326 8327 /// Helper method to factor out the common pattern of adding overloads 8328 /// for '++' and '--' builtin operators. 8329 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8330 bool HasVolatile, 8331 bool HasRestrict) { 8332 QualType ParamTypes[2] = { 8333 S.Context.getLValueReferenceType(CandidateTy), 8334 S.Context.IntTy 8335 }; 8336 8337 // Non-volatile version. 8338 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8339 8340 // Use a heuristic to reduce number of builtin candidates in the set: 8341 // add volatile version only if there are conversions to a volatile type. 8342 if (HasVolatile) { 8343 ParamTypes[0] = 8344 S.Context.getLValueReferenceType( 8345 S.Context.getVolatileType(CandidateTy)); 8346 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8347 } 8348 8349 // Add restrict version only if there are conversions to a restrict type 8350 // and our candidate type is a non-restrict-qualified pointer. 8351 if (HasRestrict && CandidateTy->isAnyPointerType() && 8352 !CandidateTy.isRestrictQualified()) { 8353 ParamTypes[0] 8354 = S.Context.getLValueReferenceType( 8355 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8356 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8357 8358 if (HasVolatile) { 8359 ParamTypes[0] 8360 = S.Context.getLValueReferenceType( 8361 S.Context.getCVRQualifiedType(CandidateTy, 8362 (Qualifiers::Volatile | 8363 Qualifiers::Restrict))); 8364 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8365 } 8366 } 8367 8368 } 8369 8370 /// Helper to add an overload candidate for a binary builtin with types \p L 8371 /// and \p R. 8372 void AddCandidate(QualType L, QualType R) { 8373 QualType LandR[2] = {L, R}; 8374 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8375 } 8376 8377 public: 8378 BuiltinOperatorOverloadBuilder( 8379 Sema &S, ArrayRef<Expr *> Args, 8380 QualifiersAndAtomic VisibleTypeConversionsQuals, 8381 bool HasArithmeticOrEnumeralCandidateType, 8382 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8383 OverloadCandidateSet &CandidateSet) 8384 : S(S), Args(Args), 8385 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8386 HasArithmeticOrEnumeralCandidateType( 8387 HasArithmeticOrEnumeralCandidateType), 8388 CandidateTypes(CandidateTypes), 8389 CandidateSet(CandidateSet) { 8390 8391 InitArithmeticTypes(); 8392 } 8393 8394 // Increment is deprecated for bool since C++17. 8395 // 8396 // C++ [over.built]p3: 8397 // 8398 // For every pair (T, VQ), where T is an arithmetic type other 8399 // than bool, and VQ is either volatile or empty, there exist 8400 // candidate operator functions of the form 8401 // 8402 // VQ T& operator++(VQ T&); 8403 // T operator++(VQ T&, int); 8404 // 8405 // C++ [over.built]p4: 8406 // 8407 // For every pair (T, VQ), where T is an arithmetic type other 8408 // than bool, and VQ is either volatile or empty, there exist 8409 // candidate operator functions of the form 8410 // 8411 // VQ T& operator--(VQ T&); 8412 // T operator--(VQ T&, int); 8413 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8414 if (!HasArithmeticOrEnumeralCandidateType) 8415 return; 8416 8417 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8418 const auto TypeOfT = ArithmeticTypes[Arith]; 8419 if (TypeOfT == S.Context.BoolTy) { 8420 if (Op == OO_MinusMinus) 8421 continue; 8422 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8423 continue; 8424 } 8425 addPlusPlusMinusMinusStyleOverloads( 8426 TypeOfT, 8427 VisibleTypeConversionsQuals.hasVolatile(), 8428 VisibleTypeConversionsQuals.hasRestrict()); 8429 } 8430 } 8431 8432 // C++ [over.built]p5: 8433 // 8434 // For every pair (T, VQ), where T is a cv-qualified or 8435 // cv-unqualified object type, and VQ is either volatile or 8436 // empty, there exist candidate operator functions of the form 8437 // 8438 // T*VQ& operator++(T*VQ&); 8439 // T*VQ& operator--(T*VQ&); 8440 // T* operator++(T*VQ&, int); 8441 // T* operator--(T*VQ&, int); 8442 void addPlusPlusMinusMinusPointerOverloads() { 8443 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8444 // Skip pointer types that aren't pointers to object types. 8445 if (!PtrTy->getPointeeType()->isObjectType()) 8446 continue; 8447 8448 addPlusPlusMinusMinusStyleOverloads( 8449 PtrTy, 8450 (!PtrTy.isVolatileQualified() && 8451 VisibleTypeConversionsQuals.hasVolatile()), 8452 (!PtrTy.isRestrictQualified() && 8453 VisibleTypeConversionsQuals.hasRestrict())); 8454 } 8455 } 8456 8457 // C++ [over.built]p6: 8458 // For every cv-qualified or cv-unqualified object type T, there 8459 // exist candidate operator functions of the form 8460 // 8461 // T& operator*(T*); 8462 // 8463 // C++ [over.built]p7: 8464 // For every function type T that does not have cv-qualifiers or a 8465 // ref-qualifier, there exist candidate operator functions of the form 8466 // T& operator*(T*); 8467 void addUnaryStarPointerOverloads() { 8468 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8469 QualType PointeeTy = ParamTy->getPointeeType(); 8470 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8471 continue; 8472 8473 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8474 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8475 continue; 8476 8477 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8478 } 8479 } 8480 8481 // C++ [over.built]p9: 8482 // For every promoted arithmetic type T, there exist candidate 8483 // operator functions of the form 8484 // 8485 // T operator+(T); 8486 // T operator-(T); 8487 void addUnaryPlusOrMinusArithmeticOverloads() { 8488 if (!HasArithmeticOrEnumeralCandidateType) 8489 return; 8490 8491 for (unsigned Arith = FirstPromotedArithmeticType; 8492 Arith < LastPromotedArithmeticType; ++Arith) { 8493 QualType ArithTy = ArithmeticTypes[Arith]; 8494 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8495 } 8496 8497 // Extension: We also add these operators for vector types. 8498 for (QualType VecTy : CandidateTypes[0].vector_types()) 8499 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8500 } 8501 8502 // C++ [over.built]p8: 8503 // For every type T, there exist candidate operator functions of 8504 // the form 8505 // 8506 // T* operator+(T*); 8507 void addUnaryPlusPointerOverloads() { 8508 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8509 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8510 } 8511 8512 // C++ [over.built]p10: 8513 // For every promoted integral type T, there exist candidate 8514 // operator functions of the form 8515 // 8516 // T operator~(T); 8517 void addUnaryTildePromotedIntegralOverloads() { 8518 if (!HasArithmeticOrEnumeralCandidateType) 8519 return; 8520 8521 for (unsigned Int = FirstPromotedIntegralType; 8522 Int < LastPromotedIntegralType; ++Int) { 8523 QualType IntTy = ArithmeticTypes[Int]; 8524 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8525 } 8526 8527 // Extension: We also add this operator for vector types. 8528 for (QualType VecTy : CandidateTypes[0].vector_types()) 8529 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8530 } 8531 8532 // C++ [over.match.oper]p16: 8533 // For every pointer to member type T or type std::nullptr_t, there 8534 // exist candidate operator functions of the form 8535 // 8536 // bool operator==(T,T); 8537 // bool operator!=(T,T); 8538 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8539 /// Set of (canonical) types that we've already handled. 8540 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8541 8542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8543 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8544 // Don't add the same builtin candidate twice. 8545 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8546 continue; 8547 8548 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8549 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8550 } 8551 8552 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8553 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8554 if (AddedTypes.insert(NullPtrTy).second) { 8555 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8556 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8557 } 8558 } 8559 } 8560 } 8561 8562 // C++ [over.built]p15: 8563 // 8564 // For every T, where T is an enumeration type or a pointer type, 8565 // there exist candidate operator functions of the form 8566 // 8567 // bool operator<(T, T); 8568 // bool operator>(T, T); 8569 // bool operator<=(T, T); 8570 // bool operator>=(T, T); 8571 // bool operator==(T, T); 8572 // bool operator!=(T, T); 8573 // R operator<=>(T, T) 8574 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 8575 // C++ [over.match.oper]p3: 8576 // [...]the built-in candidates include all of the candidate operator 8577 // functions defined in 13.6 that, compared to the given operator, [...] 8578 // do not have the same parameter-type-list as any non-template non-member 8579 // candidate. 8580 // 8581 // Note that in practice, this only affects enumeration types because there 8582 // aren't any built-in candidates of record type, and a user-defined operator 8583 // must have an operand of record or enumeration type. Also, the only other 8584 // overloaded operator with enumeration arguments, operator=, 8585 // cannot be overloaded for enumeration types, so this is the only place 8586 // where we must suppress candidates like this. 8587 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8588 UserDefinedBinaryOperators; 8589 8590 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8591 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8592 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8593 CEnd = CandidateSet.end(); 8594 C != CEnd; ++C) { 8595 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8596 continue; 8597 8598 if (C->Function->isFunctionTemplateSpecialization()) 8599 continue; 8600 8601 // We interpret "same parameter-type-list" as applying to the 8602 // "synthesized candidate, with the order of the two parameters 8603 // reversed", not to the original function. 8604 bool Reversed = C->isReversed(); 8605 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8606 ->getType() 8607 .getUnqualifiedType(); 8608 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8609 ->getType() 8610 .getUnqualifiedType(); 8611 8612 // Skip if either parameter isn't of enumeral type. 8613 if (!FirstParamType->isEnumeralType() || 8614 !SecondParamType->isEnumeralType()) 8615 continue; 8616 8617 // Add this operator to the set of known user-defined operators. 8618 UserDefinedBinaryOperators.insert( 8619 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8620 S.Context.getCanonicalType(SecondParamType))); 8621 } 8622 } 8623 } 8624 8625 /// Set of (canonical) types that we've already handled. 8626 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8627 8628 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8629 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8630 // Don't add the same builtin candidate twice. 8631 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8632 continue; 8633 if (IsSpaceship && PtrTy->isFunctionPointerType()) 8634 continue; 8635 8636 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8637 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8638 } 8639 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8640 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8641 8642 // Don't add the same builtin candidate twice, or if a user defined 8643 // candidate exists. 8644 if (!AddedTypes.insert(CanonType).second || 8645 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8646 CanonType))) 8647 continue; 8648 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8650 } 8651 } 8652 } 8653 8654 // C++ [over.built]p13: 8655 // 8656 // For every cv-qualified or cv-unqualified object type T 8657 // there exist candidate operator functions of the form 8658 // 8659 // T* operator+(T*, ptrdiff_t); 8660 // T& operator[](T*, ptrdiff_t); [BELOW] 8661 // T* operator-(T*, ptrdiff_t); 8662 // T* operator+(ptrdiff_t, T*); 8663 // T& operator[](ptrdiff_t, T*); [BELOW] 8664 // 8665 // C++ [over.built]p14: 8666 // 8667 // For every T, where T is a pointer to object type, there 8668 // exist candidate operator functions of the form 8669 // 8670 // ptrdiff_t operator-(T, T); 8671 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8672 /// Set of (canonical) types that we've already handled. 8673 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8674 8675 for (int Arg = 0; Arg < 2; ++Arg) { 8676 QualType AsymmetricParamTypes[2] = { 8677 S.Context.getPointerDiffType(), 8678 S.Context.getPointerDiffType(), 8679 }; 8680 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8681 QualType PointeeTy = PtrTy->getPointeeType(); 8682 if (!PointeeTy->isObjectType()) 8683 continue; 8684 8685 AsymmetricParamTypes[Arg] = PtrTy; 8686 if (Arg == 0 || Op == OO_Plus) { 8687 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8688 // T* operator+(ptrdiff_t, T*); 8689 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8690 } 8691 if (Op == OO_Minus) { 8692 // ptrdiff_t operator-(T, T); 8693 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8694 continue; 8695 8696 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8697 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8698 } 8699 } 8700 } 8701 } 8702 8703 // C++ [over.built]p12: 8704 // 8705 // For every pair of promoted arithmetic types L and R, there 8706 // exist candidate operator functions of the form 8707 // 8708 // LR operator*(L, R); 8709 // LR operator/(L, R); 8710 // LR operator+(L, R); 8711 // LR operator-(L, R); 8712 // bool operator<(L, R); 8713 // bool operator>(L, R); 8714 // bool operator<=(L, R); 8715 // bool operator>=(L, R); 8716 // bool operator==(L, R); 8717 // bool operator!=(L, R); 8718 // 8719 // where LR is the result of the usual arithmetic conversions 8720 // between types L and R. 8721 // 8722 // C++ [over.built]p24: 8723 // 8724 // For every pair of promoted arithmetic types L and R, there exist 8725 // candidate operator functions of the form 8726 // 8727 // LR operator?(bool, L, R); 8728 // 8729 // where LR is the result of the usual arithmetic conversions 8730 // between types L and R. 8731 // Our candidates ignore the first parameter. 8732 void addGenericBinaryArithmeticOverloads() { 8733 if (!HasArithmeticOrEnumeralCandidateType) 8734 return; 8735 8736 for (unsigned Left = FirstPromotedArithmeticType; 8737 Left < LastPromotedArithmeticType; ++Left) { 8738 for (unsigned Right = FirstPromotedArithmeticType; 8739 Right < LastPromotedArithmeticType; ++Right) { 8740 QualType LandR[2] = { ArithmeticTypes[Left], 8741 ArithmeticTypes[Right] }; 8742 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8743 } 8744 } 8745 8746 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8747 // conditional operator for vector types. 8748 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8749 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8750 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8751 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8752 } 8753 } 8754 8755 /// Add binary operator overloads for each candidate matrix type M1, M2: 8756 /// * (M1, M1) -> M1 8757 /// * (M1, M1.getElementType()) -> M1 8758 /// * (M2.getElementType(), M2) -> M2 8759 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8760 void addMatrixBinaryArithmeticOverloads() { 8761 if (!HasArithmeticOrEnumeralCandidateType) 8762 return; 8763 8764 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8765 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8766 AddCandidate(M1, M1); 8767 } 8768 8769 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8770 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8771 if (!CandidateTypes[0].containsMatrixType(M2)) 8772 AddCandidate(M2, M2); 8773 } 8774 } 8775 8776 // C++2a [over.built]p14: 8777 // 8778 // For every integral type T there exists a candidate operator function 8779 // of the form 8780 // 8781 // std::strong_ordering operator<=>(T, T) 8782 // 8783 // C++2a [over.built]p15: 8784 // 8785 // For every pair of floating-point types L and R, there exists a candidate 8786 // operator function of the form 8787 // 8788 // std::partial_ordering operator<=>(L, R); 8789 // 8790 // FIXME: The current specification for integral types doesn't play nice with 8791 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8792 // comparisons. Under the current spec this can lead to ambiguity during 8793 // overload resolution. For example: 8794 // 8795 // enum A : int {a}; 8796 // auto x = (a <=> (long)42); 8797 // 8798 // error: call is ambiguous for arguments 'A' and 'long'. 8799 // note: candidate operator<=>(int, int) 8800 // note: candidate operator<=>(long, long) 8801 // 8802 // To avoid this error, this function deviates from the specification and adds 8803 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8804 // arithmetic types (the same as the generic relational overloads). 8805 // 8806 // For now this function acts as a placeholder. 8807 void addThreeWayArithmeticOverloads() { 8808 addGenericBinaryArithmeticOverloads(); 8809 } 8810 8811 // C++ [over.built]p17: 8812 // 8813 // For every pair of promoted integral types L and R, there 8814 // exist candidate operator functions of the form 8815 // 8816 // LR operator%(L, R); 8817 // LR operator&(L, R); 8818 // LR operator^(L, R); 8819 // LR operator|(L, R); 8820 // L operator<<(L, R); 8821 // L operator>>(L, R); 8822 // 8823 // where LR is the result of the usual arithmetic conversions 8824 // between types L and R. 8825 void addBinaryBitwiseArithmeticOverloads() { 8826 if (!HasArithmeticOrEnumeralCandidateType) 8827 return; 8828 8829 for (unsigned Left = FirstPromotedIntegralType; 8830 Left < LastPromotedIntegralType; ++Left) { 8831 for (unsigned Right = FirstPromotedIntegralType; 8832 Right < LastPromotedIntegralType; ++Right) { 8833 QualType LandR[2] = { ArithmeticTypes[Left], 8834 ArithmeticTypes[Right] }; 8835 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8836 } 8837 } 8838 } 8839 8840 // C++ [over.built]p20: 8841 // 8842 // For every pair (T, VQ), where T is an enumeration or 8843 // pointer to member type and VQ is either volatile or 8844 // empty, there exist candidate operator functions of the form 8845 // 8846 // VQ T& operator=(VQ T&, T); 8847 void addAssignmentMemberPointerOrEnumeralOverloads() { 8848 /// Set of (canonical) types that we've already handled. 8849 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8850 8851 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8852 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8853 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8854 continue; 8855 8856 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8857 } 8858 8859 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8860 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8861 continue; 8862 8863 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8864 } 8865 } 8866 } 8867 8868 // C++ [over.built]p19: 8869 // 8870 // For every pair (T, VQ), where T is any type and VQ is either 8871 // volatile or empty, there exist candidate operator functions 8872 // of the form 8873 // 8874 // T*VQ& operator=(T*VQ&, T*); 8875 // 8876 // C++ [over.built]p21: 8877 // 8878 // For every pair (T, VQ), where T is a cv-qualified or 8879 // cv-unqualified object type and VQ is either volatile or 8880 // empty, there exist candidate operator functions of the form 8881 // 8882 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8883 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8884 void addAssignmentPointerOverloads(bool isEqualOp) { 8885 /// Set of (canonical) types that we've already handled. 8886 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8887 8888 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8889 // If this is operator=, keep track of the builtin candidates we added. 8890 if (isEqualOp) 8891 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8892 else if (!PtrTy->getPointeeType()->isObjectType()) 8893 continue; 8894 8895 // non-volatile version 8896 QualType ParamTypes[2] = { 8897 S.Context.getLValueReferenceType(PtrTy), 8898 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8899 }; 8900 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8901 /*IsAssignmentOperator=*/ isEqualOp); 8902 8903 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8904 VisibleTypeConversionsQuals.hasVolatile(); 8905 if (NeedVolatile) { 8906 // volatile version 8907 ParamTypes[0] = 8908 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8909 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8910 /*IsAssignmentOperator=*/isEqualOp); 8911 } 8912 8913 if (!PtrTy.isRestrictQualified() && 8914 VisibleTypeConversionsQuals.hasRestrict()) { 8915 // restrict version 8916 ParamTypes[0] = 8917 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8918 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8919 /*IsAssignmentOperator=*/isEqualOp); 8920 8921 if (NeedVolatile) { 8922 // volatile restrict version 8923 ParamTypes[0] = 8924 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8925 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8926 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8927 /*IsAssignmentOperator=*/isEqualOp); 8928 } 8929 } 8930 } 8931 8932 if (isEqualOp) { 8933 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8934 // Make sure we don't add the same candidate twice. 8935 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8936 continue; 8937 8938 QualType ParamTypes[2] = { 8939 S.Context.getLValueReferenceType(PtrTy), 8940 PtrTy, 8941 }; 8942 8943 // non-volatile version 8944 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8945 /*IsAssignmentOperator=*/true); 8946 8947 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8948 VisibleTypeConversionsQuals.hasVolatile(); 8949 if (NeedVolatile) { 8950 // volatile version 8951 ParamTypes[0] = S.Context.getLValueReferenceType( 8952 S.Context.getVolatileType(PtrTy)); 8953 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8954 /*IsAssignmentOperator=*/true); 8955 } 8956 8957 if (!PtrTy.isRestrictQualified() && 8958 VisibleTypeConversionsQuals.hasRestrict()) { 8959 // restrict version 8960 ParamTypes[0] = S.Context.getLValueReferenceType( 8961 S.Context.getRestrictType(PtrTy)); 8962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8963 /*IsAssignmentOperator=*/true); 8964 8965 if (NeedVolatile) { 8966 // volatile restrict version 8967 ParamTypes[0] = 8968 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8969 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8970 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8971 /*IsAssignmentOperator=*/true); 8972 } 8973 } 8974 } 8975 } 8976 } 8977 8978 // C++ [over.built]p18: 8979 // 8980 // For every triple (L, VQ, R), where L is an arithmetic type, 8981 // VQ is either volatile or empty, and R is a promoted 8982 // arithmetic type, there exist candidate operator functions of 8983 // the form 8984 // 8985 // VQ L& operator=(VQ L&, R); 8986 // VQ L& operator*=(VQ L&, R); 8987 // VQ L& operator/=(VQ L&, R); 8988 // VQ L& operator+=(VQ L&, R); 8989 // VQ L& operator-=(VQ L&, R); 8990 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8991 if (!HasArithmeticOrEnumeralCandidateType) 8992 return; 8993 8994 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8995 for (unsigned Right = FirstPromotedArithmeticType; 8996 Right < LastPromotedArithmeticType; ++Right) { 8997 QualType ParamTypes[2]; 8998 ParamTypes[1] = ArithmeticTypes[Right]; 8999 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9000 S, ArithmeticTypes[Left], Args[0]); 9001 9002 forAllQualifierCombinations( 9003 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9004 ParamTypes[0] = 9005 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9007 /*IsAssignmentOperator=*/isEqualOp); 9008 }); 9009 } 9010 } 9011 9012 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 9013 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9014 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 9015 QualType ParamTypes[2]; 9016 ParamTypes[1] = Vec2Ty; 9017 // Add this built-in operator as a candidate (VQ is empty). 9018 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 9019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9020 /*IsAssignmentOperator=*/isEqualOp); 9021 9022 // Add this built-in operator as a candidate (VQ is 'volatile'). 9023 if (VisibleTypeConversionsQuals.hasVolatile()) { 9024 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 9025 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9026 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9027 /*IsAssignmentOperator=*/isEqualOp); 9028 } 9029 } 9030 } 9031 9032 // C++ [over.built]p22: 9033 // 9034 // For every triple (L, VQ, R), where L is an integral type, VQ 9035 // is either volatile or empty, and R is a promoted integral 9036 // type, there exist candidate operator functions of the form 9037 // 9038 // VQ L& operator%=(VQ L&, R); 9039 // VQ L& operator<<=(VQ L&, R); 9040 // VQ L& operator>>=(VQ L&, R); 9041 // VQ L& operator&=(VQ L&, R); 9042 // VQ L& operator^=(VQ L&, R); 9043 // VQ L& operator|=(VQ L&, R); 9044 void addAssignmentIntegralOverloads() { 9045 if (!HasArithmeticOrEnumeralCandidateType) 9046 return; 9047 9048 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9049 for (unsigned Right = FirstPromotedIntegralType; 9050 Right < LastPromotedIntegralType; ++Right) { 9051 QualType ParamTypes[2]; 9052 ParamTypes[1] = ArithmeticTypes[Right]; 9053 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9054 S, ArithmeticTypes[Left], Args[0]); 9055 9056 forAllQualifierCombinations( 9057 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9058 ParamTypes[0] = 9059 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9061 }); 9062 } 9063 } 9064 } 9065 9066 // C++ [over.operator]p23: 9067 // 9068 // There also exist candidate operator functions of the form 9069 // 9070 // bool operator!(bool); 9071 // bool operator&&(bool, bool); 9072 // bool operator||(bool, bool); 9073 void addExclaimOverload() { 9074 QualType ParamTy = S.Context.BoolTy; 9075 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9076 /*IsAssignmentOperator=*/false, 9077 /*NumContextualBoolArguments=*/1); 9078 } 9079 void addAmpAmpOrPipePipeOverload() { 9080 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9081 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9082 /*IsAssignmentOperator=*/false, 9083 /*NumContextualBoolArguments=*/2); 9084 } 9085 9086 // C++ [over.built]p13: 9087 // 9088 // For every cv-qualified or cv-unqualified object type T there 9089 // exist candidate operator functions of the form 9090 // 9091 // T* operator+(T*, ptrdiff_t); [ABOVE] 9092 // T& operator[](T*, ptrdiff_t); 9093 // T* operator-(T*, ptrdiff_t); [ABOVE] 9094 // T* operator+(ptrdiff_t, T*); [ABOVE] 9095 // T& operator[](ptrdiff_t, T*); 9096 void addSubscriptOverloads() { 9097 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9098 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9099 QualType PointeeType = PtrTy->getPointeeType(); 9100 if (!PointeeType->isObjectType()) 9101 continue; 9102 9103 // T& operator[](T*, ptrdiff_t) 9104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9105 } 9106 9107 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9108 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9109 QualType PointeeType = PtrTy->getPointeeType(); 9110 if (!PointeeType->isObjectType()) 9111 continue; 9112 9113 // T& operator[](ptrdiff_t, T*) 9114 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9115 } 9116 } 9117 9118 // C++ [over.built]p11: 9119 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9120 // C1 is the same type as C2 or is a derived class of C2, T is an object 9121 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9122 // there exist candidate operator functions of the form 9123 // 9124 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9125 // 9126 // where CV12 is the union of CV1 and CV2. 9127 void addArrowStarOverloads() { 9128 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9129 QualType C1Ty = PtrTy; 9130 QualType C1; 9131 QualifierCollector Q1; 9132 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9133 if (!isa<RecordType>(C1)) 9134 continue; 9135 // heuristic to reduce number of builtin candidates in the set. 9136 // Add volatile/restrict version only if there are conversions to a 9137 // volatile/restrict type. 9138 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9139 continue; 9140 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9141 continue; 9142 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9143 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9144 QualType C2 = QualType(mptr->getClass(), 0); 9145 C2 = C2.getUnqualifiedType(); 9146 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9147 break; 9148 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9149 // build CV12 T& 9150 QualType T = mptr->getPointeeType(); 9151 if (!VisibleTypeConversionsQuals.hasVolatile() && 9152 T.isVolatileQualified()) 9153 continue; 9154 if (!VisibleTypeConversionsQuals.hasRestrict() && 9155 T.isRestrictQualified()) 9156 continue; 9157 T = Q1.apply(S.Context, T); 9158 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9159 } 9160 } 9161 } 9162 9163 // Note that we don't consider the first argument, since it has been 9164 // contextually converted to bool long ago. The candidates below are 9165 // therefore added as binary. 9166 // 9167 // C++ [over.built]p25: 9168 // For every type T, where T is a pointer, pointer-to-member, or scoped 9169 // enumeration type, there exist candidate operator functions of the form 9170 // 9171 // T operator?(bool, T, T); 9172 // 9173 void addConditionalOperatorOverloads() { 9174 /// Set of (canonical) types that we've already handled. 9175 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9176 9177 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9178 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9179 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9180 continue; 9181 9182 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9183 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9184 } 9185 9186 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9187 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9188 continue; 9189 9190 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9191 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9192 } 9193 9194 if (S.getLangOpts().CPlusPlus11) { 9195 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9196 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9197 continue; 9198 9199 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9200 continue; 9201 9202 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9203 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9204 } 9205 } 9206 } 9207 } 9208 }; 9209 9210 } // end anonymous namespace 9211 9212 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9213 /// operator overloads to the candidate set (C++ [over.built]), based 9214 /// on the operator @p Op and the arguments given. For example, if the 9215 /// operator is a binary '+', this routine might add "int 9216 /// operator+(int, int)" to cover integer addition. 9217 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9218 SourceLocation OpLoc, 9219 ArrayRef<Expr *> Args, 9220 OverloadCandidateSet &CandidateSet) { 9221 // Find all of the types that the arguments can convert to, but only 9222 // if the operator we're looking at has built-in operator candidates 9223 // that make use of these types. Also record whether we encounter non-record 9224 // candidate types or either arithmetic or enumeral candidate types. 9225 QualifiersAndAtomic VisibleTypeConversionsQuals; 9226 VisibleTypeConversionsQuals.addConst(); 9227 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9228 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9229 if (Args[ArgIdx]->getType()->isAtomicType()) 9230 VisibleTypeConversionsQuals.addAtomic(); 9231 } 9232 9233 bool HasNonRecordCandidateType = false; 9234 bool HasArithmeticOrEnumeralCandidateType = false; 9235 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9236 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9237 CandidateTypes.emplace_back(*this); 9238 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9239 OpLoc, 9240 true, 9241 (Op == OO_Exclaim || 9242 Op == OO_AmpAmp || 9243 Op == OO_PipePipe), 9244 VisibleTypeConversionsQuals); 9245 HasNonRecordCandidateType = HasNonRecordCandidateType || 9246 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9247 HasArithmeticOrEnumeralCandidateType = 9248 HasArithmeticOrEnumeralCandidateType || 9249 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9250 } 9251 9252 // Exit early when no non-record types have been added to the candidate set 9253 // for any of the arguments to the operator. 9254 // 9255 // We can't exit early for !, ||, or &&, since there we have always have 9256 // 'bool' overloads. 9257 if (!HasNonRecordCandidateType && 9258 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9259 return; 9260 9261 // Setup an object to manage the common state for building overloads. 9262 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9263 VisibleTypeConversionsQuals, 9264 HasArithmeticOrEnumeralCandidateType, 9265 CandidateTypes, CandidateSet); 9266 9267 // Dispatch over the operation to add in only those overloads which apply. 9268 switch (Op) { 9269 case OO_None: 9270 case NUM_OVERLOADED_OPERATORS: 9271 llvm_unreachable("Expected an overloaded operator"); 9272 9273 case OO_New: 9274 case OO_Delete: 9275 case OO_Array_New: 9276 case OO_Array_Delete: 9277 case OO_Call: 9278 llvm_unreachable( 9279 "Special operators don't use AddBuiltinOperatorCandidates"); 9280 9281 case OO_Comma: 9282 case OO_Arrow: 9283 case OO_Coawait: 9284 // C++ [over.match.oper]p3: 9285 // -- For the operator ',', the unary operator '&', the 9286 // operator '->', or the operator 'co_await', the 9287 // built-in candidates set is empty. 9288 break; 9289 9290 case OO_Plus: // '+' is either unary or binary 9291 if (Args.size() == 1) 9292 OpBuilder.addUnaryPlusPointerOverloads(); 9293 LLVM_FALLTHROUGH; 9294 9295 case OO_Minus: // '-' is either unary or binary 9296 if (Args.size() == 1) { 9297 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9298 } else { 9299 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9300 OpBuilder.addGenericBinaryArithmeticOverloads(); 9301 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9302 } 9303 break; 9304 9305 case OO_Star: // '*' is either unary or binary 9306 if (Args.size() == 1) 9307 OpBuilder.addUnaryStarPointerOverloads(); 9308 else { 9309 OpBuilder.addGenericBinaryArithmeticOverloads(); 9310 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9311 } 9312 break; 9313 9314 case OO_Slash: 9315 OpBuilder.addGenericBinaryArithmeticOverloads(); 9316 break; 9317 9318 case OO_PlusPlus: 9319 case OO_MinusMinus: 9320 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9321 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9322 break; 9323 9324 case OO_EqualEqual: 9325 case OO_ExclaimEqual: 9326 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9327 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9328 OpBuilder.addGenericBinaryArithmeticOverloads(); 9329 break; 9330 9331 case OO_Less: 9332 case OO_Greater: 9333 case OO_LessEqual: 9334 case OO_GreaterEqual: 9335 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9336 OpBuilder.addGenericBinaryArithmeticOverloads(); 9337 break; 9338 9339 case OO_Spaceship: 9340 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9341 OpBuilder.addThreeWayArithmeticOverloads(); 9342 break; 9343 9344 case OO_Percent: 9345 case OO_Caret: 9346 case OO_Pipe: 9347 case OO_LessLess: 9348 case OO_GreaterGreater: 9349 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9350 break; 9351 9352 case OO_Amp: // '&' is either unary or binary 9353 if (Args.size() == 1) 9354 // C++ [over.match.oper]p3: 9355 // -- For the operator ',', the unary operator '&', or the 9356 // operator '->', the built-in candidates set is empty. 9357 break; 9358 9359 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9360 break; 9361 9362 case OO_Tilde: 9363 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9364 break; 9365 9366 case OO_Equal: 9367 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9368 LLVM_FALLTHROUGH; 9369 9370 case OO_PlusEqual: 9371 case OO_MinusEqual: 9372 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9373 LLVM_FALLTHROUGH; 9374 9375 case OO_StarEqual: 9376 case OO_SlashEqual: 9377 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9378 break; 9379 9380 case OO_PercentEqual: 9381 case OO_LessLessEqual: 9382 case OO_GreaterGreaterEqual: 9383 case OO_AmpEqual: 9384 case OO_CaretEqual: 9385 case OO_PipeEqual: 9386 OpBuilder.addAssignmentIntegralOverloads(); 9387 break; 9388 9389 case OO_Exclaim: 9390 OpBuilder.addExclaimOverload(); 9391 break; 9392 9393 case OO_AmpAmp: 9394 case OO_PipePipe: 9395 OpBuilder.addAmpAmpOrPipePipeOverload(); 9396 break; 9397 9398 case OO_Subscript: 9399 if (Args.size() == 2) 9400 OpBuilder.addSubscriptOverloads(); 9401 break; 9402 9403 case OO_ArrowStar: 9404 OpBuilder.addArrowStarOverloads(); 9405 break; 9406 9407 case OO_Conditional: 9408 OpBuilder.addConditionalOperatorOverloads(); 9409 OpBuilder.addGenericBinaryArithmeticOverloads(); 9410 break; 9411 } 9412 } 9413 9414 /// Add function candidates found via argument-dependent lookup 9415 /// to the set of overloading candidates. 9416 /// 9417 /// This routine performs argument-dependent name lookup based on the 9418 /// given function name (which may also be an operator name) and adds 9419 /// all of the overload candidates found by ADL to the overload 9420 /// candidate set (C++ [basic.lookup.argdep]). 9421 void 9422 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9423 SourceLocation Loc, 9424 ArrayRef<Expr *> Args, 9425 TemplateArgumentListInfo *ExplicitTemplateArgs, 9426 OverloadCandidateSet& CandidateSet, 9427 bool PartialOverloading) { 9428 ADLResult Fns; 9429 9430 // FIXME: This approach for uniquing ADL results (and removing 9431 // redundant candidates from the set) relies on pointer-equality, 9432 // which means we need to key off the canonical decl. However, 9433 // always going back to the canonical decl might not get us the 9434 // right set of default arguments. What default arguments are 9435 // we supposed to consider on ADL candidates, anyway? 9436 9437 // FIXME: Pass in the explicit template arguments? 9438 ArgumentDependentLookup(Name, Loc, Args, Fns); 9439 9440 // Erase all of the candidates we already knew about. 9441 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9442 CandEnd = CandidateSet.end(); 9443 Cand != CandEnd; ++Cand) 9444 if (Cand->Function) { 9445 Fns.erase(Cand->Function); 9446 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9447 Fns.erase(FunTmpl); 9448 } 9449 9450 // For each of the ADL candidates we found, add it to the overload 9451 // set. 9452 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9453 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9454 9455 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9456 if (ExplicitTemplateArgs) 9457 continue; 9458 9459 AddOverloadCandidate( 9460 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9461 PartialOverloading, /*AllowExplicit=*/true, 9462 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9463 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9464 AddOverloadCandidate( 9465 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9466 /*SuppressUserConversions=*/false, PartialOverloading, 9467 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9468 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9469 } 9470 } else { 9471 auto *FTD = cast<FunctionTemplateDecl>(*I); 9472 AddTemplateOverloadCandidate( 9473 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9474 /*SuppressUserConversions=*/false, PartialOverloading, 9475 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9476 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9477 Context, FTD->getTemplatedDecl())) { 9478 AddTemplateOverloadCandidate( 9479 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9480 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9481 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9482 OverloadCandidateParamOrder::Reversed); 9483 } 9484 } 9485 } 9486 } 9487 9488 namespace { 9489 enum class Comparison { Equal, Better, Worse }; 9490 } 9491 9492 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9493 /// overload resolution. 9494 /// 9495 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9496 /// Cand1's first N enable_if attributes have precisely the same conditions as 9497 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9498 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9499 /// 9500 /// Note that you can have a pair of candidates such that Cand1's enable_if 9501 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9502 /// worse than Cand1's. 9503 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9504 const FunctionDecl *Cand2) { 9505 // Common case: One (or both) decls don't have enable_if attrs. 9506 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9507 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9508 if (!Cand1Attr || !Cand2Attr) { 9509 if (Cand1Attr == Cand2Attr) 9510 return Comparison::Equal; 9511 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9512 } 9513 9514 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9515 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9516 9517 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9518 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9519 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9520 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9521 9522 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9523 // has fewer enable_if attributes than Cand2, and vice versa. 9524 if (!Cand1A) 9525 return Comparison::Worse; 9526 if (!Cand2A) 9527 return Comparison::Better; 9528 9529 Cand1ID.clear(); 9530 Cand2ID.clear(); 9531 9532 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9533 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9534 if (Cand1ID != Cand2ID) 9535 return Comparison::Worse; 9536 } 9537 9538 return Comparison::Equal; 9539 } 9540 9541 static Comparison 9542 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9543 const OverloadCandidate &Cand2) { 9544 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9545 !Cand2.Function->isMultiVersion()) 9546 return Comparison::Equal; 9547 9548 // If both are invalid, they are equal. If one of them is invalid, the other 9549 // is better. 9550 if (Cand1.Function->isInvalidDecl()) { 9551 if (Cand2.Function->isInvalidDecl()) 9552 return Comparison::Equal; 9553 return Comparison::Worse; 9554 } 9555 if (Cand2.Function->isInvalidDecl()) 9556 return Comparison::Better; 9557 9558 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9559 // cpu_dispatch, else arbitrarily based on the identifiers. 9560 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9561 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9562 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9563 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9564 9565 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9566 return Comparison::Equal; 9567 9568 if (Cand1CPUDisp && !Cand2CPUDisp) 9569 return Comparison::Better; 9570 if (Cand2CPUDisp && !Cand1CPUDisp) 9571 return Comparison::Worse; 9572 9573 if (Cand1CPUSpec && Cand2CPUSpec) { 9574 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9575 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9576 ? Comparison::Better 9577 : Comparison::Worse; 9578 9579 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9580 FirstDiff = std::mismatch( 9581 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9582 Cand2CPUSpec->cpus_begin(), 9583 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9584 return LHS->getName() == RHS->getName(); 9585 }); 9586 9587 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9588 "Two different cpu-specific versions should not have the same " 9589 "identifier list, otherwise they'd be the same decl!"); 9590 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9591 ? Comparison::Better 9592 : Comparison::Worse; 9593 } 9594 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9595 } 9596 9597 /// Compute the type of the implicit object parameter for the given function, 9598 /// if any. Returns None if there is no implicit object parameter, and a null 9599 /// QualType if there is a 'matches anything' implicit object parameter. 9600 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9601 const FunctionDecl *F) { 9602 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9603 return llvm::None; 9604 9605 auto *M = cast<CXXMethodDecl>(F); 9606 // Static member functions' object parameters match all types. 9607 if (M->isStatic()) 9608 return QualType(); 9609 9610 QualType T = M->getThisObjectType(); 9611 if (M->getRefQualifier() == RQ_RValue) 9612 return Context.getRValueReferenceType(T); 9613 return Context.getLValueReferenceType(T); 9614 } 9615 9616 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9617 const FunctionDecl *F2, unsigned NumParams) { 9618 if (declaresSameEntity(F1, F2)) 9619 return true; 9620 9621 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9622 if (First) { 9623 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9624 return *T; 9625 } 9626 assert(I < F->getNumParams()); 9627 return F->getParamDecl(I++)->getType(); 9628 }; 9629 9630 unsigned I1 = 0, I2 = 0; 9631 for (unsigned I = 0; I != NumParams; ++I) { 9632 QualType T1 = NextParam(F1, I1, I == 0); 9633 QualType T2 = NextParam(F2, I2, I == 0); 9634 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 9635 if (!Context.hasSameUnqualifiedType(T1, T2)) 9636 return false; 9637 } 9638 return true; 9639 } 9640 9641 /// We're allowed to use constraints partial ordering only if the candidates 9642 /// have the same parameter types: 9643 /// [temp.func.order]p6.2.2 [...] or if the function parameters that 9644 /// positionally correspond between the two templates are not of the same type, 9645 /// neither template is more specialized than the other. 9646 /// [over.match.best]p2.6 9647 /// F1 and F2 are non-template functions with the same parameter-type-lists, 9648 /// and F1 is more constrained than F2 [...] 9649 static bool canCompareFunctionConstraints(Sema &S, 9650 const OverloadCandidate &Cand1, 9651 const OverloadCandidate &Cand2) { 9652 // FIXME: Per P2113R0 we also need to compare the template parameter lists 9653 // when comparing template functions. 9654 if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() && 9655 Cand2.Function->hasPrototype()) { 9656 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9657 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9658 if (PT1->getNumParams() == PT2->getNumParams() && 9659 PT1->isVariadic() == PT2->isVariadic() && 9660 S.FunctionParamTypesAreEqual(PT1, PT2, nullptr, 9661 Cand1.isReversed() ^ Cand2.isReversed())) 9662 return true; 9663 } 9664 return false; 9665 } 9666 9667 /// isBetterOverloadCandidate - Determines whether the first overload 9668 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9669 bool clang::isBetterOverloadCandidate( 9670 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9671 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9672 // Define viable functions to be better candidates than non-viable 9673 // functions. 9674 if (!Cand2.Viable) 9675 return Cand1.Viable; 9676 else if (!Cand1.Viable) 9677 return false; 9678 9679 // [CUDA] A function with 'never' preference is marked not viable, therefore 9680 // is never shown up here. The worst preference shown up here is 'wrong side', 9681 // e.g. an H function called by a HD function in device compilation. This is 9682 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9683 // function which is called only by an H function. A deferred diagnostic will 9684 // be triggered if it is emitted. However a wrong-sided function is still 9685 // a viable candidate here. 9686 // 9687 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9688 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9689 // can be emitted, Cand1 is not better than Cand2. This rule should have 9690 // precedence over other rules. 9691 // 9692 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9693 // other rules should be used to determine which is better. This is because 9694 // host/device based overloading resolution is mostly for determining 9695 // viability of a function. If two functions are both viable, other factors 9696 // should take precedence in preference, e.g. the standard-defined preferences 9697 // like argument conversion ranks or enable_if partial-ordering. The 9698 // preference for pass-object-size parameters is probably most similar to a 9699 // type-based-overloading decision and so should take priority. 9700 // 9701 // If other rules cannot determine which is better, CUDA preference will be 9702 // used again to determine which is better. 9703 // 9704 // TODO: Currently IdentifyCUDAPreference does not return correct values 9705 // for functions called in global variable initializers due to missing 9706 // correct context about device/host. Therefore we can only enforce this 9707 // rule when there is a caller. We should enforce this rule for functions 9708 // in global variable initializers once proper context is added. 9709 // 9710 // TODO: We can only enable the hostness based overloading resolution when 9711 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9712 // overloading resolution diagnostics. 9713 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9714 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9715 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { 9716 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9717 bool IsCand1ImplicitHD = 9718 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9719 bool IsCand2ImplicitHD = 9720 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9721 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9722 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9723 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9724 // The implicit HD function may be a function in a system header which 9725 // is forced by pragma. In device compilation, if we prefer HD candidates 9726 // over wrong-sided candidates, overloading resolution may change, which 9727 // may result in non-deferrable diagnostics. As a workaround, we let 9728 // implicit HD candidates take equal preference as wrong-sided candidates. 9729 // This will preserve the overloading resolution. 9730 // TODO: We still need special handling of implicit HD functions since 9731 // they may incur other diagnostics to be deferred. We should make all 9732 // host/device related diagnostics deferrable and remove special handling 9733 // of implicit HD functions. 9734 auto EmitThreshold = 9735 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9736 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9737 ? Sema::CFP_Never 9738 : Sema::CFP_WrongSide; 9739 auto Cand1Emittable = P1 > EmitThreshold; 9740 auto Cand2Emittable = P2 > EmitThreshold; 9741 if (Cand1Emittable && !Cand2Emittable) 9742 return true; 9743 if (!Cand1Emittable && Cand2Emittable) 9744 return false; 9745 } 9746 } 9747 9748 // C++ [over.match.best]p1: 9749 // 9750 // -- if F is a static member function, ICS1(F) is defined such 9751 // that ICS1(F) is neither better nor worse than ICS1(G) for 9752 // any function G, and, symmetrically, ICS1(G) is neither 9753 // better nor worse than ICS1(F). 9754 unsigned StartArg = 0; 9755 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9756 StartArg = 1; 9757 9758 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9759 // We don't allow incompatible pointer conversions in C++. 9760 if (!S.getLangOpts().CPlusPlus) 9761 return ICS.isStandard() && 9762 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9763 9764 // The only ill-formed conversion we allow in C++ is the string literal to 9765 // char* conversion, which is only considered ill-formed after C++11. 9766 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9767 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9768 }; 9769 9770 // Define functions that don't require ill-formed conversions for a given 9771 // argument to be better candidates than functions that do. 9772 unsigned NumArgs = Cand1.Conversions.size(); 9773 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9774 bool HasBetterConversion = false; 9775 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9776 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9777 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9778 if (Cand1Bad != Cand2Bad) { 9779 if (Cand1Bad) 9780 return false; 9781 HasBetterConversion = true; 9782 } 9783 } 9784 9785 if (HasBetterConversion) 9786 return true; 9787 9788 // C++ [over.match.best]p1: 9789 // A viable function F1 is defined to be a better function than another 9790 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9791 // conversion sequence than ICSi(F2), and then... 9792 bool HasWorseConversion = false; 9793 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9794 switch (CompareImplicitConversionSequences(S, Loc, 9795 Cand1.Conversions[ArgIdx], 9796 Cand2.Conversions[ArgIdx])) { 9797 case ImplicitConversionSequence::Better: 9798 // Cand1 has a better conversion sequence. 9799 HasBetterConversion = true; 9800 break; 9801 9802 case ImplicitConversionSequence::Worse: 9803 if (Cand1.Function && Cand2.Function && 9804 Cand1.isReversed() != Cand2.isReversed() && 9805 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9806 NumArgs)) { 9807 // Work around large-scale breakage caused by considering reversed 9808 // forms of operator== in C++20: 9809 // 9810 // When comparing a function against a reversed function with the same 9811 // parameter types, if we have a better conversion for one argument and 9812 // a worse conversion for the other, the implicit conversion sequences 9813 // are treated as being equally good. 9814 // 9815 // This prevents a comparison function from being considered ambiguous 9816 // with a reversed form that is written in the same way. 9817 // 9818 // We diagnose this as an extension from CreateOverloadedBinOp. 9819 HasWorseConversion = true; 9820 break; 9821 } 9822 9823 // Cand1 can't be better than Cand2. 9824 return false; 9825 9826 case ImplicitConversionSequence::Indistinguishable: 9827 // Do nothing. 9828 break; 9829 } 9830 } 9831 9832 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9833 // ICSj(F2), or, if not that, 9834 if (HasBetterConversion && !HasWorseConversion) 9835 return true; 9836 9837 // -- the context is an initialization by user-defined conversion 9838 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9839 // from the return type of F1 to the destination type (i.e., 9840 // the type of the entity being initialized) is a better 9841 // conversion sequence than the standard conversion sequence 9842 // from the return type of F2 to the destination type. 9843 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9844 Cand1.Function && Cand2.Function && 9845 isa<CXXConversionDecl>(Cand1.Function) && 9846 isa<CXXConversionDecl>(Cand2.Function)) { 9847 // First check whether we prefer one of the conversion functions over the 9848 // other. This only distinguishes the results in non-standard, extension 9849 // cases such as the conversion from a lambda closure type to a function 9850 // pointer or block. 9851 ImplicitConversionSequence::CompareKind Result = 9852 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9853 if (Result == ImplicitConversionSequence::Indistinguishable) 9854 Result = CompareStandardConversionSequences(S, Loc, 9855 Cand1.FinalConversion, 9856 Cand2.FinalConversion); 9857 9858 if (Result != ImplicitConversionSequence::Indistinguishable) 9859 return Result == ImplicitConversionSequence::Better; 9860 9861 // FIXME: Compare kind of reference binding if conversion functions 9862 // convert to a reference type used in direct reference binding, per 9863 // C++14 [over.match.best]p1 section 2 bullet 3. 9864 } 9865 9866 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9867 // as combined with the resolution to CWG issue 243. 9868 // 9869 // When the context is initialization by constructor ([over.match.ctor] or 9870 // either phase of [over.match.list]), a constructor is preferred over 9871 // a conversion function. 9872 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9873 Cand1.Function && Cand2.Function && 9874 isa<CXXConstructorDecl>(Cand1.Function) != 9875 isa<CXXConstructorDecl>(Cand2.Function)) 9876 return isa<CXXConstructorDecl>(Cand1.Function); 9877 9878 // -- F1 is a non-template function and F2 is a function template 9879 // specialization, or, if not that, 9880 bool Cand1IsSpecialization = Cand1.Function && 9881 Cand1.Function->getPrimaryTemplate(); 9882 bool Cand2IsSpecialization = Cand2.Function && 9883 Cand2.Function->getPrimaryTemplate(); 9884 if (Cand1IsSpecialization != Cand2IsSpecialization) 9885 return Cand2IsSpecialization; 9886 9887 // -- F1 and F2 are function template specializations, and the function 9888 // template for F1 is more specialized than the template for F2 9889 // according to the partial ordering rules described in 14.5.5.2, or, 9890 // if not that, 9891 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9892 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9893 Cand1.Function->getPrimaryTemplate(), 9894 Cand2.Function->getPrimaryTemplate(), Loc, 9895 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9896 : TPOC_Call, 9897 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9898 Cand1.isReversed() ^ Cand2.isReversed(), 9899 canCompareFunctionConstraints(S, Cand1, Cand2))) 9900 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9901 } 9902 9903 // -— F1 and F2 are non-template functions with the same 9904 // parameter-type-lists, and F1 is more constrained than F2 [...], 9905 if (!Cand1IsSpecialization && !Cand2IsSpecialization && 9906 canCompareFunctionConstraints(S, Cand1, Cand2)) { 9907 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9908 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9909 if (RC1 && RC2) { 9910 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9911 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2}, 9912 AtLeastAsConstrained1) || 9913 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1}, 9914 AtLeastAsConstrained2)) 9915 return false; 9916 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9917 return AtLeastAsConstrained1; 9918 } else if (RC1 || RC2) { 9919 return RC1 != nullptr; 9920 } 9921 } 9922 9923 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9924 // class B of D, and for all arguments the corresponding parameters of 9925 // F1 and F2 have the same type. 9926 // FIXME: Implement the "all parameters have the same type" check. 9927 bool Cand1IsInherited = 9928 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9929 bool Cand2IsInherited = 9930 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9931 if (Cand1IsInherited != Cand2IsInherited) 9932 return Cand2IsInherited; 9933 else if (Cand1IsInherited) { 9934 assert(Cand2IsInherited); 9935 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9936 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9937 if (Cand1Class->isDerivedFrom(Cand2Class)) 9938 return true; 9939 if (Cand2Class->isDerivedFrom(Cand1Class)) 9940 return false; 9941 // Inherited from sibling base classes: still ambiguous. 9942 } 9943 9944 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9945 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9946 // with reversed order of parameters and F1 is not 9947 // 9948 // We rank reversed + different operator as worse than just reversed, but 9949 // that comparison can never happen, because we only consider reversing for 9950 // the maximally-rewritten operator (== or <=>). 9951 if (Cand1.RewriteKind != Cand2.RewriteKind) 9952 return Cand1.RewriteKind < Cand2.RewriteKind; 9953 9954 // Check C++17 tie-breakers for deduction guides. 9955 { 9956 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9957 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9958 if (Guide1 && Guide2) { 9959 // -- F1 is generated from a deduction-guide and F2 is not 9960 if (Guide1->isImplicit() != Guide2->isImplicit()) 9961 return Guide2->isImplicit(); 9962 9963 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9964 if (Guide1->isCopyDeductionCandidate()) 9965 return true; 9966 } 9967 } 9968 9969 // Check for enable_if value-based overload resolution. 9970 if (Cand1.Function && Cand2.Function) { 9971 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9972 if (Cmp != Comparison::Equal) 9973 return Cmp == Comparison::Better; 9974 } 9975 9976 bool HasPS1 = Cand1.Function != nullptr && 9977 functionHasPassObjectSizeParams(Cand1.Function); 9978 bool HasPS2 = Cand2.Function != nullptr && 9979 functionHasPassObjectSizeParams(Cand2.Function); 9980 if (HasPS1 != HasPS2 && HasPS1) 9981 return true; 9982 9983 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9984 if (MV == Comparison::Better) 9985 return true; 9986 if (MV == Comparison::Worse) 9987 return false; 9988 9989 // If other rules cannot determine which is better, CUDA preference is used 9990 // to determine which is better. 9991 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9992 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 9993 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9994 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9995 } 9996 9997 // General member function overloading is handled above, so this only handles 9998 // constructors with address spaces. 9999 // This only handles address spaces since C++ has no other 10000 // qualifier that can be used with constructors. 10001 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 10002 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 10003 if (CD1 && CD2) { 10004 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 10005 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 10006 if (AS1 != AS2) { 10007 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10008 return true; 10009 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10010 return false; 10011 } 10012 } 10013 10014 return false; 10015 } 10016 10017 /// Determine whether two declarations are "equivalent" for the purposes of 10018 /// name lookup and overload resolution. This applies when the same internal/no 10019 /// linkage entity is defined by two modules (probably by textually including 10020 /// the same header). In such a case, we don't consider the declarations to 10021 /// declare the same entity, but we also don't want lookups with both 10022 /// declarations visible to be ambiguous in some cases (this happens when using 10023 /// a modularized libstdc++). 10024 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10025 const NamedDecl *B) { 10026 auto *VA = dyn_cast_or_null<ValueDecl>(A); 10027 auto *VB = dyn_cast_or_null<ValueDecl>(B); 10028 if (!VA || !VB) 10029 return false; 10030 10031 // The declarations must be declaring the same name as an internal linkage 10032 // entity in different modules. 10033 if (!VA->getDeclContext()->getRedeclContext()->Equals( 10034 VB->getDeclContext()->getRedeclContext()) || 10035 getOwningModule(VA) == getOwningModule(VB) || 10036 VA->isExternallyVisible() || VB->isExternallyVisible()) 10037 return false; 10038 10039 // Check that the declarations appear to be equivalent. 10040 // 10041 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 10042 // For constants and functions, we should check the initializer or body is 10043 // the same. For non-constant variables, we shouldn't allow it at all. 10044 if (Context.hasSameType(VA->getType(), VB->getType())) 10045 return true; 10046 10047 // Enum constants within unnamed enumerations will have different types, but 10048 // may still be similar enough to be interchangeable for our purposes. 10049 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 10050 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 10051 // Only handle anonymous enums. If the enumerations were named and 10052 // equivalent, they would have been merged to the same type. 10053 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 10054 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 10055 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 10056 !Context.hasSameType(EnumA->getIntegerType(), 10057 EnumB->getIntegerType())) 10058 return false; 10059 // Allow this only if the value is the same for both enumerators. 10060 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 10061 } 10062 } 10063 10064 // Nothing else is sufficiently similar. 10065 return false; 10066 } 10067 10068 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10069 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10070 assert(D && "Unknown declaration"); 10071 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10072 10073 Module *M = getOwningModule(D); 10074 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10075 << !M << (M ? M->getFullModuleName() : ""); 10076 10077 for (auto *E : Equiv) { 10078 Module *M = getOwningModule(E); 10079 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10080 << !M << (M ? M->getFullModuleName() : ""); 10081 } 10082 } 10083 10084 /// Computes the best viable function (C++ 13.3.3) 10085 /// within an overload candidate set. 10086 /// 10087 /// \param Loc The location of the function name (or operator symbol) for 10088 /// which overload resolution occurs. 10089 /// 10090 /// \param Best If overload resolution was successful or found a deleted 10091 /// function, \p Best points to the candidate function found. 10092 /// 10093 /// \returns The result of overload resolution. 10094 OverloadingResult 10095 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10096 iterator &Best) { 10097 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10098 std::transform(begin(), end(), std::back_inserter(Candidates), 10099 [](OverloadCandidate &Cand) { return &Cand; }); 10100 10101 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10102 // are accepted by both clang and NVCC. However, during a particular 10103 // compilation mode only one call variant is viable. We need to 10104 // exclude non-viable overload candidates from consideration based 10105 // only on their host/device attributes. Specifically, if one 10106 // candidate call is WrongSide and the other is SameSide, we ignore 10107 // the WrongSide candidate. 10108 // We only need to remove wrong-sided candidates here if 10109 // -fgpu-exclude-wrong-side-overloads is off. When 10110 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10111 // uniformly in isBetterOverloadCandidate. 10112 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10113 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10114 bool ContainsSameSideCandidate = 10115 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10116 // Check viable function only. 10117 return Cand->Viable && Cand->Function && 10118 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10119 Sema::CFP_SameSide; 10120 }); 10121 if (ContainsSameSideCandidate) { 10122 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10123 // Check viable function only to avoid unnecessary data copying/moving. 10124 return Cand->Viable && Cand->Function && 10125 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10126 Sema::CFP_WrongSide; 10127 }; 10128 llvm::erase_if(Candidates, IsWrongSideCandidate); 10129 } 10130 } 10131 10132 // Find the best viable function. 10133 Best = end(); 10134 for (auto *Cand : Candidates) { 10135 Cand->Best = false; 10136 if (Cand->Viable) 10137 if (Best == end() || 10138 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10139 Best = Cand; 10140 } 10141 10142 // If we didn't find any viable functions, abort. 10143 if (Best == end()) 10144 return OR_No_Viable_Function; 10145 10146 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10147 10148 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10149 PendingBest.push_back(&*Best); 10150 Best->Best = true; 10151 10152 // Make sure that this function is better than every other viable 10153 // function. If not, we have an ambiguity. 10154 while (!PendingBest.empty()) { 10155 auto *Curr = PendingBest.pop_back_val(); 10156 for (auto *Cand : Candidates) { 10157 if (Cand->Viable && !Cand->Best && 10158 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10159 PendingBest.push_back(Cand); 10160 Cand->Best = true; 10161 10162 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10163 Curr->Function)) 10164 EquivalentCands.push_back(Cand->Function); 10165 else 10166 Best = end(); 10167 } 10168 } 10169 } 10170 10171 // If we found more than one best candidate, this is ambiguous. 10172 if (Best == end()) 10173 return OR_Ambiguous; 10174 10175 // Best is the best viable function. 10176 if (Best->Function && Best->Function->isDeleted()) 10177 return OR_Deleted; 10178 10179 if (!EquivalentCands.empty()) 10180 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10181 EquivalentCands); 10182 10183 return OR_Success; 10184 } 10185 10186 namespace { 10187 10188 enum OverloadCandidateKind { 10189 oc_function, 10190 oc_method, 10191 oc_reversed_binary_operator, 10192 oc_constructor, 10193 oc_implicit_default_constructor, 10194 oc_implicit_copy_constructor, 10195 oc_implicit_move_constructor, 10196 oc_implicit_copy_assignment, 10197 oc_implicit_move_assignment, 10198 oc_implicit_equality_comparison, 10199 oc_inherited_constructor 10200 }; 10201 10202 enum OverloadCandidateSelect { 10203 ocs_non_template, 10204 ocs_template, 10205 ocs_described_template, 10206 }; 10207 10208 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10209 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10210 OverloadCandidateRewriteKind CRK, 10211 std::string &Description) { 10212 10213 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10214 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10215 isTemplate = true; 10216 Description = S.getTemplateArgumentBindingsText( 10217 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10218 } 10219 10220 OverloadCandidateSelect Select = [&]() { 10221 if (!Description.empty()) 10222 return ocs_described_template; 10223 return isTemplate ? ocs_template : ocs_non_template; 10224 }(); 10225 10226 OverloadCandidateKind Kind = [&]() { 10227 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10228 return oc_implicit_equality_comparison; 10229 10230 if (CRK & CRK_Reversed) 10231 return oc_reversed_binary_operator; 10232 10233 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10234 if (!Ctor->isImplicit()) { 10235 if (isa<ConstructorUsingShadowDecl>(Found)) 10236 return oc_inherited_constructor; 10237 else 10238 return oc_constructor; 10239 } 10240 10241 if (Ctor->isDefaultConstructor()) 10242 return oc_implicit_default_constructor; 10243 10244 if (Ctor->isMoveConstructor()) 10245 return oc_implicit_move_constructor; 10246 10247 assert(Ctor->isCopyConstructor() && 10248 "unexpected sort of implicit constructor"); 10249 return oc_implicit_copy_constructor; 10250 } 10251 10252 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10253 // This actually gets spelled 'candidate function' for now, but 10254 // it doesn't hurt to split it out. 10255 if (!Meth->isImplicit()) 10256 return oc_method; 10257 10258 if (Meth->isMoveAssignmentOperator()) 10259 return oc_implicit_move_assignment; 10260 10261 if (Meth->isCopyAssignmentOperator()) 10262 return oc_implicit_copy_assignment; 10263 10264 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10265 return oc_method; 10266 } 10267 10268 return oc_function; 10269 }(); 10270 10271 return std::make_pair(Kind, Select); 10272 } 10273 10274 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10275 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10276 // set. 10277 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10278 S.Diag(FoundDecl->getLocation(), 10279 diag::note_ovl_candidate_inherited_constructor) 10280 << Shadow->getNominatedBaseClass(); 10281 } 10282 10283 } // end anonymous namespace 10284 10285 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10286 const FunctionDecl *FD) { 10287 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10288 bool AlwaysTrue; 10289 if (EnableIf->getCond()->isValueDependent() || 10290 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10291 return false; 10292 if (!AlwaysTrue) 10293 return false; 10294 } 10295 return true; 10296 } 10297 10298 /// Returns true if we can take the address of the function. 10299 /// 10300 /// \param Complain - If true, we'll emit a diagnostic 10301 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10302 /// we in overload resolution? 10303 /// \param Loc - The location of the statement we're complaining about. Ignored 10304 /// if we're not complaining, or if we're in overload resolution. 10305 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10306 bool Complain, 10307 bool InOverloadResolution, 10308 SourceLocation Loc) { 10309 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10310 if (Complain) { 10311 if (InOverloadResolution) 10312 S.Diag(FD->getBeginLoc(), 10313 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10314 else 10315 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10316 } 10317 return false; 10318 } 10319 10320 if (FD->getTrailingRequiresClause()) { 10321 ConstraintSatisfaction Satisfaction; 10322 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10323 return false; 10324 if (!Satisfaction.IsSatisfied) { 10325 if (Complain) { 10326 if (InOverloadResolution) { 10327 SmallString<128> TemplateArgString; 10328 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 10329 TemplateArgString += " "; 10330 TemplateArgString += S.getTemplateArgumentBindingsText( 10331 FunTmpl->getTemplateParameters(), 10332 *FD->getTemplateSpecializationArgs()); 10333 } 10334 10335 S.Diag(FD->getBeginLoc(), 10336 diag::note_ovl_candidate_unsatisfied_constraints) 10337 << TemplateArgString; 10338 } else 10339 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10340 << FD; 10341 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10342 } 10343 return false; 10344 } 10345 } 10346 10347 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10348 return P->hasAttr<PassObjectSizeAttr>(); 10349 }); 10350 if (I == FD->param_end()) 10351 return true; 10352 10353 if (Complain) { 10354 // Add one to ParamNo because it's user-facing 10355 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10356 if (InOverloadResolution) 10357 S.Diag(FD->getLocation(), 10358 diag::note_ovl_candidate_has_pass_object_size_params) 10359 << ParamNo; 10360 else 10361 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10362 << FD << ParamNo; 10363 } 10364 return false; 10365 } 10366 10367 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10368 const FunctionDecl *FD) { 10369 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10370 /*InOverloadResolution=*/true, 10371 /*Loc=*/SourceLocation()); 10372 } 10373 10374 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10375 bool Complain, 10376 SourceLocation Loc) { 10377 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10378 /*InOverloadResolution=*/false, 10379 Loc); 10380 } 10381 10382 // Don't print candidates other than the one that matches the calling 10383 // convention of the call operator, since that is guaranteed to exist. 10384 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10385 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10386 10387 if (!ConvD) 10388 return false; 10389 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10390 if (!RD->isLambda()) 10391 return false; 10392 10393 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10394 CallingConv CallOpCC = 10395 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10396 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10397 CallingConv ConvToCC = 10398 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10399 10400 return ConvToCC != CallOpCC; 10401 } 10402 10403 // Notes the location of an overload candidate. 10404 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10405 OverloadCandidateRewriteKind RewriteKind, 10406 QualType DestType, bool TakingAddress) { 10407 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10408 return; 10409 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10410 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10411 return; 10412 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10413 return; 10414 10415 std::string FnDesc; 10416 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10417 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10418 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10419 << (unsigned)KSPair.first << (unsigned)KSPair.second 10420 << Fn << FnDesc; 10421 10422 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10423 Diag(Fn->getLocation(), PD); 10424 MaybeEmitInheritedConstructorNote(*this, Found); 10425 } 10426 10427 static void 10428 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10429 // Perhaps the ambiguity was caused by two atomic constraints that are 10430 // 'identical' but not equivalent: 10431 // 10432 // void foo() requires (sizeof(T) > 4) { } // #1 10433 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10434 // 10435 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10436 // #2 to subsume #1, but these constraint are not considered equivalent 10437 // according to the subsumption rules because they are not the same 10438 // source-level construct. This behavior is quite confusing and we should try 10439 // to help the user figure out what happened. 10440 10441 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10442 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10443 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10444 if (!I->Function) 10445 continue; 10446 SmallVector<const Expr *, 3> AC; 10447 if (auto *Template = I->Function->getPrimaryTemplate()) 10448 Template->getAssociatedConstraints(AC); 10449 else 10450 I->Function->getAssociatedConstraints(AC); 10451 if (AC.empty()) 10452 continue; 10453 if (FirstCand == nullptr) { 10454 FirstCand = I->Function; 10455 FirstAC = AC; 10456 } else if (SecondCand == nullptr) { 10457 SecondCand = I->Function; 10458 SecondAC = AC; 10459 } else { 10460 // We have more than one pair of constrained functions - this check is 10461 // expensive and we'd rather not try to diagnose it. 10462 return; 10463 } 10464 } 10465 if (!SecondCand) 10466 return; 10467 // The diagnostic can only happen if there are associated constraints on 10468 // both sides (there needs to be some identical atomic constraint). 10469 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10470 SecondCand, SecondAC)) 10471 // Just show the user one diagnostic, they'll probably figure it out 10472 // from here. 10473 return; 10474 } 10475 10476 // Notes the location of all overload candidates designated through 10477 // OverloadedExpr 10478 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10479 bool TakingAddress) { 10480 assert(OverloadedExpr->getType() == Context.OverloadTy); 10481 10482 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10483 OverloadExpr *OvlExpr = Ovl.Expression; 10484 10485 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10486 IEnd = OvlExpr->decls_end(); 10487 I != IEnd; ++I) { 10488 if (FunctionTemplateDecl *FunTmpl = 10489 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10490 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10491 TakingAddress); 10492 } else if (FunctionDecl *Fun 10493 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10494 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10495 } 10496 } 10497 } 10498 10499 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10500 /// "lead" diagnostic; it will be given two arguments, the source and 10501 /// target types of the conversion. 10502 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10503 Sema &S, 10504 SourceLocation CaretLoc, 10505 const PartialDiagnostic &PDiag) const { 10506 S.Diag(CaretLoc, PDiag) 10507 << Ambiguous.getFromType() << Ambiguous.getToType(); 10508 unsigned CandsShown = 0; 10509 AmbiguousConversionSequence::const_iterator I, E; 10510 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10511 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10512 break; 10513 ++CandsShown; 10514 S.NoteOverloadCandidate(I->first, I->second); 10515 } 10516 S.Diags.overloadCandidatesShown(CandsShown); 10517 if (I != E) 10518 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10519 } 10520 10521 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10522 unsigned I, bool TakingCandidateAddress) { 10523 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10524 assert(Conv.isBad()); 10525 assert(Cand->Function && "for now, candidate must be a function"); 10526 FunctionDecl *Fn = Cand->Function; 10527 10528 // There's a conversion slot for the object argument if this is a 10529 // non-constructor method. Note that 'I' corresponds the 10530 // conversion-slot index. 10531 bool isObjectArgument = false; 10532 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10533 if (I == 0) 10534 isObjectArgument = true; 10535 else 10536 I--; 10537 } 10538 10539 std::string FnDesc; 10540 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10541 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10542 FnDesc); 10543 10544 Expr *FromExpr = Conv.Bad.FromExpr; 10545 QualType FromTy = Conv.Bad.getFromType(); 10546 QualType ToTy = Conv.Bad.getToType(); 10547 10548 if (FromTy == S.Context.OverloadTy) { 10549 assert(FromExpr && "overload set argument came from implicit argument?"); 10550 Expr *E = FromExpr->IgnoreParens(); 10551 if (isa<UnaryOperator>(E)) 10552 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10553 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10554 10555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10556 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10557 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10558 << Name << I + 1; 10559 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10560 return; 10561 } 10562 10563 // Do some hand-waving analysis to see if the non-viability is due 10564 // to a qualifier mismatch. 10565 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10566 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10567 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10568 CToTy = RT->getPointeeType(); 10569 else { 10570 // TODO: detect and diagnose the full richness of const mismatches. 10571 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10572 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10573 CFromTy = FromPT->getPointeeType(); 10574 CToTy = ToPT->getPointeeType(); 10575 } 10576 } 10577 10578 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10579 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10580 Qualifiers FromQs = CFromTy.getQualifiers(); 10581 Qualifiers ToQs = CToTy.getQualifiers(); 10582 10583 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10584 if (isObjectArgument) 10585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10586 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10587 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10588 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10589 else 10590 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10591 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10592 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10593 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10594 << ToTy->isReferenceType() << I + 1; 10595 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10596 return; 10597 } 10598 10599 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10601 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10602 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10603 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10604 << (unsigned)isObjectArgument << I + 1; 10605 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10606 return; 10607 } 10608 10609 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10610 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10611 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10612 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10613 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10614 << (unsigned)isObjectArgument << I + 1; 10615 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10616 return; 10617 } 10618 10619 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10621 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10622 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10623 << FromQs.hasUnaligned() << I + 1; 10624 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10625 return; 10626 } 10627 10628 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10629 assert(CVR && "expected qualifiers mismatch"); 10630 10631 if (isObjectArgument) { 10632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10633 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10634 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10635 << (CVR - 1); 10636 } else { 10637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10638 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10640 << (CVR - 1) << I + 1; 10641 } 10642 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10643 return; 10644 } 10645 10646 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10647 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10648 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10649 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10650 << (unsigned)isObjectArgument << I + 1 10651 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10652 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10653 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10654 return; 10655 } 10656 10657 // Special diagnostic for failure to convert an initializer list, since 10658 // telling the user that it has type void is not useful. 10659 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10660 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10661 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10662 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10663 << ToTy << (unsigned)isObjectArgument << I + 1 10664 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 10665 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 10666 ? 2 10667 : 0); 10668 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10669 return; 10670 } 10671 10672 // Diagnose references or pointers to incomplete types differently, 10673 // since it's far from impossible that the incompleteness triggered 10674 // the failure. 10675 QualType TempFromTy = FromTy.getNonReferenceType(); 10676 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10677 TempFromTy = PTy->getPointeeType(); 10678 if (TempFromTy->isIncompleteType()) { 10679 // Emit the generic diagnostic and, optionally, add the hints to it. 10680 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10681 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10682 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10683 << ToTy << (unsigned)isObjectArgument << I + 1 10684 << (unsigned)(Cand->Fix.Kind); 10685 10686 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10687 return; 10688 } 10689 10690 // Diagnose base -> derived pointer conversions. 10691 unsigned BaseToDerivedConversion = 0; 10692 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10693 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10694 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10695 FromPtrTy->getPointeeType()) && 10696 !FromPtrTy->getPointeeType()->isIncompleteType() && 10697 !ToPtrTy->getPointeeType()->isIncompleteType() && 10698 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10699 FromPtrTy->getPointeeType())) 10700 BaseToDerivedConversion = 1; 10701 } 10702 } else if (const ObjCObjectPointerType *FromPtrTy 10703 = FromTy->getAs<ObjCObjectPointerType>()) { 10704 if (const ObjCObjectPointerType *ToPtrTy 10705 = ToTy->getAs<ObjCObjectPointerType>()) 10706 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10707 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10708 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10709 FromPtrTy->getPointeeType()) && 10710 FromIface->isSuperClassOf(ToIface)) 10711 BaseToDerivedConversion = 2; 10712 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10713 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10714 !FromTy->isIncompleteType() && 10715 !ToRefTy->getPointeeType()->isIncompleteType() && 10716 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10717 BaseToDerivedConversion = 3; 10718 } 10719 } 10720 10721 if (BaseToDerivedConversion) { 10722 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10723 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10724 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10725 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10726 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10727 return; 10728 } 10729 10730 if (isa<ObjCObjectPointerType>(CFromTy) && 10731 isa<PointerType>(CToTy)) { 10732 Qualifiers FromQs = CFromTy.getQualifiers(); 10733 Qualifiers ToQs = CToTy.getQualifiers(); 10734 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10735 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10736 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10737 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10738 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10739 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10740 return; 10741 } 10742 } 10743 10744 if (TakingCandidateAddress && 10745 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10746 return; 10747 10748 // Emit the generic diagnostic and, optionally, add the hints to it. 10749 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10750 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10752 << ToTy << (unsigned)isObjectArgument << I + 1 10753 << (unsigned)(Cand->Fix.Kind); 10754 10755 // If we can fix the conversion, suggest the FixIts. 10756 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10757 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10758 FDiag << *HI; 10759 S.Diag(Fn->getLocation(), FDiag); 10760 10761 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10762 } 10763 10764 /// Additional arity mismatch diagnosis specific to a function overload 10765 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10766 /// over a candidate in any candidate set. 10767 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10768 unsigned NumArgs) { 10769 FunctionDecl *Fn = Cand->Function; 10770 unsigned MinParams = Fn->getMinRequiredArguments(); 10771 10772 // With invalid overloaded operators, it's possible that we think we 10773 // have an arity mismatch when in fact it looks like we have the 10774 // right number of arguments, because only overloaded operators have 10775 // the weird behavior of overloading member and non-member functions. 10776 // Just don't report anything. 10777 if (Fn->isInvalidDecl() && 10778 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10779 return true; 10780 10781 if (NumArgs < MinParams) { 10782 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10783 (Cand->FailureKind == ovl_fail_bad_deduction && 10784 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10785 } else { 10786 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10787 (Cand->FailureKind == ovl_fail_bad_deduction && 10788 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10789 } 10790 10791 return false; 10792 } 10793 10794 /// General arity mismatch diagnosis over a candidate in a candidate set. 10795 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10796 unsigned NumFormalArgs) { 10797 assert(isa<FunctionDecl>(D) && 10798 "The templated declaration should at least be a function" 10799 " when diagnosing bad template argument deduction due to too many" 10800 " or too few arguments"); 10801 10802 FunctionDecl *Fn = cast<FunctionDecl>(D); 10803 10804 // TODO: treat calls to a missing default constructor as a special case 10805 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10806 unsigned MinParams = Fn->getMinRequiredArguments(); 10807 10808 // at least / at most / exactly 10809 unsigned mode, modeCount; 10810 if (NumFormalArgs < MinParams) { 10811 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10812 FnTy->isTemplateVariadic()) 10813 mode = 0; // "at least" 10814 else 10815 mode = 2; // "exactly" 10816 modeCount = MinParams; 10817 } else { 10818 if (MinParams != FnTy->getNumParams()) 10819 mode = 1; // "at most" 10820 else 10821 mode = 2; // "exactly" 10822 modeCount = FnTy->getNumParams(); 10823 } 10824 10825 std::string Description; 10826 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10827 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10828 10829 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10830 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10831 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10832 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10833 else 10834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10835 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10836 << Description << mode << modeCount << NumFormalArgs; 10837 10838 MaybeEmitInheritedConstructorNote(S, Found); 10839 } 10840 10841 /// Arity mismatch diagnosis specific to a function overload candidate. 10842 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10843 unsigned NumFormalArgs) { 10844 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10845 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10846 } 10847 10848 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10849 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10850 return TD; 10851 llvm_unreachable("Unsupported: Getting the described template declaration" 10852 " for bad deduction diagnosis"); 10853 } 10854 10855 /// Diagnose a failed template-argument deduction. 10856 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10857 DeductionFailureInfo &DeductionFailure, 10858 unsigned NumArgs, 10859 bool TakingCandidateAddress) { 10860 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10861 NamedDecl *ParamD; 10862 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10863 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10864 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10865 switch (DeductionFailure.Result) { 10866 case Sema::TDK_Success: 10867 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10868 10869 case Sema::TDK_Incomplete: { 10870 assert(ParamD && "no parameter found for incomplete deduction result"); 10871 S.Diag(Templated->getLocation(), 10872 diag::note_ovl_candidate_incomplete_deduction) 10873 << ParamD->getDeclName(); 10874 MaybeEmitInheritedConstructorNote(S, Found); 10875 return; 10876 } 10877 10878 case Sema::TDK_IncompletePack: { 10879 assert(ParamD && "no parameter found for incomplete deduction result"); 10880 S.Diag(Templated->getLocation(), 10881 diag::note_ovl_candidate_incomplete_deduction_pack) 10882 << ParamD->getDeclName() 10883 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10884 << *DeductionFailure.getFirstArg(); 10885 MaybeEmitInheritedConstructorNote(S, Found); 10886 return; 10887 } 10888 10889 case Sema::TDK_Underqualified: { 10890 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10891 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10892 10893 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10894 10895 // Param will have been canonicalized, but it should just be a 10896 // qualified version of ParamD, so move the qualifiers to that. 10897 QualifierCollector Qs; 10898 Qs.strip(Param); 10899 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10900 assert(S.Context.hasSameType(Param, NonCanonParam)); 10901 10902 // Arg has also been canonicalized, but there's nothing we can do 10903 // about that. It also doesn't matter as much, because it won't 10904 // have any template parameters in it (because deduction isn't 10905 // done on dependent types). 10906 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10907 10908 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10909 << ParamD->getDeclName() << Arg << NonCanonParam; 10910 MaybeEmitInheritedConstructorNote(S, Found); 10911 return; 10912 } 10913 10914 case Sema::TDK_Inconsistent: { 10915 assert(ParamD && "no parameter found for inconsistent deduction result"); 10916 int which = 0; 10917 if (isa<TemplateTypeParmDecl>(ParamD)) 10918 which = 0; 10919 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10920 // Deduction might have failed because we deduced arguments of two 10921 // different types for a non-type template parameter. 10922 // FIXME: Use a different TDK value for this. 10923 QualType T1 = 10924 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10925 QualType T2 = 10926 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10927 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10928 S.Diag(Templated->getLocation(), 10929 diag::note_ovl_candidate_inconsistent_deduction_types) 10930 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10931 << *DeductionFailure.getSecondArg() << T2; 10932 MaybeEmitInheritedConstructorNote(S, Found); 10933 return; 10934 } 10935 10936 which = 1; 10937 } else { 10938 which = 2; 10939 } 10940 10941 // Tweak the diagnostic if the problem is that we deduced packs of 10942 // different arities. We'll print the actual packs anyway in case that 10943 // includes additional useful information. 10944 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10945 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10946 DeductionFailure.getFirstArg()->pack_size() != 10947 DeductionFailure.getSecondArg()->pack_size()) { 10948 which = 3; 10949 } 10950 10951 S.Diag(Templated->getLocation(), 10952 diag::note_ovl_candidate_inconsistent_deduction) 10953 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10954 << *DeductionFailure.getSecondArg(); 10955 MaybeEmitInheritedConstructorNote(S, Found); 10956 return; 10957 } 10958 10959 case Sema::TDK_InvalidExplicitArguments: 10960 assert(ParamD && "no parameter found for invalid explicit arguments"); 10961 if (ParamD->getDeclName()) 10962 S.Diag(Templated->getLocation(), 10963 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10964 << ParamD->getDeclName(); 10965 else { 10966 int index = 0; 10967 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10968 index = TTP->getIndex(); 10969 else if (NonTypeTemplateParmDecl *NTTP 10970 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10971 index = NTTP->getIndex(); 10972 else 10973 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10974 S.Diag(Templated->getLocation(), 10975 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10976 << (index + 1); 10977 } 10978 MaybeEmitInheritedConstructorNote(S, Found); 10979 return; 10980 10981 case Sema::TDK_ConstraintsNotSatisfied: { 10982 // Format the template argument list into the argument string. 10983 SmallString<128> TemplateArgString; 10984 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10985 TemplateArgString = " "; 10986 TemplateArgString += S.getTemplateArgumentBindingsText( 10987 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10988 if (TemplateArgString.size() == 1) 10989 TemplateArgString.clear(); 10990 S.Diag(Templated->getLocation(), 10991 diag::note_ovl_candidate_unsatisfied_constraints) 10992 << TemplateArgString; 10993 10994 S.DiagnoseUnsatisfiedConstraint( 10995 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10996 return; 10997 } 10998 case Sema::TDK_TooManyArguments: 10999 case Sema::TDK_TooFewArguments: 11000 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 11001 return; 11002 11003 case Sema::TDK_InstantiationDepth: 11004 S.Diag(Templated->getLocation(), 11005 diag::note_ovl_candidate_instantiation_depth); 11006 MaybeEmitInheritedConstructorNote(S, Found); 11007 return; 11008 11009 case Sema::TDK_SubstitutionFailure: { 11010 // Format the template argument list into the argument string. 11011 SmallString<128> TemplateArgString; 11012 if (TemplateArgumentList *Args = 11013 DeductionFailure.getTemplateArgumentList()) { 11014 TemplateArgString = " "; 11015 TemplateArgString += S.getTemplateArgumentBindingsText( 11016 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11017 if (TemplateArgString.size() == 1) 11018 TemplateArgString.clear(); 11019 } 11020 11021 // If this candidate was disabled by enable_if, say so. 11022 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 11023 if (PDiag && PDiag->second.getDiagID() == 11024 diag::err_typename_nested_not_found_enable_if) { 11025 // FIXME: Use the source range of the condition, and the fully-qualified 11026 // name of the enable_if template. These are both present in PDiag. 11027 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 11028 << "'enable_if'" << TemplateArgString; 11029 return; 11030 } 11031 11032 // We found a specific requirement that disabled the enable_if. 11033 if (PDiag && PDiag->second.getDiagID() == 11034 diag::err_typename_nested_not_found_requirement) { 11035 S.Diag(Templated->getLocation(), 11036 diag::note_ovl_candidate_disabled_by_requirement) 11037 << PDiag->second.getStringArg(0) << TemplateArgString; 11038 return; 11039 } 11040 11041 // Format the SFINAE diagnostic into the argument string. 11042 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 11043 // formatted message in another diagnostic. 11044 SmallString<128> SFINAEArgString; 11045 SourceRange R; 11046 if (PDiag) { 11047 SFINAEArgString = ": "; 11048 R = SourceRange(PDiag->first, PDiag->first); 11049 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 11050 } 11051 11052 S.Diag(Templated->getLocation(), 11053 diag::note_ovl_candidate_substitution_failure) 11054 << TemplateArgString << SFINAEArgString << R; 11055 MaybeEmitInheritedConstructorNote(S, Found); 11056 return; 11057 } 11058 11059 case Sema::TDK_DeducedMismatch: 11060 case Sema::TDK_DeducedMismatchNested: { 11061 // Format the template argument list into the argument string. 11062 SmallString<128> TemplateArgString; 11063 if (TemplateArgumentList *Args = 11064 DeductionFailure.getTemplateArgumentList()) { 11065 TemplateArgString = " "; 11066 TemplateArgString += S.getTemplateArgumentBindingsText( 11067 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11068 if (TemplateArgString.size() == 1) 11069 TemplateArgString.clear(); 11070 } 11071 11072 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11073 << (*DeductionFailure.getCallArgIndex() + 1) 11074 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11075 << TemplateArgString 11076 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11077 break; 11078 } 11079 11080 case Sema::TDK_NonDeducedMismatch: { 11081 // FIXME: Provide a source location to indicate what we couldn't match. 11082 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11083 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11084 if (FirstTA.getKind() == TemplateArgument::Template && 11085 SecondTA.getKind() == TemplateArgument::Template) { 11086 TemplateName FirstTN = FirstTA.getAsTemplate(); 11087 TemplateName SecondTN = SecondTA.getAsTemplate(); 11088 if (FirstTN.getKind() == TemplateName::Template && 11089 SecondTN.getKind() == TemplateName::Template) { 11090 if (FirstTN.getAsTemplateDecl()->getName() == 11091 SecondTN.getAsTemplateDecl()->getName()) { 11092 // FIXME: This fixes a bad diagnostic where both templates are named 11093 // the same. This particular case is a bit difficult since: 11094 // 1) It is passed as a string to the diagnostic printer. 11095 // 2) The diagnostic printer only attempts to find a better 11096 // name for types, not decls. 11097 // Ideally, this should folded into the diagnostic printer. 11098 S.Diag(Templated->getLocation(), 11099 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11100 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11101 return; 11102 } 11103 } 11104 } 11105 11106 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11107 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11108 return; 11109 11110 // FIXME: For generic lambda parameters, check if the function is a lambda 11111 // call operator, and if so, emit a prettier and more informative 11112 // diagnostic that mentions 'auto' and lambda in addition to 11113 // (or instead of?) the canonical template type parameters. 11114 S.Diag(Templated->getLocation(), 11115 diag::note_ovl_candidate_non_deduced_mismatch) 11116 << FirstTA << SecondTA; 11117 return; 11118 } 11119 // TODO: diagnose these individually, then kill off 11120 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11121 case Sema::TDK_MiscellaneousDeductionFailure: 11122 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11123 MaybeEmitInheritedConstructorNote(S, Found); 11124 return; 11125 case Sema::TDK_CUDATargetMismatch: 11126 S.Diag(Templated->getLocation(), 11127 diag::note_cuda_ovl_candidate_target_mismatch); 11128 return; 11129 } 11130 } 11131 11132 /// Diagnose a failed template-argument deduction, for function calls. 11133 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11134 unsigned NumArgs, 11135 bool TakingCandidateAddress) { 11136 unsigned TDK = Cand->DeductionFailure.Result; 11137 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11138 if (CheckArityMismatch(S, Cand, NumArgs)) 11139 return; 11140 } 11141 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11142 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11143 } 11144 11145 /// CUDA: diagnose an invalid call across targets. 11146 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11147 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 11148 FunctionDecl *Callee = Cand->Function; 11149 11150 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11151 CalleeTarget = S.IdentifyCUDATarget(Callee); 11152 11153 std::string FnDesc; 11154 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11155 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11156 Cand->getRewriteKind(), FnDesc); 11157 11158 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11159 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11160 << FnDesc /* Ignored */ 11161 << CalleeTarget << CallerTarget; 11162 11163 // This could be an implicit constructor for which we could not infer the 11164 // target due to a collsion. Diagnose that case. 11165 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11166 if (Meth != nullptr && Meth->isImplicit()) { 11167 CXXRecordDecl *ParentClass = Meth->getParent(); 11168 Sema::CXXSpecialMember CSM; 11169 11170 switch (FnKindPair.first) { 11171 default: 11172 return; 11173 case oc_implicit_default_constructor: 11174 CSM = Sema::CXXDefaultConstructor; 11175 break; 11176 case oc_implicit_copy_constructor: 11177 CSM = Sema::CXXCopyConstructor; 11178 break; 11179 case oc_implicit_move_constructor: 11180 CSM = Sema::CXXMoveConstructor; 11181 break; 11182 case oc_implicit_copy_assignment: 11183 CSM = Sema::CXXCopyAssignment; 11184 break; 11185 case oc_implicit_move_assignment: 11186 CSM = Sema::CXXMoveAssignment; 11187 break; 11188 }; 11189 11190 bool ConstRHS = false; 11191 if (Meth->getNumParams()) { 11192 if (const ReferenceType *RT = 11193 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11194 ConstRHS = RT->getPointeeType().isConstQualified(); 11195 } 11196 } 11197 11198 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11199 /* ConstRHS */ ConstRHS, 11200 /* Diagnose */ true); 11201 } 11202 } 11203 11204 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11205 FunctionDecl *Callee = Cand->Function; 11206 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11207 11208 S.Diag(Callee->getLocation(), 11209 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11210 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11211 } 11212 11213 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11214 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11215 assert(ES.isExplicit() && "not an explicit candidate"); 11216 11217 unsigned Kind; 11218 switch (Cand->Function->getDeclKind()) { 11219 case Decl::Kind::CXXConstructor: 11220 Kind = 0; 11221 break; 11222 case Decl::Kind::CXXConversion: 11223 Kind = 1; 11224 break; 11225 case Decl::Kind::CXXDeductionGuide: 11226 Kind = Cand->Function->isImplicit() ? 0 : 2; 11227 break; 11228 default: 11229 llvm_unreachable("invalid Decl"); 11230 } 11231 11232 // Note the location of the first (in-class) declaration; a redeclaration 11233 // (particularly an out-of-class definition) will typically lack the 11234 // 'explicit' specifier. 11235 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11236 FunctionDecl *First = Cand->Function->getFirstDecl(); 11237 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11238 First = Pattern->getFirstDecl(); 11239 11240 S.Diag(First->getLocation(), 11241 diag::note_ovl_candidate_explicit) 11242 << Kind << (ES.getExpr() ? 1 : 0) 11243 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11244 } 11245 11246 /// Generates a 'note' diagnostic for an overload candidate. We've 11247 /// already generated a primary error at the call site. 11248 /// 11249 /// It really does need to be a single diagnostic with its caret 11250 /// pointed at the candidate declaration. Yes, this creates some 11251 /// major challenges of technical writing. Yes, this makes pointing 11252 /// out problems with specific arguments quite awkward. It's still 11253 /// better than generating twenty screens of text for every failed 11254 /// overload. 11255 /// 11256 /// It would be great to be able to express per-candidate problems 11257 /// more richly for those diagnostic clients that cared, but we'd 11258 /// still have to be just as careful with the default diagnostics. 11259 /// \param CtorDestAS Addr space of object being constructed (for ctor 11260 /// candidates only). 11261 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11262 unsigned NumArgs, 11263 bool TakingCandidateAddress, 11264 LangAS CtorDestAS = LangAS::Default) { 11265 FunctionDecl *Fn = Cand->Function; 11266 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11267 return; 11268 11269 // There is no physical candidate declaration to point to for OpenCL builtins. 11270 // Except for failed conversions, the notes are identical for each candidate, 11271 // so do not generate such notes. 11272 if (S.getLangOpts().OpenCL && Fn->isImplicit() && 11273 Cand->FailureKind != ovl_fail_bad_conversion) 11274 return; 11275 11276 // Note deleted candidates, but only if they're viable. 11277 if (Cand->Viable) { 11278 if (Fn->isDeleted()) { 11279 std::string FnDesc; 11280 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11281 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11282 Cand->getRewriteKind(), FnDesc); 11283 11284 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11285 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11286 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11287 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11288 return; 11289 } 11290 11291 // We don't really have anything else to say about viable candidates. 11292 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11293 return; 11294 } 11295 11296 switch (Cand->FailureKind) { 11297 case ovl_fail_too_many_arguments: 11298 case ovl_fail_too_few_arguments: 11299 return DiagnoseArityMismatch(S, Cand, NumArgs); 11300 11301 case ovl_fail_bad_deduction: 11302 return DiagnoseBadDeduction(S, Cand, NumArgs, 11303 TakingCandidateAddress); 11304 11305 case ovl_fail_illegal_constructor: { 11306 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11307 << (Fn->getPrimaryTemplate() ? 1 : 0); 11308 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11309 return; 11310 } 11311 11312 case ovl_fail_object_addrspace_mismatch: { 11313 Qualifiers QualsForPrinting; 11314 QualsForPrinting.setAddressSpace(CtorDestAS); 11315 S.Diag(Fn->getLocation(), 11316 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11317 << QualsForPrinting; 11318 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11319 return; 11320 } 11321 11322 case ovl_fail_trivial_conversion: 11323 case ovl_fail_bad_final_conversion: 11324 case ovl_fail_final_conversion_not_exact: 11325 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11326 11327 case ovl_fail_bad_conversion: { 11328 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11329 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11330 if (Cand->Conversions[I].isBad()) 11331 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11332 11333 // FIXME: this currently happens when we're called from SemaInit 11334 // when user-conversion overload fails. Figure out how to handle 11335 // those conditions and diagnose them well. 11336 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11337 } 11338 11339 case ovl_fail_bad_target: 11340 return DiagnoseBadTarget(S, Cand); 11341 11342 case ovl_fail_enable_if: 11343 return DiagnoseFailedEnableIfAttr(S, Cand); 11344 11345 case ovl_fail_explicit: 11346 return DiagnoseFailedExplicitSpec(S, Cand); 11347 11348 case ovl_fail_inhctor_slice: 11349 // It's generally not interesting to note copy/move constructors here. 11350 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11351 return; 11352 S.Diag(Fn->getLocation(), 11353 diag::note_ovl_candidate_inherited_constructor_slice) 11354 << (Fn->getPrimaryTemplate() ? 1 : 0) 11355 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11356 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11357 return; 11358 11359 case ovl_fail_addr_not_available: { 11360 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11361 (void)Available; 11362 assert(!Available); 11363 break; 11364 } 11365 case ovl_non_default_multiversion_function: 11366 // Do nothing, these should simply be ignored. 11367 break; 11368 11369 case ovl_fail_constraints_not_satisfied: { 11370 std::string FnDesc; 11371 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11372 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11373 Cand->getRewriteKind(), FnDesc); 11374 11375 S.Diag(Fn->getLocation(), 11376 diag::note_ovl_candidate_constraints_not_satisfied) 11377 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11378 << FnDesc /* Ignored */; 11379 ConstraintSatisfaction Satisfaction; 11380 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11381 break; 11382 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11383 } 11384 } 11385 } 11386 11387 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11388 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11389 return; 11390 11391 // Desugar the type of the surrogate down to a function type, 11392 // retaining as many typedefs as possible while still showing 11393 // the function type (and, therefore, its parameter types). 11394 QualType FnType = Cand->Surrogate->getConversionType(); 11395 bool isLValueReference = false; 11396 bool isRValueReference = false; 11397 bool isPointer = false; 11398 if (const LValueReferenceType *FnTypeRef = 11399 FnType->getAs<LValueReferenceType>()) { 11400 FnType = FnTypeRef->getPointeeType(); 11401 isLValueReference = true; 11402 } else if (const RValueReferenceType *FnTypeRef = 11403 FnType->getAs<RValueReferenceType>()) { 11404 FnType = FnTypeRef->getPointeeType(); 11405 isRValueReference = true; 11406 } 11407 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11408 FnType = FnTypePtr->getPointeeType(); 11409 isPointer = true; 11410 } 11411 // Desugar down to a function type. 11412 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11413 // Reconstruct the pointer/reference as appropriate. 11414 if (isPointer) FnType = S.Context.getPointerType(FnType); 11415 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11416 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11417 11418 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11419 << FnType; 11420 } 11421 11422 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11423 SourceLocation OpLoc, 11424 OverloadCandidate *Cand) { 11425 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11426 std::string TypeStr("operator"); 11427 TypeStr += Opc; 11428 TypeStr += "("; 11429 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11430 if (Cand->Conversions.size() == 1) { 11431 TypeStr += ")"; 11432 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11433 } else { 11434 TypeStr += ", "; 11435 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11436 TypeStr += ")"; 11437 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11438 } 11439 } 11440 11441 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11442 OverloadCandidate *Cand) { 11443 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11444 if (ICS.isBad()) break; // all meaningless after first invalid 11445 if (!ICS.isAmbiguous()) continue; 11446 11447 ICS.DiagnoseAmbiguousConversion( 11448 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11449 } 11450 } 11451 11452 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11453 if (Cand->Function) 11454 return Cand->Function->getLocation(); 11455 if (Cand->IsSurrogate) 11456 return Cand->Surrogate->getLocation(); 11457 return SourceLocation(); 11458 } 11459 11460 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11461 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11462 case Sema::TDK_Success: 11463 case Sema::TDK_NonDependentConversionFailure: 11464 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11465 11466 case Sema::TDK_Invalid: 11467 case Sema::TDK_Incomplete: 11468 case Sema::TDK_IncompletePack: 11469 return 1; 11470 11471 case Sema::TDK_Underqualified: 11472 case Sema::TDK_Inconsistent: 11473 return 2; 11474 11475 case Sema::TDK_SubstitutionFailure: 11476 case Sema::TDK_DeducedMismatch: 11477 case Sema::TDK_ConstraintsNotSatisfied: 11478 case Sema::TDK_DeducedMismatchNested: 11479 case Sema::TDK_NonDeducedMismatch: 11480 case Sema::TDK_MiscellaneousDeductionFailure: 11481 case Sema::TDK_CUDATargetMismatch: 11482 return 3; 11483 11484 case Sema::TDK_InstantiationDepth: 11485 return 4; 11486 11487 case Sema::TDK_InvalidExplicitArguments: 11488 return 5; 11489 11490 case Sema::TDK_TooManyArguments: 11491 case Sema::TDK_TooFewArguments: 11492 return 6; 11493 } 11494 llvm_unreachable("Unhandled deduction result"); 11495 } 11496 11497 namespace { 11498 struct CompareOverloadCandidatesForDisplay { 11499 Sema &S; 11500 SourceLocation Loc; 11501 size_t NumArgs; 11502 OverloadCandidateSet::CandidateSetKind CSK; 11503 11504 CompareOverloadCandidatesForDisplay( 11505 Sema &S, SourceLocation Loc, size_t NArgs, 11506 OverloadCandidateSet::CandidateSetKind CSK) 11507 : S(S), NumArgs(NArgs), CSK(CSK) {} 11508 11509 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11510 // If there are too many or too few arguments, that's the high-order bit we 11511 // want to sort by, even if the immediate failure kind was something else. 11512 if (C->FailureKind == ovl_fail_too_many_arguments || 11513 C->FailureKind == ovl_fail_too_few_arguments) 11514 return static_cast<OverloadFailureKind>(C->FailureKind); 11515 11516 if (C->Function) { 11517 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11518 return ovl_fail_too_many_arguments; 11519 if (NumArgs < C->Function->getMinRequiredArguments()) 11520 return ovl_fail_too_few_arguments; 11521 } 11522 11523 return static_cast<OverloadFailureKind>(C->FailureKind); 11524 } 11525 11526 bool operator()(const OverloadCandidate *L, 11527 const OverloadCandidate *R) { 11528 // Fast-path this check. 11529 if (L == R) return false; 11530 11531 // Order first by viability. 11532 if (L->Viable) { 11533 if (!R->Viable) return true; 11534 11535 // TODO: introduce a tri-valued comparison for overload 11536 // candidates. Would be more worthwhile if we had a sort 11537 // that could exploit it. 11538 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11539 return true; 11540 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11541 return false; 11542 } else if (R->Viable) 11543 return false; 11544 11545 assert(L->Viable == R->Viable); 11546 11547 // Criteria by which we can sort non-viable candidates: 11548 if (!L->Viable) { 11549 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11550 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11551 11552 // 1. Arity mismatches come after other candidates. 11553 if (LFailureKind == ovl_fail_too_many_arguments || 11554 LFailureKind == ovl_fail_too_few_arguments) { 11555 if (RFailureKind == ovl_fail_too_many_arguments || 11556 RFailureKind == ovl_fail_too_few_arguments) { 11557 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11558 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11559 if (LDist == RDist) { 11560 if (LFailureKind == RFailureKind) 11561 // Sort non-surrogates before surrogates. 11562 return !L->IsSurrogate && R->IsSurrogate; 11563 // Sort candidates requiring fewer parameters than there were 11564 // arguments given after candidates requiring more parameters 11565 // than there were arguments given. 11566 return LFailureKind == ovl_fail_too_many_arguments; 11567 } 11568 return LDist < RDist; 11569 } 11570 return false; 11571 } 11572 if (RFailureKind == ovl_fail_too_many_arguments || 11573 RFailureKind == ovl_fail_too_few_arguments) 11574 return true; 11575 11576 // 2. Bad conversions come first and are ordered by the number 11577 // of bad conversions and quality of good conversions. 11578 if (LFailureKind == ovl_fail_bad_conversion) { 11579 if (RFailureKind != ovl_fail_bad_conversion) 11580 return true; 11581 11582 // The conversion that can be fixed with a smaller number of changes, 11583 // comes first. 11584 unsigned numLFixes = L->Fix.NumConversionsFixed; 11585 unsigned numRFixes = R->Fix.NumConversionsFixed; 11586 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11587 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11588 if (numLFixes != numRFixes) { 11589 return numLFixes < numRFixes; 11590 } 11591 11592 // If there's any ordering between the defined conversions... 11593 // FIXME: this might not be transitive. 11594 assert(L->Conversions.size() == R->Conversions.size()); 11595 11596 int leftBetter = 0; 11597 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11598 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11599 switch (CompareImplicitConversionSequences(S, Loc, 11600 L->Conversions[I], 11601 R->Conversions[I])) { 11602 case ImplicitConversionSequence::Better: 11603 leftBetter++; 11604 break; 11605 11606 case ImplicitConversionSequence::Worse: 11607 leftBetter--; 11608 break; 11609 11610 case ImplicitConversionSequence::Indistinguishable: 11611 break; 11612 } 11613 } 11614 if (leftBetter > 0) return true; 11615 if (leftBetter < 0) return false; 11616 11617 } else if (RFailureKind == ovl_fail_bad_conversion) 11618 return false; 11619 11620 if (LFailureKind == ovl_fail_bad_deduction) { 11621 if (RFailureKind != ovl_fail_bad_deduction) 11622 return true; 11623 11624 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11625 return RankDeductionFailure(L->DeductionFailure) 11626 < RankDeductionFailure(R->DeductionFailure); 11627 } else if (RFailureKind == ovl_fail_bad_deduction) 11628 return false; 11629 11630 // TODO: others? 11631 } 11632 11633 // Sort everything else by location. 11634 SourceLocation LLoc = GetLocationForCandidate(L); 11635 SourceLocation RLoc = GetLocationForCandidate(R); 11636 11637 // Put candidates without locations (e.g. builtins) at the end. 11638 if (LLoc.isInvalid()) return false; 11639 if (RLoc.isInvalid()) return true; 11640 11641 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11642 } 11643 }; 11644 } 11645 11646 /// CompleteNonViableCandidate - Normally, overload resolution only 11647 /// computes up to the first bad conversion. Produces the FixIt set if 11648 /// possible. 11649 static void 11650 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11651 ArrayRef<Expr *> Args, 11652 OverloadCandidateSet::CandidateSetKind CSK) { 11653 assert(!Cand->Viable); 11654 11655 // Don't do anything on failures other than bad conversion. 11656 if (Cand->FailureKind != ovl_fail_bad_conversion) 11657 return; 11658 11659 // We only want the FixIts if all the arguments can be corrected. 11660 bool Unfixable = false; 11661 // Use a implicit copy initialization to check conversion fixes. 11662 Cand->Fix.setConversionChecker(TryCopyInitialization); 11663 11664 // Attempt to fix the bad conversion. 11665 unsigned ConvCount = Cand->Conversions.size(); 11666 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11667 ++ConvIdx) { 11668 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11669 if (Cand->Conversions[ConvIdx].isInitialized() && 11670 Cand->Conversions[ConvIdx].isBad()) { 11671 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11672 break; 11673 } 11674 } 11675 11676 // FIXME: this should probably be preserved from the overload 11677 // operation somehow. 11678 bool SuppressUserConversions = false; 11679 11680 unsigned ConvIdx = 0; 11681 unsigned ArgIdx = 0; 11682 ArrayRef<QualType> ParamTypes; 11683 bool Reversed = Cand->isReversed(); 11684 11685 if (Cand->IsSurrogate) { 11686 QualType ConvType 11687 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11688 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11689 ConvType = ConvPtrType->getPointeeType(); 11690 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11691 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11692 ConvIdx = 1; 11693 } else if (Cand->Function) { 11694 ParamTypes = 11695 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11696 if (isa<CXXMethodDecl>(Cand->Function) && 11697 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11698 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11699 ConvIdx = 1; 11700 if (CSK == OverloadCandidateSet::CSK_Operator && 11701 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 11702 Cand->Function->getDeclName().getCXXOverloadedOperator() != 11703 OO_Subscript) 11704 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11705 ArgIdx = 1; 11706 } 11707 } else { 11708 // Builtin operator. 11709 assert(ConvCount <= 3); 11710 ParamTypes = Cand->BuiltinParamTypes; 11711 } 11712 11713 // Fill in the rest of the conversions. 11714 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11715 ConvIdx != ConvCount; 11716 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11717 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11718 if (Cand->Conversions[ConvIdx].isInitialized()) { 11719 // We've already checked this conversion. 11720 } else if (ParamIdx < ParamTypes.size()) { 11721 if (ParamTypes[ParamIdx]->isDependentType()) 11722 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11723 Args[ArgIdx]->getType()); 11724 else { 11725 Cand->Conversions[ConvIdx] = 11726 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11727 SuppressUserConversions, 11728 /*InOverloadResolution=*/true, 11729 /*AllowObjCWritebackConversion=*/ 11730 S.getLangOpts().ObjCAutoRefCount); 11731 // Store the FixIt in the candidate if it exists. 11732 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11733 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11734 } 11735 } else 11736 Cand->Conversions[ConvIdx].setEllipsis(); 11737 } 11738 } 11739 11740 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11741 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11742 SourceLocation OpLoc, 11743 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11744 // Sort the candidates by viability and position. Sorting directly would 11745 // be prohibitive, so we make a set of pointers and sort those. 11746 SmallVector<OverloadCandidate*, 32> Cands; 11747 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11748 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11749 if (!Filter(*Cand)) 11750 continue; 11751 switch (OCD) { 11752 case OCD_AllCandidates: 11753 if (!Cand->Viable) { 11754 if (!Cand->Function && !Cand->IsSurrogate) { 11755 // This a non-viable builtin candidate. We do not, in general, 11756 // want to list every possible builtin candidate. 11757 continue; 11758 } 11759 CompleteNonViableCandidate(S, Cand, Args, Kind); 11760 } 11761 break; 11762 11763 case OCD_ViableCandidates: 11764 if (!Cand->Viable) 11765 continue; 11766 break; 11767 11768 case OCD_AmbiguousCandidates: 11769 if (!Cand->Best) 11770 continue; 11771 break; 11772 } 11773 11774 Cands.push_back(Cand); 11775 } 11776 11777 llvm::stable_sort( 11778 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11779 11780 return Cands; 11781 } 11782 11783 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11784 SourceLocation OpLoc) { 11785 bool DeferHint = false; 11786 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11787 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11788 // host device candidates. 11789 auto WrongSidedCands = 11790 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11791 return (Cand.Viable == false && 11792 Cand.FailureKind == ovl_fail_bad_target) || 11793 (Cand.Function && 11794 Cand.Function->template hasAttr<CUDAHostAttr>() && 11795 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11796 }); 11797 DeferHint = !WrongSidedCands.empty(); 11798 } 11799 return DeferHint; 11800 } 11801 11802 /// When overload resolution fails, prints diagnostic messages containing the 11803 /// candidates in the candidate set. 11804 void OverloadCandidateSet::NoteCandidates( 11805 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11806 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11807 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11808 11809 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11810 11811 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11812 11813 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11814 11815 if (OCD == OCD_AmbiguousCandidates) 11816 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11817 } 11818 11819 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11820 ArrayRef<OverloadCandidate *> Cands, 11821 StringRef Opc, SourceLocation OpLoc) { 11822 bool ReportedAmbiguousConversions = false; 11823 11824 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11825 unsigned CandsShown = 0; 11826 auto I = Cands.begin(), E = Cands.end(); 11827 for (; I != E; ++I) { 11828 OverloadCandidate *Cand = *I; 11829 11830 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11831 ShowOverloads == Ovl_Best) { 11832 break; 11833 } 11834 ++CandsShown; 11835 11836 if (Cand->Function) 11837 NoteFunctionCandidate(S, Cand, Args.size(), 11838 /*TakingCandidateAddress=*/false, DestAS); 11839 else if (Cand->IsSurrogate) 11840 NoteSurrogateCandidate(S, Cand); 11841 else { 11842 assert(Cand->Viable && 11843 "Non-viable built-in candidates are not added to Cands."); 11844 // Generally we only see ambiguities including viable builtin 11845 // operators if overload resolution got screwed up by an 11846 // ambiguous user-defined conversion. 11847 // 11848 // FIXME: It's quite possible for different conversions to see 11849 // different ambiguities, though. 11850 if (!ReportedAmbiguousConversions) { 11851 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11852 ReportedAmbiguousConversions = true; 11853 } 11854 11855 // If this is a viable builtin, print it. 11856 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11857 } 11858 } 11859 11860 // Inform S.Diags that we've shown an overload set with N elements. This may 11861 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11862 S.Diags.overloadCandidatesShown(CandsShown); 11863 11864 if (I != E) 11865 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11866 shouldDeferDiags(S, Args, OpLoc)) 11867 << int(E - I); 11868 } 11869 11870 static SourceLocation 11871 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11872 return Cand->Specialization ? Cand->Specialization->getLocation() 11873 : SourceLocation(); 11874 } 11875 11876 namespace { 11877 struct CompareTemplateSpecCandidatesForDisplay { 11878 Sema &S; 11879 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11880 11881 bool operator()(const TemplateSpecCandidate *L, 11882 const TemplateSpecCandidate *R) { 11883 // Fast-path this check. 11884 if (L == R) 11885 return false; 11886 11887 // Assuming that both candidates are not matches... 11888 11889 // Sort by the ranking of deduction failures. 11890 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11891 return RankDeductionFailure(L->DeductionFailure) < 11892 RankDeductionFailure(R->DeductionFailure); 11893 11894 // Sort everything else by location. 11895 SourceLocation LLoc = GetLocationForCandidate(L); 11896 SourceLocation RLoc = GetLocationForCandidate(R); 11897 11898 // Put candidates without locations (e.g. builtins) at the end. 11899 if (LLoc.isInvalid()) 11900 return false; 11901 if (RLoc.isInvalid()) 11902 return true; 11903 11904 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11905 } 11906 }; 11907 } 11908 11909 /// Diagnose a template argument deduction failure. 11910 /// We are treating these failures as overload failures due to bad 11911 /// deductions. 11912 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11913 bool ForTakingAddress) { 11914 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11915 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11916 } 11917 11918 void TemplateSpecCandidateSet::destroyCandidates() { 11919 for (iterator i = begin(), e = end(); i != e; ++i) { 11920 i->DeductionFailure.Destroy(); 11921 } 11922 } 11923 11924 void TemplateSpecCandidateSet::clear() { 11925 destroyCandidates(); 11926 Candidates.clear(); 11927 } 11928 11929 /// NoteCandidates - When no template specialization match is found, prints 11930 /// diagnostic messages containing the non-matching specializations that form 11931 /// the candidate set. 11932 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11933 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11934 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11935 // Sort the candidates by position (assuming no candidate is a match). 11936 // Sorting directly would be prohibitive, so we make a set of pointers 11937 // and sort those. 11938 SmallVector<TemplateSpecCandidate *, 32> Cands; 11939 Cands.reserve(size()); 11940 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11941 if (Cand->Specialization) 11942 Cands.push_back(Cand); 11943 // Otherwise, this is a non-matching builtin candidate. We do not, 11944 // in general, want to list every possible builtin candidate. 11945 } 11946 11947 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11948 11949 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11950 // for generalization purposes (?). 11951 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11952 11953 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11954 unsigned CandsShown = 0; 11955 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11956 TemplateSpecCandidate *Cand = *I; 11957 11958 // Set an arbitrary limit on the number of candidates we'll spam 11959 // the user with. FIXME: This limit should depend on details of the 11960 // candidate list. 11961 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11962 break; 11963 ++CandsShown; 11964 11965 assert(Cand->Specialization && 11966 "Non-matching built-in candidates are not added to Cands."); 11967 Cand->NoteDeductionFailure(S, ForTakingAddress); 11968 } 11969 11970 if (I != E) 11971 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11972 } 11973 11974 // [PossiblyAFunctionType] --> [Return] 11975 // NonFunctionType --> NonFunctionType 11976 // R (A) --> R(A) 11977 // R (*)(A) --> R (A) 11978 // R (&)(A) --> R (A) 11979 // R (S::*)(A) --> R (A) 11980 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11981 QualType Ret = PossiblyAFunctionType; 11982 if (const PointerType *ToTypePtr = 11983 PossiblyAFunctionType->getAs<PointerType>()) 11984 Ret = ToTypePtr->getPointeeType(); 11985 else if (const ReferenceType *ToTypeRef = 11986 PossiblyAFunctionType->getAs<ReferenceType>()) 11987 Ret = ToTypeRef->getPointeeType(); 11988 else if (const MemberPointerType *MemTypePtr = 11989 PossiblyAFunctionType->getAs<MemberPointerType>()) 11990 Ret = MemTypePtr->getPointeeType(); 11991 Ret = 11992 Context.getCanonicalType(Ret).getUnqualifiedType(); 11993 return Ret; 11994 } 11995 11996 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11997 bool Complain = true) { 11998 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11999 S.DeduceReturnType(FD, Loc, Complain)) 12000 return true; 12001 12002 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 12003 if (S.getLangOpts().CPlusPlus17 && 12004 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 12005 !S.ResolveExceptionSpec(Loc, FPT)) 12006 return true; 12007 12008 return false; 12009 } 12010 12011 namespace { 12012 // A helper class to help with address of function resolution 12013 // - allows us to avoid passing around all those ugly parameters 12014 class AddressOfFunctionResolver { 12015 Sema& S; 12016 Expr* SourceExpr; 12017 const QualType& TargetType; 12018 QualType TargetFunctionType; // Extracted function type from target type 12019 12020 bool Complain; 12021 //DeclAccessPair& ResultFunctionAccessPair; 12022 ASTContext& Context; 12023 12024 bool TargetTypeIsNonStaticMemberFunction; 12025 bool FoundNonTemplateFunction; 12026 bool StaticMemberFunctionFromBoundPointer; 12027 bool HasComplained; 12028 12029 OverloadExpr::FindResult OvlExprInfo; 12030 OverloadExpr *OvlExpr; 12031 TemplateArgumentListInfo OvlExplicitTemplateArgs; 12032 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 12033 TemplateSpecCandidateSet FailedCandidates; 12034 12035 public: 12036 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 12037 const QualType &TargetType, bool Complain) 12038 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 12039 Complain(Complain), Context(S.getASTContext()), 12040 TargetTypeIsNonStaticMemberFunction( 12041 !!TargetType->getAs<MemberPointerType>()), 12042 FoundNonTemplateFunction(false), 12043 StaticMemberFunctionFromBoundPointer(false), 12044 HasComplained(false), 12045 OvlExprInfo(OverloadExpr::find(SourceExpr)), 12046 OvlExpr(OvlExprInfo.Expression), 12047 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 12048 ExtractUnqualifiedFunctionTypeFromTargetType(); 12049 12050 if (TargetFunctionType->isFunctionType()) { 12051 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 12052 if (!UME->isImplicitAccess() && 12053 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 12054 StaticMemberFunctionFromBoundPointer = true; 12055 } else if (OvlExpr->hasExplicitTemplateArgs()) { 12056 DeclAccessPair dap; 12057 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 12058 OvlExpr, false, &dap)) { 12059 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 12060 if (!Method->isStatic()) { 12061 // If the target type is a non-function type and the function found 12062 // is a non-static member function, pretend as if that was the 12063 // target, it's the only possible type to end up with. 12064 TargetTypeIsNonStaticMemberFunction = true; 12065 12066 // And skip adding the function if its not in the proper form. 12067 // We'll diagnose this due to an empty set of functions. 12068 if (!OvlExprInfo.HasFormOfMemberPointer) 12069 return; 12070 } 12071 12072 Matches.push_back(std::make_pair(dap, Fn)); 12073 } 12074 return; 12075 } 12076 12077 if (OvlExpr->hasExplicitTemplateArgs()) 12078 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 12079 12080 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 12081 // C++ [over.over]p4: 12082 // If more than one function is selected, [...] 12083 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12084 if (FoundNonTemplateFunction) 12085 EliminateAllTemplateMatches(); 12086 else 12087 EliminateAllExceptMostSpecializedTemplate(); 12088 } 12089 } 12090 12091 if (S.getLangOpts().CUDA && Matches.size() > 1) 12092 EliminateSuboptimalCudaMatches(); 12093 } 12094 12095 bool hasComplained() const { return HasComplained; } 12096 12097 private: 12098 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12099 QualType Discard; 12100 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12101 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12102 } 12103 12104 /// \return true if A is considered a better overload candidate for the 12105 /// desired type than B. 12106 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12107 // If A doesn't have exactly the correct type, we don't want to classify it 12108 // as "better" than anything else. This way, the user is required to 12109 // disambiguate for us if there are multiple candidates and no exact match. 12110 return candidateHasExactlyCorrectType(A) && 12111 (!candidateHasExactlyCorrectType(B) || 12112 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12113 } 12114 12115 /// \return true if we were able to eliminate all but one overload candidate, 12116 /// false otherwise. 12117 bool eliminiateSuboptimalOverloadCandidates() { 12118 // Same algorithm as overload resolution -- one pass to pick the "best", 12119 // another pass to be sure that nothing is better than the best. 12120 auto Best = Matches.begin(); 12121 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12122 if (isBetterCandidate(I->second, Best->second)) 12123 Best = I; 12124 12125 const FunctionDecl *BestFn = Best->second; 12126 auto IsBestOrInferiorToBest = [this, BestFn]( 12127 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12128 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12129 }; 12130 12131 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12132 // option, so we can potentially give the user a better error 12133 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12134 return false; 12135 Matches[0] = *Best; 12136 Matches.resize(1); 12137 return true; 12138 } 12139 12140 bool isTargetTypeAFunction() const { 12141 return TargetFunctionType->isFunctionType(); 12142 } 12143 12144 // [ToType] [Return] 12145 12146 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12147 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12148 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12149 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12150 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12151 } 12152 12153 // return true if any matching specializations were found 12154 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12155 const DeclAccessPair& CurAccessFunPair) { 12156 if (CXXMethodDecl *Method 12157 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12158 // Skip non-static function templates when converting to pointer, and 12159 // static when converting to member pointer. 12160 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12161 return false; 12162 } 12163 else if (TargetTypeIsNonStaticMemberFunction) 12164 return false; 12165 12166 // C++ [over.over]p2: 12167 // If the name is a function template, template argument deduction is 12168 // done (14.8.2.2), and if the argument deduction succeeds, the 12169 // resulting template argument list is used to generate a single 12170 // function template specialization, which is added to the set of 12171 // overloaded functions considered. 12172 FunctionDecl *Specialization = nullptr; 12173 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12174 if (Sema::TemplateDeductionResult Result 12175 = S.DeduceTemplateArguments(FunctionTemplate, 12176 &OvlExplicitTemplateArgs, 12177 TargetFunctionType, Specialization, 12178 Info, /*IsAddressOfFunction*/true)) { 12179 // Make a note of the failed deduction for diagnostics. 12180 FailedCandidates.addCandidate() 12181 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12182 MakeDeductionFailureInfo(Context, Result, Info)); 12183 return false; 12184 } 12185 12186 // Template argument deduction ensures that we have an exact match or 12187 // compatible pointer-to-function arguments that would be adjusted by ICS. 12188 // This function template specicalization works. 12189 assert(S.isSameOrCompatibleFunctionType( 12190 Context.getCanonicalType(Specialization->getType()), 12191 Context.getCanonicalType(TargetFunctionType))); 12192 12193 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12194 return false; 12195 12196 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12197 return true; 12198 } 12199 12200 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12201 const DeclAccessPair& CurAccessFunPair) { 12202 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12203 // Skip non-static functions when converting to pointer, and static 12204 // when converting to member pointer. 12205 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12206 return false; 12207 } 12208 else if (TargetTypeIsNonStaticMemberFunction) 12209 return false; 12210 12211 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12212 if (S.getLangOpts().CUDA) 12213 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) 12214 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12215 return false; 12216 if (FunDecl->isMultiVersion()) { 12217 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12218 if (TA && !TA->isDefaultVersion()) 12219 return false; 12220 } 12221 12222 // If any candidate has a placeholder return type, trigger its deduction 12223 // now. 12224 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12225 Complain)) { 12226 HasComplained |= Complain; 12227 return false; 12228 } 12229 12230 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12231 return false; 12232 12233 // If we're in C, we need to support types that aren't exactly identical. 12234 if (!S.getLangOpts().CPlusPlus || 12235 candidateHasExactlyCorrectType(FunDecl)) { 12236 Matches.push_back(std::make_pair( 12237 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12238 FoundNonTemplateFunction = true; 12239 return true; 12240 } 12241 } 12242 12243 return false; 12244 } 12245 12246 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12247 bool Ret = false; 12248 12249 // If the overload expression doesn't have the form of a pointer to 12250 // member, don't try to convert it to a pointer-to-member type. 12251 if (IsInvalidFormOfPointerToMemberFunction()) 12252 return false; 12253 12254 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12255 E = OvlExpr->decls_end(); 12256 I != E; ++I) { 12257 // Look through any using declarations to find the underlying function. 12258 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12259 12260 // C++ [over.over]p3: 12261 // Non-member functions and static member functions match 12262 // targets of type "pointer-to-function" or "reference-to-function." 12263 // Nonstatic member functions match targets of 12264 // type "pointer-to-member-function." 12265 // Note that according to DR 247, the containing class does not matter. 12266 if (FunctionTemplateDecl *FunctionTemplate 12267 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12268 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12269 Ret = true; 12270 } 12271 // If we have explicit template arguments supplied, skip non-templates. 12272 else if (!OvlExpr->hasExplicitTemplateArgs() && 12273 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12274 Ret = true; 12275 } 12276 assert(Ret || Matches.empty()); 12277 return Ret; 12278 } 12279 12280 void EliminateAllExceptMostSpecializedTemplate() { 12281 // [...] and any given function template specialization F1 is 12282 // eliminated if the set contains a second function template 12283 // specialization whose function template is more specialized 12284 // than the function template of F1 according to the partial 12285 // ordering rules of 14.5.5.2. 12286 12287 // The algorithm specified above is quadratic. We instead use a 12288 // two-pass algorithm (similar to the one used to identify the 12289 // best viable function in an overload set) that identifies the 12290 // best function template (if it exists). 12291 12292 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12293 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12294 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12295 12296 // TODO: It looks like FailedCandidates does not serve much purpose 12297 // here, since the no_viable diagnostic has index 0. 12298 UnresolvedSetIterator Result = S.getMostSpecialized( 12299 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12300 SourceExpr->getBeginLoc(), S.PDiag(), 12301 S.PDiag(diag::err_addr_ovl_ambiguous) 12302 << Matches[0].second->getDeclName(), 12303 S.PDiag(diag::note_ovl_candidate) 12304 << (unsigned)oc_function << (unsigned)ocs_described_template, 12305 Complain, TargetFunctionType); 12306 12307 if (Result != MatchesCopy.end()) { 12308 // Make it the first and only element 12309 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12310 Matches[0].second = cast<FunctionDecl>(*Result); 12311 Matches.resize(1); 12312 } else 12313 HasComplained |= Complain; 12314 } 12315 12316 void EliminateAllTemplateMatches() { 12317 // [...] any function template specializations in the set are 12318 // eliminated if the set also contains a non-template function, [...] 12319 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12320 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12321 ++I; 12322 else { 12323 Matches[I] = Matches[--N]; 12324 Matches.resize(N); 12325 } 12326 } 12327 } 12328 12329 void EliminateSuboptimalCudaMatches() { 12330 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), 12331 Matches); 12332 } 12333 12334 public: 12335 void ComplainNoMatchesFound() const { 12336 assert(Matches.empty()); 12337 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12338 << OvlExpr->getName() << TargetFunctionType 12339 << OvlExpr->getSourceRange(); 12340 if (FailedCandidates.empty()) 12341 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12342 /*TakingAddress=*/true); 12343 else { 12344 // We have some deduction failure messages. Use them to diagnose 12345 // the function templates, and diagnose the non-template candidates 12346 // normally. 12347 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12348 IEnd = OvlExpr->decls_end(); 12349 I != IEnd; ++I) 12350 if (FunctionDecl *Fun = 12351 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12352 if (!functionHasPassObjectSizeParams(Fun)) 12353 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12354 /*TakingAddress=*/true); 12355 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12356 } 12357 } 12358 12359 bool IsInvalidFormOfPointerToMemberFunction() const { 12360 return TargetTypeIsNonStaticMemberFunction && 12361 !OvlExprInfo.HasFormOfMemberPointer; 12362 } 12363 12364 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12365 // TODO: Should we condition this on whether any functions might 12366 // have matched, or is it more appropriate to do that in callers? 12367 // TODO: a fixit wouldn't hurt. 12368 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12369 << TargetType << OvlExpr->getSourceRange(); 12370 } 12371 12372 bool IsStaticMemberFunctionFromBoundPointer() const { 12373 return StaticMemberFunctionFromBoundPointer; 12374 } 12375 12376 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12377 S.Diag(OvlExpr->getBeginLoc(), 12378 diag::err_invalid_form_pointer_member_function) 12379 << OvlExpr->getSourceRange(); 12380 } 12381 12382 void ComplainOfInvalidConversion() const { 12383 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12384 << OvlExpr->getName() << TargetType; 12385 } 12386 12387 void ComplainMultipleMatchesFound() const { 12388 assert(Matches.size() > 1); 12389 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12390 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12391 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12392 /*TakingAddress=*/true); 12393 } 12394 12395 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12396 12397 int getNumMatches() const { return Matches.size(); } 12398 12399 FunctionDecl* getMatchingFunctionDecl() const { 12400 if (Matches.size() != 1) return nullptr; 12401 return Matches[0].second; 12402 } 12403 12404 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12405 if (Matches.size() != 1) return nullptr; 12406 return &Matches[0].first; 12407 } 12408 }; 12409 } 12410 12411 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12412 /// an overloaded function (C++ [over.over]), where @p From is an 12413 /// expression with overloaded function type and @p ToType is the type 12414 /// we're trying to resolve to. For example: 12415 /// 12416 /// @code 12417 /// int f(double); 12418 /// int f(int); 12419 /// 12420 /// int (*pfd)(double) = f; // selects f(double) 12421 /// @endcode 12422 /// 12423 /// This routine returns the resulting FunctionDecl if it could be 12424 /// resolved, and NULL otherwise. When @p Complain is true, this 12425 /// routine will emit diagnostics if there is an error. 12426 FunctionDecl * 12427 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12428 QualType TargetType, 12429 bool Complain, 12430 DeclAccessPair &FoundResult, 12431 bool *pHadMultipleCandidates) { 12432 assert(AddressOfExpr->getType() == Context.OverloadTy); 12433 12434 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12435 Complain); 12436 int NumMatches = Resolver.getNumMatches(); 12437 FunctionDecl *Fn = nullptr; 12438 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12439 if (NumMatches == 0 && ShouldComplain) { 12440 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12441 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12442 else 12443 Resolver.ComplainNoMatchesFound(); 12444 } 12445 else if (NumMatches > 1 && ShouldComplain) 12446 Resolver.ComplainMultipleMatchesFound(); 12447 else if (NumMatches == 1) { 12448 Fn = Resolver.getMatchingFunctionDecl(); 12449 assert(Fn); 12450 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12451 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12452 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12453 if (Complain) { 12454 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12455 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12456 else 12457 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12458 } 12459 } 12460 12461 if (pHadMultipleCandidates) 12462 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12463 return Fn; 12464 } 12465 12466 /// Given an expression that refers to an overloaded function, try to 12467 /// resolve that function to a single function that can have its address taken. 12468 /// This will modify `Pair` iff it returns non-null. 12469 /// 12470 /// This routine can only succeed if from all of the candidates in the overload 12471 /// set for SrcExpr that can have their addresses taken, there is one candidate 12472 /// that is more constrained than the rest. 12473 FunctionDecl * 12474 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12475 OverloadExpr::FindResult R = OverloadExpr::find(E); 12476 OverloadExpr *Ovl = R.Expression; 12477 bool IsResultAmbiguous = false; 12478 FunctionDecl *Result = nullptr; 12479 DeclAccessPair DAP; 12480 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12481 12482 auto CheckMoreConstrained = 12483 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12484 SmallVector<const Expr *, 1> AC1, AC2; 12485 FD1->getAssociatedConstraints(AC1); 12486 FD2->getAssociatedConstraints(AC2); 12487 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12488 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12489 return None; 12490 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12491 return None; 12492 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12493 return None; 12494 return AtLeastAsConstrained1; 12495 }; 12496 12497 // Don't use the AddressOfResolver because we're specifically looking for 12498 // cases where we have one overload candidate that lacks 12499 // enable_if/pass_object_size/... 12500 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12501 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12502 if (!FD) 12503 return nullptr; 12504 12505 if (!checkAddressOfFunctionIsAvailable(FD)) 12506 continue; 12507 12508 // We have more than one result - see if it is more constrained than the 12509 // previous one. 12510 if (Result) { 12511 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12512 Result); 12513 if (!MoreConstrainedThanPrevious) { 12514 IsResultAmbiguous = true; 12515 AmbiguousDecls.push_back(FD); 12516 continue; 12517 } 12518 if (!*MoreConstrainedThanPrevious) 12519 continue; 12520 // FD is more constrained - replace Result with it. 12521 } 12522 IsResultAmbiguous = false; 12523 DAP = I.getPair(); 12524 Result = FD; 12525 } 12526 12527 if (IsResultAmbiguous) 12528 return nullptr; 12529 12530 if (Result) { 12531 SmallVector<const Expr *, 1> ResultAC; 12532 // We skipped over some ambiguous declarations which might be ambiguous with 12533 // the selected result. 12534 for (FunctionDecl *Skipped : AmbiguousDecls) 12535 if (!CheckMoreConstrained(Skipped, Result)) 12536 return nullptr; 12537 Pair = DAP; 12538 } 12539 return Result; 12540 } 12541 12542 /// Given an overloaded function, tries to turn it into a non-overloaded 12543 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12544 /// will perform access checks, diagnose the use of the resultant decl, and, if 12545 /// requested, potentially perform a function-to-pointer decay. 12546 /// 12547 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12548 /// Otherwise, returns true. This may emit diagnostics and return true. 12549 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12550 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12551 Expr *E = SrcExpr.get(); 12552 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12553 12554 DeclAccessPair DAP; 12555 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12556 if (!Found || Found->isCPUDispatchMultiVersion() || 12557 Found->isCPUSpecificMultiVersion()) 12558 return false; 12559 12560 // Emitting multiple diagnostics for a function that is both inaccessible and 12561 // unavailable is consistent with our behavior elsewhere. So, always check 12562 // for both. 12563 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12564 CheckAddressOfMemberAccess(E, DAP); 12565 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12566 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12567 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12568 else 12569 SrcExpr = Fixed; 12570 return true; 12571 } 12572 12573 /// Given an expression that refers to an overloaded function, try to 12574 /// resolve that overloaded function expression down to a single function. 12575 /// 12576 /// This routine can only resolve template-ids that refer to a single function 12577 /// template, where that template-id refers to a single template whose template 12578 /// arguments are either provided by the template-id or have defaults, 12579 /// as described in C++0x [temp.arg.explicit]p3. 12580 /// 12581 /// If no template-ids are found, no diagnostics are emitted and NULL is 12582 /// returned. 12583 FunctionDecl * 12584 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12585 bool Complain, 12586 DeclAccessPair *FoundResult) { 12587 // C++ [over.over]p1: 12588 // [...] [Note: any redundant set of parentheses surrounding the 12589 // overloaded function name is ignored (5.1). ] 12590 // C++ [over.over]p1: 12591 // [...] The overloaded function name can be preceded by the & 12592 // operator. 12593 12594 // If we didn't actually find any template-ids, we're done. 12595 if (!ovl->hasExplicitTemplateArgs()) 12596 return nullptr; 12597 12598 TemplateArgumentListInfo ExplicitTemplateArgs; 12599 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12600 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12601 12602 // Look through all of the overloaded functions, searching for one 12603 // whose type matches exactly. 12604 FunctionDecl *Matched = nullptr; 12605 for (UnresolvedSetIterator I = ovl->decls_begin(), 12606 E = ovl->decls_end(); I != E; ++I) { 12607 // C++0x [temp.arg.explicit]p3: 12608 // [...] In contexts where deduction is done and fails, or in contexts 12609 // where deduction is not done, if a template argument list is 12610 // specified and it, along with any default template arguments, 12611 // identifies a single function template specialization, then the 12612 // template-id is an lvalue for the function template specialization. 12613 FunctionTemplateDecl *FunctionTemplate 12614 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12615 12616 // C++ [over.over]p2: 12617 // If the name is a function template, template argument deduction is 12618 // done (14.8.2.2), and if the argument deduction succeeds, the 12619 // resulting template argument list is used to generate a single 12620 // function template specialization, which is added to the set of 12621 // overloaded functions considered. 12622 FunctionDecl *Specialization = nullptr; 12623 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12624 if (TemplateDeductionResult Result 12625 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12626 Specialization, Info, 12627 /*IsAddressOfFunction*/true)) { 12628 // Make a note of the failed deduction for diagnostics. 12629 // TODO: Actually use the failed-deduction info? 12630 FailedCandidates.addCandidate() 12631 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12632 MakeDeductionFailureInfo(Context, Result, Info)); 12633 continue; 12634 } 12635 12636 assert(Specialization && "no specialization and no error?"); 12637 12638 // Multiple matches; we can't resolve to a single declaration. 12639 if (Matched) { 12640 if (Complain) { 12641 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12642 << ovl->getName(); 12643 NoteAllOverloadCandidates(ovl); 12644 } 12645 return nullptr; 12646 } 12647 12648 Matched = Specialization; 12649 if (FoundResult) *FoundResult = I.getPair(); 12650 } 12651 12652 if (Matched && 12653 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12654 return nullptr; 12655 12656 return Matched; 12657 } 12658 12659 // Resolve and fix an overloaded expression that can be resolved 12660 // because it identifies a single function template specialization. 12661 // 12662 // Last three arguments should only be supplied if Complain = true 12663 // 12664 // Return true if it was logically possible to so resolve the 12665 // expression, regardless of whether or not it succeeded. Always 12666 // returns true if 'complain' is set. 12667 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12668 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12669 bool complain, SourceRange OpRangeForComplaining, 12670 QualType DestTypeForComplaining, 12671 unsigned DiagIDForComplaining) { 12672 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12673 12674 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12675 12676 DeclAccessPair found; 12677 ExprResult SingleFunctionExpression; 12678 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12679 ovl.Expression, /*complain*/ false, &found)) { 12680 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12681 SrcExpr = ExprError(); 12682 return true; 12683 } 12684 12685 // It is only correct to resolve to an instance method if we're 12686 // resolving a form that's permitted to be a pointer to member. 12687 // Otherwise we'll end up making a bound member expression, which 12688 // is illegal in all the contexts we resolve like this. 12689 if (!ovl.HasFormOfMemberPointer && 12690 isa<CXXMethodDecl>(fn) && 12691 cast<CXXMethodDecl>(fn)->isInstance()) { 12692 if (!complain) return false; 12693 12694 Diag(ovl.Expression->getExprLoc(), 12695 diag::err_bound_member_function) 12696 << 0 << ovl.Expression->getSourceRange(); 12697 12698 // TODO: I believe we only end up here if there's a mix of 12699 // static and non-static candidates (otherwise the expression 12700 // would have 'bound member' type, not 'overload' type). 12701 // Ideally we would note which candidate was chosen and why 12702 // the static candidates were rejected. 12703 SrcExpr = ExprError(); 12704 return true; 12705 } 12706 12707 // Fix the expression to refer to 'fn'. 12708 SingleFunctionExpression = 12709 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12710 12711 // If desired, do function-to-pointer decay. 12712 if (doFunctionPointerConverion) { 12713 SingleFunctionExpression = 12714 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12715 if (SingleFunctionExpression.isInvalid()) { 12716 SrcExpr = ExprError(); 12717 return true; 12718 } 12719 } 12720 } 12721 12722 if (!SingleFunctionExpression.isUsable()) { 12723 if (complain) { 12724 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12725 << ovl.Expression->getName() 12726 << DestTypeForComplaining 12727 << OpRangeForComplaining 12728 << ovl.Expression->getQualifierLoc().getSourceRange(); 12729 NoteAllOverloadCandidates(SrcExpr.get()); 12730 12731 SrcExpr = ExprError(); 12732 return true; 12733 } 12734 12735 return false; 12736 } 12737 12738 SrcExpr = SingleFunctionExpression; 12739 return true; 12740 } 12741 12742 /// Add a single candidate to the overload set. 12743 static void AddOverloadedCallCandidate(Sema &S, 12744 DeclAccessPair FoundDecl, 12745 TemplateArgumentListInfo *ExplicitTemplateArgs, 12746 ArrayRef<Expr *> Args, 12747 OverloadCandidateSet &CandidateSet, 12748 bool PartialOverloading, 12749 bool KnownValid) { 12750 NamedDecl *Callee = FoundDecl.getDecl(); 12751 if (isa<UsingShadowDecl>(Callee)) 12752 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12753 12754 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12755 if (ExplicitTemplateArgs) { 12756 assert(!KnownValid && "Explicit template arguments?"); 12757 return; 12758 } 12759 // Prevent ill-formed function decls to be added as overload candidates. 12760 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12761 return; 12762 12763 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12764 /*SuppressUserConversions=*/false, 12765 PartialOverloading); 12766 return; 12767 } 12768 12769 if (FunctionTemplateDecl *FuncTemplate 12770 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12771 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12772 ExplicitTemplateArgs, Args, CandidateSet, 12773 /*SuppressUserConversions=*/false, 12774 PartialOverloading); 12775 return; 12776 } 12777 12778 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12779 } 12780 12781 /// Add the overload candidates named by callee and/or found by argument 12782 /// dependent lookup to the given overload set. 12783 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12784 ArrayRef<Expr *> Args, 12785 OverloadCandidateSet &CandidateSet, 12786 bool PartialOverloading) { 12787 12788 #ifndef NDEBUG 12789 // Verify that ArgumentDependentLookup is consistent with the rules 12790 // in C++0x [basic.lookup.argdep]p3: 12791 // 12792 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12793 // and let Y be the lookup set produced by argument dependent 12794 // lookup (defined as follows). If X contains 12795 // 12796 // -- a declaration of a class member, or 12797 // 12798 // -- a block-scope function declaration that is not a 12799 // using-declaration, or 12800 // 12801 // -- a declaration that is neither a function or a function 12802 // template 12803 // 12804 // then Y is empty. 12805 12806 if (ULE->requiresADL()) { 12807 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12808 E = ULE->decls_end(); I != E; ++I) { 12809 assert(!(*I)->getDeclContext()->isRecord()); 12810 assert(isa<UsingShadowDecl>(*I) || 12811 !(*I)->getDeclContext()->isFunctionOrMethod()); 12812 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12813 } 12814 } 12815 #endif 12816 12817 // It would be nice to avoid this copy. 12818 TemplateArgumentListInfo TABuffer; 12819 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12820 if (ULE->hasExplicitTemplateArgs()) { 12821 ULE->copyTemplateArgumentsInto(TABuffer); 12822 ExplicitTemplateArgs = &TABuffer; 12823 } 12824 12825 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12826 E = ULE->decls_end(); I != E; ++I) 12827 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12828 CandidateSet, PartialOverloading, 12829 /*KnownValid*/ true); 12830 12831 if (ULE->requiresADL()) 12832 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12833 Args, ExplicitTemplateArgs, 12834 CandidateSet, PartialOverloading); 12835 } 12836 12837 /// Add the call candidates from the given set of lookup results to the given 12838 /// overload set. Non-function lookup results are ignored. 12839 void Sema::AddOverloadedCallCandidates( 12840 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12841 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12842 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12843 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12844 CandidateSet, false, /*KnownValid*/ false); 12845 } 12846 12847 /// Determine whether a declaration with the specified name could be moved into 12848 /// a different namespace. 12849 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12850 switch (Name.getCXXOverloadedOperator()) { 12851 case OO_New: case OO_Array_New: 12852 case OO_Delete: case OO_Array_Delete: 12853 return false; 12854 12855 default: 12856 return true; 12857 } 12858 } 12859 12860 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12861 /// template, where the non-dependent name was declared after the template 12862 /// was defined. This is common in code written for a compilers which do not 12863 /// correctly implement two-stage name lookup. 12864 /// 12865 /// Returns true if a viable candidate was found and a diagnostic was issued. 12866 static bool DiagnoseTwoPhaseLookup( 12867 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12868 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12869 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12870 CXXRecordDecl **FoundInClass = nullptr) { 12871 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12872 return false; 12873 12874 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12875 if (DC->isTransparentContext()) 12876 continue; 12877 12878 SemaRef.LookupQualifiedName(R, DC); 12879 12880 if (!R.empty()) { 12881 R.suppressDiagnostics(); 12882 12883 OverloadCandidateSet Candidates(FnLoc, CSK); 12884 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12885 Candidates); 12886 12887 OverloadCandidateSet::iterator Best; 12888 OverloadingResult OR = 12889 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12890 12891 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12892 // We either found non-function declarations or a best viable function 12893 // at class scope. A class-scope lookup result disables ADL. Don't 12894 // look past this, but let the caller know that we found something that 12895 // either is, or might be, usable in this class. 12896 if (FoundInClass) { 12897 *FoundInClass = RD; 12898 if (OR == OR_Success) { 12899 R.clear(); 12900 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12901 R.resolveKind(); 12902 } 12903 } 12904 return false; 12905 } 12906 12907 if (OR != OR_Success) { 12908 // There wasn't a unique best function or function template. 12909 return false; 12910 } 12911 12912 // Find the namespaces where ADL would have looked, and suggest 12913 // declaring the function there instead. 12914 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12915 Sema::AssociatedClassSet AssociatedClasses; 12916 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12917 AssociatedNamespaces, 12918 AssociatedClasses); 12919 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12920 if (canBeDeclaredInNamespace(R.getLookupName())) { 12921 DeclContext *Std = SemaRef.getStdNamespace(); 12922 for (Sema::AssociatedNamespaceSet::iterator 12923 it = AssociatedNamespaces.begin(), 12924 end = AssociatedNamespaces.end(); it != end; ++it) { 12925 // Never suggest declaring a function within namespace 'std'. 12926 if (Std && Std->Encloses(*it)) 12927 continue; 12928 12929 // Never suggest declaring a function within a namespace with a 12930 // reserved name, like __gnu_cxx. 12931 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12932 if (NS && 12933 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12934 continue; 12935 12936 SuggestedNamespaces.insert(*it); 12937 } 12938 } 12939 12940 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12941 << R.getLookupName(); 12942 if (SuggestedNamespaces.empty()) { 12943 SemaRef.Diag(Best->Function->getLocation(), 12944 diag::note_not_found_by_two_phase_lookup) 12945 << R.getLookupName() << 0; 12946 } else if (SuggestedNamespaces.size() == 1) { 12947 SemaRef.Diag(Best->Function->getLocation(), 12948 diag::note_not_found_by_two_phase_lookup) 12949 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12950 } else { 12951 // FIXME: It would be useful to list the associated namespaces here, 12952 // but the diagnostics infrastructure doesn't provide a way to produce 12953 // a localized representation of a list of items. 12954 SemaRef.Diag(Best->Function->getLocation(), 12955 diag::note_not_found_by_two_phase_lookup) 12956 << R.getLookupName() << 2; 12957 } 12958 12959 // Try to recover by calling this function. 12960 return true; 12961 } 12962 12963 R.clear(); 12964 } 12965 12966 return false; 12967 } 12968 12969 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12970 /// template, where the non-dependent operator was declared after the template 12971 /// was defined. 12972 /// 12973 /// Returns true if a viable candidate was found and a diagnostic was issued. 12974 static bool 12975 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12976 SourceLocation OpLoc, 12977 ArrayRef<Expr *> Args) { 12978 DeclarationName OpName = 12979 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12980 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12981 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12982 OverloadCandidateSet::CSK_Operator, 12983 /*ExplicitTemplateArgs=*/nullptr, Args); 12984 } 12985 12986 namespace { 12987 class BuildRecoveryCallExprRAII { 12988 Sema &SemaRef; 12989 public: 12990 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12991 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12992 SemaRef.IsBuildingRecoveryCallExpr = true; 12993 } 12994 12995 ~BuildRecoveryCallExprRAII() { 12996 SemaRef.IsBuildingRecoveryCallExpr = false; 12997 } 12998 }; 12999 13000 } 13001 13002 /// Attempts to recover from a call where no functions were found. 13003 /// 13004 /// This function will do one of three things: 13005 /// * Diagnose, recover, and return a recovery expression. 13006 /// * Diagnose, fail to recover, and return ExprError(). 13007 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 13008 /// expected to diagnose as appropriate. 13009 static ExprResult 13010 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13011 UnresolvedLookupExpr *ULE, 13012 SourceLocation LParenLoc, 13013 MutableArrayRef<Expr *> Args, 13014 SourceLocation RParenLoc, 13015 bool EmptyLookup, bool AllowTypoCorrection) { 13016 // Do not try to recover if it is already building a recovery call. 13017 // This stops infinite loops for template instantiations like 13018 // 13019 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 13020 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 13021 if (SemaRef.IsBuildingRecoveryCallExpr) 13022 return ExprResult(); 13023 BuildRecoveryCallExprRAII RCE(SemaRef); 13024 13025 CXXScopeSpec SS; 13026 SS.Adopt(ULE->getQualifierLoc()); 13027 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 13028 13029 TemplateArgumentListInfo TABuffer; 13030 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13031 if (ULE->hasExplicitTemplateArgs()) { 13032 ULE->copyTemplateArgumentsInto(TABuffer); 13033 ExplicitTemplateArgs = &TABuffer; 13034 } 13035 13036 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 13037 Sema::LookupOrdinaryName); 13038 CXXRecordDecl *FoundInClass = nullptr; 13039 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 13040 OverloadCandidateSet::CSK_Normal, 13041 ExplicitTemplateArgs, Args, &FoundInClass)) { 13042 // OK, diagnosed a two-phase lookup issue. 13043 } else if (EmptyLookup) { 13044 // Try to recover from an empty lookup with typo correction. 13045 R.clear(); 13046 NoTypoCorrectionCCC NoTypoValidator{}; 13047 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 13048 ExplicitTemplateArgs != nullptr, 13049 dyn_cast<MemberExpr>(Fn)); 13050 CorrectionCandidateCallback &Validator = 13051 AllowTypoCorrection 13052 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 13053 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 13054 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 13055 Args)) 13056 return ExprError(); 13057 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 13058 // We found a usable declaration of the name in a dependent base of some 13059 // enclosing class. 13060 // FIXME: We should also explain why the candidates found by name lookup 13061 // were not viable. 13062 if (SemaRef.DiagnoseDependentMemberLookup(R)) 13063 return ExprError(); 13064 } else { 13065 // We had viable candidates and couldn't recover; let the caller diagnose 13066 // this. 13067 return ExprResult(); 13068 } 13069 13070 // If we get here, we should have issued a diagnostic and formed a recovery 13071 // lookup result. 13072 assert(!R.empty() && "lookup results empty despite recovery"); 13073 13074 // If recovery created an ambiguity, just bail out. 13075 if (R.isAmbiguous()) { 13076 R.suppressDiagnostics(); 13077 return ExprError(); 13078 } 13079 13080 // Build an implicit member call if appropriate. Just drop the 13081 // casts and such from the call, we don't really care. 13082 ExprResult NewFn = ExprError(); 13083 if ((*R.begin())->isCXXClassMember()) 13084 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13085 ExplicitTemplateArgs, S); 13086 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13087 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13088 ExplicitTemplateArgs); 13089 else 13090 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13091 13092 if (NewFn.isInvalid()) 13093 return ExprError(); 13094 13095 // This shouldn't cause an infinite loop because we're giving it 13096 // an expression with viable lookup results, which should never 13097 // end up here. 13098 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13099 MultiExprArg(Args.data(), Args.size()), 13100 RParenLoc); 13101 } 13102 13103 /// Constructs and populates an OverloadedCandidateSet from 13104 /// the given function. 13105 /// \returns true when an the ExprResult output parameter has been set. 13106 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13107 UnresolvedLookupExpr *ULE, 13108 MultiExprArg Args, 13109 SourceLocation RParenLoc, 13110 OverloadCandidateSet *CandidateSet, 13111 ExprResult *Result) { 13112 #ifndef NDEBUG 13113 if (ULE->requiresADL()) { 13114 // To do ADL, we must have found an unqualified name. 13115 assert(!ULE->getQualifier() && "qualified name with ADL"); 13116 13117 // We don't perform ADL for implicit declarations of builtins. 13118 // Verify that this was correctly set up. 13119 FunctionDecl *F; 13120 if (ULE->decls_begin() != ULE->decls_end() && 13121 ULE->decls_begin() + 1 == ULE->decls_end() && 13122 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13123 F->getBuiltinID() && F->isImplicit()) 13124 llvm_unreachable("performing ADL for builtin"); 13125 13126 // We don't perform ADL in C. 13127 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13128 } 13129 #endif 13130 13131 UnbridgedCastsSet UnbridgedCasts; 13132 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13133 *Result = ExprError(); 13134 return true; 13135 } 13136 13137 // Add the functions denoted by the callee to the set of candidate 13138 // functions, including those from argument-dependent lookup. 13139 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13140 13141 if (getLangOpts().MSVCCompat && 13142 CurContext->isDependentContext() && !isSFINAEContext() && 13143 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13144 13145 OverloadCandidateSet::iterator Best; 13146 if (CandidateSet->empty() || 13147 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13148 OR_No_Viable_Function) { 13149 // In Microsoft mode, if we are inside a template class member function 13150 // then create a type dependent CallExpr. The goal is to postpone name 13151 // lookup to instantiation time to be able to search into type dependent 13152 // base classes. 13153 CallExpr *CE = 13154 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13155 RParenLoc, CurFPFeatureOverrides()); 13156 CE->markDependentForPostponedNameLookup(); 13157 *Result = CE; 13158 return true; 13159 } 13160 } 13161 13162 if (CandidateSet->empty()) 13163 return false; 13164 13165 UnbridgedCasts.restore(); 13166 return false; 13167 } 13168 13169 // Guess at what the return type for an unresolvable overload should be. 13170 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13171 OverloadCandidateSet::iterator *Best) { 13172 llvm::Optional<QualType> Result; 13173 // Adjust Type after seeing a candidate. 13174 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13175 if (!Candidate.Function) 13176 return; 13177 if (Candidate.Function->isInvalidDecl()) 13178 return; 13179 QualType T = Candidate.Function->getReturnType(); 13180 if (T.isNull()) 13181 return; 13182 if (!Result) 13183 Result = T; 13184 else if (Result != T) 13185 Result = QualType(); 13186 }; 13187 13188 // Look for an unambiguous type from a progressively larger subset. 13189 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13190 // 13191 // First, consider only the best candidate. 13192 if (Best && *Best != CS.end()) 13193 ConsiderCandidate(**Best); 13194 // Next, consider only viable candidates. 13195 if (!Result) 13196 for (const auto &C : CS) 13197 if (C.Viable) 13198 ConsiderCandidate(C); 13199 // Finally, consider all candidates. 13200 if (!Result) 13201 for (const auto &C : CS) 13202 ConsiderCandidate(C); 13203 13204 if (!Result) 13205 return QualType(); 13206 auto Value = *Result; 13207 if (Value.isNull() || Value->isUndeducedType()) 13208 return QualType(); 13209 return Value; 13210 } 13211 13212 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13213 /// the completed call expression. If overload resolution fails, emits 13214 /// diagnostics and returns ExprError() 13215 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13216 UnresolvedLookupExpr *ULE, 13217 SourceLocation LParenLoc, 13218 MultiExprArg Args, 13219 SourceLocation RParenLoc, 13220 Expr *ExecConfig, 13221 OverloadCandidateSet *CandidateSet, 13222 OverloadCandidateSet::iterator *Best, 13223 OverloadingResult OverloadResult, 13224 bool AllowTypoCorrection) { 13225 switch (OverloadResult) { 13226 case OR_Success: { 13227 FunctionDecl *FDecl = (*Best)->Function; 13228 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13229 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13230 return ExprError(); 13231 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13232 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13233 ExecConfig, /*IsExecConfig=*/false, 13234 (*Best)->IsADLCandidate); 13235 } 13236 13237 case OR_No_Viable_Function: { 13238 // Try to recover by looking for viable functions which the user might 13239 // have meant to call. 13240 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13241 Args, RParenLoc, 13242 CandidateSet->empty(), 13243 AllowTypoCorrection); 13244 if (Recovery.isInvalid() || Recovery.isUsable()) 13245 return Recovery; 13246 13247 // If the user passes in a function that we can't take the address of, we 13248 // generally end up emitting really bad error messages. Here, we attempt to 13249 // emit better ones. 13250 for (const Expr *Arg : Args) { 13251 if (!Arg->getType()->isFunctionType()) 13252 continue; 13253 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13254 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13255 if (FD && 13256 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13257 Arg->getExprLoc())) 13258 return ExprError(); 13259 } 13260 } 13261 13262 CandidateSet->NoteCandidates( 13263 PartialDiagnosticAt( 13264 Fn->getBeginLoc(), 13265 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13266 << ULE->getName() << Fn->getSourceRange()), 13267 SemaRef, OCD_AllCandidates, Args); 13268 break; 13269 } 13270 13271 case OR_Ambiguous: 13272 CandidateSet->NoteCandidates( 13273 PartialDiagnosticAt(Fn->getBeginLoc(), 13274 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13275 << ULE->getName() << Fn->getSourceRange()), 13276 SemaRef, OCD_AmbiguousCandidates, Args); 13277 break; 13278 13279 case OR_Deleted: { 13280 CandidateSet->NoteCandidates( 13281 PartialDiagnosticAt(Fn->getBeginLoc(), 13282 SemaRef.PDiag(diag::err_ovl_deleted_call) 13283 << ULE->getName() << Fn->getSourceRange()), 13284 SemaRef, OCD_AllCandidates, Args); 13285 13286 // We emitted an error for the unavailable/deleted function call but keep 13287 // the call in the AST. 13288 FunctionDecl *FDecl = (*Best)->Function; 13289 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13290 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13291 ExecConfig, /*IsExecConfig=*/false, 13292 (*Best)->IsADLCandidate); 13293 } 13294 } 13295 13296 // Overload resolution failed, try to recover. 13297 SmallVector<Expr *, 8> SubExprs = {Fn}; 13298 SubExprs.append(Args.begin(), Args.end()); 13299 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13300 chooseRecoveryType(*CandidateSet, Best)); 13301 } 13302 13303 static void markUnaddressableCandidatesUnviable(Sema &S, 13304 OverloadCandidateSet &CS) { 13305 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13306 if (I->Viable && 13307 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13308 I->Viable = false; 13309 I->FailureKind = ovl_fail_addr_not_available; 13310 } 13311 } 13312 } 13313 13314 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13315 /// (which eventually refers to the declaration Func) and the call 13316 /// arguments Args/NumArgs, attempt to resolve the function call down 13317 /// to a specific function. If overload resolution succeeds, returns 13318 /// the call expression produced by overload resolution. 13319 /// Otherwise, emits diagnostics and returns ExprError. 13320 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13321 UnresolvedLookupExpr *ULE, 13322 SourceLocation LParenLoc, 13323 MultiExprArg Args, 13324 SourceLocation RParenLoc, 13325 Expr *ExecConfig, 13326 bool AllowTypoCorrection, 13327 bool CalleesAddressIsTaken) { 13328 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13329 OverloadCandidateSet::CSK_Normal); 13330 ExprResult result; 13331 13332 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13333 &result)) 13334 return result; 13335 13336 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13337 // functions that aren't addressible are considered unviable. 13338 if (CalleesAddressIsTaken) 13339 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13340 13341 OverloadCandidateSet::iterator Best; 13342 OverloadingResult OverloadResult = 13343 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13344 13345 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13346 ExecConfig, &CandidateSet, &Best, 13347 OverloadResult, AllowTypoCorrection); 13348 } 13349 13350 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13351 return Functions.size() > 1 || 13352 (Functions.size() == 1 && 13353 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13354 } 13355 13356 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13357 NestedNameSpecifierLoc NNSLoc, 13358 DeclarationNameInfo DNI, 13359 const UnresolvedSetImpl &Fns, 13360 bool PerformADL) { 13361 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13362 PerformADL, IsOverloaded(Fns), 13363 Fns.begin(), Fns.end()); 13364 } 13365 13366 /// Create a unary operation that may resolve to an overloaded 13367 /// operator. 13368 /// 13369 /// \param OpLoc The location of the operator itself (e.g., '*'). 13370 /// 13371 /// \param Opc The UnaryOperatorKind that describes this operator. 13372 /// 13373 /// \param Fns The set of non-member functions that will be 13374 /// considered by overload resolution. The caller needs to build this 13375 /// set based on the context using, e.g., 13376 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13377 /// set should not contain any member functions; those will be added 13378 /// by CreateOverloadedUnaryOp(). 13379 /// 13380 /// \param Input The input argument. 13381 ExprResult 13382 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13383 const UnresolvedSetImpl &Fns, 13384 Expr *Input, bool PerformADL) { 13385 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13386 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13387 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13388 // TODO: provide better source location info. 13389 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13390 13391 if (checkPlaceholderForOverload(*this, Input)) 13392 return ExprError(); 13393 13394 Expr *Args[2] = { Input, nullptr }; 13395 unsigned NumArgs = 1; 13396 13397 // For post-increment and post-decrement, add the implicit '0' as 13398 // the second argument, so that we know this is a post-increment or 13399 // post-decrement. 13400 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13401 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13402 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13403 SourceLocation()); 13404 NumArgs = 2; 13405 } 13406 13407 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13408 13409 if (Input->isTypeDependent()) { 13410 if (Fns.empty()) 13411 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13412 VK_PRValue, OK_Ordinary, OpLoc, false, 13413 CurFPFeatureOverrides()); 13414 13415 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13416 ExprResult Fn = CreateUnresolvedLookupExpr( 13417 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13418 if (Fn.isInvalid()) 13419 return ExprError(); 13420 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13421 Context.DependentTy, VK_PRValue, OpLoc, 13422 CurFPFeatureOverrides()); 13423 } 13424 13425 // Build an empty overload set. 13426 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13427 13428 // Add the candidates from the given function set. 13429 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13430 13431 // Add operator candidates that are member functions. 13432 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13433 13434 // Add candidates from ADL. 13435 if (PerformADL) { 13436 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13437 /*ExplicitTemplateArgs*/nullptr, 13438 CandidateSet); 13439 } 13440 13441 // Add builtin operator candidates. 13442 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13443 13444 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13445 13446 // Perform overload resolution. 13447 OverloadCandidateSet::iterator Best; 13448 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13449 case OR_Success: { 13450 // We found a built-in operator or an overloaded operator. 13451 FunctionDecl *FnDecl = Best->Function; 13452 13453 if (FnDecl) { 13454 Expr *Base = nullptr; 13455 // We matched an overloaded operator. Build a call to that 13456 // operator. 13457 13458 // Convert the arguments. 13459 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13460 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13461 13462 ExprResult InputRes = 13463 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13464 Best->FoundDecl, Method); 13465 if (InputRes.isInvalid()) 13466 return ExprError(); 13467 Base = Input = InputRes.get(); 13468 } else { 13469 // Convert the arguments. 13470 ExprResult InputInit 13471 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13472 Context, 13473 FnDecl->getParamDecl(0)), 13474 SourceLocation(), 13475 Input); 13476 if (InputInit.isInvalid()) 13477 return ExprError(); 13478 Input = InputInit.get(); 13479 } 13480 13481 // Build the actual expression node. 13482 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13483 Base, HadMultipleCandidates, 13484 OpLoc); 13485 if (FnExpr.isInvalid()) 13486 return ExprError(); 13487 13488 // Determine the result type. 13489 QualType ResultTy = FnDecl->getReturnType(); 13490 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13491 ResultTy = ResultTy.getNonLValueExprType(Context); 13492 13493 Args[0] = Input; 13494 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13495 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13496 CurFPFeatureOverrides(), Best->IsADLCandidate); 13497 13498 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13499 return ExprError(); 13500 13501 if (CheckFunctionCall(FnDecl, TheCall, 13502 FnDecl->getType()->castAs<FunctionProtoType>())) 13503 return ExprError(); 13504 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13505 } else { 13506 // We matched a built-in operator. Convert the arguments, then 13507 // break out so that we will build the appropriate built-in 13508 // operator node. 13509 ExprResult InputRes = PerformImplicitConversion( 13510 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13511 CCK_ForBuiltinOverloadedOp); 13512 if (InputRes.isInvalid()) 13513 return ExprError(); 13514 Input = InputRes.get(); 13515 break; 13516 } 13517 } 13518 13519 case OR_No_Viable_Function: 13520 // This is an erroneous use of an operator which can be overloaded by 13521 // a non-member function. Check for non-member operators which were 13522 // defined too late to be candidates. 13523 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13524 // FIXME: Recover by calling the found function. 13525 return ExprError(); 13526 13527 // No viable function; fall through to handling this as a 13528 // built-in operator, which will produce an error message for us. 13529 break; 13530 13531 case OR_Ambiguous: 13532 CandidateSet.NoteCandidates( 13533 PartialDiagnosticAt(OpLoc, 13534 PDiag(diag::err_ovl_ambiguous_oper_unary) 13535 << UnaryOperator::getOpcodeStr(Opc) 13536 << Input->getType() << Input->getSourceRange()), 13537 *this, OCD_AmbiguousCandidates, ArgsArray, 13538 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13539 return ExprError(); 13540 13541 case OR_Deleted: 13542 CandidateSet.NoteCandidates( 13543 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13544 << UnaryOperator::getOpcodeStr(Opc) 13545 << Input->getSourceRange()), 13546 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13547 OpLoc); 13548 return ExprError(); 13549 } 13550 13551 // Either we found no viable overloaded operator or we matched a 13552 // built-in operator. In either case, fall through to trying to 13553 // build a built-in operation. 13554 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13555 } 13556 13557 /// Perform lookup for an overloaded binary operator. 13558 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13559 OverloadedOperatorKind Op, 13560 const UnresolvedSetImpl &Fns, 13561 ArrayRef<Expr *> Args, bool PerformADL) { 13562 SourceLocation OpLoc = CandidateSet.getLocation(); 13563 13564 OverloadedOperatorKind ExtraOp = 13565 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13566 ? getRewrittenOverloadedOperator(Op) 13567 : OO_None; 13568 13569 // Add the candidates from the given function set. This also adds the 13570 // rewritten candidates using these functions if necessary. 13571 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13572 13573 // Add operator candidates that are member functions. 13574 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13575 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13576 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13577 OverloadCandidateParamOrder::Reversed); 13578 13579 // In C++20, also add any rewritten member candidates. 13580 if (ExtraOp) { 13581 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13582 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13583 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13584 CandidateSet, 13585 OverloadCandidateParamOrder::Reversed); 13586 } 13587 13588 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13589 // performed for an assignment operator (nor for operator[] nor operator->, 13590 // which don't get here). 13591 if (Op != OO_Equal && PerformADL) { 13592 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13593 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13594 /*ExplicitTemplateArgs*/ nullptr, 13595 CandidateSet); 13596 if (ExtraOp) { 13597 DeclarationName ExtraOpName = 13598 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13599 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13600 /*ExplicitTemplateArgs*/ nullptr, 13601 CandidateSet); 13602 } 13603 } 13604 13605 // Add builtin operator candidates. 13606 // 13607 // FIXME: We don't add any rewritten candidates here. This is strictly 13608 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13609 // resulting in our selecting a rewritten builtin candidate. For example: 13610 // 13611 // enum class E { e }; 13612 // bool operator!=(E, E) requires false; 13613 // bool k = E::e != E::e; 13614 // 13615 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13616 // it seems unreasonable to consider rewritten builtin candidates. A core 13617 // issue has been filed proposing to removed this requirement. 13618 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13619 } 13620 13621 /// Create a binary operation that may resolve to an overloaded 13622 /// operator. 13623 /// 13624 /// \param OpLoc The location of the operator itself (e.g., '+'). 13625 /// 13626 /// \param Opc The BinaryOperatorKind that describes this operator. 13627 /// 13628 /// \param Fns The set of non-member functions that will be 13629 /// considered by overload resolution. The caller needs to build this 13630 /// set based on the context using, e.g., 13631 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13632 /// set should not contain any member functions; those will be added 13633 /// by CreateOverloadedBinOp(). 13634 /// 13635 /// \param LHS Left-hand argument. 13636 /// \param RHS Right-hand argument. 13637 /// \param PerformADL Whether to consider operator candidates found by ADL. 13638 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13639 /// C++20 operator rewrites. 13640 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13641 /// the function in question. Such a function is never a candidate in 13642 /// our overload resolution. This also enables synthesizing a three-way 13643 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13644 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13645 BinaryOperatorKind Opc, 13646 const UnresolvedSetImpl &Fns, Expr *LHS, 13647 Expr *RHS, bool PerformADL, 13648 bool AllowRewrittenCandidates, 13649 FunctionDecl *DefaultedFn) { 13650 Expr *Args[2] = { LHS, RHS }; 13651 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13652 13653 if (!getLangOpts().CPlusPlus20) 13654 AllowRewrittenCandidates = false; 13655 13656 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13657 13658 // If either side is type-dependent, create an appropriate dependent 13659 // expression. 13660 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13661 if (Fns.empty()) { 13662 // If there are no functions to store, just build a dependent 13663 // BinaryOperator or CompoundAssignment. 13664 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13665 return CompoundAssignOperator::Create( 13666 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13667 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13668 Context.DependentTy); 13669 return BinaryOperator::Create( 13670 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 13671 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13672 } 13673 13674 // FIXME: save results of ADL from here? 13675 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13676 // TODO: provide better source location info in DNLoc component. 13677 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13678 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13679 ExprResult Fn = CreateUnresolvedLookupExpr( 13680 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13681 if (Fn.isInvalid()) 13682 return ExprError(); 13683 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13684 Context.DependentTy, VK_PRValue, OpLoc, 13685 CurFPFeatureOverrides()); 13686 } 13687 13688 // Always do placeholder-like conversions on the RHS. 13689 if (checkPlaceholderForOverload(*this, Args[1])) 13690 return ExprError(); 13691 13692 // Do placeholder-like conversion on the LHS; note that we should 13693 // not get here with a PseudoObject LHS. 13694 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13695 if (checkPlaceholderForOverload(*this, Args[0])) 13696 return ExprError(); 13697 13698 // If this is the assignment operator, we only perform overload resolution 13699 // if the left-hand side is a class or enumeration type. This is actually 13700 // a hack. The standard requires that we do overload resolution between the 13701 // various built-in candidates, but as DR507 points out, this can lead to 13702 // problems. So we do it this way, which pretty much follows what GCC does. 13703 // Note that we go the traditional code path for compound assignment forms. 13704 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13705 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13706 13707 // If this is the .* operator, which is not overloadable, just 13708 // create a built-in binary operator. 13709 if (Opc == BO_PtrMemD) 13710 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13711 13712 // Build the overload set. 13713 OverloadCandidateSet CandidateSet( 13714 OpLoc, OverloadCandidateSet::CSK_Operator, 13715 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13716 if (DefaultedFn) 13717 CandidateSet.exclude(DefaultedFn); 13718 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13719 13720 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13721 13722 // Perform overload resolution. 13723 OverloadCandidateSet::iterator Best; 13724 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13725 case OR_Success: { 13726 // We found a built-in operator or an overloaded operator. 13727 FunctionDecl *FnDecl = Best->Function; 13728 13729 bool IsReversed = Best->isReversed(); 13730 if (IsReversed) 13731 std::swap(Args[0], Args[1]); 13732 13733 if (FnDecl) { 13734 Expr *Base = nullptr; 13735 // We matched an overloaded operator. Build a call to that 13736 // operator. 13737 13738 OverloadedOperatorKind ChosenOp = 13739 FnDecl->getDeclName().getCXXOverloadedOperator(); 13740 13741 // C++2a [over.match.oper]p9: 13742 // If a rewritten operator== candidate is selected by overload 13743 // resolution for an operator@, its return type shall be cv bool 13744 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13745 !FnDecl->getReturnType()->isBooleanType()) { 13746 bool IsExtension = 13747 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13748 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13749 : diag::err_ovl_rewrite_equalequal_not_bool) 13750 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13751 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13752 Diag(FnDecl->getLocation(), diag::note_declared_at); 13753 if (!IsExtension) 13754 return ExprError(); 13755 } 13756 13757 if (AllowRewrittenCandidates && !IsReversed && 13758 CandidateSet.getRewriteInfo().isReversible()) { 13759 // We could have reversed this operator, but didn't. Check if some 13760 // reversed form was a viable candidate, and if so, if it had a 13761 // better conversion for either parameter. If so, this call is 13762 // formally ambiguous, and allowing it is an extension. 13763 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13764 for (OverloadCandidate &Cand : CandidateSet) { 13765 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13766 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13767 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13768 if (CompareImplicitConversionSequences( 13769 *this, OpLoc, Cand.Conversions[ArgIdx], 13770 Best->Conversions[ArgIdx]) == 13771 ImplicitConversionSequence::Better) { 13772 AmbiguousWith.push_back(Cand.Function); 13773 break; 13774 } 13775 } 13776 } 13777 } 13778 13779 if (!AmbiguousWith.empty()) { 13780 bool AmbiguousWithSelf = 13781 AmbiguousWith.size() == 1 && 13782 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13783 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13784 << BinaryOperator::getOpcodeStr(Opc) 13785 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13786 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13787 if (AmbiguousWithSelf) { 13788 Diag(FnDecl->getLocation(), 13789 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13790 } else { 13791 Diag(FnDecl->getLocation(), 13792 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13793 for (auto *F : AmbiguousWith) 13794 Diag(F->getLocation(), 13795 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13796 } 13797 } 13798 } 13799 13800 // Convert the arguments. 13801 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13802 // Best->Access is only meaningful for class members. 13803 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13804 13805 ExprResult Arg1 = 13806 PerformCopyInitialization( 13807 InitializedEntity::InitializeParameter(Context, 13808 FnDecl->getParamDecl(0)), 13809 SourceLocation(), Args[1]); 13810 if (Arg1.isInvalid()) 13811 return ExprError(); 13812 13813 ExprResult Arg0 = 13814 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13815 Best->FoundDecl, Method); 13816 if (Arg0.isInvalid()) 13817 return ExprError(); 13818 Base = Args[0] = Arg0.getAs<Expr>(); 13819 Args[1] = RHS = Arg1.getAs<Expr>(); 13820 } else { 13821 // Convert the arguments. 13822 ExprResult Arg0 = PerformCopyInitialization( 13823 InitializedEntity::InitializeParameter(Context, 13824 FnDecl->getParamDecl(0)), 13825 SourceLocation(), Args[0]); 13826 if (Arg0.isInvalid()) 13827 return ExprError(); 13828 13829 ExprResult Arg1 = 13830 PerformCopyInitialization( 13831 InitializedEntity::InitializeParameter(Context, 13832 FnDecl->getParamDecl(1)), 13833 SourceLocation(), Args[1]); 13834 if (Arg1.isInvalid()) 13835 return ExprError(); 13836 Args[0] = LHS = Arg0.getAs<Expr>(); 13837 Args[1] = RHS = Arg1.getAs<Expr>(); 13838 } 13839 13840 // Build the actual expression node. 13841 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13842 Best->FoundDecl, Base, 13843 HadMultipleCandidates, OpLoc); 13844 if (FnExpr.isInvalid()) 13845 return ExprError(); 13846 13847 // Determine the result type. 13848 QualType ResultTy = FnDecl->getReturnType(); 13849 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13850 ResultTy = ResultTy.getNonLValueExprType(Context); 13851 13852 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13853 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13854 CurFPFeatureOverrides(), Best->IsADLCandidate); 13855 13856 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13857 FnDecl)) 13858 return ExprError(); 13859 13860 ArrayRef<const Expr *> ArgsArray(Args, 2); 13861 const Expr *ImplicitThis = nullptr; 13862 // Cut off the implicit 'this'. 13863 if (isa<CXXMethodDecl>(FnDecl)) { 13864 ImplicitThis = ArgsArray[0]; 13865 ArgsArray = ArgsArray.slice(1); 13866 } 13867 13868 // Check for a self move. 13869 if (Op == OO_Equal) 13870 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13871 13872 if (ImplicitThis) { 13873 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13874 QualType ThisTypeFromDecl = Context.getPointerType( 13875 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13876 13877 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13878 ThisTypeFromDecl); 13879 } 13880 13881 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13882 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13883 VariadicDoesNotApply); 13884 13885 ExprResult R = MaybeBindToTemporary(TheCall); 13886 if (R.isInvalid()) 13887 return ExprError(); 13888 13889 R = CheckForImmediateInvocation(R, FnDecl); 13890 if (R.isInvalid()) 13891 return ExprError(); 13892 13893 // For a rewritten candidate, we've already reversed the arguments 13894 // if needed. Perform the rest of the rewrite now. 13895 if ((Best->RewriteKind & CRK_DifferentOperator) || 13896 (Op == OO_Spaceship && IsReversed)) { 13897 if (Op == OO_ExclaimEqual) { 13898 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13899 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13900 } else { 13901 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13902 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13903 Expr *ZeroLiteral = 13904 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13905 13906 Sema::CodeSynthesisContext Ctx; 13907 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13908 Ctx.Entity = FnDecl; 13909 pushCodeSynthesisContext(Ctx); 13910 13911 R = CreateOverloadedBinOp( 13912 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13913 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13914 /*AllowRewrittenCandidates=*/false); 13915 13916 popCodeSynthesisContext(); 13917 } 13918 if (R.isInvalid()) 13919 return ExprError(); 13920 } else { 13921 assert(ChosenOp == Op && "unexpected operator name"); 13922 } 13923 13924 // Make a note in the AST if we did any rewriting. 13925 if (Best->RewriteKind != CRK_None) 13926 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13927 13928 return R; 13929 } else { 13930 // We matched a built-in operator. Convert the arguments, then 13931 // break out so that we will build the appropriate built-in 13932 // operator node. 13933 ExprResult ArgsRes0 = PerformImplicitConversion( 13934 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13935 AA_Passing, CCK_ForBuiltinOverloadedOp); 13936 if (ArgsRes0.isInvalid()) 13937 return ExprError(); 13938 Args[0] = ArgsRes0.get(); 13939 13940 ExprResult ArgsRes1 = PerformImplicitConversion( 13941 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13942 AA_Passing, CCK_ForBuiltinOverloadedOp); 13943 if (ArgsRes1.isInvalid()) 13944 return ExprError(); 13945 Args[1] = ArgsRes1.get(); 13946 break; 13947 } 13948 } 13949 13950 case OR_No_Viable_Function: { 13951 // C++ [over.match.oper]p9: 13952 // If the operator is the operator , [...] and there are no 13953 // viable functions, then the operator is assumed to be the 13954 // built-in operator and interpreted according to clause 5. 13955 if (Opc == BO_Comma) 13956 break; 13957 13958 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13959 // compare result using '==' and '<'. 13960 if (DefaultedFn && Opc == BO_Cmp) { 13961 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13962 Args[1], DefaultedFn); 13963 if (E.isInvalid() || E.isUsable()) 13964 return E; 13965 } 13966 13967 // For class as left operand for assignment or compound assignment 13968 // operator do not fall through to handling in built-in, but report that 13969 // no overloaded assignment operator found 13970 ExprResult Result = ExprError(); 13971 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13972 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13973 Args, OpLoc); 13974 DeferDiagsRAII DDR(*this, 13975 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 13976 if (Args[0]->getType()->isRecordType() && 13977 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13978 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13979 << BinaryOperator::getOpcodeStr(Opc) 13980 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13981 if (Args[0]->getType()->isIncompleteType()) { 13982 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13983 << Args[0]->getType() 13984 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13985 } 13986 } else { 13987 // This is an erroneous use of an operator which can be overloaded by 13988 // a non-member function. Check for non-member operators which were 13989 // defined too late to be candidates. 13990 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13991 // FIXME: Recover by calling the found function. 13992 return ExprError(); 13993 13994 // No viable function; try to create a built-in operation, which will 13995 // produce an error. Then, show the non-viable candidates. 13996 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13997 } 13998 assert(Result.isInvalid() && 13999 "C++ binary operator overloading is missing candidates!"); 14000 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 14001 return Result; 14002 } 14003 14004 case OR_Ambiguous: 14005 CandidateSet.NoteCandidates( 14006 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14007 << BinaryOperator::getOpcodeStr(Opc) 14008 << Args[0]->getType() 14009 << Args[1]->getType() 14010 << Args[0]->getSourceRange() 14011 << Args[1]->getSourceRange()), 14012 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14013 OpLoc); 14014 return ExprError(); 14015 14016 case OR_Deleted: 14017 if (isImplicitlyDeleted(Best->Function)) { 14018 FunctionDecl *DeletedFD = Best->Function; 14019 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 14020 if (DFK.isSpecialMember()) { 14021 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 14022 << Args[0]->getType() << DFK.asSpecialMember(); 14023 } else { 14024 assert(DFK.isComparison()); 14025 Diag(OpLoc, diag::err_ovl_deleted_comparison) 14026 << Args[0]->getType() << DeletedFD; 14027 } 14028 14029 // The user probably meant to call this special member. Just 14030 // explain why it's deleted. 14031 NoteDeletedFunction(DeletedFD); 14032 return ExprError(); 14033 } 14034 CandidateSet.NoteCandidates( 14035 PartialDiagnosticAt( 14036 OpLoc, PDiag(diag::err_ovl_deleted_oper) 14037 << getOperatorSpelling(Best->Function->getDeclName() 14038 .getCXXOverloadedOperator()) 14039 << Args[0]->getSourceRange() 14040 << Args[1]->getSourceRange()), 14041 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14042 OpLoc); 14043 return ExprError(); 14044 } 14045 14046 // We matched a built-in operator; build it. 14047 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14048 } 14049 14050 ExprResult Sema::BuildSynthesizedThreeWayComparison( 14051 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 14052 FunctionDecl *DefaultedFn) { 14053 const ComparisonCategoryInfo *Info = 14054 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 14055 // If we're not producing a known comparison category type, we can't 14056 // synthesize a three-way comparison. Let the caller diagnose this. 14057 if (!Info) 14058 return ExprResult((Expr*)nullptr); 14059 14060 // If we ever want to perform this synthesis more generally, we will need to 14061 // apply the temporary materialization conversion to the operands. 14062 assert(LHS->isGLValue() && RHS->isGLValue() && 14063 "cannot use prvalue expressions more than once"); 14064 Expr *OrigLHS = LHS; 14065 Expr *OrigRHS = RHS; 14066 14067 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 14068 // each of them multiple times below. 14069 LHS = new (Context) 14070 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 14071 LHS->getObjectKind(), LHS); 14072 RHS = new (Context) 14073 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 14074 RHS->getObjectKind(), RHS); 14075 14076 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 14077 DefaultedFn); 14078 if (Eq.isInvalid()) 14079 return ExprError(); 14080 14081 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 14082 true, DefaultedFn); 14083 if (Less.isInvalid()) 14084 return ExprError(); 14085 14086 ExprResult Greater; 14087 if (Info->isPartial()) { 14088 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14089 DefaultedFn); 14090 if (Greater.isInvalid()) 14091 return ExprError(); 14092 } 14093 14094 // Form the list of comparisons we're going to perform. 14095 struct Comparison { 14096 ExprResult Cmp; 14097 ComparisonCategoryResult Result; 14098 } Comparisons[4] = 14099 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14100 : ComparisonCategoryResult::Equivalent}, 14101 {Less, ComparisonCategoryResult::Less}, 14102 {Greater, ComparisonCategoryResult::Greater}, 14103 {ExprResult(), ComparisonCategoryResult::Unordered}, 14104 }; 14105 14106 int I = Info->isPartial() ? 3 : 2; 14107 14108 // Combine the comparisons with suitable conditional expressions. 14109 ExprResult Result; 14110 for (; I >= 0; --I) { 14111 // Build a reference to the comparison category constant. 14112 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14113 // FIXME: Missing a constant for a comparison category. Diagnose this? 14114 if (!VI) 14115 return ExprResult((Expr*)nullptr); 14116 ExprResult ThisResult = 14117 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14118 if (ThisResult.isInvalid()) 14119 return ExprError(); 14120 14121 // Build a conditional unless this is the final case. 14122 if (Result.get()) { 14123 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14124 ThisResult.get(), Result.get()); 14125 if (Result.isInvalid()) 14126 return ExprError(); 14127 } else { 14128 Result = ThisResult; 14129 } 14130 } 14131 14132 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14133 // bind the OpaqueValueExprs before they're (repeatedly) used. 14134 Expr *SyntacticForm = BinaryOperator::Create( 14135 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14136 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14137 CurFPFeatureOverrides()); 14138 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14139 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14140 } 14141 14142 static bool PrepareArgumentsForCallToObjectOfClassType( 14143 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 14144 MultiExprArg Args, SourceLocation LParenLoc) { 14145 14146 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14147 unsigned NumParams = Proto->getNumParams(); 14148 unsigned NumArgsSlots = 14149 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 14150 // Build the full argument list for the method call (the implicit object 14151 // parameter is placed at the beginning of the list). 14152 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 14153 bool IsError = false; 14154 // Initialize the implicit object parameter. 14155 // Check the argument types. 14156 for (unsigned i = 0; i != NumParams; i++) { 14157 Expr *Arg; 14158 if (i < Args.size()) { 14159 Arg = Args[i]; 14160 ExprResult InputInit = 14161 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 14162 S.Context, Method->getParamDecl(i)), 14163 SourceLocation(), Arg); 14164 IsError |= InputInit.isInvalid(); 14165 Arg = InputInit.getAs<Expr>(); 14166 } else { 14167 ExprResult DefArg = 14168 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14169 if (DefArg.isInvalid()) { 14170 IsError = true; 14171 break; 14172 } 14173 Arg = DefArg.getAs<Expr>(); 14174 } 14175 14176 MethodArgs.push_back(Arg); 14177 } 14178 return IsError; 14179 } 14180 14181 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14182 SourceLocation RLoc, 14183 Expr *Base, 14184 MultiExprArg ArgExpr) { 14185 SmallVector<Expr *, 2> Args; 14186 Args.push_back(Base); 14187 for (auto e : ArgExpr) { 14188 Args.push_back(e); 14189 } 14190 DeclarationName OpName = 14191 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14192 14193 SourceRange Range = ArgExpr.empty() 14194 ? SourceRange{} 14195 : SourceRange(ArgExpr.front()->getBeginLoc(), 14196 ArgExpr.back()->getEndLoc()); 14197 14198 // If either side is type-dependent, create an appropriate dependent 14199 // expression. 14200 if (Expr::hasAnyTypeDependentArguments(Args)) { 14201 14202 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14203 // CHECKME: no 'operator' keyword? 14204 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14205 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14206 ExprResult Fn = CreateUnresolvedLookupExpr( 14207 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14208 if (Fn.isInvalid()) 14209 return ExprError(); 14210 // Can't add any actual overloads yet 14211 14212 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14213 Context.DependentTy, VK_PRValue, RLoc, 14214 CurFPFeatureOverrides()); 14215 } 14216 14217 // Handle placeholders 14218 UnbridgedCastsSet UnbridgedCasts; 14219 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 14220 return ExprError(); 14221 } 14222 // Build an empty overload set. 14223 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14224 14225 // Subscript can only be overloaded as a member function. 14226 14227 // Add operator candidates that are member functions. 14228 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14229 14230 // Add builtin operator candidates. 14231 if (Args.size() == 2) 14232 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14233 14234 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14235 14236 // Perform overload resolution. 14237 OverloadCandidateSet::iterator Best; 14238 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14239 case OR_Success: { 14240 // We found a built-in operator or an overloaded operator. 14241 FunctionDecl *FnDecl = Best->Function; 14242 14243 if (FnDecl) { 14244 // We matched an overloaded operator. Build a call to that 14245 // operator. 14246 14247 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 14248 14249 // Convert the arguments. 14250 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14251 SmallVector<Expr *, 2> MethodArgs; 14252 ExprResult Arg0 = PerformObjectArgumentInitialization( 14253 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14254 if (Arg0.isInvalid()) 14255 return ExprError(); 14256 14257 MethodArgs.push_back(Arg0.get()); 14258 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 14259 *this, MethodArgs, Method, ArgExpr, LLoc); 14260 if (IsError) 14261 return ExprError(); 14262 14263 // Build the actual expression node. 14264 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14265 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14266 ExprResult FnExpr = CreateFunctionRefExpr( 14267 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 14268 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 14269 if (FnExpr.isInvalid()) 14270 return ExprError(); 14271 14272 // Determine the result type 14273 QualType ResultTy = FnDecl->getReturnType(); 14274 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14275 ResultTy = ResultTy.getNonLValueExprType(Context); 14276 14277 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14278 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc, 14279 CurFPFeatureOverrides()); 14280 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14281 return ExprError(); 14282 14283 if (CheckFunctionCall(Method, TheCall, 14284 Method->getType()->castAs<FunctionProtoType>())) 14285 return ExprError(); 14286 14287 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14288 FnDecl); 14289 } else { 14290 // We matched a built-in operator. Convert the arguments, then 14291 // break out so that we will build the appropriate built-in 14292 // operator node. 14293 ExprResult ArgsRes0 = PerformImplicitConversion( 14294 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14295 AA_Passing, CCK_ForBuiltinOverloadedOp); 14296 if (ArgsRes0.isInvalid()) 14297 return ExprError(); 14298 Args[0] = ArgsRes0.get(); 14299 14300 ExprResult ArgsRes1 = PerformImplicitConversion( 14301 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14302 AA_Passing, CCK_ForBuiltinOverloadedOp); 14303 if (ArgsRes1.isInvalid()) 14304 return ExprError(); 14305 Args[1] = ArgsRes1.get(); 14306 14307 break; 14308 } 14309 } 14310 14311 case OR_No_Viable_Function: { 14312 PartialDiagnostic PD = 14313 CandidateSet.empty() 14314 ? (PDiag(diag::err_ovl_no_oper) 14315 << Args[0]->getType() << /*subscript*/ 0 14316 << Args[0]->getSourceRange() << Range) 14317 : (PDiag(diag::err_ovl_no_viable_subscript) 14318 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 14319 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14320 OCD_AllCandidates, ArgExpr, "[]", LLoc); 14321 return ExprError(); 14322 } 14323 14324 case OR_Ambiguous: 14325 if (Args.size() == 2) { 14326 CandidateSet.NoteCandidates( 14327 PartialDiagnosticAt( 14328 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14329 << "[]" << Args[0]->getType() << Args[1]->getType() 14330 << Args[0]->getSourceRange() << Range), 14331 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14332 } else { 14333 CandidateSet.NoteCandidates( 14334 PartialDiagnosticAt(LLoc, 14335 PDiag(diag::err_ovl_ambiguous_subscript_call) 14336 << Args[0]->getType() 14337 << Args[0]->getSourceRange() << Range), 14338 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14339 } 14340 return ExprError(); 14341 14342 case OR_Deleted: 14343 CandidateSet.NoteCandidates( 14344 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14345 << "[]" << Args[0]->getSourceRange() 14346 << Range), 14347 *this, OCD_AllCandidates, Args, "[]", LLoc); 14348 return ExprError(); 14349 } 14350 14351 // We matched a built-in operator; build it. 14352 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14353 } 14354 14355 /// BuildCallToMemberFunction - Build a call to a member 14356 /// function. MemExpr is the expression that refers to the member 14357 /// function (and includes the object parameter), Args/NumArgs are the 14358 /// arguments to the function call (not including the object 14359 /// parameter). The caller needs to validate that the member 14360 /// expression refers to a non-static member function or an overloaded 14361 /// member function. 14362 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14363 SourceLocation LParenLoc, 14364 MultiExprArg Args, 14365 SourceLocation RParenLoc, 14366 Expr *ExecConfig, bool IsExecConfig, 14367 bool AllowRecovery) { 14368 assert(MemExprE->getType() == Context.BoundMemberTy || 14369 MemExprE->getType() == Context.OverloadTy); 14370 14371 // Dig out the member expression. This holds both the object 14372 // argument and the member function we're referring to. 14373 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14374 14375 // Determine whether this is a call to a pointer-to-member function. 14376 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14377 assert(op->getType() == Context.BoundMemberTy); 14378 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14379 14380 QualType fnType = 14381 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14382 14383 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14384 QualType resultType = proto->getCallResultType(Context); 14385 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14386 14387 // Check that the object type isn't more qualified than the 14388 // member function we're calling. 14389 Qualifiers funcQuals = proto->getMethodQuals(); 14390 14391 QualType objectType = op->getLHS()->getType(); 14392 if (op->getOpcode() == BO_PtrMemI) 14393 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14394 Qualifiers objectQuals = objectType.getQualifiers(); 14395 14396 Qualifiers difference = objectQuals - funcQuals; 14397 difference.removeObjCGCAttr(); 14398 difference.removeAddressSpace(); 14399 if (difference) { 14400 std::string qualsString = difference.getAsString(); 14401 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14402 << fnType.getUnqualifiedType() 14403 << qualsString 14404 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14405 } 14406 14407 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14408 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14409 CurFPFeatureOverrides(), proto->getNumParams()); 14410 14411 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14412 call, nullptr)) 14413 return ExprError(); 14414 14415 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14416 return ExprError(); 14417 14418 if (CheckOtherCall(call, proto)) 14419 return ExprError(); 14420 14421 return MaybeBindToTemporary(call); 14422 } 14423 14424 // We only try to build a recovery expr at this level if we can preserve 14425 // the return type, otherwise we return ExprError() and let the caller 14426 // recover. 14427 auto BuildRecoveryExpr = [&](QualType Type) { 14428 if (!AllowRecovery) 14429 return ExprError(); 14430 std::vector<Expr *> SubExprs = {MemExprE}; 14431 llvm::append_range(SubExprs, Args); 14432 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14433 Type); 14434 }; 14435 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14436 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 14437 RParenLoc, CurFPFeatureOverrides()); 14438 14439 UnbridgedCastsSet UnbridgedCasts; 14440 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14441 return ExprError(); 14442 14443 MemberExpr *MemExpr; 14444 CXXMethodDecl *Method = nullptr; 14445 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14446 NestedNameSpecifier *Qualifier = nullptr; 14447 if (isa<MemberExpr>(NakedMemExpr)) { 14448 MemExpr = cast<MemberExpr>(NakedMemExpr); 14449 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14450 FoundDecl = MemExpr->getFoundDecl(); 14451 Qualifier = MemExpr->getQualifier(); 14452 UnbridgedCasts.restore(); 14453 } else { 14454 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14455 Qualifier = UnresExpr->getQualifier(); 14456 14457 QualType ObjectType = UnresExpr->getBaseType(); 14458 Expr::Classification ObjectClassification 14459 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14460 : UnresExpr->getBase()->Classify(Context); 14461 14462 // Add overload candidates 14463 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14464 OverloadCandidateSet::CSK_Normal); 14465 14466 // FIXME: avoid copy. 14467 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14468 if (UnresExpr->hasExplicitTemplateArgs()) { 14469 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14470 TemplateArgs = &TemplateArgsBuffer; 14471 } 14472 14473 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14474 E = UnresExpr->decls_end(); I != E; ++I) { 14475 14476 NamedDecl *Func = *I; 14477 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14478 if (isa<UsingShadowDecl>(Func)) 14479 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14480 14481 14482 // Microsoft supports direct constructor calls. 14483 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14484 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14485 CandidateSet, 14486 /*SuppressUserConversions*/ false); 14487 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14488 // If explicit template arguments were provided, we can't call a 14489 // non-template member function. 14490 if (TemplateArgs) 14491 continue; 14492 14493 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14494 ObjectClassification, Args, CandidateSet, 14495 /*SuppressUserConversions=*/false); 14496 } else { 14497 AddMethodTemplateCandidate( 14498 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14499 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14500 /*SuppressUserConversions=*/false); 14501 } 14502 } 14503 14504 DeclarationName DeclName = UnresExpr->getMemberName(); 14505 14506 UnbridgedCasts.restore(); 14507 14508 OverloadCandidateSet::iterator Best; 14509 bool Succeeded = false; 14510 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14511 Best)) { 14512 case OR_Success: 14513 Method = cast<CXXMethodDecl>(Best->Function); 14514 FoundDecl = Best->FoundDecl; 14515 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14516 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14517 break; 14518 // If FoundDecl is different from Method (such as if one is a template 14519 // and the other a specialization), make sure DiagnoseUseOfDecl is 14520 // called on both. 14521 // FIXME: This would be more comprehensively addressed by modifying 14522 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14523 // being used. 14524 if (Method != FoundDecl.getDecl() && 14525 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14526 break; 14527 Succeeded = true; 14528 break; 14529 14530 case OR_No_Viable_Function: 14531 CandidateSet.NoteCandidates( 14532 PartialDiagnosticAt( 14533 UnresExpr->getMemberLoc(), 14534 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14535 << DeclName << MemExprE->getSourceRange()), 14536 *this, OCD_AllCandidates, Args); 14537 break; 14538 case OR_Ambiguous: 14539 CandidateSet.NoteCandidates( 14540 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14541 PDiag(diag::err_ovl_ambiguous_member_call) 14542 << DeclName << MemExprE->getSourceRange()), 14543 *this, OCD_AmbiguousCandidates, Args); 14544 break; 14545 case OR_Deleted: 14546 CandidateSet.NoteCandidates( 14547 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14548 PDiag(diag::err_ovl_deleted_member_call) 14549 << DeclName << MemExprE->getSourceRange()), 14550 *this, OCD_AllCandidates, Args); 14551 break; 14552 } 14553 // Overload resolution fails, try to recover. 14554 if (!Succeeded) 14555 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14556 14557 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14558 14559 // If overload resolution picked a static member, build a 14560 // non-member call based on that function. 14561 if (Method->isStatic()) { 14562 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 14563 ExecConfig, IsExecConfig); 14564 } 14565 14566 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14567 } 14568 14569 QualType ResultType = Method->getReturnType(); 14570 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14571 ResultType = ResultType.getNonLValueExprType(Context); 14572 14573 assert(Method && "Member call to something that isn't a method?"); 14574 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14575 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14576 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14577 CurFPFeatureOverrides(), Proto->getNumParams()); 14578 14579 // Check for a valid return type. 14580 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14581 TheCall, Method)) 14582 return BuildRecoveryExpr(ResultType); 14583 14584 // Convert the object argument (for a non-static member function call). 14585 // We only need to do this if there was actually an overload; otherwise 14586 // it was done at lookup. 14587 if (!Method->isStatic()) { 14588 ExprResult ObjectArg = 14589 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14590 FoundDecl, Method); 14591 if (ObjectArg.isInvalid()) 14592 return ExprError(); 14593 MemExpr->setBase(ObjectArg.get()); 14594 } 14595 14596 // Convert the rest of the arguments 14597 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14598 RParenLoc)) 14599 return BuildRecoveryExpr(ResultType); 14600 14601 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14602 14603 if (CheckFunctionCall(Method, TheCall, Proto)) 14604 return ExprError(); 14605 14606 // In the case the method to call was not selected by the overloading 14607 // resolution process, we still need to handle the enable_if attribute. Do 14608 // that here, so it will not hide previous -- and more relevant -- errors. 14609 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14610 if (const EnableIfAttr *Attr = 14611 CheckEnableIf(Method, LParenLoc, Args, true)) { 14612 Diag(MemE->getMemberLoc(), 14613 diag::err_ovl_no_viable_member_function_in_call) 14614 << Method << Method->getSourceRange(); 14615 Diag(Method->getLocation(), 14616 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14617 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14618 return ExprError(); 14619 } 14620 } 14621 14622 if ((isa<CXXConstructorDecl>(CurContext) || 14623 isa<CXXDestructorDecl>(CurContext)) && 14624 TheCall->getMethodDecl()->isPure()) { 14625 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14626 14627 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14628 MemExpr->performsVirtualDispatch(getLangOpts())) { 14629 Diag(MemExpr->getBeginLoc(), 14630 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14631 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14632 << MD->getParent(); 14633 14634 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14635 if (getLangOpts().AppleKext) 14636 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14637 << MD->getParent() << MD->getDeclName(); 14638 } 14639 } 14640 14641 if (CXXDestructorDecl *DD = 14642 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14643 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14644 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14645 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14646 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14647 MemExpr->getMemberLoc()); 14648 } 14649 14650 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14651 TheCall->getMethodDecl()); 14652 } 14653 14654 /// BuildCallToObjectOfClassType - Build a call to an object of class 14655 /// type (C++ [over.call.object]), which can end up invoking an 14656 /// overloaded function call operator (@c operator()) or performing a 14657 /// user-defined conversion on the object argument. 14658 ExprResult 14659 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14660 SourceLocation LParenLoc, 14661 MultiExprArg Args, 14662 SourceLocation RParenLoc) { 14663 if (checkPlaceholderForOverload(*this, Obj)) 14664 return ExprError(); 14665 ExprResult Object = Obj; 14666 14667 UnbridgedCastsSet UnbridgedCasts; 14668 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14669 return ExprError(); 14670 14671 assert(Object.get()->getType()->isRecordType() && 14672 "Requires object type argument"); 14673 14674 // C++ [over.call.object]p1: 14675 // If the primary-expression E in the function call syntax 14676 // evaluates to a class object of type "cv T", then the set of 14677 // candidate functions includes at least the function call 14678 // operators of T. The function call operators of T are obtained by 14679 // ordinary lookup of the name operator() in the context of 14680 // (E).operator(). 14681 OverloadCandidateSet CandidateSet(LParenLoc, 14682 OverloadCandidateSet::CSK_Operator); 14683 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14684 14685 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14686 diag::err_incomplete_object_call, Object.get())) 14687 return true; 14688 14689 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14690 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14691 LookupQualifiedName(R, Record->getDecl()); 14692 R.suppressDiagnostics(); 14693 14694 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14695 Oper != OperEnd; ++Oper) { 14696 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14697 Object.get()->Classify(Context), Args, CandidateSet, 14698 /*SuppressUserConversion=*/false); 14699 } 14700 14701 // C++ [over.call.object]p2: 14702 // In addition, for each (non-explicit in C++0x) conversion function 14703 // declared in T of the form 14704 // 14705 // operator conversion-type-id () cv-qualifier; 14706 // 14707 // where cv-qualifier is the same cv-qualification as, or a 14708 // greater cv-qualification than, cv, and where conversion-type-id 14709 // denotes the type "pointer to function of (P1,...,Pn) returning 14710 // R", or the type "reference to pointer to function of 14711 // (P1,...,Pn) returning R", or the type "reference to function 14712 // of (P1,...,Pn) returning R", a surrogate call function [...] 14713 // is also considered as a candidate function. Similarly, 14714 // surrogate call functions are added to the set of candidate 14715 // functions for each conversion function declared in an 14716 // accessible base class provided the function is not hidden 14717 // within T by another intervening declaration. 14718 const auto &Conversions = 14719 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14720 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14721 NamedDecl *D = *I; 14722 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14723 if (isa<UsingShadowDecl>(D)) 14724 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14725 14726 // Skip over templated conversion functions; they aren't 14727 // surrogates. 14728 if (isa<FunctionTemplateDecl>(D)) 14729 continue; 14730 14731 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14732 if (!Conv->isExplicit()) { 14733 // Strip the reference type (if any) and then the pointer type (if 14734 // any) to get down to what might be a function type. 14735 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14736 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14737 ConvType = ConvPtrType->getPointeeType(); 14738 14739 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14740 { 14741 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14742 Object.get(), Args, CandidateSet); 14743 } 14744 } 14745 } 14746 14747 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14748 14749 // Perform overload resolution. 14750 OverloadCandidateSet::iterator Best; 14751 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14752 Best)) { 14753 case OR_Success: 14754 // Overload resolution succeeded; we'll build the appropriate call 14755 // below. 14756 break; 14757 14758 case OR_No_Viable_Function: { 14759 PartialDiagnostic PD = 14760 CandidateSet.empty() 14761 ? (PDiag(diag::err_ovl_no_oper) 14762 << Object.get()->getType() << /*call*/ 1 14763 << Object.get()->getSourceRange()) 14764 : (PDiag(diag::err_ovl_no_viable_object_call) 14765 << Object.get()->getType() << Object.get()->getSourceRange()); 14766 CandidateSet.NoteCandidates( 14767 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14768 OCD_AllCandidates, Args); 14769 break; 14770 } 14771 case OR_Ambiguous: 14772 CandidateSet.NoteCandidates( 14773 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14774 PDiag(diag::err_ovl_ambiguous_object_call) 14775 << Object.get()->getType() 14776 << Object.get()->getSourceRange()), 14777 *this, OCD_AmbiguousCandidates, Args); 14778 break; 14779 14780 case OR_Deleted: 14781 CandidateSet.NoteCandidates( 14782 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14783 PDiag(diag::err_ovl_deleted_object_call) 14784 << Object.get()->getType() 14785 << Object.get()->getSourceRange()), 14786 *this, OCD_AllCandidates, Args); 14787 break; 14788 } 14789 14790 if (Best == CandidateSet.end()) 14791 return true; 14792 14793 UnbridgedCasts.restore(); 14794 14795 if (Best->Function == nullptr) { 14796 // Since there is no function declaration, this is one of the 14797 // surrogate candidates. Dig out the conversion function. 14798 CXXConversionDecl *Conv 14799 = cast<CXXConversionDecl>( 14800 Best->Conversions[0].UserDefined.ConversionFunction); 14801 14802 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14803 Best->FoundDecl); 14804 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14805 return ExprError(); 14806 assert(Conv == Best->FoundDecl.getDecl() && 14807 "Found Decl & conversion-to-functionptr should be same, right?!"); 14808 // We selected one of the surrogate functions that converts the 14809 // object parameter to a function pointer. Perform the conversion 14810 // on the object argument, then let BuildCallExpr finish the job. 14811 14812 // Create an implicit member expr to refer to the conversion operator. 14813 // and then call it. 14814 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14815 Conv, HadMultipleCandidates); 14816 if (Call.isInvalid()) 14817 return ExprError(); 14818 // Record usage of conversion in an implicit cast. 14819 Call = ImplicitCastExpr::Create( 14820 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14821 nullptr, VK_PRValue, CurFPFeatureOverrides()); 14822 14823 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14824 } 14825 14826 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14827 14828 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14829 // that calls this method, using Object for the implicit object 14830 // parameter and passing along the remaining arguments. 14831 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14832 14833 // An error diagnostic has already been printed when parsing the declaration. 14834 if (Method->isInvalidDecl()) 14835 return ExprError(); 14836 14837 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14838 unsigned NumParams = Proto->getNumParams(); 14839 14840 DeclarationNameInfo OpLocInfo( 14841 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14842 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14843 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14844 Obj, HadMultipleCandidates, 14845 OpLocInfo.getLoc(), 14846 OpLocInfo.getInfo()); 14847 if (NewFn.isInvalid()) 14848 return true; 14849 14850 SmallVector<Expr *, 8> MethodArgs; 14851 MethodArgs.reserve(NumParams + 1); 14852 14853 bool IsError = false; 14854 14855 // Initialize the implicit object parameter. 14856 ExprResult ObjRes = 14857 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14858 Best->FoundDecl, Method); 14859 if (ObjRes.isInvalid()) 14860 IsError = true; 14861 else 14862 Object = ObjRes; 14863 MethodArgs.push_back(Object.get()); 14864 14865 IsError |= PrepareArgumentsForCallToObjectOfClassType( 14866 *this, MethodArgs, Method, Args, LParenLoc); 14867 14868 // If this is a variadic call, handle args passed through "...". 14869 if (Proto->isVariadic()) { 14870 // Promote the arguments (C99 6.5.2.2p7). 14871 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14872 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14873 nullptr); 14874 IsError |= Arg.isInvalid(); 14875 MethodArgs.push_back(Arg.get()); 14876 } 14877 } 14878 14879 if (IsError) 14880 return true; 14881 14882 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14883 14884 // Once we've built TheCall, all of the expressions are properly owned. 14885 QualType ResultTy = Method->getReturnType(); 14886 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14887 ResultTy = ResultTy.getNonLValueExprType(Context); 14888 14889 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14890 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14891 CurFPFeatureOverrides()); 14892 14893 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14894 return true; 14895 14896 if (CheckFunctionCall(Method, TheCall, Proto)) 14897 return true; 14898 14899 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14900 } 14901 14902 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14903 /// (if one exists), where @c Base is an expression of class type and 14904 /// @c Member is the name of the member we're trying to find. 14905 ExprResult 14906 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14907 bool *NoArrowOperatorFound) { 14908 assert(Base->getType()->isRecordType() && 14909 "left-hand side must have class type"); 14910 14911 if (checkPlaceholderForOverload(*this, Base)) 14912 return ExprError(); 14913 14914 SourceLocation Loc = Base->getExprLoc(); 14915 14916 // C++ [over.ref]p1: 14917 // 14918 // [...] An expression x->m is interpreted as (x.operator->())->m 14919 // for a class object x of type T if T::operator->() exists and if 14920 // the operator is selected as the best match function by the 14921 // overload resolution mechanism (13.3). 14922 DeclarationName OpName = 14923 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14924 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14925 14926 if (RequireCompleteType(Loc, Base->getType(), 14927 diag::err_typecheck_incomplete_tag, Base)) 14928 return ExprError(); 14929 14930 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14931 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14932 R.suppressDiagnostics(); 14933 14934 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14935 Oper != OperEnd; ++Oper) { 14936 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14937 None, CandidateSet, /*SuppressUserConversion=*/false); 14938 } 14939 14940 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14941 14942 // Perform overload resolution. 14943 OverloadCandidateSet::iterator Best; 14944 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14945 case OR_Success: 14946 // Overload resolution succeeded; we'll build the call below. 14947 break; 14948 14949 case OR_No_Viable_Function: { 14950 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14951 if (CandidateSet.empty()) { 14952 QualType BaseType = Base->getType(); 14953 if (NoArrowOperatorFound) { 14954 // Report this specific error to the caller instead of emitting a 14955 // diagnostic, as requested. 14956 *NoArrowOperatorFound = true; 14957 return ExprError(); 14958 } 14959 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14960 << BaseType << Base->getSourceRange(); 14961 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14962 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14963 << FixItHint::CreateReplacement(OpLoc, "."); 14964 } 14965 } else 14966 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14967 << "operator->" << Base->getSourceRange(); 14968 CandidateSet.NoteCandidates(*this, Base, Cands); 14969 return ExprError(); 14970 } 14971 case OR_Ambiguous: 14972 CandidateSet.NoteCandidates( 14973 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14974 << "->" << Base->getType() 14975 << Base->getSourceRange()), 14976 *this, OCD_AmbiguousCandidates, Base); 14977 return ExprError(); 14978 14979 case OR_Deleted: 14980 CandidateSet.NoteCandidates( 14981 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14982 << "->" << Base->getSourceRange()), 14983 *this, OCD_AllCandidates, Base); 14984 return ExprError(); 14985 } 14986 14987 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14988 14989 // Convert the object parameter. 14990 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14991 ExprResult BaseResult = 14992 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14993 Best->FoundDecl, Method); 14994 if (BaseResult.isInvalid()) 14995 return ExprError(); 14996 Base = BaseResult.get(); 14997 14998 // Build the operator call. 14999 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15000 Base, HadMultipleCandidates, OpLoc); 15001 if (FnExpr.isInvalid()) 15002 return ExprError(); 15003 15004 QualType ResultTy = Method->getReturnType(); 15005 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15006 ResultTy = ResultTy.getNonLValueExprType(Context); 15007 CXXOperatorCallExpr *TheCall = 15008 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 15009 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 15010 15011 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 15012 return ExprError(); 15013 15014 if (CheckFunctionCall(Method, TheCall, 15015 Method->getType()->castAs<FunctionProtoType>())) 15016 return ExprError(); 15017 15018 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15019 } 15020 15021 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 15022 /// a literal operator described by the provided lookup results. 15023 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 15024 DeclarationNameInfo &SuffixInfo, 15025 ArrayRef<Expr*> Args, 15026 SourceLocation LitEndLoc, 15027 TemplateArgumentListInfo *TemplateArgs) { 15028 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 15029 15030 OverloadCandidateSet CandidateSet(UDSuffixLoc, 15031 OverloadCandidateSet::CSK_Normal); 15032 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 15033 TemplateArgs); 15034 15035 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15036 15037 // Perform overload resolution. This will usually be trivial, but might need 15038 // to perform substitutions for a literal operator template. 15039 OverloadCandidateSet::iterator Best; 15040 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 15041 case OR_Success: 15042 case OR_Deleted: 15043 break; 15044 15045 case OR_No_Viable_Function: 15046 CandidateSet.NoteCandidates( 15047 PartialDiagnosticAt(UDSuffixLoc, 15048 PDiag(diag::err_ovl_no_viable_function_in_call) 15049 << R.getLookupName()), 15050 *this, OCD_AllCandidates, Args); 15051 return ExprError(); 15052 15053 case OR_Ambiguous: 15054 CandidateSet.NoteCandidates( 15055 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 15056 << R.getLookupName()), 15057 *this, OCD_AmbiguousCandidates, Args); 15058 return ExprError(); 15059 } 15060 15061 FunctionDecl *FD = Best->Function; 15062 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 15063 nullptr, HadMultipleCandidates, 15064 SuffixInfo.getLoc(), 15065 SuffixInfo.getInfo()); 15066 if (Fn.isInvalid()) 15067 return true; 15068 15069 // Check the argument types. This should almost always be a no-op, except 15070 // that array-to-pointer decay is applied to string literals. 15071 Expr *ConvArgs[2]; 15072 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 15073 ExprResult InputInit = PerformCopyInitialization( 15074 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 15075 SourceLocation(), Args[ArgIdx]); 15076 if (InputInit.isInvalid()) 15077 return true; 15078 ConvArgs[ArgIdx] = InputInit.get(); 15079 } 15080 15081 QualType ResultTy = FD->getReturnType(); 15082 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15083 ResultTy = ResultTy.getNonLValueExprType(Context); 15084 15085 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 15086 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 15087 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 15088 15089 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 15090 return ExprError(); 15091 15092 if (CheckFunctionCall(FD, UDL, nullptr)) 15093 return ExprError(); 15094 15095 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 15096 } 15097 15098 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 15099 /// given LookupResult is non-empty, it is assumed to describe a member which 15100 /// will be invoked. Otherwise, the function will be found via argument 15101 /// dependent lookup. 15102 /// CallExpr is set to a valid expression and FRS_Success returned on success, 15103 /// otherwise CallExpr is set to ExprError() and some non-success value 15104 /// is returned. 15105 Sema::ForRangeStatus 15106 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 15107 SourceLocation RangeLoc, 15108 const DeclarationNameInfo &NameInfo, 15109 LookupResult &MemberLookup, 15110 OverloadCandidateSet *CandidateSet, 15111 Expr *Range, ExprResult *CallExpr) { 15112 Scope *S = nullptr; 15113 15114 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 15115 if (!MemberLookup.empty()) { 15116 ExprResult MemberRef = 15117 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 15118 /*IsPtr=*/false, CXXScopeSpec(), 15119 /*TemplateKWLoc=*/SourceLocation(), 15120 /*FirstQualifierInScope=*/nullptr, 15121 MemberLookup, 15122 /*TemplateArgs=*/nullptr, S); 15123 if (MemberRef.isInvalid()) { 15124 *CallExpr = ExprError(); 15125 return FRS_DiagnosticIssued; 15126 } 15127 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 15128 if (CallExpr->isInvalid()) { 15129 *CallExpr = ExprError(); 15130 return FRS_DiagnosticIssued; 15131 } 15132 } else { 15133 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 15134 NestedNameSpecifierLoc(), 15135 NameInfo, UnresolvedSet<0>()); 15136 if (FnR.isInvalid()) 15137 return FRS_DiagnosticIssued; 15138 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 15139 15140 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 15141 CandidateSet, CallExpr); 15142 if (CandidateSet->empty() || CandidateSetError) { 15143 *CallExpr = ExprError(); 15144 return FRS_NoViableFunction; 15145 } 15146 OverloadCandidateSet::iterator Best; 15147 OverloadingResult OverloadResult = 15148 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 15149 15150 if (OverloadResult == OR_No_Viable_Function) { 15151 *CallExpr = ExprError(); 15152 return FRS_NoViableFunction; 15153 } 15154 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 15155 Loc, nullptr, CandidateSet, &Best, 15156 OverloadResult, 15157 /*AllowTypoCorrection=*/false); 15158 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 15159 *CallExpr = ExprError(); 15160 return FRS_DiagnosticIssued; 15161 } 15162 } 15163 return FRS_Success; 15164 } 15165 15166 15167 /// FixOverloadedFunctionReference - E is an expression that refers to 15168 /// a C++ overloaded function (possibly with some parentheses and 15169 /// perhaps a '&' around it). We have resolved the overloaded function 15170 /// to the function declaration Fn, so patch up the expression E to 15171 /// refer (possibly indirectly) to Fn. Returns the new expr. 15172 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15173 FunctionDecl *Fn) { 15174 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15175 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15176 Found, Fn); 15177 if (SubExpr == PE->getSubExpr()) 15178 return PE; 15179 15180 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15181 } 15182 15183 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15184 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15185 Found, Fn); 15186 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15187 SubExpr->getType()) && 15188 "Implicit cast type cannot be determined from overload"); 15189 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15190 if (SubExpr == ICE->getSubExpr()) 15191 return ICE; 15192 15193 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15194 SubExpr, nullptr, ICE->getValueKind(), 15195 CurFPFeatureOverrides()); 15196 } 15197 15198 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15199 if (!GSE->isResultDependent()) { 15200 Expr *SubExpr = 15201 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15202 if (SubExpr == GSE->getResultExpr()) 15203 return GSE; 15204 15205 // Replace the resulting type information before rebuilding the generic 15206 // selection expression. 15207 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15208 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15209 unsigned ResultIdx = GSE->getResultIndex(); 15210 AssocExprs[ResultIdx] = SubExpr; 15211 15212 return GenericSelectionExpr::Create( 15213 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15214 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15215 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15216 ResultIdx); 15217 } 15218 // Rather than fall through to the unreachable, return the original generic 15219 // selection expression. 15220 return GSE; 15221 } 15222 15223 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15224 assert(UnOp->getOpcode() == UO_AddrOf && 15225 "Can only take the address of an overloaded function"); 15226 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15227 if (Method->isStatic()) { 15228 // Do nothing: static member functions aren't any different 15229 // from non-member functions. 15230 } else { 15231 // Fix the subexpression, which really has to be an 15232 // UnresolvedLookupExpr holding an overloaded member function 15233 // or template. 15234 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15235 Found, Fn); 15236 if (SubExpr == UnOp->getSubExpr()) 15237 return UnOp; 15238 15239 assert(isa<DeclRefExpr>(SubExpr) 15240 && "fixed to something other than a decl ref"); 15241 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15242 && "fixed to a member ref with no nested name qualifier"); 15243 15244 // We have taken the address of a pointer to member 15245 // function. Perform the computation here so that we get the 15246 // appropriate pointer to member type. 15247 QualType ClassType 15248 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15249 QualType MemPtrType 15250 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15251 // Under the MS ABI, lock down the inheritance model now. 15252 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15253 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15254 15255 return UnaryOperator::Create( 15256 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, 15257 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15258 } 15259 } 15260 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15261 Found, Fn); 15262 if (SubExpr == UnOp->getSubExpr()) 15263 return UnOp; 15264 15265 // FIXME: This can't currently fail, but in principle it could. 15266 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr) 15267 .get(); 15268 } 15269 15270 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15271 // FIXME: avoid copy. 15272 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15273 if (ULE->hasExplicitTemplateArgs()) { 15274 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15275 TemplateArgs = &TemplateArgsBuffer; 15276 } 15277 15278 QualType Type = Fn->getType(); 15279 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; 15280 15281 // FIXME: Duplicated from BuildDeclarationNameExpr. 15282 if (unsigned BID = Fn->getBuiltinID()) { 15283 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 15284 Type = Context.BuiltinFnTy; 15285 ValueKind = VK_PRValue; 15286 } 15287 } 15288 15289 DeclRefExpr *DRE = BuildDeclRefExpr( 15290 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), 15291 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); 15292 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15293 return DRE; 15294 } 15295 15296 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15297 // FIXME: avoid copy. 15298 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15299 if (MemExpr->hasExplicitTemplateArgs()) { 15300 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15301 TemplateArgs = &TemplateArgsBuffer; 15302 } 15303 15304 Expr *Base; 15305 15306 // If we're filling in a static method where we used to have an 15307 // implicit member access, rewrite to a simple decl ref. 15308 if (MemExpr->isImplicitAccess()) { 15309 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15310 DeclRefExpr *DRE = BuildDeclRefExpr( 15311 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15312 MemExpr->getQualifierLoc(), Found.getDecl(), 15313 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15314 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15315 return DRE; 15316 } else { 15317 SourceLocation Loc = MemExpr->getMemberLoc(); 15318 if (MemExpr->getQualifier()) 15319 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15320 Base = 15321 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15322 } 15323 } else 15324 Base = MemExpr->getBase(); 15325 15326 ExprValueKind valueKind; 15327 QualType type; 15328 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15329 valueKind = VK_LValue; 15330 type = Fn->getType(); 15331 } else { 15332 valueKind = VK_PRValue; 15333 type = Context.BoundMemberTy; 15334 } 15335 15336 return BuildMemberExpr( 15337 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15338 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15339 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15340 type, valueKind, OK_Ordinary, TemplateArgs); 15341 } 15342 15343 llvm_unreachable("Invalid reference to overloaded function"); 15344 } 15345 15346 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15347 DeclAccessPair Found, 15348 FunctionDecl *Fn) { 15349 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15350 } 15351 15352 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 15353 FunctionDecl *Function) { 15354 if (!PartialOverloading || !Function) 15355 return true; 15356 if (Function->isVariadic()) 15357 return false; 15358 if (const auto *Proto = 15359 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 15360 if (Proto->isTemplateVariadic()) 15361 return false; 15362 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 15363 if (const auto *Proto = 15364 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 15365 if (Proto->isTemplateVariadic()) 15366 return false; 15367 return true; 15368 } 15369