1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult 53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 54 const Expr *Base, bool HadMultipleCandidates, 55 SourceLocation Loc = SourceLocation(), 56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 58 return ExprError(); 59 // If FoundDecl is different from Fn (such as if one is a template 60 // and the other a specialization), make sure DiagnoseUseOfDecl is 61 // called on both. 62 // FIXME: This would be more comprehensively addressed by modifying 63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 64 // being used. 65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 66 return ExprError(); 67 DeclRefExpr *DRE = new (S.Context) 68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 69 if (HadMultipleCandidates) 70 DRE->setHadMultipleCandidates(true); 71 72 S.MarkDeclRefReferenced(DRE, Base); 73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 75 S.ResolveExceptionSpec(Loc, FPT); 76 DRE->setType(Fn->getType()); 77 } 78 } 79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 80 CK_FunctionToPointerDecay); 81 } 82 83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle, 87 bool AllowObjCWritebackConversion); 88 89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 90 QualType &ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle); 94 static OverloadingResult 95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 96 UserDefinedConversionSequence& User, 97 OverloadCandidateSet& Conversions, 98 AllowedExplicit AllowExplicit, 99 bool AllowObjCConversionOnExplicit); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 static ImplicitConversionSequence::CompareKind 107 CompareQualificationConversions(Sema &S, 108 const StandardConversionSequence& SCS1, 109 const StandardConversionSequence& SCS2); 110 111 static ImplicitConversionSequence::CompareKind 112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 113 const StandardConversionSequence& SCS1, 114 const StandardConversionSequence& SCS2); 115 116 /// GetConversionRank - Retrieve the implicit conversion rank 117 /// corresponding to the given implicit conversion kind. 118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 119 static const ImplicitConversionRank 120 Rank[(int)ICK_Num_Conversion_Kinds] = { 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Exact_Match, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Promotion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_OCL_Scalar_Widening, 142 ICR_Complex_Real_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Writeback_Conversion, 146 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 147 // it was omitted by the patch that added 148 // ICK_Zero_Event_Conversion 149 ICR_C_Conversion, 150 ICR_C_Conversion_Extension 151 }; 152 return Rank[(int)Kind]; 153 } 154 155 /// GetImplicitConversionName - Return the name of this kind of 156 /// implicit conversion. 157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Function pointer conversion", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "SVE Vector conversion", 179 "Vector splat", 180 "Complex-real conversion", 181 "Block Pointer conversion", 182 "Transparent Union Conversion", 183 "Writeback conversion", 184 "OpenCL Zero Event Conversion", 185 "C specific type conversion", 186 "Incompatible pointer conversion" 187 }; 188 return Name[Kind]; 189 } 190 191 /// StandardConversionSequence - Set the standard conversion 192 /// sequence to the identity conversion. 193 void StandardConversionSequence::setAsIdentityConversion() { 194 First = ICK_Identity; 195 Second = ICK_Identity; 196 Third = ICK_Identity; 197 DeprecatedStringLiteralToCharPtr = false; 198 QualificationIncludesObjCLifetime = false; 199 ReferenceBinding = false; 200 DirectBinding = false; 201 IsLvalueReference = true; 202 BindsToFunctionLvalue = false; 203 BindsToRvalue = false; 204 BindsImplicitObjectArgumentWithoutRefQualifier = false; 205 ObjCLifetimeConversionBinding = false; 206 CopyConstructor = nullptr; 207 } 208 209 /// getRank - Retrieve the rank of this standard conversion sequence 210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 211 /// implicit conversions. 212 ImplicitConversionRank StandardConversionSequence::getRank() const { 213 ImplicitConversionRank Rank = ICR_Exact_Match; 214 if (GetConversionRank(First) > Rank) 215 Rank = GetConversionRank(First); 216 if (GetConversionRank(Second) > Rank) 217 Rank = GetConversionRank(Second); 218 if (GetConversionRank(Third) > Rank) 219 Rank = GetConversionRank(Third); 220 return Rank; 221 } 222 223 /// isPointerConversionToBool - Determines whether this conversion is 224 /// a conversion of a pointer or pointer-to-member to bool. This is 225 /// used as part of the ranking of standard conversion sequences 226 /// (C++ 13.3.3.2p4). 227 bool StandardConversionSequence::isPointerConversionToBool() const { 228 // Note that FromType has not necessarily been transformed by the 229 // array-to-pointer or function-to-pointer implicit conversions, so 230 // check for their presence as well as checking whether FromType is 231 // a pointer. 232 if (getToType(1)->isBooleanType() && 233 (getFromType()->isPointerType() || 234 getFromType()->isMemberPointerType() || 235 getFromType()->isObjCObjectPointerType() || 236 getFromType()->isBlockPointerType() || 237 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 238 return true; 239 240 return false; 241 } 242 243 /// isPointerConversionToVoidPointer - Determines whether this 244 /// conversion is a conversion of a pointer to a void pointer. This is 245 /// used as part of the ranking of standard conversion sequences (C++ 246 /// 13.3.3.2p4). 247 bool 248 StandardConversionSequence:: 249 isPointerConversionToVoidPointer(ASTContext& Context) const { 250 QualType FromType = getFromType(); 251 QualType ToType = getToType(1); 252 253 // Note that FromType has not necessarily been transformed by the 254 // array-to-pointer implicit conversion, so check for its presence 255 // and redo the conversion to get a pointer. 256 if (First == ICK_Array_To_Pointer) 257 FromType = Context.getArrayDecayedType(FromType); 258 259 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 260 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 261 return ToPtrType->getPointeeType()->isVoidType(); 262 263 return false; 264 } 265 266 /// Skip any implicit casts which could be either part of a narrowing conversion 267 /// or after one in an implicit conversion. 268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 269 const Expr *Converted) { 270 // We can have cleanups wrapping the converted expression; these need to be 271 // preserved so that destructors run if necessary. 272 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 273 Expr *Inner = 274 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 275 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 276 EWC->getObjects()); 277 } 278 279 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_BooleanToSignedIntegral: 286 case CK_FloatingToIntegral: 287 case CK_FloatingToBoolean: 288 case CK_FloatingCast: 289 Converted = ICE->getSubExpr(); 290 continue; 291 292 default: 293 return Converted; 294 } 295 } 296 297 return Converted; 298 } 299 300 /// Check if this standard conversion sequence represents a narrowing 301 /// conversion, according to C++11 [dcl.init.list]p7. 302 /// 303 /// \param Ctx The AST context. 304 /// \param Converted The result of applying this standard conversion sequence. 305 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 306 /// value of the expression prior to the narrowing conversion. 307 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 308 /// type of the expression prior to the narrowing conversion. 309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 310 /// from floating point types to integral types should be ignored. 311 NarrowingKind StandardConversionSequence::getNarrowingKind( 312 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 313 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 315 316 // C++11 [dcl.init.list]p7: 317 // A narrowing conversion is an implicit conversion ... 318 QualType FromType = getToType(0); 319 QualType ToType = getToType(1); 320 321 // A conversion to an enumeration type is narrowing if the conversion to 322 // the underlying type is narrowing. This only arises for expressions of 323 // the form 'Enum{init}'. 324 if (auto *ET = ToType->getAs<EnumType>()) 325 ToType = ET->getDecl()->getIntegerType(); 326 327 switch (Second) { 328 // 'bool' is an integral type; dispatch to the right place to handle it. 329 case ICK_Boolean_Conversion: 330 if (FromType->isRealFloatingType()) 331 goto FloatingIntegralConversion; 332 if (FromType->isIntegralOrUnscopedEnumerationType()) 333 goto IntegralConversion; 334 // -- from a pointer type or pointer-to-member type to bool, or 335 return NK_Type_Narrowing; 336 337 // -- from a floating-point type to an integer type, or 338 // 339 // -- from an integer type or unscoped enumeration type to a floating-point 340 // type, except where the source is a constant expression and the actual 341 // value after conversion will fit into the target type and will produce 342 // the original value when converted back to the original type, or 343 case ICK_Floating_Integral: 344 FloatingIntegralConversion: 345 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 346 return NK_Type_Narrowing; 347 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 348 ToType->isRealFloatingType()) { 349 if (IgnoreFloatToIntegralConversion) 350 return NK_Not_Narrowing; 351 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 352 assert(Initializer && "Unknown conversion expression"); 353 354 // If it's value-dependent, we can't tell whether it's narrowing. 355 if (Initializer->isValueDependent()) 356 return NK_Dependent_Narrowing; 357 358 if (Optional<llvm::APSInt> IntConstantValue = 359 Initializer->getIntegerConstantExpr(Ctx)) { 360 // Convert the integer to the floating type. 361 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 362 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 363 llvm::APFloat::rmNearestTiesToEven); 364 // And back. 365 llvm::APSInt ConvertedValue = *IntConstantValue; 366 bool ignored; 367 Result.convertToInteger(ConvertedValue, 368 llvm::APFloat::rmTowardZero, &ignored); 369 // If the resulting value is different, this was a narrowing conversion. 370 if (*IntConstantValue != ConvertedValue) { 371 ConstantValue = APValue(*IntConstantValue); 372 ConstantType = Initializer->getType(); 373 return NK_Constant_Narrowing; 374 } 375 } else { 376 // Variables are always narrowings. 377 return NK_Variable_Narrowing; 378 } 379 } 380 return NK_Not_Narrowing; 381 382 // -- from long double to double or float, or from double to float, except 383 // where the source is a constant expression and the actual value after 384 // conversion is within the range of values that can be represented (even 385 // if it cannot be represented exactly), or 386 case ICK_Floating_Conversion: 387 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 388 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 389 // FromType is larger than ToType. 390 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 391 392 // If it's value-dependent, we can't tell whether it's narrowing. 393 if (Initializer->isValueDependent()) 394 return NK_Dependent_Narrowing; 395 396 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 397 // Constant! 398 assert(ConstantValue.isFloat()); 399 llvm::APFloat FloatVal = ConstantValue.getFloat(); 400 // Convert the source value into the target type. 401 bool ignored; 402 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 403 Ctx.getFloatTypeSemantics(ToType), 404 llvm::APFloat::rmNearestTiesToEven, &ignored); 405 // If there was no overflow, the source value is within the range of 406 // values that can be represented. 407 if (ConvertStatus & llvm::APFloat::opOverflow) { 408 ConstantType = Initializer->getType(); 409 return NK_Constant_Narrowing; 410 } 411 } else { 412 return NK_Variable_Narrowing; 413 } 414 } 415 return NK_Not_Narrowing; 416 417 // -- from an integer type or unscoped enumeration type to an integer type 418 // that cannot represent all the values of the original type, except where 419 // the source is a constant expression and the actual value after 420 // conversion will fit into the target type and will produce the original 421 // value when converted back to the original type. 422 case ICK_Integral_Conversion: 423 IntegralConversion: { 424 assert(FromType->isIntegralOrUnscopedEnumerationType()); 425 assert(ToType->isIntegralOrUnscopedEnumerationType()); 426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 427 const unsigned FromWidth = Ctx.getIntWidth(FromType); 428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 429 const unsigned ToWidth = Ctx.getIntWidth(ToType); 430 431 if (FromWidth > ToWidth || 432 (FromWidth == ToWidth && FromSigned != ToSigned) || 433 (FromSigned && !ToSigned)) { 434 // Not all values of FromType can be represented in ToType. 435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 436 437 // If it's value-dependent, we can't tell whether it's narrowing. 438 if (Initializer->isValueDependent()) 439 return NK_Dependent_Narrowing; 440 441 Optional<llvm::APSInt> OptInitializerValue; 442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 443 // Such conversions on variables are always narrowing. 444 return NK_Variable_Narrowing; 445 } 446 llvm::APSInt &InitializerValue = *OptInitializerValue; 447 bool Narrowing = false; 448 if (FromWidth < ToWidth) { 449 // Negative -> unsigned is narrowing. Otherwise, more bits is never 450 // narrowing. 451 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 452 Narrowing = true; 453 } else { 454 // Add a bit to the InitializerValue so we don't have to worry about 455 // signed vs. unsigned comparisons. 456 InitializerValue = InitializerValue.extend( 457 InitializerValue.getBitWidth() + 1); 458 // Convert the initializer to and from the target width and signed-ness. 459 llvm::APSInt ConvertedValue = InitializerValue; 460 ConvertedValue = ConvertedValue.trunc(ToWidth); 461 ConvertedValue.setIsSigned(ToSigned); 462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 463 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 464 // If the result is different, this was a narrowing conversion. 465 if (ConvertedValue != InitializerValue) 466 Narrowing = true; 467 } 468 if (Narrowing) { 469 ConstantType = Initializer->getType(); 470 ConstantValue = APValue(InitializerValue); 471 return NK_Constant_Narrowing; 472 } 473 } 474 return NK_Not_Narrowing; 475 } 476 477 default: 478 // Other kinds of conversions are not narrowings. 479 return NK_Not_Narrowing; 480 } 481 } 482 483 /// dump - Print this standard conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 bool PrintedSomething = false; 488 if (First != ICK_Identity) { 489 OS << GetImplicitConversionName(First); 490 PrintedSomething = true; 491 } 492 493 if (Second != ICK_Identity) { 494 if (PrintedSomething) { 495 OS << " -> "; 496 } 497 OS << GetImplicitConversionName(Second); 498 499 if (CopyConstructor) { 500 OS << " (by copy constructor)"; 501 } else if (DirectBinding) { 502 OS << " (direct reference binding)"; 503 } else if (ReferenceBinding) { 504 OS << " (reference binding)"; 505 } 506 PrintedSomething = true; 507 } 508 509 if (Third != ICK_Identity) { 510 if (PrintedSomething) { 511 OS << " -> "; 512 } 513 OS << GetImplicitConversionName(Third); 514 PrintedSomething = true; 515 } 516 517 if (!PrintedSomething) { 518 OS << "No conversions required"; 519 } 520 } 521 522 /// dump - Print this user-defined conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void UserDefinedConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (Before.First || Before.Second || Before.Third) { 527 Before.dump(); 528 OS << " -> "; 529 } 530 if (ConversionFunction) 531 OS << '\'' << *ConversionFunction << '\''; 532 else 533 OS << "aggregate initialization"; 534 if (After.First || After.Second || After.Third) { 535 OS << " -> "; 536 After.dump(); 537 } 538 } 539 540 /// dump - Print this implicit conversion sequence to standard 541 /// error. Useful for debugging overloading issues. 542 void ImplicitConversionSequence::dump() const { 543 raw_ostream &OS = llvm::errs(); 544 if (isStdInitializerListElement()) 545 OS << "Worst std::initializer_list element conversion: "; 546 switch (ConversionKind) { 547 case StandardConversion: 548 OS << "Standard conversion: "; 549 Standard.dump(); 550 break; 551 case UserDefinedConversion: 552 OS << "User-defined conversion: "; 553 UserDefined.dump(); 554 break; 555 case EllipsisConversion: 556 OS << "Ellipsis conversion"; 557 break; 558 case AmbiguousConversion: 559 OS << "Ambiguous conversion"; 560 break; 561 case BadConversion: 562 OS << "Bad conversion"; 563 break; 564 } 565 566 OS << "\n"; 567 } 568 569 void AmbiguousConversionSequence::construct() { 570 new (&conversions()) ConversionSet(); 571 } 572 573 void AmbiguousConversionSequence::destruct() { 574 conversions().~ConversionSet(); 575 } 576 577 void 578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 579 FromTypePtr = O.FromTypePtr; 580 ToTypePtr = O.ToTypePtr; 581 new (&conversions()) ConversionSet(O.conversions()); 582 } 583 584 namespace { 585 // Structure used by DeductionFailureInfo to store 586 // template argument information. 587 struct DFIArguments { 588 TemplateArgument FirstArg; 589 TemplateArgument SecondArg; 590 }; 591 // Structure used by DeductionFailureInfo to store 592 // template parameter and template argument information. 593 struct DFIParamWithArguments : DFIArguments { 594 TemplateParameter Param; 595 }; 596 // Structure used by DeductionFailureInfo to store template argument 597 // information and the index of the problematic call argument. 598 struct DFIDeducedMismatchArgs : DFIArguments { 599 TemplateArgumentList *TemplateArgs; 600 unsigned CallArgIndex; 601 }; 602 // Structure used by DeductionFailureInfo to store information about 603 // unsatisfied constraints. 604 struct CNSInfo { 605 TemplateArgumentList *TemplateArgs; 606 ConstraintSatisfaction Satisfaction; 607 }; 608 } 609 610 /// Convert from Sema's representation of template deduction information 611 /// to the form used in overload-candidate information. 612 DeductionFailureInfo 613 clang::MakeDeductionFailureInfo(ASTContext &Context, 614 Sema::TemplateDeductionResult TDK, 615 TemplateDeductionInfo &Info) { 616 DeductionFailureInfo Result; 617 Result.Result = static_cast<unsigned>(TDK); 618 Result.HasDiagnostic = false; 619 switch (TDK) { 620 case Sema::TDK_Invalid: 621 case Sema::TDK_InstantiationDepth: 622 case Sema::TDK_TooManyArguments: 623 case Sema::TDK_TooFewArguments: 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 case Sema::TDK_CUDATargetMismatch: 626 Result.Data = nullptr; 627 break; 628 629 case Sema::TDK_Incomplete: 630 case Sema::TDK_InvalidExplicitArguments: 631 Result.Data = Info.Param.getOpaqueValue(); 632 break; 633 634 case Sema::TDK_DeducedMismatch: 635 case Sema::TDK_DeducedMismatchNested: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 auto *Saved = new (Context) DFIDeducedMismatchArgs; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Saved->TemplateArgs = Info.take(); 641 Saved->CallArgIndex = Info.CallArgIndex; 642 Result.Data = Saved; 643 break; 644 } 645 646 case Sema::TDK_NonDeducedMismatch: { 647 // FIXME: Should allocate from normal heap so that we can free this later. 648 DFIArguments *Saved = new (Context) DFIArguments; 649 Saved->FirstArg = Info.FirstArg; 650 Saved->SecondArg = Info.SecondArg; 651 Result.Data = Saved; 652 break; 653 } 654 655 case Sema::TDK_IncompletePack: 656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 657 case Sema::TDK_Inconsistent: 658 case Sema::TDK_Underqualified: { 659 // FIXME: Should allocate from normal heap so that we can free this later. 660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 661 Saved->Param = Info.Param; 662 Saved->FirstArg = Info.FirstArg; 663 Saved->SecondArg = Info.SecondArg; 664 Result.Data = Saved; 665 break; 666 } 667 668 case Sema::TDK_SubstitutionFailure: 669 Result.Data = Info.take(); 670 if (Info.hasSFINAEDiagnostic()) { 671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 672 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 673 Info.takeSFINAEDiagnostic(*Diag); 674 Result.HasDiagnostic = true; 675 } 676 break; 677 678 case Sema::TDK_ConstraintsNotSatisfied: { 679 CNSInfo *Saved = new (Context) CNSInfo; 680 Saved->TemplateArgs = Info.take(); 681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 682 Result.Data = Saved; 683 break; 684 } 685 686 case Sema::TDK_Success: 687 case Sema::TDK_NonDependentConversionFailure: 688 llvm_unreachable("not a deduction failure"); 689 } 690 691 return Result; 692 } 693 694 void DeductionFailureInfo::Destroy() { 695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 696 case Sema::TDK_Success: 697 case Sema::TDK_Invalid: 698 case Sema::TDK_InstantiationDepth: 699 case Sema::TDK_Incomplete: 700 case Sema::TDK_TooManyArguments: 701 case Sema::TDK_TooFewArguments: 702 case Sema::TDK_InvalidExplicitArguments: 703 case Sema::TDK_CUDATargetMismatch: 704 case Sema::TDK_NonDependentConversionFailure: 705 break; 706 707 case Sema::TDK_IncompletePack: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_DeducedMismatch: 711 case Sema::TDK_DeducedMismatchNested: 712 case Sema::TDK_NonDeducedMismatch: 713 // FIXME: Destroy the data? 714 Data = nullptr; 715 break; 716 717 case Sema::TDK_SubstitutionFailure: 718 // FIXME: Destroy the template argument list? 719 Data = nullptr; 720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 721 Diag->~PartialDiagnosticAt(); 722 HasDiagnostic = false; 723 } 724 break; 725 726 case Sema::TDK_ConstraintsNotSatisfied: 727 // FIXME: Destroy the template argument list? 728 Data = nullptr; 729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 730 Diag->~PartialDiagnosticAt(); 731 HasDiagnostic = false; 732 } 733 break; 734 735 // Unhandled 736 case Sema::TDK_MiscellaneousDeductionFailure: 737 break; 738 } 739 } 740 741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 742 if (HasDiagnostic) 743 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 744 return nullptr; 745 } 746 747 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 749 case Sema::TDK_Success: 750 case Sema::TDK_Invalid: 751 case Sema::TDK_InstantiationDepth: 752 case Sema::TDK_TooManyArguments: 753 case Sema::TDK_TooFewArguments: 754 case Sema::TDK_SubstitutionFailure: 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 case Sema::TDK_NonDeducedMismatch: 758 case Sema::TDK_CUDATargetMismatch: 759 case Sema::TDK_NonDependentConversionFailure: 760 case Sema::TDK_ConstraintsNotSatisfied: 761 return TemplateParameter(); 762 763 case Sema::TDK_Incomplete: 764 case Sema::TDK_InvalidExplicitArguments: 765 return TemplateParameter::getFromOpaqueValue(Data); 766 767 case Sema::TDK_IncompletePack: 768 case Sema::TDK_Inconsistent: 769 case Sema::TDK_Underqualified: 770 return static_cast<DFIParamWithArguments*>(Data)->Param; 771 772 // Unhandled 773 case Sema::TDK_MiscellaneousDeductionFailure: 774 break; 775 } 776 777 return TemplateParameter(); 778 } 779 780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 782 case Sema::TDK_Success: 783 case Sema::TDK_Invalid: 784 case Sema::TDK_InstantiationDepth: 785 case Sema::TDK_TooManyArguments: 786 case Sema::TDK_TooFewArguments: 787 case Sema::TDK_Incomplete: 788 case Sema::TDK_IncompletePack: 789 case Sema::TDK_InvalidExplicitArguments: 790 case Sema::TDK_Inconsistent: 791 case Sema::TDK_Underqualified: 792 case Sema::TDK_NonDeducedMismatch: 793 case Sema::TDK_CUDATargetMismatch: 794 case Sema::TDK_NonDependentConversionFailure: 795 return nullptr; 796 797 case Sema::TDK_DeducedMismatch: 798 case Sema::TDK_DeducedMismatchNested: 799 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 800 801 case Sema::TDK_SubstitutionFailure: 802 return static_cast<TemplateArgumentList*>(Data); 803 804 case Sema::TDK_ConstraintsNotSatisfied: 805 return static_cast<CNSInfo*>(Data)->TemplateArgs; 806 807 // Unhandled 808 case Sema::TDK_MiscellaneousDeductionFailure: 809 break; 810 } 811 812 return nullptr; 813 } 814 815 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 816 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 817 case Sema::TDK_Success: 818 case Sema::TDK_Invalid: 819 case Sema::TDK_InstantiationDepth: 820 case Sema::TDK_Incomplete: 821 case Sema::TDK_TooManyArguments: 822 case Sema::TDK_TooFewArguments: 823 case Sema::TDK_InvalidExplicitArguments: 824 case Sema::TDK_SubstitutionFailure: 825 case Sema::TDK_CUDATargetMismatch: 826 case Sema::TDK_NonDependentConversionFailure: 827 case Sema::TDK_ConstraintsNotSatisfied: 828 return nullptr; 829 830 case Sema::TDK_IncompletePack: 831 case Sema::TDK_Inconsistent: 832 case Sema::TDK_Underqualified: 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 case Sema::TDK_NonDeducedMismatch: 836 return &static_cast<DFIArguments*>(Data)->FirstArg; 837 838 // Unhandled 839 case Sema::TDK_MiscellaneousDeductionFailure: 840 break; 841 } 842 843 return nullptr; 844 } 845 846 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 847 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 848 case Sema::TDK_Success: 849 case Sema::TDK_Invalid: 850 case Sema::TDK_InstantiationDepth: 851 case Sema::TDK_Incomplete: 852 case Sema::TDK_IncompletePack: 853 case Sema::TDK_TooManyArguments: 854 case Sema::TDK_TooFewArguments: 855 case Sema::TDK_InvalidExplicitArguments: 856 case Sema::TDK_SubstitutionFailure: 857 case Sema::TDK_CUDATargetMismatch: 858 case Sema::TDK_NonDependentConversionFailure: 859 case Sema::TDK_ConstraintsNotSatisfied: 860 return nullptr; 861 862 case Sema::TDK_Inconsistent: 863 case Sema::TDK_Underqualified: 864 case Sema::TDK_DeducedMismatch: 865 case Sema::TDK_DeducedMismatchNested: 866 case Sema::TDK_NonDeducedMismatch: 867 return &static_cast<DFIArguments*>(Data)->SecondArg; 868 869 // Unhandled 870 case Sema::TDK_MiscellaneousDeductionFailure: 871 break; 872 } 873 874 return nullptr; 875 } 876 877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 878 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 879 case Sema::TDK_DeducedMismatch: 880 case Sema::TDK_DeducedMismatchNested: 881 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 882 883 default: 884 return llvm::None; 885 } 886 } 887 888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 889 OverloadedOperatorKind Op) { 890 if (!AllowRewrittenCandidates) 891 return false; 892 return Op == OO_EqualEqual || Op == OO_Spaceship; 893 } 894 895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 896 ASTContext &Ctx, const FunctionDecl *FD) { 897 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 898 return false; 899 // Don't bother adding a reversed candidate that can never be a better 900 // match than the non-reversed version. 901 return FD->getNumParams() != 2 || 902 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 903 FD->getParamDecl(1)->getType()) || 904 FD->hasAttr<EnableIfAttr>(); 905 } 906 907 void OverloadCandidateSet::destroyCandidates() { 908 for (iterator i = begin(), e = end(); i != e; ++i) { 909 for (auto &C : i->Conversions) 910 C.~ImplicitConversionSequence(); 911 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 912 i->DeductionFailure.Destroy(); 913 } 914 } 915 916 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 917 destroyCandidates(); 918 SlabAllocator.Reset(); 919 NumInlineBytesUsed = 0; 920 Candidates.clear(); 921 Functions.clear(); 922 Kind = CSK; 923 } 924 925 namespace { 926 class UnbridgedCastsSet { 927 struct Entry { 928 Expr **Addr; 929 Expr *Saved; 930 }; 931 SmallVector<Entry, 2> Entries; 932 933 public: 934 void save(Sema &S, Expr *&E) { 935 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 936 Entry entry = { &E, E }; 937 Entries.push_back(entry); 938 E = S.stripARCUnbridgedCast(E); 939 } 940 941 void restore() { 942 for (SmallVectorImpl<Entry>::iterator 943 i = Entries.begin(), e = Entries.end(); i != e; ++i) 944 *i->Addr = i->Saved; 945 } 946 }; 947 } 948 949 /// checkPlaceholderForOverload - Do any interesting placeholder-like 950 /// preprocessing on the given expression. 951 /// 952 /// \param unbridgedCasts a collection to which to add unbridged casts; 953 /// without this, they will be immediately diagnosed as errors 954 /// 955 /// Return true on unrecoverable error. 956 static bool 957 checkPlaceholderForOverload(Sema &S, Expr *&E, 958 UnbridgedCastsSet *unbridgedCasts = nullptr) { 959 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 960 // We can't handle overloaded expressions here because overload 961 // resolution might reasonably tweak them. 962 if (placeholder->getKind() == BuiltinType::Overload) return false; 963 964 // If the context potentially accepts unbridged ARC casts, strip 965 // the unbridged cast and add it to the collection for later restoration. 966 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 967 unbridgedCasts) { 968 unbridgedCasts->save(S, E); 969 return false; 970 } 971 972 // Go ahead and check everything else. 973 ExprResult result = S.CheckPlaceholderExpr(E); 974 if (result.isInvalid()) 975 return true; 976 977 E = result.get(); 978 return false; 979 } 980 981 // Nothing to do. 982 return false; 983 } 984 985 /// checkArgPlaceholdersForOverload - Check a set of call operands for 986 /// placeholders. 987 static bool checkArgPlaceholdersForOverload(Sema &S, 988 MultiExprArg Args, 989 UnbridgedCastsSet &unbridged) { 990 for (unsigned i = 0, e = Args.size(); i != e; ++i) 991 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 992 return true; 993 994 return false; 995 } 996 997 /// Determine whether the given New declaration is an overload of the 998 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 999 /// New and Old cannot be overloaded, e.g., if New has the same signature as 1000 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 1001 /// functions (or function templates) at all. When it does return Ovl_Match or 1002 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1003 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1004 /// declaration. 1005 /// 1006 /// Example: Given the following input: 1007 /// 1008 /// void f(int, float); // #1 1009 /// void f(int, int); // #2 1010 /// int f(int, int); // #3 1011 /// 1012 /// When we process #1, there is no previous declaration of "f", so IsOverload 1013 /// will not be used. 1014 /// 1015 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1016 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1017 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1018 /// unchanged. 1019 /// 1020 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1021 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1022 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1023 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1024 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1025 /// 1026 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1027 /// by a using declaration. The rules for whether to hide shadow declarations 1028 /// ignore some properties which otherwise figure into a function template's 1029 /// signature. 1030 Sema::OverloadKind 1031 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1032 NamedDecl *&Match, bool NewIsUsingDecl) { 1033 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1034 I != E; ++I) { 1035 NamedDecl *OldD = *I; 1036 1037 bool OldIsUsingDecl = false; 1038 if (isa<UsingShadowDecl>(OldD)) { 1039 OldIsUsingDecl = true; 1040 1041 // We can always introduce two using declarations into the same 1042 // context, even if they have identical signatures. 1043 if (NewIsUsingDecl) continue; 1044 1045 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1046 } 1047 1048 // A using-declaration does not conflict with another declaration 1049 // if one of them is hidden. 1050 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1051 continue; 1052 1053 // If either declaration was introduced by a using declaration, 1054 // we'll need to use slightly different rules for matching. 1055 // Essentially, these rules are the normal rules, except that 1056 // function templates hide function templates with different 1057 // return types or template parameter lists. 1058 bool UseMemberUsingDeclRules = 1059 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1060 !New->getFriendObjectKind(); 1061 1062 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1063 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1064 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1065 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1066 continue; 1067 } 1068 1069 if (!isa<FunctionTemplateDecl>(OldD) && 1070 !shouldLinkPossiblyHiddenDecl(*I, New)) 1071 continue; 1072 1073 Match = *I; 1074 return Ovl_Match; 1075 } 1076 1077 // Builtins that have custom typechecking or have a reference should 1078 // not be overloadable or redeclarable. 1079 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1080 Match = *I; 1081 return Ovl_NonFunction; 1082 } 1083 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1084 // We can overload with these, which can show up when doing 1085 // redeclaration checks for UsingDecls. 1086 assert(Old.getLookupKind() == LookupUsingDeclName); 1087 } else if (isa<TagDecl>(OldD)) { 1088 // We can always overload with tags by hiding them. 1089 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1090 // Optimistically assume that an unresolved using decl will 1091 // overload; if it doesn't, we'll have to diagnose during 1092 // template instantiation. 1093 // 1094 // Exception: if the scope is dependent and this is not a class 1095 // member, the using declaration can only introduce an enumerator. 1096 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1097 Match = *I; 1098 return Ovl_NonFunction; 1099 } 1100 } else { 1101 // (C++ 13p1): 1102 // Only function declarations can be overloaded; object and type 1103 // declarations cannot be overloaded. 1104 Match = *I; 1105 return Ovl_NonFunction; 1106 } 1107 } 1108 1109 // C++ [temp.friend]p1: 1110 // For a friend function declaration that is not a template declaration: 1111 // -- if the name of the friend is a qualified or unqualified template-id, 1112 // [...], otherwise 1113 // -- if the name of the friend is a qualified-id and a matching 1114 // non-template function is found in the specified class or namespace, 1115 // the friend declaration refers to that function, otherwise, 1116 // -- if the name of the friend is a qualified-id and a matching function 1117 // template is found in the specified class or namespace, the friend 1118 // declaration refers to the deduced specialization of that function 1119 // template, otherwise 1120 // -- the name shall be an unqualified-id [...] 1121 // If we get here for a qualified friend declaration, we've just reached the 1122 // third bullet. If the type of the friend is dependent, skip this lookup 1123 // until instantiation. 1124 if (New->getFriendObjectKind() && New->getQualifier() && 1125 !New->getDescribedFunctionTemplate() && 1126 !New->getDependentSpecializationInfo() && 1127 !New->getType()->isDependentType()) { 1128 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1129 TemplateSpecResult.addAllDecls(Old); 1130 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1131 /*QualifiedFriend*/true)) { 1132 New->setInvalidDecl(); 1133 return Ovl_Overload; 1134 } 1135 1136 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1137 return Ovl_Match; 1138 } 1139 1140 return Ovl_Overload; 1141 } 1142 1143 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1145 bool ConsiderRequiresClauses) { 1146 // C++ [basic.start.main]p2: This function shall not be overloaded. 1147 if (New->isMain()) 1148 return false; 1149 1150 // MSVCRT user defined entry points cannot be overloaded. 1151 if (New->isMSVCRTEntryPoint()) 1152 return false; 1153 1154 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1155 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1156 1157 // C++ [temp.fct]p2: 1158 // A function template can be overloaded with other function templates 1159 // and with normal (non-template) functions. 1160 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1161 return true; 1162 1163 // Is the function New an overload of the function Old? 1164 QualType OldQType = Context.getCanonicalType(Old->getType()); 1165 QualType NewQType = Context.getCanonicalType(New->getType()); 1166 1167 // Compare the signatures (C++ 1.3.10) of the two functions to 1168 // determine whether they are overloads. If we find any mismatch 1169 // in the signature, they are overloads. 1170 1171 // If either of these functions is a K&R-style function (no 1172 // prototype), then we consider them to have matching signatures. 1173 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1174 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1175 return false; 1176 1177 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1178 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1179 1180 // The signature of a function includes the types of its 1181 // parameters (C++ 1.3.10), which includes the presence or absence 1182 // of the ellipsis; see C++ DR 357). 1183 if (OldQType != NewQType && 1184 (OldType->getNumParams() != NewType->getNumParams() || 1185 OldType->isVariadic() != NewType->isVariadic() || 1186 !FunctionParamTypesAreEqual(OldType, NewType))) 1187 return true; 1188 1189 // C++ [temp.over.link]p4: 1190 // The signature of a function template consists of its function 1191 // signature, its return type and its template parameter list. The names 1192 // of the template parameters are significant only for establishing the 1193 // relationship between the template parameters and the rest of the 1194 // signature. 1195 // 1196 // We check the return type and template parameter lists for function 1197 // templates first; the remaining checks follow. 1198 // 1199 // However, we don't consider either of these when deciding whether 1200 // a member introduced by a shadow declaration is hidden. 1201 if (!UseMemberUsingDeclRules && NewTemplate && 1202 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1203 OldTemplate->getTemplateParameters(), 1204 false, TPL_TemplateMatch) || 1205 !Context.hasSameType(Old->getDeclaredReturnType(), 1206 New->getDeclaredReturnType()))) 1207 return true; 1208 1209 // If the function is a class member, its signature includes the 1210 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1211 // 1212 // As part of this, also check whether one of the member functions 1213 // is static, in which case they are not overloads (C++ 1214 // 13.1p2). While not part of the definition of the signature, 1215 // this check is important to determine whether these functions 1216 // can be overloaded. 1217 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1218 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1219 if (OldMethod && NewMethod && 1220 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1221 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1222 if (!UseMemberUsingDeclRules && 1223 (OldMethod->getRefQualifier() == RQ_None || 1224 NewMethod->getRefQualifier() == RQ_None)) { 1225 // C++0x [over.load]p2: 1226 // - Member function declarations with the same name and the same 1227 // parameter-type-list as well as member function template 1228 // declarations with the same name, the same parameter-type-list, and 1229 // the same template parameter lists cannot be overloaded if any of 1230 // them, but not all, have a ref-qualifier (8.3.5). 1231 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1232 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1233 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1234 } 1235 return true; 1236 } 1237 1238 // We may not have applied the implicit const for a constexpr member 1239 // function yet (because we haven't yet resolved whether this is a static 1240 // or non-static member function). Add it now, on the assumption that this 1241 // is a redeclaration of OldMethod. 1242 auto OldQuals = OldMethod->getMethodQualifiers(); 1243 auto NewQuals = NewMethod->getMethodQualifiers(); 1244 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1245 !isa<CXXConstructorDecl>(NewMethod)) 1246 NewQuals.addConst(); 1247 // We do not allow overloading based off of '__restrict'. 1248 OldQuals.removeRestrict(); 1249 NewQuals.removeRestrict(); 1250 if (OldQuals != NewQuals) 1251 return true; 1252 } 1253 1254 // Though pass_object_size is placed on parameters and takes an argument, we 1255 // consider it to be a function-level modifier for the sake of function 1256 // identity. Either the function has one or more parameters with 1257 // pass_object_size or it doesn't. 1258 if (functionHasPassObjectSizeParams(New) != 1259 functionHasPassObjectSizeParams(Old)) 1260 return true; 1261 1262 // enable_if attributes are an order-sensitive part of the signature. 1263 for (specific_attr_iterator<EnableIfAttr> 1264 NewI = New->specific_attr_begin<EnableIfAttr>(), 1265 NewE = New->specific_attr_end<EnableIfAttr>(), 1266 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1267 OldE = Old->specific_attr_end<EnableIfAttr>(); 1268 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1269 if (NewI == NewE || OldI == OldE) 1270 return true; 1271 llvm::FoldingSetNodeID NewID, OldID; 1272 NewI->getCond()->Profile(NewID, Context, true); 1273 OldI->getCond()->Profile(OldID, Context, true); 1274 if (NewID != OldID) 1275 return true; 1276 } 1277 1278 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1279 // Don't allow overloading of destructors. (In theory we could, but it 1280 // would be a giant change to clang.) 1281 if (!isa<CXXDestructorDecl>(New)) { 1282 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1283 OldTarget = IdentifyCUDATarget(Old); 1284 if (NewTarget != CFT_InvalidTarget) { 1285 assert((OldTarget != CFT_InvalidTarget) && 1286 "Unexpected invalid target."); 1287 1288 // Allow overloading of functions with same signature and different CUDA 1289 // target attributes. 1290 if (NewTarget != OldTarget) 1291 return true; 1292 } 1293 } 1294 } 1295 1296 if (ConsiderRequiresClauses) { 1297 Expr *NewRC = New->getTrailingRequiresClause(), 1298 *OldRC = Old->getTrailingRequiresClause(); 1299 if ((NewRC != nullptr) != (OldRC != nullptr)) 1300 // RC are most certainly different - these are overloads. 1301 return true; 1302 1303 if (NewRC) { 1304 llvm::FoldingSetNodeID NewID, OldID; 1305 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1306 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1307 if (NewID != OldID) 1308 // RCs are not equivalent - these are overloads. 1309 return true; 1310 } 1311 } 1312 1313 // The signatures match; this is not an overload. 1314 return false; 1315 } 1316 1317 /// Tries a user-defined conversion from From to ToType. 1318 /// 1319 /// Produces an implicit conversion sequence for when a standard conversion 1320 /// is not an option. See TryImplicitConversion for more information. 1321 static ImplicitConversionSequence 1322 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1323 bool SuppressUserConversions, 1324 AllowedExplicit AllowExplicit, 1325 bool InOverloadResolution, 1326 bool CStyle, 1327 bool AllowObjCWritebackConversion, 1328 bool AllowObjCConversionOnExplicit) { 1329 ImplicitConversionSequence ICS; 1330 1331 if (SuppressUserConversions) { 1332 // We're not in the case above, so there is no conversion that 1333 // we can perform. 1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1335 return ICS; 1336 } 1337 1338 // Attempt user-defined conversion. 1339 OverloadCandidateSet Conversions(From->getExprLoc(), 1340 OverloadCandidateSet::CSK_Normal); 1341 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1342 Conversions, AllowExplicit, 1343 AllowObjCConversionOnExplicit)) { 1344 case OR_Success: 1345 case OR_Deleted: 1346 ICS.setUserDefined(); 1347 // C++ [over.ics.user]p4: 1348 // A conversion of an expression of class type to the same class 1349 // type is given Exact Match rank, and a conversion of an 1350 // expression of class type to a base class of that type is 1351 // given Conversion rank, in spite of the fact that a copy 1352 // constructor (i.e., a user-defined conversion function) is 1353 // called for those cases. 1354 if (CXXConstructorDecl *Constructor 1355 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1356 QualType FromCanon 1357 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1358 QualType ToCanon 1359 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1360 if (Constructor->isCopyConstructor() && 1361 (FromCanon == ToCanon || 1362 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1363 // Turn this into a "standard" conversion sequence, so that it 1364 // gets ranked with standard conversion sequences. 1365 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1366 ICS.setStandard(); 1367 ICS.Standard.setAsIdentityConversion(); 1368 ICS.Standard.setFromType(From->getType()); 1369 ICS.Standard.setAllToTypes(ToType); 1370 ICS.Standard.CopyConstructor = Constructor; 1371 ICS.Standard.FoundCopyConstructor = Found; 1372 if (ToCanon != FromCanon) 1373 ICS.Standard.Second = ICK_Derived_To_Base; 1374 } 1375 } 1376 break; 1377 1378 case OR_Ambiguous: 1379 ICS.setAmbiguous(); 1380 ICS.Ambiguous.setFromType(From->getType()); 1381 ICS.Ambiguous.setToType(ToType); 1382 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1383 Cand != Conversions.end(); ++Cand) 1384 if (Cand->Best) 1385 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1386 break; 1387 1388 // Fall through. 1389 case OR_No_Viable_Function: 1390 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1391 break; 1392 } 1393 1394 return ICS; 1395 } 1396 1397 /// TryImplicitConversion - Attempt to perform an implicit conversion 1398 /// from the given expression (Expr) to the given type (ToType). This 1399 /// function returns an implicit conversion sequence that can be used 1400 /// to perform the initialization. Given 1401 /// 1402 /// void f(float f); 1403 /// void g(int i) { f(i); } 1404 /// 1405 /// this routine would produce an implicit conversion sequence to 1406 /// describe the initialization of f from i, which will be a standard 1407 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1408 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1409 // 1410 /// Note that this routine only determines how the conversion can be 1411 /// performed; it does not actually perform the conversion. As such, 1412 /// it will not produce any diagnostics if no conversion is available, 1413 /// but will instead return an implicit conversion sequence of kind 1414 /// "BadConversion". 1415 /// 1416 /// If @p SuppressUserConversions, then user-defined conversions are 1417 /// not permitted. 1418 /// If @p AllowExplicit, then explicit user-defined conversions are 1419 /// permitted. 1420 /// 1421 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1422 /// writeback conversion, which allows __autoreleasing id* parameters to 1423 /// be initialized with __strong id* or __weak id* arguments. 1424 static ImplicitConversionSequence 1425 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1426 bool SuppressUserConversions, 1427 AllowedExplicit AllowExplicit, 1428 bool InOverloadResolution, 1429 bool CStyle, 1430 bool AllowObjCWritebackConversion, 1431 bool AllowObjCConversionOnExplicit) { 1432 ImplicitConversionSequence ICS; 1433 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1434 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1435 ICS.setStandard(); 1436 return ICS; 1437 } 1438 1439 if (!S.getLangOpts().CPlusPlus) { 1440 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1441 return ICS; 1442 } 1443 1444 // C++ [over.ics.user]p4: 1445 // A conversion of an expression of class type to the same class 1446 // type is given Exact Match rank, and a conversion of an 1447 // expression of class type to a base class of that type is 1448 // given Conversion rank, in spite of the fact that a copy/move 1449 // constructor (i.e., a user-defined conversion function) is 1450 // called for those cases. 1451 QualType FromType = From->getType(); 1452 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1453 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1454 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1455 ICS.setStandard(); 1456 ICS.Standard.setAsIdentityConversion(); 1457 ICS.Standard.setFromType(FromType); 1458 ICS.Standard.setAllToTypes(ToType); 1459 1460 // We don't actually check at this point whether there is a valid 1461 // copy/move constructor, since overloading just assumes that it 1462 // exists. When we actually perform initialization, we'll find the 1463 // appropriate constructor to copy the returned object, if needed. 1464 ICS.Standard.CopyConstructor = nullptr; 1465 1466 // Determine whether this is considered a derived-to-base conversion. 1467 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1468 ICS.Standard.Second = ICK_Derived_To_Base; 1469 1470 return ICS; 1471 } 1472 1473 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1474 AllowExplicit, InOverloadResolution, CStyle, 1475 AllowObjCWritebackConversion, 1476 AllowObjCConversionOnExplicit); 1477 } 1478 1479 ImplicitConversionSequence 1480 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1481 bool SuppressUserConversions, 1482 AllowedExplicit AllowExplicit, 1483 bool InOverloadResolution, 1484 bool CStyle, 1485 bool AllowObjCWritebackConversion) { 1486 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1487 AllowExplicit, InOverloadResolution, CStyle, 1488 AllowObjCWritebackConversion, 1489 /*AllowObjCConversionOnExplicit=*/false); 1490 } 1491 1492 /// PerformImplicitConversion - Perform an implicit conversion of the 1493 /// expression From to the type ToType. Returns the 1494 /// converted expression. Flavor is the kind of conversion we're 1495 /// performing, used in the error message. If @p AllowExplicit, 1496 /// explicit user-defined conversions are permitted. 1497 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1498 AssignmentAction Action, 1499 bool AllowExplicit) { 1500 if (checkPlaceholderForOverload(*this, From)) 1501 return ExprError(); 1502 1503 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1504 bool AllowObjCWritebackConversion 1505 = getLangOpts().ObjCAutoRefCount && 1506 (Action == AA_Passing || Action == AA_Sending); 1507 if (getLangOpts().ObjC) 1508 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1509 From->getType(), From); 1510 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1511 *this, From, ToType, 1512 /*SuppressUserConversions=*/false, 1513 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1514 /*InOverloadResolution=*/false, 1515 /*CStyle=*/false, AllowObjCWritebackConversion, 1516 /*AllowObjCConversionOnExplicit=*/false); 1517 return PerformImplicitConversion(From, ToType, ICS, Action); 1518 } 1519 1520 /// Determine whether the conversion from FromType to ToType is a valid 1521 /// conversion that strips "noexcept" or "noreturn" off the nested function 1522 /// type. 1523 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1524 QualType &ResultTy) { 1525 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1526 return false; 1527 1528 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1529 // or F(t noexcept) -> F(t) 1530 // where F adds one of the following at most once: 1531 // - a pointer 1532 // - a member pointer 1533 // - a block pointer 1534 // Changes here need matching changes in FindCompositePointerType. 1535 CanQualType CanTo = Context.getCanonicalType(ToType); 1536 CanQualType CanFrom = Context.getCanonicalType(FromType); 1537 Type::TypeClass TyClass = CanTo->getTypeClass(); 1538 if (TyClass != CanFrom->getTypeClass()) return false; 1539 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1540 if (TyClass == Type::Pointer) { 1541 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1542 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1543 } else if (TyClass == Type::BlockPointer) { 1544 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1545 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1546 } else if (TyClass == Type::MemberPointer) { 1547 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1548 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1549 // A function pointer conversion cannot change the class of the function. 1550 if (ToMPT->getClass() != FromMPT->getClass()) 1551 return false; 1552 CanTo = ToMPT->getPointeeType(); 1553 CanFrom = FromMPT->getPointeeType(); 1554 } else { 1555 return false; 1556 } 1557 1558 TyClass = CanTo->getTypeClass(); 1559 if (TyClass != CanFrom->getTypeClass()) return false; 1560 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1561 return false; 1562 } 1563 1564 const auto *FromFn = cast<FunctionType>(CanFrom); 1565 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1566 1567 const auto *ToFn = cast<FunctionType>(CanTo); 1568 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1569 1570 bool Changed = false; 1571 1572 // Drop 'noreturn' if not present in target type. 1573 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1574 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1575 Changed = true; 1576 } 1577 1578 // Drop 'noexcept' if not present in target type. 1579 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1580 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1581 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1582 FromFn = cast<FunctionType>( 1583 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1584 EST_None) 1585 .getTypePtr()); 1586 Changed = true; 1587 } 1588 1589 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1590 // only if the ExtParameterInfo lists of the two function prototypes can be 1591 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1592 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1593 bool CanUseToFPT, CanUseFromFPT; 1594 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1595 CanUseFromFPT, NewParamInfos) && 1596 CanUseToFPT && !CanUseFromFPT) { 1597 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1598 ExtInfo.ExtParameterInfos = 1599 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1600 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1601 FromFPT->getParamTypes(), ExtInfo); 1602 FromFn = QT->getAs<FunctionType>(); 1603 Changed = true; 1604 } 1605 } 1606 1607 if (!Changed) 1608 return false; 1609 1610 assert(QualType(FromFn, 0).isCanonical()); 1611 if (QualType(FromFn, 0) != CanTo) return false; 1612 1613 ResultTy = ToType; 1614 return true; 1615 } 1616 1617 /// Determine whether the conversion from FromType to ToType is a valid 1618 /// vector conversion. 1619 /// 1620 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1621 /// conversion. 1622 static bool IsVectorConversion(Sema &S, QualType FromType, 1623 QualType ToType, ImplicitConversionKind &ICK) { 1624 // We need at least one of these types to be a vector type to have a vector 1625 // conversion. 1626 if (!ToType->isVectorType() && !FromType->isVectorType()) 1627 return false; 1628 1629 // Identical types require no conversions. 1630 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1631 return false; 1632 1633 // There are no conversions between extended vector types, only identity. 1634 if (ToType->isExtVectorType()) { 1635 // There are no conversions between extended vector types other than the 1636 // identity conversion. 1637 if (FromType->isExtVectorType()) 1638 return false; 1639 1640 // Vector splat from any arithmetic type to a vector. 1641 if (FromType->isArithmeticType()) { 1642 ICK = ICK_Vector_Splat; 1643 return true; 1644 } 1645 } 1646 1647 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1648 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1649 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1650 ICK = ICK_SVE_Vector_Conversion; 1651 return true; 1652 } 1653 1654 // We can perform the conversion between vector types in the following cases: 1655 // 1)vector types are equivalent AltiVec and GCC vector types 1656 // 2)lax vector conversions are permitted and the vector types are of the 1657 // same size 1658 // 3)the destination type does not have the ARM MVE strict-polymorphism 1659 // attribute, which inhibits lax vector conversion for overload resolution 1660 // only 1661 if (ToType->isVectorType() && FromType->isVectorType()) { 1662 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1663 (S.isLaxVectorConversion(FromType, ToType) && 1664 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1665 ICK = ICK_Vector_Conversion; 1666 return true; 1667 } 1668 } 1669 1670 return false; 1671 } 1672 1673 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1674 bool InOverloadResolution, 1675 StandardConversionSequence &SCS, 1676 bool CStyle); 1677 1678 /// IsStandardConversion - Determines whether there is a standard 1679 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1680 /// expression From to the type ToType. Standard conversion sequences 1681 /// only consider non-class types; for conversions that involve class 1682 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1683 /// contain the standard conversion sequence required to perform this 1684 /// conversion and this routine will return true. Otherwise, this 1685 /// routine will return false and the value of SCS is unspecified. 1686 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1687 bool InOverloadResolution, 1688 StandardConversionSequence &SCS, 1689 bool CStyle, 1690 bool AllowObjCWritebackConversion) { 1691 QualType FromType = From->getType(); 1692 1693 // Standard conversions (C++ [conv]) 1694 SCS.setAsIdentityConversion(); 1695 SCS.IncompatibleObjC = false; 1696 SCS.setFromType(FromType); 1697 SCS.CopyConstructor = nullptr; 1698 1699 // There are no standard conversions for class types in C++, so 1700 // abort early. When overloading in C, however, we do permit them. 1701 if (S.getLangOpts().CPlusPlus && 1702 (FromType->isRecordType() || ToType->isRecordType())) 1703 return false; 1704 1705 // The first conversion can be an lvalue-to-rvalue conversion, 1706 // array-to-pointer conversion, or function-to-pointer conversion 1707 // (C++ 4p1). 1708 1709 if (FromType == S.Context.OverloadTy) { 1710 DeclAccessPair AccessPair; 1711 if (FunctionDecl *Fn 1712 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1713 AccessPair)) { 1714 // We were able to resolve the address of the overloaded function, 1715 // so we can convert to the type of that function. 1716 FromType = Fn->getType(); 1717 SCS.setFromType(FromType); 1718 1719 // we can sometimes resolve &foo<int> regardless of ToType, so check 1720 // if the type matches (identity) or we are converting to bool 1721 if (!S.Context.hasSameUnqualifiedType( 1722 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1723 QualType resultTy; 1724 // if the function type matches except for [[noreturn]], it's ok 1725 if (!S.IsFunctionConversion(FromType, 1726 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1727 // otherwise, only a boolean conversion is standard 1728 if (!ToType->isBooleanType()) 1729 return false; 1730 } 1731 1732 // Check if the "from" expression is taking the address of an overloaded 1733 // function and recompute the FromType accordingly. Take advantage of the 1734 // fact that non-static member functions *must* have such an address-of 1735 // expression. 1736 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1737 if (Method && !Method->isStatic()) { 1738 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1739 "Non-unary operator on non-static member address"); 1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1741 == UO_AddrOf && 1742 "Non-address-of operator on non-static member address"); 1743 const Type *ClassType 1744 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1745 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1746 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1748 UO_AddrOf && 1749 "Non-address-of operator for overloaded function expression"); 1750 FromType = S.Context.getPointerType(FromType); 1751 } 1752 1753 // Check that we've computed the proper type after overload resolution. 1754 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1755 // be calling it from within an NDEBUG block. 1756 assert(S.Context.hasSameType( 1757 FromType, 1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1759 } else { 1760 return false; 1761 } 1762 } 1763 // Lvalue-to-rvalue conversion (C++11 4.1): 1764 // A glvalue (3.10) of a non-function, non-array type T can 1765 // be converted to a prvalue. 1766 bool argIsLValue = From->isGLValue(); 1767 if (argIsLValue && 1768 !FromType->isFunctionType() && !FromType->isArrayType() && 1769 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1770 SCS.First = ICK_Lvalue_To_Rvalue; 1771 1772 // C11 6.3.2.1p2: 1773 // ... if the lvalue has atomic type, the value has the non-atomic version 1774 // of the type of the lvalue ... 1775 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1776 FromType = Atomic->getValueType(); 1777 1778 // If T is a non-class type, the type of the rvalue is the 1779 // cv-unqualified version of T. Otherwise, the type of the rvalue 1780 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1781 // just strip the qualifiers because they don't matter. 1782 FromType = FromType.getUnqualifiedType(); 1783 } else if (FromType->isArrayType()) { 1784 // Array-to-pointer conversion (C++ 4.2) 1785 SCS.First = ICK_Array_To_Pointer; 1786 1787 // An lvalue or rvalue of type "array of N T" or "array of unknown 1788 // bound of T" can be converted to an rvalue of type "pointer to 1789 // T" (C++ 4.2p1). 1790 FromType = S.Context.getArrayDecayedType(FromType); 1791 1792 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1793 // This conversion is deprecated in C++03 (D.4) 1794 SCS.DeprecatedStringLiteralToCharPtr = true; 1795 1796 // For the purpose of ranking in overload resolution 1797 // (13.3.3.1.1), this conversion is considered an 1798 // array-to-pointer conversion followed by a qualification 1799 // conversion (4.4). (C++ 4.2p2) 1800 SCS.Second = ICK_Identity; 1801 SCS.Third = ICK_Qualification; 1802 SCS.QualificationIncludesObjCLifetime = false; 1803 SCS.setAllToTypes(FromType); 1804 return true; 1805 } 1806 } else if (FromType->isFunctionType() && argIsLValue) { 1807 // Function-to-pointer conversion (C++ 4.3). 1808 SCS.First = ICK_Function_To_Pointer; 1809 1810 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1811 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1812 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1813 return false; 1814 1815 // An lvalue of function type T can be converted to an rvalue of 1816 // type "pointer to T." The result is a pointer to the 1817 // function. (C++ 4.3p1). 1818 FromType = S.Context.getPointerType(FromType); 1819 } else { 1820 // We don't require any conversions for the first step. 1821 SCS.First = ICK_Identity; 1822 } 1823 SCS.setToType(0, FromType); 1824 1825 // The second conversion can be an integral promotion, floating 1826 // point promotion, integral conversion, floating point conversion, 1827 // floating-integral conversion, pointer conversion, 1828 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1829 // For overloading in C, this can also be a "compatible-type" 1830 // conversion. 1831 bool IncompatibleObjC = false; 1832 ImplicitConversionKind SecondICK = ICK_Identity; 1833 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1834 // The unqualified versions of the types are the same: there's no 1835 // conversion to do. 1836 SCS.Second = ICK_Identity; 1837 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1838 // Integral promotion (C++ 4.5). 1839 SCS.Second = ICK_Integral_Promotion; 1840 FromType = ToType.getUnqualifiedType(); 1841 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1842 // Floating point promotion (C++ 4.6). 1843 SCS.Second = ICK_Floating_Promotion; 1844 FromType = ToType.getUnqualifiedType(); 1845 } else if (S.IsComplexPromotion(FromType, ToType)) { 1846 // Complex promotion (Clang extension) 1847 SCS.Second = ICK_Complex_Promotion; 1848 FromType = ToType.getUnqualifiedType(); 1849 } else if (ToType->isBooleanType() && 1850 (FromType->isArithmeticType() || 1851 FromType->isAnyPointerType() || 1852 FromType->isBlockPointerType() || 1853 FromType->isMemberPointerType())) { 1854 // Boolean conversions (C++ 4.12). 1855 SCS.Second = ICK_Boolean_Conversion; 1856 FromType = S.Context.BoolTy; 1857 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1858 ToType->isIntegralType(S.Context)) { 1859 // Integral conversions (C++ 4.7). 1860 SCS.Second = ICK_Integral_Conversion; 1861 FromType = ToType.getUnqualifiedType(); 1862 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1863 // Complex conversions (C99 6.3.1.6) 1864 SCS.Second = ICK_Complex_Conversion; 1865 FromType = ToType.getUnqualifiedType(); 1866 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1867 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1868 // Complex-real conversions (C99 6.3.1.7) 1869 SCS.Second = ICK_Complex_Real; 1870 FromType = ToType.getUnqualifiedType(); 1871 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1872 // FIXME: disable conversions between long double, __ibm128 and __float128 1873 // if their representation is different until there is back end support 1874 // We of course allow this conversion if long double is really double. 1875 1876 // Conversions between bfloat and other floats are not permitted. 1877 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1878 return false; 1879 1880 // Conversions between IEEE-quad and IBM-extended semantics are not 1881 // permitted. 1882 const llvm::fltSemantics &FromSem = 1883 S.Context.getFloatTypeSemantics(FromType); 1884 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 1885 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 1886 &ToSem == &llvm::APFloat::IEEEquad()) || 1887 (&FromSem == &llvm::APFloat::IEEEquad() && 1888 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 1889 return false; 1890 1891 // Floating point conversions (C++ 4.8). 1892 SCS.Second = ICK_Floating_Conversion; 1893 FromType = ToType.getUnqualifiedType(); 1894 } else if ((FromType->isRealFloatingType() && 1895 ToType->isIntegralType(S.Context)) || 1896 (FromType->isIntegralOrUnscopedEnumerationType() && 1897 ToType->isRealFloatingType())) { 1898 // Conversions between bfloat and int are not permitted. 1899 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1900 return false; 1901 1902 // Floating-integral conversions (C++ 4.9). 1903 SCS.Second = ICK_Floating_Integral; 1904 FromType = ToType.getUnqualifiedType(); 1905 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1906 SCS.Second = ICK_Block_Pointer_Conversion; 1907 } else if (AllowObjCWritebackConversion && 1908 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1909 SCS.Second = ICK_Writeback_Conversion; 1910 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1911 FromType, IncompatibleObjC)) { 1912 // Pointer conversions (C++ 4.10). 1913 SCS.Second = ICK_Pointer_Conversion; 1914 SCS.IncompatibleObjC = IncompatibleObjC; 1915 FromType = FromType.getUnqualifiedType(); 1916 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1917 InOverloadResolution, FromType)) { 1918 // Pointer to member conversions (4.11). 1919 SCS.Second = ICK_Pointer_Member; 1920 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 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->getAs<ObjCObjectPointerType>(), 2409 ToPointeeType, 2410 ToType, Context); 2411 return true; 2412 } 2413 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2414 if (!FromTypePtr) 2415 return false; 2416 2417 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2418 2419 // If the unqualified pointee types are the same, this can't be a 2420 // pointer conversion, so don't do all of the work below. 2421 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2422 return false; 2423 2424 // An rvalue of type "pointer to cv T," where T is an object type, 2425 // can be converted to an rvalue of type "pointer to cv void" (C++ 2426 // 4.10p2). 2427 if (FromPointeeType->isIncompleteOrObjectType() && 2428 ToPointeeType->isVoidType()) { 2429 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2430 ToPointeeType, 2431 ToType, Context, 2432 /*StripObjCLifetime=*/true); 2433 return true; 2434 } 2435 2436 // MSVC allows implicit function to void* type conversion. 2437 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2438 ToPointeeType->isVoidType()) { 2439 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2440 ToPointeeType, 2441 ToType, Context); 2442 return true; 2443 } 2444 2445 // When we're overloading in C, we allow a special kind of pointer 2446 // conversion for compatible-but-not-identical pointee types. 2447 if (!getLangOpts().CPlusPlus && 2448 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2449 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2450 ToPointeeType, 2451 ToType, Context); 2452 return true; 2453 } 2454 2455 // C++ [conv.ptr]p3: 2456 // 2457 // An rvalue of type "pointer to cv D," where D is a class type, 2458 // can be converted to an rvalue of type "pointer to cv B," where 2459 // B is a base class (clause 10) of D. If B is an inaccessible 2460 // (clause 11) or ambiguous (10.2) base class of D, a program that 2461 // necessitates this conversion is ill-formed. The result of the 2462 // conversion is a pointer to the base class sub-object of the 2463 // derived class object. The null pointer value is converted to 2464 // the null pointer value of the destination type. 2465 // 2466 // Note that we do not check for ambiguity or inaccessibility 2467 // here. That is handled by CheckPointerConversion. 2468 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2469 ToPointeeType->isRecordType() && 2470 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2471 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2472 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2473 ToPointeeType, 2474 ToType, Context); 2475 return true; 2476 } 2477 2478 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2479 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2480 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2481 ToPointeeType, 2482 ToType, Context); 2483 return true; 2484 } 2485 2486 return false; 2487 } 2488 2489 /// Adopt the given qualifiers for the given type. 2490 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2491 Qualifiers TQs = T.getQualifiers(); 2492 2493 // Check whether qualifiers already match. 2494 if (TQs == Qs) 2495 return T; 2496 2497 if (Qs.compatiblyIncludes(TQs)) 2498 return Context.getQualifiedType(T, Qs); 2499 2500 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2501 } 2502 2503 /// isObjCPointerConversion - Determines whether this is an 2504 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2505 /// with the same arguments and return values. 2506 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2507 QualType& ConvertedType, 2508 bool &IncompatibleObjC) { 2509 if (!getLangOpts().ObjC) 2510 return false; 2511 2512 // The set of qualifiers on the type we're converting from. 2513 Qualifiers FromQualifiers = FromType.getQualifiers(); 2514 2515 // First, we handle all conversions on ObjC object pointer types. 2516 const ObjCObjectPointerType* ToObjCPtr = 2517 ToType->getAs<ObjCObjectPointerType>(); 2518 const ObjCObjectPointerType *FromObjCPtr = 2519 FromType->getAs<ObjCObjectPointerType>(); 2520 2521 if (ToObjCPtr && FromObjCPtr) { 2522 // If the pointee types are the same (ignoring qualifications), 2523 // then this is not a pointer conversion. 2524 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2525 FromObjCPtr->getPointeeType())) 2526 return false; 2527 2528 // Conversion between Objective-C pointers. 2529 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2530 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2531 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2532 if (getLangOpts().CPlusPlus && LHS && RHS && 2533 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2534 FromObjCPtr->getPointeeType())) 2535 return false; 2536 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2537 ToObjCPtr->getPointeeType(), 2538 ToType, Context); 2539 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2540 return true; 2541 } 2542 2543 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2544 // Okay: this is some kind of implicit downcast of Objective-C 2545 // interfaces, which is permitted. However, we're going to 2546 // complain about it. 2547 IncompatibleObjC = true; 2548 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2549 ToObjCPtr->getPointeeType(), 2550 ToType, Context); 2551 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2552 return true; 2553 } 2554 } 2555 // Beyond this point, both types need to be C pointers or block pointers. 2556 QualType ToPointeeType; 2557 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2558 ToPointeeType = ToCPtr->getPointeeType(); 2559 else if (const BlockPointerType *ToBlockPtr = 2560 ToType->getAs<BlockPointerType>()) { 2561 // Objective C++: We're able to convert from a pointer to any object 2562 // to a block pointer type. 2563 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2564 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2565 return true; 2566 } 2567 ToPointeeType = ToBlockPtr->getPointeeType(); 2568 } 2569 else if (FromType->getAs<BlockPointerType>() && 2570 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2571 // Objective C++: We're able to convert from a block pointer type to a 2572 // pointer to any object. 2573 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2574 return true; 2575 } 2576 else 2577 return false; 2578 2579 QualType FromPointeeType; 2580 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2581 FromPointeeType = FromCPtr->getPointeeType(); 2582 else if (const BlockPointerType *FromBlockPtr = 2583 FromType->getAs<BlockPointerType>()) 2584 FromPointeeType = FromBlockPtr->getPointeeType(); 2585 else 2586 return false; 2587 2588 // If we have pointers to pointers, recursively check whether this 2589 // is an Objective-C conversion. 2590 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2591 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2592 IncompatibleObjC)) { 2593 // We always complain about this conversion. 2594 IncompatibleObjC = true; 2595 ConvertedType = Context.getPointerType(ConvertedType); 2596 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2597 return true; 2598 } 2599 // Allow conversion of pointee being objective-c pointer to another one; 2600 // as in I* to id. 2601 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2602 ToPointeeType->getAs<ObjCObjectPointerType>() && 2603 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2604 IncompatibleObjC)) { 2605 2606 ConvertedType = Context.getPointerType(ConvertedType); 2607 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2608 return true; 2609 } 2610 2611 // If we have pointers to functions or blocks, check whether the only 2612 // differences in the argument and result types are in Objective-C 2613 // pointer conversions. If so, we permit the conversion (but 2614 // complain about it). 2615 const FunctionProtoType *FromFunctionType 2616 = FromPointeeType->getAs<FunctionProtoType>(); 2617 const FunctionProtoType *ToFunctionType 2618 = ToPointeeType->getAs<FunctionProtoType>(); 2619 if (FromFunctionType && ToFunctionType) { 2620 // If the function types are exactly the same, this isn't an 2621 // Objective-C pointer conversion. 2622 if (Context.getCanonicalType(FromPointeeType) 2623 == Context.getCanonicalType(ToPointeeType)) 2624 return false; 2625 2626 // Perform the quick checks that will tell us whether these 2627 // function types are obviously different. 2628 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2629 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2630 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2631 return false; 2632 2633 bool HasObjCConversion = false; 2634 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2635 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2636 // Okay, the types match exactly. Nothing to do. 2637 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2638 ToFunctionType->getReturnType(), 2639 ConvertedType, IncompatibleObjC)) { 2640 // Okay, we have an Objective-C pointer conversion. 2641 HasObjCConversion = true; 2642 } else { 2643 // Function types are too different. Abort. 2644 return false; 2645 } 2646 2647 // Check argument types. 2648 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2649 ArgIdx != NumArgs; ++ArgIdx) { 2650 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2651 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2652 if (Context.getCanonicalType(FromArgType) 2653 == Context.getCanonicalType(ToArgType)) { 2654 // Okay, the types match exactly. Nothing to do. 2655 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2656 ConvertedType, IncompatibleObjC)) { 2657 // Okay, we have an Objective-C pointer conversion. 2658 HasObjCConversion = true; 2659 } else { 2660 // Argument types are too different. Abort. 2661 return false; 2662 } 2663 } 2664 2665 if (HasObjCConversion) { 2666 // We had an Objective-C conversion. Allow this pointer 2667 // conversion, but complain about it. 2668 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2669 IncompatibleObjC = true; 2670 return true; 2671 } 2672 } 2673 2674 return false; 2675 } 2676 2677 /// Determine whether this is an Objective-C writeback conversion, 2678 /// used for parameter passing when performing automatic reference counting. 2679 /// 2680 /// \param FromType The type we're converting form. 2681 /// 2682 /// \param ToType The type we're converting to. 2683 /// 2684 /// \param ConvertedType The type that will be produced after applying 2685 /// this conversion. 2686 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2687 QualType &ConvertedType) { 2688 if (!getLangOpts().ObjCAutoRefCount || 2689 Context.hasSameUnqualifiedType(FromType, ToType)) 2690 return false; 2691 2692 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2693 QualType ToPointee; 2694 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2695 ToPointee = ToPointer->getPointeeType(); 2696 else 2697 return false; 2698 2699 Qualifiers ToQuals = ToPointee.getQualifiers(); 2700 if (!ToPointee->isObjCLifetimeType() || 2701 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2702 !ToQuals.withoutObjCLifetime().empty()) 2703 return false; 2704 2705 // Argument must be a pointer to __strong to __weak. 2706 QualType FromPointee; 2707 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2708 FromPointee = FromPointer->getPointeeType(); 2709 else 2710 return false; 2711 2712 Qualifiers FromQuals = FromPointee.getQualifiers(); 2713 if (!FromPointee->isObjCLifetimeType() || 2714 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2715 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2716 return false; 2717 2718 // Make sure that we have compatible qualifiers. 2719 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2720 if (!ToQuals.compatiblyIncludes(FromQuals)) 2721 return false; 2722 2723 // Remove qualifiers from the pointee type we're converting from; they 2724 // aren't used in the compatibility check belong, and we'll be adding back 2725 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2726 FromPointee = FromPointee.getUnqualifiedType(); 2727 2728 // The unqualified form of the pointee types must be compatible. 2729 ToPointee = ToPointee.getUnqualifiedType(); 2730 bool IncompatibleObjC; 2731 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2732 FromPointee = ToPointee; 2733 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2734 IncompatibleObjC)) 2735 return false; 2736 2737 /// Construct the type we're converting to, which is a pointer to 2738 /// __autoreleasing pointee. 2739 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2740 ConvertedType = Context.getPointerType(FromPointee); 2741 return true; 2742 } 2743 2744 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2745 QualType& ConvertedType) { 2746 QualType ToPointeeType; 2747 if (const BlockPointerType *ToBlockPtr = 2748 ToType->getAs<BlockPointerType>()) 2749 ToPointeeType = ToBlockPtr->getPointeeType(); 2750 else 2751 return false; 2752 2753 QualType FromPointeeType; 2754 if (const BlockPointerType *FromBlockPtr = 2755 FromType->getAs<BlockPointerType>()) 2756 FromPointeeType = FromBlockPtr->getPointeeType(); 2757 else 2758 return false; 2759 // We have pointer to blocks, check whether the only 2760 // differences in the argument and result types are in Objective-C 2761 // pointer conversions. If so, we permit the conversion. 2762 2763 const FunctionProtoType *FromFunctionType 2764 = FromPointeeType->getAs<FunctionProtoType>(); 2765 const FunctionProtoType *ToFunctionType 2766 = ToPointeeType->getAs<FunctionProtoType>(); 2767 2768 if (!FromFunctionType || !ToFunctionType) 2769 return false; 2770 2771 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2772 return true; 2773 2774 // Perform the quick checks that will tell us whether these 2775 // function types are obviously different. 2776 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2777 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2778 return false; 2779 2780 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2781 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2782 if (FromEInfo != ToEInfo) 2783 return false; 2784 2785 bool IncompatibleObjC = false; 2786 if (Context.hasSameType(FromFunctionType->getReturnType(), 2787 ToFunctionType->getReturnType())) { 2788 // Okay, the types match exactly. Nothing to do. 2789 } else { 2790 QualType RHS = FromFunctionType->getReturnType(); 2791 QualType LHS = ToFunctionType->getReturnType(); 2792 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2793 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2794 LHS = LHS.getUnqualifiedType(); 2795 2796 if (Context.hasSameType(RHS,LHS)) { 2797 // OK exact match. 2798 } else if (isObjCPointerConversion(RHS, LHS, 2799 ConvertedType, IncompatibleObjC)) { 2800 if (IncompatibleObjC) 2801 return false; 2802 // Okay, we have an Objective-C pointer conversion. 2803 } 2804 else 2805 return false; 2806 } 2807 2808 // Check argument types. 2809 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2810 ArgIdx != NumArgs; ++ArgIdx) { 2811 IncompatibleObjC = false; 2812 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2813 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2814 if (Context.hasSameType(FromArgType, ToArgType)) { 2815 // Okay, the types match exactly. Nothing to do. 2816 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2817 ConvertedType, IncompatibleObjC)) { 2818 if (IncompatibleObjC) 2819 return false; 2820 // Okay, we have an Objective-C pointer conversion. 2821 } else 2822 // Argument types are too different. Abort. 2823 return false; 2824 } 2825 2826 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2827 bool CanUseToFPT, CanUseFromFPT; 2828 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2829 CanUseToFPT, CanUseFromFPT, 2830 NewParamInfos)) 2831 return false; 2832 2833 ConvertedType = ToType; 2834 return true; 2835 } 2836 2837 enum { 2838 ft_default, 2839 ft_different_class, 2840 ft_parameter_arity, 2841 ft_parameter_mismatch, 2842 ft_return_type, 2843 ft_qualifer_mismatch, 2844 ft_noexcept 2845 }; 2846 2847 /// Attempts to get the FunctionProtoType from a Type. Handles 2848 /// MemberFunctionPointers properly. 2849 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2850 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2851 return FPT; 2852 2853 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2854 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2855 2856 return nullptr; 2857 } 2858 2859 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2860 /// function types. Catches different number of parameter, mismatch in 2861 /// parameter types, and different return types. 2862 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2863 QualType FromType, QualType ToType) { 2864 // If either type is not valid, include no extra info. 2865 if (FromType.isNull() || ToType.isNull()) { 2866 PDiag << ft_default; 2867 return; 2868 } 2869 2870 // Get the function type from the pointers. 2871 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2872 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2873 *ToMember = ToType->castAs<MemberPointerType>(); 2874 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2875 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2876 << QualType(FromMember->getClass(), 0); 2877 return; 2878 } 2879 FromType = FromMember->getPointeeType(); 2880 ToType = ToMember->getPointeeType(); 2881 } 2882 2883 if (FromType->isPointerType()) 2884 FromType = FromType->getPointeeType(); 2885 if (ToType->isPointerType()) 2886 ToType = ToType->getPointeeType(); 2887 2888 // Remove references. 2889 FromType = FromType.getNonReferenceType(); 2890 ToType = ToType.getNonReferenceType(); 2891 2892 // Don't print extra info for non-specialized template functions. 2893 if (FromType->isInstantiationDependentType() && 2894 !FromType->getAs<TemplateSpecializationType>()) { 2895 PDiag << ft_default; 2896 return; 2897 } 2898 2899 // No extra info for same types. 2900 if (Context.hasSameType(FromType, ToType)) { 2901 PDiag << ft_default; 2902 return; 2903 } 2904 2905 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2906 *ToFunction = tryGetFunctionProtoType(ToType); 2907 2908 // Both types need to be function types. 2909 if (!FromFunction || !ToFunction) { 2910 PDiag << ft_default; 2911 return; 2912 } 2913 2914 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2915 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2916 << FromFunction->getNumParams(); 2917 return; 2918 } 2919 2920 // Handle different parameter types. 2921 unsigned ArgPos; 2922 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2923 PDiag << ft_parameter_mismatch << ArgPos + 1 2924 << ToFunction->getParamType(ArgPos) 2925 << FromFunction->getParamType(ArgPos); 2926 return; 2927 } 2928 2929 // Handle different return type. 2930 if (!Context.hasSameType(FromFunction->getReturnType(), 2931 ToFunction->getReturnType())) { 2932 PDiag << ft_return_type << ToFunction->getReturnType() 2933 << FromFunction->getReturnType(); 2934 return; 2935 } 2936 2937 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2938 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2939 << FromFunction->getMethodQuals(); 2940 return; 2941 } 2942 2943 // Handle exception specification differences on canonical type (in C++17 2944 // onwards). 2945 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2946 ->isNothrow() != 2947 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2948 ->isNothrow()) { 2949 PDiag << ft_noexcept; 2950 return; 2951 } 2952 2953 // Unable to find a difference, so add no extra info. 2954 PDiag << ft_default; 2955 } 2956 2957 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2958 /// for equality of their argument types. Caller has already checked that 2959 /// they have same number of arguments. If the parameters are different, 2960 /// ArgPos will have the parameter index of the first different parameter. 2961 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2962 const FunctionProtoType *NewType, 2963 unsigned *ArgPos) { 2964 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2965 N = NewType->param_type_begin(), 2966 E = OldType->param_type_end(); 2967 O && (O != E); ++O, ++N) { 2968 // Ignore address spaces in pointee type. This is to disallow overloading 2969 // on __ptr32/__ptr64 address spaces. 2970 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2971 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2972 2973 if (!Context.hasSameType(Old, New)) { 2974 if (ArgPos) 2975 *ArgPos = O - OldType->param_type_begin(); 2976 return false; 2977 } 2978 } 2979 return true; 2980 } 2981 2982 /// CheckPointerConversion - Check the pointer conversion from the 2983 /// expression From to the type ToType. This routine checks for 2984 /// ambiguous or inaccessible derived-to-base pointer 2985 /// conversions for which IsPointerConversion has already returned 2986 /// true. It returns true and produces a diagnostic if there was an 2987 /// error, or returns false otherwise. 2988 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2989 CastKind &Kind, 2990 CXXCastPath& BasePath, 2991 bool IgnoreBaseAccess, 2992 bool Diagnose) { 2993 QualType FromType = From->getType(); 2994 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2995 2996 Kind = CK_BitCast; 2997 2998 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2999 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3000 Expr::NPCK_ZeroExpression) { 3001 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3002 DiagRuntimeBehavior(From->getExprLoc(), From, 3003 PDiag(diag::warn_impcast_bool_to_null_pointer) 3004 << ToType << From->getSourceRange()); 3005 else if (!isUnevaluatedContext()) 3006 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3007 << ToType << From->getSourceRange(); 3008 } 3009 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3010 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3011 QualType FromPointeeType = FromPtrType->getPointeeType(), 3012 ToPointeeType = ToPtrType->getPointeeType(); 3013 3014 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3015 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3016 // We must have a derived-to-base conversion. Check an 3017 // ambiguous or inaccessible conversion. 3018 unsigned InaccessibleID = 0; 3019 unsigned AmbiguousID = 0; 3020 if (Diagnose) { 3021 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3022 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3023 } 3024 if (CheckDerivedToBaseConversion( 3025 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3026 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3027 &BasePath, IgnoreBaseAccess)) 3028 return true; 3029 3030 // The conversion was successful. 3031 Kind = CK_DerivedToBase; 3032 } 3033 3034 if (Diagnose && !IsCStyleOrFunctionalCast && 3035 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3036 assert(getLangOpts().MSVCCompat && 3037 "this should only be possible with MSVCCompat!"); 3038 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3039 << From->getSourceRange(); 3040 } 3041 } 3042 } else if (const ObjCObjectPointerType *ToPtrType = 3043 ToType->getAs<ObjCObjectPointerType>()) { 3044 if (const ObjCObjectPointerType *FromPtrType = 3045 FromType->getAs<ObjCObjectPointerType>()) { 3046 // Objective-C++ conversions are always okay. 3047 // FIXME: We should have a different class of conversions for the 3048 // Objective-C++ implicit conversions. 3049 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3050 return false; 3051 } else if (FromType->isBlockPointerType()) { 3052 Kind = CK_BlockPointerToObjCPointerCast; 3053 } else { 3054 Kind = CK_CPointerToObjCPointerCast; 3055 } 3056 } else if (ToType->isBlockPointerType()) { 3057 if (!FromType->isBlockPointerType()) 3058 Kind = CK_AnyPointerToBlockPointerCast; 3059 } 3060 3061 // We shouldn't fall into this case unless it's valid for other 3062 // reasons. 3063 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3064 Kind = CK_NullToPointer; 3065 3066 return false; 3067 } 3068 3069 /// IsMemberPointerConversion - Determines whether the conversion of the 3070 /// expression From, which has the (possibly adjusted) type FromType, can be 3071 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3072 /// If so, returns true and places the converted type (that might differ from 3073 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3074 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3075 QualType ToType, 3076 bool InOverloadResolution, 3077 QualType &ConvertedType) { 3078 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3079 if (!ToTypePtr) 3080 return false; 3081 3082 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3083 if (From->isNullPointerConstant(Context, 3084 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3085 : Expr::NPC_ValueDependentIsNull)) { 3086 ConvertedType = ToType; 3087 return true; 3088 } 3089 3090 // Otherwise, both types have to be member pointers. 3091 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3092 if (!FromTypePtr) 3093 return false; 3094 3095 // A pointer to member of B can be converted to a pointer to member of D, 3096 // where D is derived from B (C++ 4.11p2). 3097 QualType FromClass(FromTypePtr->getClass(), 0); 3098 QualType ToClass(ToTypePtr->getClass(), 0); 3099 3100 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3101 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3102 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3103 ToClass.getTypePtr()); 3104 return true; 3105 } 3106 3107 return false; 3108 } 3109 3110 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3111 /// expression From to the type ToType. This routine checks for ambiguous or 3112 /// virtual or inaccessible base-to-derived member pointer conversions 3113 /// for which IsMemberPointerConversion has already returned true. It returns 3114 /// true and produces a diagnostic if there was an error, or returns false 3115 /// otherwise. 3116 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3117 CastKind &Kind, 3118 CXXCastPath &BasePath, 3119 bool IgnoreBaseAccess) { 3120 QualType FromType = From->getType(); 3121 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3122 if (!FromPtrType) { 3123 // This must be a null pointer to member pointer conversion 3124 assert(From->isNullPointerConstant(Context, 3125 Expr::NPC_ValueDependentIsNull) && 3126 "Expr must be null pointer constant!"); 3127 Kind = CK_NullToMemberPointer; 3128 return false; 3129 } 3130 3131 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3132 assert(ToPtrType && "No member pointer cast has a target type " 3133 "that is not a member pointer."); 3134 3135 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3136 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3137 3138 // FIXME: What about dependent types? 3139 assert(FromClass->isRecordType() && "Pointer into non-class."); 3140 assert(ToClass->isRecordType() && "Pointer into non-class."); 3141 3142 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3143 /*DetectVirtual=*/true); 3144 bool DerivationOkay = 3145 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3146 assert(DerivationOkay && 3147 "Should not have been called if derivation isn't OK."); 3148 (void)DerivationOkay; 3149 3150 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3151 getUnqualifiedType())) { 3152 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3153 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3154 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3155 return true; 3156 } 3157 3158 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3159 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3160 << FromClass << ToClass << QualType(VBase, 0) 3161 << From->getSourceRange(); 3162 return true; 3163 } 3164 3165 if (!IgnoreBaseAccess) 3166 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3167 Paths.front(), 3168 diag::err_downcast_from_inaccessible_base); 3169 3170 // Must be a base to derived member conversion. 3171 BuildBasePathArray(Paths, BasePath); 3172 Kind = CK_BaseToDerivedMemberPointer; 3173 return false; 3174 } 3175 3176 /// Determine whether the lifetime conversion between the two given 3177 /// qualifiers sets is nontrivial. 3178 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3179 Qualifiers ToQuals) { 3180 // Converting anything to const __unsafe_unretained is trivial. 3181 if (ToQuals.hasConst() && 3182 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3183 return false; 3184 3185 return true; 3186 } 3187 3188 /// Perform a single iteration of the loop for checking if a qualification 3189 /// conversion is valid. 3190 /// 3191 /// Specifically, check whether any change between the qualifiers of \p 3192 /// FromType and \p ToType is permissible, given knowledge about whether every 3193 /// outer layer is const-qualified. 3194 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3195 bool CStyle, bool IsTopLevel, 3196 bool &PreviousToQualsIncludeConst, 3197 bool &ObjCLifetimeConversion) { 3198 Qualifiers FromQuals = FromType.getQualifiers(); 3199 Qualifiers ToQuals = ToType.getQualifiers(); 3200 3201 // Ignore __unaligned qualifier if this type is void. 3202 if (ToType.getUnqualifiedType()->isVoidType()) 3203 FromQuals.removeUnaligned(); 3204 3205 // Objective-C ARC: 3206 // Check Objective-C lifetime conversions. 3207 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3208 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3209 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3210 ObjCLifetimeConversion = true; 3211 FromQuals.removeObjCLifetime(); 3212 ToQuals.removeObjCLifetime(); 3213 } else { 3214 // Qualification conversions cannot cast between different 3215 // Objective-C lifetime qualifiers. 3216 return false; 3217 } 3218 } 3219 3220 // Allow addition/removal of GC attributes but not changing GC attributes. 3221 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3222 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3223 FromQuals.removeObjCGCAttr(); 3224 ToQuals.removeObjCGCAttr(); 3225 } 3226 3227 // -- for every j > 0, if const is in cv 1,j then const is in cv 3228 // 2,j, and similarly for volatile. 3229 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3230 return false; 3231 3232 // If address spaces mismatch: 3233 // - in top level it is only valid to convert to addr space that is a 3234 // superset in all cases apart from C-style casts where we allow 3235 // conversions between overlapping address spaces. 3236 // - in non-top levels it is not a valid conversion. 3237 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3238 (!IsTopLevel || 3239 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3240 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3241 return false; 3242 3243 // -- if the cv 1,j and cv 2,j are different, then const is in 3244 // every cv for 0 < k < j. 3245 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3246 !PreviousToQualsIncludeConst) 3247 return false; 3248 3249 // Keep track of whether all prior cv-qualifiers in the "to" type 3250 // include const. 3251 PreviousToQualsIncludeConst = 3252 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3253 return true; 3254 } 3255 3256 /// IsQualificationConversion - Determines whether the conversion from 3257 /// an rvalue of type FromType to ToType is a qualification conversion 3258 /// (C++ 4.4). 3259 /// 3260 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3261 /// when the qualification conversion involves a change in the Objective-C 3262 /// object lifetime. 3263 bool 3264 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3265 bool CStyle, bool &ObjCLifetimeConversion) { 3266 FromType = Context.getCanonicalType(FromType); 3267 ToType = Context.getCanonicalType(ToType); 3268 ObjCLifetimeConversion = false; 3269 3270 // If FromType and ToType are the same type, this is not a 3271 // qualification conversion. 3272 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3273 return false; 3274 3275 // (C++ 4.4p4): 3276 // A conversion can add cv-qualifiers at levels other than the first 3277 // in multi-level pointers, subject to the following rules: [...] 3278 bool PreviousToQualsIncludeConst = true; 3279 bool UnwrappedAnyPointer = false; 3280 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3281 if (!isQualificationConversionStep( 3282 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3283 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3284 return false; 3285 UnwrappedAnyPointer = true; 3286 } 3287 3288 // We are left with FromType and ToType being the pointee types 3289 // after unwrapping the original FromType and ToType the same number 3290 // of times. If we unwrapped any pointers, and if FromType and 3291 // ToType have the same unqualified type (since we checked 3292 // qualifiers above), then this is a qualification conversion. 3293 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3294 } 3295 3296 /// - Determine whether this is a conversion from a scalar type to an 3297 /// atomic type. 3298 /// 3299 /// If successful, updates \c SCS's second and third steps in the conversion 3300 /// sequence to finish the conversion. 3301 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3302 bool InOverloadResolution, 3303 StandardConversionSequence &SCS, 3304 bool CStyle) { 3305 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3306 if (!ToAtomic) 3307 return false; 3308 3309 StandardConversionSequence InnerSCS; 3310 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3311 InOverloadResolution, InnerSCS, 3312 CStyle, /*AllowObjCWritebackConversion=*/false)) 3313 return false; 3314 3315 SCS.Second = InnerSCS.Second; 3316 SCS.setToType(1, InnerSCS.getToType(1)); 3317 SCS.Third = InnerSCS.Third; 3318 SCS.QualificationIncludesObjCLifetime 3319 = InnerSCS.QualificationIncludesObjCLifetime; 3320 SCS.setToType(2, InnerSCS.getToType(2)); 3321 return true; 3322 } 3323 3324 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3325 CXXConstructorDecl *Constructor, 3326 QualType Type) { 3327 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3328 if (CtorType->getNumParams() > 0) { 3329 QualType FirstArg = CtorType->getParamType(0); 3330 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3331 return true; 3332 } 3333 return false; 3334 } 3335 3336 static OverloadingResult 3337 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3338 CXXRecordDecl *To, 3339 UserDefinedConversionSequence &User, 3340 OverloadCandidateSet &CandidateSet, 3341 bool AllowExplicit) { 3342 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3343 for (auto *D : S.LookupConstructors(To)) { 3344 auto Info = getConstructorInfo(D); 3345 if (!Info) 3346 continue; 3347 3348 bool Usable = !Info.Constructor->isInvalidDecl() && 3349 S.isInitListConstructor(Info.Constructor); 3350 if (Usable) { 3351 bool SuppressUserConversions = false; 3352 if (Info.ConstructorTmpl) 3353 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3354 /*ExplicitArgs*/ nullptr, From, 3355 CandidateSet, SuppressUserConversions, 3356 /*PartialOverloading*/ false, 3357 AllowExplicit); 3358 else 3359 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3360 CandidateSet, SuppressUserConversions, 3361 /*PartialOverloading*/ false, AllowExplicit); 3362 } 3363 } 3364 3365 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3366 3367 OverloadCandidateSet::iterator Best; 3368 switch (auto Result = 3369 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3370 case OR_Deleted: 3371 case OR_Success: { 3372 // Record the standard conversion we used and the conversion function. 3373 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3374 QualType ThisType = Constructor->getThisType(); 3375 // Initializer lists don't have conversions as such. 3376 User.Before.setAsIdentityConversion(); 3377 User.HadMultipleCandidates = HadMultipleCandidates; 3378 User.ConversionFunction = Constructor; 3379 User.FoundConversionFunction = Best->FoundDecl; 3380 User.After.setAsIdentityConversion(); 3381 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3382 User.After.setAllToTypes(ToType); 3383 return Result; 3384 } 3385 3386 case OR_No_Viable_Function: 3387 return OR_No_Viable_Function; 3388 case OR_Ambiguous: 3389 return OR_Ambiguous; 3390 } 3391 3392 llvm_unreachable("Invalid OverloadResult!"); 3393 } 3394 3395 /// Determines whether there is a user-defined conversion sequence 3396 /// (C++ [over.ics.user]) that converts expression From to the type 3397 /// ToType. If such a conversion exists, User will contain the 3398 /// user-defined conversion sequence that performs such a conversion 3399 /// and this routine will return true. Otherwise, this routine returns 3400 /// false and User is unspecified. 3401 /// 3402 /// \param AllowExplicit true if the conversion should consider C++0x 3403 /// "explicit" conversion functions as well as non-explicit conversion 3404 /// functions (C++0x [class.conv.fct]p2). 3405 /// 3406 /// \param AllowObjCConversionOnExplicit true if the conversion should 3407 /// allow an extra Objective-C pointer conversion on uses of explicit 3408 /// constructors. Requires \c AllowExplicit to also be set. 3409 static OverloadingResult 3410 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3411 UserDefinedConversionSequence &User, 3412 OverloadCandidateSet &CandidateSet, 3413 AllowedExplicit AllowExplicit, 3414 bool AllowObjCConversionOnExplicit) { 3415 assert(AllowExplicit != AllowedExplicit::None || 3416 !AllowObjCConversionOnExplicit); 3417 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3418 3419 // Whether we will only visit constructors. 3420 bool ConstructorsOnly = false; 3421 3422 // If the type we are conversion to is a class type, enumerate its 3423 // constructors. 3424 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3425 // C++ [over.match.ctor]p1: 3426 // When objects of class type are direct-initialized (8.5), or 3427 // copy-initialized from an expression of the same or a 3428 // derived class type (8.5), overload resolution selects the 3429 // constructor. [...] For copy-initialization, the candidate 3430 // functions are all the converting constructors (12.3.1) of 3431 // that class. The argument list is the expression-list within 3432 // the parentheses of the initializer. 3433 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3434 (From->getType()->getAs<RecordType>() && 3435 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3436 ConstructorsOnly = true; 3437 3438 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3439 // We're not going to find any constructors. 3440 } else if (CXXRecordDecl *ToRecordDecl 3441 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3442 3443 Expr **Args = &From; 3444 unsigned NumArgs = 1; 3445 bool ListInitializing = false; 3446 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3447 // But first, see if there is an init-list-constructor that will work. 3448 OverloadingResult Result = IsInitializerListConstructorConversion( 3449 S, From, ToType, ToRecordDecl, User, CandidateSet, 3450 AllowExplicit == AllowedExplicit::All); 3451 if (Result != OR_No_Viable_Function) 3452 return Result; 3453 // Never mind. 3454 CandidateSet.clear( 3455 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3456 3457 // If we're list-initializing, we pass the individual elements as 3458 // arguments, not the entire list. 3459 Args = InitList->getInits(); 3460 NumArgs = InitList->getNumInits(); 3461 ListInitializing = true; 3462 } 3463 3464 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3465 auto Info = getConstructorInfo(D); 3466 if (!Info) 3467 continue; 3468 3469 bool Usable = !Info.Constructor->isInvalidDecl(); 3470 if (!ListInitializing) 3471 Usable = Usable && Info.Constructor->isConvertingConstructor( 3472 /*AllowExplicit*/ true); 3473 if (Usable) { 3474 bool SuppressUserConversions = !ConstructorsOnly; 3475 // C++20 [over.best.ics.general]/4.5: 3476 // if the target is the first parameter of a constructor [of class 3477 // X] and the constructor [...] is a candidate by [...] the second 3478 // phase of [over.match.list] when the initializer list has exactly 3479 // one element that is itself an initializer list, [...] and the 3480 // conversion is to X or reference to cv X, user-defined conversion 3481 // sequences are not cnosidered. 3482 if (SuppressUserConversions && ListInitializing) { 3483 SuppressUserConversions = 3484 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3485 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3486 ToType); 3487 } 3488 if (Info.ConstructorTmpl) 3489 S.AddTemplateOverloadCandidate( 3490 Info.ConstructorTmpl, Info.FoundDecl, 3491 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3492 CandidateSet, SuppressUserConversions, 3493 /*PartialOverloading*/ false, 3494 AllowExplicit == AllowedExplicit::All); 3495 else 3496 // Allow one user-defined conversion when user specifies a 3497 // From->ToType conversion via an static cast (c-style, etc). 3498 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3499 llvm::makeArrayRef(Args, NumArgs), 3500 CandidateSet, SuppressUserConversions, 3501 /*PartialOverloading*/ false, 3502 AllowExplicit == AllowedExplicit::All); 3503 } 3504 } 3505 } 3506 } 3507 3508 // Enumerate conversion functions, if we're allowed to. 3509 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3510 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3511 // No conversion functions from incomplete types. 3512 } else if (const RecordType *FromRecordType = 3513 From->getType()->getAs<RecordType>()) { 3514 if (CXXRecordDecl *FromRecordDecl 3515 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3516 // Add all of the conversion functions as candidates. 3517 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3518 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3519 DeclAccessPair FoundDecl = I.getPair(); 3520 NamedDecl *D = FoundDecl.getDecl(); 3521 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3522 if (isa<UsingShadowDecl>(D)) 3523 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3524 3525 CXXConversionDecl *Conv; 3526 FunctionTemplateDecl *ConvTemplate; 3527 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3528 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3529 else 3530 Conv = cast<CXXConversionDecl>(D); 3531 3532 if (ConvTemplate) 3533 S.AddTemplateConversionCandidate( 3534 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3535 CandidateSet, AllowObjCConversionOnExplicit, 3536 AllowExplicit != AllowedExplicit::None); 3537 else 3538 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3539 CandidateSet, AllowObjCConversionOnExplicit, 3540 AllowExplicit != AllowedExplicit::None); 3541 } 3542 } 3543 } 3544 3545 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3546 3547 OverloadCandidateSet::iterator Best; 3548 switch (auto Result = 3549 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3550 case OR_Success: 3551 case OR_Deleted: 3552 // Record the standard conversion we used and the conversion function. 3553 if (CXXConstructorDecl *Constructor 3554 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3555 // C++ [over.ics.user]p1: 3556 // If the user-defined conversion is specified by a 3557 // constructor (12.3.1), the initial standard conversion 3558 // sequence converts the source type to the type required by 3559 // the argument of the constructor. 3560 // 3561 QualType ThisType = Constructor->getThisType(); 3562 if (isa<InitListExpr>(From)) { 3563 // Initializer lists don't have conversions as such. 3564 User.Before.setAsIdentityConversion(); 3565 } else { 3566 if (Best->Conversions[0].isEllipsis()) 3567 User.EllipsisConversion = true; 3568 else { 3569 User.Before = Best->Conversions[0].Standard; 3570 User.EllipsisConversion = false; 3571 } 3572 } 3573 User.HadMultipleCandidates = HadMultipleCandidates; 3574 User.ConversionFunction = Constructor; 3575 User.FoundConversionFunction = Best->FoundDecl; 3576 User.After.setAsIdentityConversion(); 3577 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3578 User.After.setAllToTypes(ToType); 3579 return Result; 3580 } 3581 if (CXXConversionDecl *Conversion 3582 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3583 // C++ [over.ics.user]p1: 3584 // 3585 // [...] If the user-defined conversion is specified by a 3586 // conversion function (12.3.2), the initial standard 3587 // conversion sequence converts the source type to the 3588 // implicit object parameter of the conversion function. 3589 User.Before = Best->Conversions[0].Standard; 3590 User.HadMultipleCandidates = HadMultipleCandidates; 3591 User.ConversionFunction = Conversion; 3592 User.FoundConversionFunction = Best->FoundDecl; 3593 User.EllipsisConversion = false; 3594 3595 // C++ [over.ics.user]p2: 3596 // The second standard conversion sequence converts the 3597 // result of the user-defined conversion to the target type 3598 // for the sequence. Since an implicit conversion sequence 3599 // is an initialization, the special rules for 3600 // initialization by user-defined conversion apply when 3601 // selecting the best user-defined conversion for a 3602 // user-defined conversion sequence (see 13.3.3 and 3603 // 13.3.3.1). 3604 User.After = Best->FinalConversion; 3605 return Result; 3606 } 3607 llvm_unreachable("Not a constructor or conversion function?"); 3608 3609 case OR_No_Viable_Function: 3610 return OR_No_Viable_Function; 3611 3612 case OR_Ambiguous: 3613 return OR_Ambiguous; 3614 } 3615 3616 llvm_unreachable("Invalid OverloadResult!"); 3617 } 3618 3619 bool 3620 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3621 ImplicitConversionSequence ICS; 3622 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3623 OverloadCandidateSet::CSK_Normal); 3624 OverloadingResult OvResult = 3625 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3626 CandidateSet, AllowedExplicit::None, false); 3627 3628 if (!(OvResult == OR_Ambiguous || 3629 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3630 return false; 3631 3632 auto Cands = CandidateSet.CompleteCandidates( 3633 *this, 3634 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3635 From); 3636 if (OvResult == OR_Ambiguous) 3637 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3638 << From->getType() << ToType << From->getSourceRange(); 3639 else { // OR_No_Viable_Function && !CandidateSet.empty() 3640 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3641 diag::err_typecheck_nonviable_condition_incomplete, 3642 From->getType(), From->getSourceRange())) 3643 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3644 << false << From->getType() << From->getSourceRange() << ToType; 3645 } 3646 3647 CandidateSet.NoteCandidates( 3648 *this, From, Cands); 3649 return true; 3650 } 3651 3652 // Helper for compareConversionFunctions that gets the FunctionType that the 3653 // conversion-operator return value 'points' to, or nullptr. 3654 static const FunctionType * 3655 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3656 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3657 const PointerType *RetPtrTy = 3658 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3659 3660 if (!RetPtrTy) 3661 return nullptr; 3662 3663 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3664 } 3665 3666 /// Compare the user-defined conversion functions or constructors 3667 /// of two user-defined conversion sequences to determine whether any ordering 3668 /// is possible. 3669 static ImplicitConversionSequence::CompareKind 3670 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3671 FunctionDecl *Function2) { 3672 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3673 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3674 if (!Conv1 || !Conv2) 3675 return ImplicitConversionSequence::Indistinguishable; 3676 3677 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3678 return ImplicitConversionSequence::Indistinguishable; 3679 3680 // Objective-C++: 3681 // If both conversion functions are implicitly-declared conversions from 3682 // a lambda closure type to a function pointer and a block pointer, 3683 // respectively, always prefer the conversion to a function pointer, 3684 // because the function pointer is more lightweight and is more likely 3685 // to keep code working. 3686 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3687 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3688 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3689 if (Block1 != Block2) 3690 return Block1 ? ImplicitConversionSequence::Worse 3691 : ImplicitConversionSequence::Better; 3692 } 3693 3694 // In order to support multiple calling conventions for the lambda conversion 3695 // operator (such as when the free and member function calling convention is 3696 // different), prefer the 'free' mechanism, followed by the calling-convention 3697 // of operator(). The latter is in place to support the MSVC-like solution of 3698 // defining ALL of the possible conversions in regards to calling-convention. 3699 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3700 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3701 3702 if (Conv1FuncRet && Conv2FuncRet && 3703 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3704 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3705 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3706 3707 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3708 const FunctionProtoType *CallOpProto = 3709 CallOp->getType()->getAs<FunctionProtoType>(); 3710 3711 CallingConv CallOpCC = 3712 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3713 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3714 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3715 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3716 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3717 3718 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3719 for (CallingConv CC : PrefOrder) { 3720 if (Conv1CC == CC) 3721 return ImplicitConversionSequence::Better; 3722 if (Conv2CC == CC) 3723 return ImplicitConversionSequence::Worse; 3724 } 3725 } 3726 3727 return ImplicitConversionSequence::Indistinguishable; 3728 } 3729 3730 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3731 const ImplicitConversionSequence &ICS) { 3732 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3733 (ICS.isUserDefined() && 3734 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3735 } 3736 3737 /// CompareImplicitConversionSequences - Compare two implicit 3738 /// conversion sequences to determine whether one is better than the 3739 /// other or if they are indistinguishable (C++ 13.3.3.2). 3740 static ImplicitConversionSequence::CompareKind 3741 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3742 const ImplicitConversionSequence& ICS1, 3743 const ImplicitConversionSequence& ICS2) 3744 { 3745 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3746 // conversion sequences (as defined in 13.3.3.1) 3747 // -- a standard conversion sequence (13.3.3.1.1) is a better 3748 // conversion sequence than a user-defined conversion sequence or 3749 // an ellipsis conversion sequence, and 3750 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3751 // conversion sequence than an ellipsis conversion sequence 3752 // (13.3.3.1.3). 3753 // 3754 // C++0x [over.best.ics]p10: 3755 // For the purpose of ranking implicit conversion sequences as 3756 // described in 13.3.3.2, the ambiguous conversion sequence is 3757 // treated as a user-defined sequence that is indistinguishable 3758 // from any other user-defined conversion sequence. 3759 3760 // String literal to 'char *' conversion has been deprecated in C++03. It has 3761 // been removed from C++11. We still accept this conversion, if it happens at 3762 // the best viable function. Otherwise, this conversion is considered worse 3763 // than ellipsis conversion. Consider this as an extension; this is not in the 3764 // standard. For example: 3765 // 3766 // int &f(...); // #1 3767 // void f(char*); // #2 3768 // void g() { int &r = f("foo"); } 3769 // 3770 // In C++03, we pick #2 as the best viable function. 3771 // In C++11, we pick #1 as the best viable function, because ellipsis 3772 // conversion is better than string-literal to char* conversion (since there 3773 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3774 // convert arguments, #2 would be the best viable function in C++11. 3775 // If the best viable function has this conversion, a warning will be issued 3776 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3777 3778 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3779 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3780 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3781 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3782 ? ImplicitConversionSequence::Worse 3783 : ImplicitConversionSequence::Better; 3784 3785 if (ICS1.getKindRank() < ICS2.getKindRank()) 3786 return ImplicitConversionSequence::Better; 3787 if (ICS2.getKindRank() < ICS1.getKindRank()) 3788 return ImplicitConversionSequence::Worse; 3789 3790 // The following checks require both conversion sequences to be of 3791 // the same kind. 3792 if (ICS1.getKind() != ICS2.getKind()) 3793 return ImplicitConversionSequence::Indistinguishable; 3794 3795 ImplicitConversionSequence::CompareKind Result = 3796 ImplicitConversionSequence::Indistinguishable; 3797 3798 // Two implicit conversion sequences of the same form are 3799 // indistinguishable conversion sequences unless one of the 3800 // following rules apply: (C++ 13.3.3.2p3): 3801 3802 // List-initialization sequence L1 is a better conversion sequence than 3803 // list-initialization sequence L2 if: 3804 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3805 // if not that, 3806 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3807 // and N1 is smaller than N2., 3808 // even if one of the other rules in this paragraph would otherwise apply. 3809 if (!ICS1.isBad()) { 3810 if (ICS1.isStdInitializerListElement() && 3811 !ICS2.isStdInitializerListElement()) 3812 return ImplicitConversionSequence::Better; 3813 if (!ICS1.isStdInitializerListElement() && 3814 ICS2.isStdInitializerListElement()) 3815 return ImplicitConversionSequence::Worse; 3816 } 3817 3818 if (ICS1.isStandard()) 3819 // Standard conversion sequence S1 is a better conversion sequence than 3820 // standard conversion sequence S2 if [...] 3821 Result = CompareStandardConversionSequences(S, Loc, 3822 ICS1.Standard, ICS2.Standard); 3823 else if (ICS1.isUserDefined()) { 3824 // User-defined conversion sequence U1 is a better conversion 3825 // sequence than another user-defined conversion sequence U2 if 3826 // they contain the same user-defined conversion function or 3827 // constructor and if the second standard conversion sequence of 3828 // U1 is better than the second standard conversion sequence of 3829 // U2 (C++ 13.3.3.2p3). 3830 if (ICS1.UserDefined.ConversionFunction == 3831 ICS2.UserDefined.ConversionFunction) 3832 Result = CompareStandardConversionSequences(S, Loc, 3833 ICS1.UserDefined.After, 3834 ICS2.UserDefined.After); 3835 else 3836 Result = compareConversionFunctions(S, 3837 ICS1.UserDefined.ConversionFunction, 3838 ICS2.UserDefined.ConversionFunction); 3839 } 3840 3841 return Result; 3842 } 3843 3844 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3845 // determine if one is a proper subset of the other. 3846 static ImplicitConversionSequence::CompareKind 3847 compareStandardConversionSubsets(ASTContext &Context, 3848 const StandardConversionSequence& SCS1, 3849 const StandardConversionSequence& SCS2) { 3850 ImplicitConversionSequence::CompareKind Result 3851 = ImplicitConversionSequence::Indistinguishable; 3852 3853 // the identity conversion sequence is considered to be a subsequence of 3854 // any non-identity conversion sequence 3855 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3856 return ImplicitConversionSequence::Better; 3857 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3858 return ImplicitConversionSequence::Worse; 3859 3860 if (SCS1.Second != SCS2.Second) { 3861 if (SCS1.Second == ICK_Identity) 3862 Result = ImplicitConversionSequence::Better; 3863 else if (SCS2.Second == ICK_Identity) 3864 Result = ImplicitConversionSequence::Worse; 3865 else 3866 return ImplicitConversionSequence::Indistinguishable; 3867 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3868 return ImplicitConversionSequence::Indistinguishable; 3869 3870 if (SCS1.Third == SCS2.Third) { 3871 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3872 : ImplicitConversionSequence::Indistinguishable; 3873 } 3874 3875 if (SCS1.Third == ICK_Identity) 3876 return Result == ImplicitConversionSequence::Worse 3877 ? ImplicitConversionSequence::Indistinguishable 3878 : ImplicitConversionSequence::Better; 3879 3880 if (SCS2.Third == ICK_Identity) 3881 return Result == ImplicitConversionSequence::Better 3882 ? ImplicitConversionSequence::Indistinguishable 3883 : ImplicitConversionSequence::Worse; 3884 3885 return ImplicitConversionSequence::Indistinguishable; 3886 } 3887 3888 /// Determine whether one of the given reference bindings is better 3889 /// than the other based on what kind of bindings they are. 3890 static bool 3891 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3892 const StandardConversionSequence &SCS2) { 3893 // C++0x [over.ics.rank]p3b4: 3894 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3895 // implicit object parameter of a non-static member function declared 3896 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3897 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3898 // lvalue reference to a function lvalue and S2 binds an rvalue 3899 // reference*. 3900 // 3901 // FIXME: Rvalue references. We're going rogue with the above edits, 3902 // because the semantics in the current C++0x working paper (N3225 at the 3903 // time of this writing) break the standard definition of std::forward 3904 // and std::reference_wrapper when dealing with references to functions. 3905 // Proposed wording changes submitted to CWG for consideration. 3906 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3907 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3908 return false; 3909 3910 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3911 SCS2.IsLvalueReference) || 3912 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3913 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3914 } 3915 3916 enum class FixedEnumPromotion { 3917 None, 3918 ToUnderlyingType, 3919 ToPromotedUnderlyingType 3920 }; 3921 3922 /// Returns kind of fixed enum promotion the \a SCS uses. 3923 static FixedEnumPromotion 3924 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3925 3926 if (SCS.Second != ICK_Integral_Promotion) 3927 return FixedEnumPromotion::None; 3928 3929 QualType FromType = SCS.getFromType(); 3930 if (!FromType->isEnumeralType()) 3931 return FixedEnumPromotion::None; 3932 3933 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 3934 if (!Enum->isFixed()) 3935 return FixedEnumPromotion::None; 3936 3937 QualType UnderlyingType = Enum->getIntegerType(); 3938 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3939 return FixedEnumPromotion::ToUnderlyingType; 3940 3941 return FixedEnumPromotion::ToPromotedUnderlyingType; 3942 } 3943 3944 /// CompareStandardConversionSequences - Compare two standard 3945 /// conversion sequences to determine whether one is better than the 3946 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3947 static ImplicitConversionSequence::CompareKind 3948 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3949 const StandardConversionSequence& SCS1, 3950 const StandardConversionSequence& SCS2) 3951 { 3952 // Standard conversion sequence S1 is a better conversion sequence 3953 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3954 3955 // -- S1 is a proper subsequence of S2 (comparing the conversion 3956 // sequences in the canonical form defined by 13.3.3.1.1, 3957 // excluding any Lvalue Transformation; the identity conversion 3958 // sequence is considered to be a subsequence of any 3959 // non-identity conversion sequence) or, if not that, 3960 if (ImplicitConversionSequence::CompareKind CK 3961 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3962 return CK; 3963 3964 // -- the rank of S1 is better than the rank of S2 (by the rules 3965 // defined below), or, if not that, 3966 ImplicitConversionRank Rank1 = SCS1.getRank(); 3967 ImplicitConversionRank Rank2 = SCS2.getRank(); 3968 if (Rank1 < Rank2) 3969 return ImplicitConversionSequence::Better; 3970 else if (Rank2 < Rank1) 3971 return ImplicitConversionSequence::Worse; 3972 3973 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3974 // are indistinguishable unless one of the following rules 3975 // applies: 3976 3977 // A conversion that is not a conversion of a pointer, or 3978 // pointer to member, to bool is better than another conversion 3979 // that is such a conversion. 3980 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3981 return SCS2.isPointerConversionToBool() 3982 ? ImplicitConversionSequence::Better 3983 : ImplicitConversionSequence::Worse; 3984 3985 // C++14 [over.ics.rank]p4b2: 3986 // This is retroactively applied to C++11 by CWG 1601. 3987 // 3988 // A conversion that promotes an enumeration whose underlying type is fixed 3989 // to its underlying type is better than one that promotes to the promoted 3990 // underlying type, if the two are different. 3991 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3992 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3993 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3994 FEP1 != FEP2) 3995 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3996 ? ImplicitConversionSequence::Better 3997 : ImplicitConversionSequence::Worse; 3998 3999 // C++ [over.ics.rank]p4b2: 4000 // 4001 // If class B is derived directly or indirectly from class A, 4002 // conversion of B* to A* is better than conversion of B* to 4003 // void*, and conversion of A* to void* is better than conversion 4004 // of B* to void*. 4005 bool SCS1ConvertsToVoid 4006 = SCS1.isPointerConversionToVoidPointer(S.Context); 4007 bool SCS2ConvertsToVoid 4008 = SCS2.isPointerConversionToVoidPointer(S.Context); 4009 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4010 // Exactly one of the conversion sequences is a conversion to 4011 // a void pointer; it's the worse conversion. 4012 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4013 : ImplicitConversionSequence::Worse; 4014 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4015 // Neither conversion sequence converts to a void pointer; compare 4016 // their derived-to-base conversions. 4017 if (ImplicitConversionSequence::CompareKind DerivedCK 4018 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4019 return DerivedCK; 4020 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4021 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4022 // Both conversion sequences are conversions to void 4023 // pointers. Compare the source types to determine if there's an 4024 // inheritance relationship in their sources. 4025 QualType FromType1 = SCS1.getFromType(); 4026 QualType FromType2 = SCS2.getFromType(); 4027 4028 // Adjust the types we're converting from via the array-to-pointer 4029 // conversion, if we need to. 4030 if (SCS1.First == ICK_Array_To_Pointer) 4031 FromType1 = S.Context.getArrayDecayedType(FromType1); 4032 if (SCS2.First == ICK_Array_To_Pointer) 4033 FromType2 = S.Context.getArrayDecayedType(FromType2); 4034 4035 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4036 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4037 4038 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4039 return ImplicitConversionSequence::Better; 4040 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4041 return ImplicitConversionSequence::Worse; 4042 4043 // Objective-C++: If one interface is more specific than the 4044 // other, it is the better one. 4045 const ObjCObjectPointerType* FromObjCPtr1 4046 = FromType1->getAs<ObjCObjectPointerType>(); 4047 const ObjCObjectPointerType* FromObjCPtr2 4048 = FromType2->getAs<ObjCObjectPointerType>(); 4049 if (FromObjCPtr1 && FromObjCPtr2) { 4050 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4051 FromObjCPtr2); 4052 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4053 FromObjCPtr1); 4054 if (AssignLeft != AssignRight) { 4055 return AssignLeft? ImplicitConversionSequence::Better 4056 : ImplicitConversionSequence::Worse; 4057 } 4058 } 4059 } 4060 4061 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4062 // Check for a better reference binding based on the kind of bindings. 4063 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4064 return ImplicitConversionSequence::Better; 4065 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4066 return ImplicitConversionSequence::Worse; 4067 } 4068 4069 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4070 // bullet 3). 4071 if (ImplicitConversionSequence::CompareKind QualCK 4072 = CompareQualificationConversions(S, SCS1, SCS2)) 4073 return QualCK; 4074 4075 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4076 // C++ [over.ics.rank]p3b4: 4077 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4078 // which the references refer are the same type except for 4079 // top-level cv-qualifiers, and the type to which the reference 4080 // initialized by S2 refers is more cv-qualified than the type 4081 // to which the reference initialized by S1 refers. 4082 QualType T1 = SCS1.getToType(2); 4083 QualType T2 = SCS2.getToType(2); 4084 T1 = S.Context.getCanonicalType(T1); 4085 T2 = S.Context.getCanonicalType(T2); 4086 Qualifiers T1Quals, T2Quals; 4087 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4088 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4089 if (UnqualT1 == UnqualT2) { 4090 // Objective-C++ ARC: If the references refer to objects with different 4091 // lifetimes, prefer bindings that don't change lifetime. 4092 if (SCS1.ObjCLifetimeConversionBinding != 4093 SCS2.ObjCLifetimeConversionBinding) { 4094 return SCS1.ObjCLifetimeConversionBinding 4095 ? ImplicitConversionSequence::Worse 4096 : ImplicitConversionSequence::Better; 4097 } 4098 4099 // If the type is an array type, promote the element qualifiers to the 4100 // type for comparison. 4101 if (isa<ArrayType>(T1) && T1Quals) 4102 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4103 if (isa<ArrayType>(T2) && T2Quals) 4104 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4105 if (T2.isMoreQualifiedThan(T1)) 4106 return ImplicitConversionSequence::Better; 4107 if (T1.isMoreQualifiedThan(T2)) 4108 return ImplicitConversionSequence::Worse; 4109 } 4110 } 4111 4112 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4113 // floating-to-integral conversion if the integral conversion 4114 // is between types of the same size. 4115 // For example: 4116 // void f(float); 4117 // void f(int); 4118 // int main { 4119 // long a; 4120 // f(a); 4121 // } 4122 // Here, MSVC will call f(int) instead of generating a compile error 4123 // as clang will do in standard mode. 4124 if (S.getLangOpts().MSVCCompat && 4125 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4126 SCS1.Second == ICK_Integral_Conversion && 4127 SCS2.Second == ICK_Floating_Integral && 4128 S.Context.getTypeSize(SCS1.getFromType()) == 4129 S.Context.getTypeSize(SCS1.getToType(2))) 4130 return ImplicitConversionSequence::Better; 4131 4132 // Prefer a compatible vector conversion over a lax vector conversion 4133 // For example: 4134 // 4135 // typedef float __v4sf __attribute__((__vector_size__(16))); 4136 // void f(vector float); 4137 // void f(vector signed int); 4138 // int main() { 4139 // __v4sf a; 4140 // f(a); 4141 // } 4142 // Here, we'd like to choose f(vector float) and not 4143 // report an ambiguous call error 4144 if (SCS1.Second == ICK_Vector_Conversion && 4145 SCS2.Second == ICK_Vector_Conversion) { 4146 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4147 SCS1.getFromType(), SCS1.getToType(2)); 4148 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4149 SCS2.getFromType(), SCS2.getToType(2)); 4150 4151 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4152 return SCS1IsCompatibleVectorConversion 4153 ? ImplicitConversionSequence::Better 4154 : ImplicitConversionSequence::Worse; 4155 } 4156 4157 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4158 SCS2.Second == ICK_SVE_Vector_Conversion) { 4159 bool SCS1IsCompatibleSVEVectorConversion = 4160 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4161 bool SCS2IsCompatibleSVEVectorConversion = 4162 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4163 4164 if (SCS1IsCompatibleSVEVectorConversion != 4165 SCS2IsCompatibleSVEVectorConversion) 4166 return SCS1IsCompatibleSVEVectorConversion 4167 ? ImplicitConversionSequence::Better 4168 : ImplicitConversionSequence::Worse; 4169 } 4170 4171 return ImplicitConversionSequence::Indistinguishable; 4172 } 4173 4174 /// CompareQualificationConversions - Compares two standard conversion 4175 /// sequences to determine whether they can be ranked based on their 4176 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4177 static ImplicitConversionSequence::CompareKind 4178 CompareQualificationConversions(Sema &S, 4179 const StandardConversionSequence& SCS1, 4180 const StandardConversionSequence& SCS2) { 4181 // C++ 13.3.3.2p3: 4182 // -- S1 and S2 differ only in their qualification conversion and 4183 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4184 // cv-qualification signature of type T1 is a proper subset of 4185 // the cv-qualification signature of type T2, and S1 is not the 4186 // deprecated string literal array-to-pointer conversion (4.2). 4187 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4188 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4189 return ImplicitConversionSequence::Indistinguishable; 4190 4191 // FIXME: the example in the standard doesn't use a qualification 4192 // conversion (!) 4193 QualType T1 = SCS1.getToType(2); 4194 QualType T2 = SCS2.getToType(2); 4195 T1 = S.Context.getCanonicalType(T1); 4196 T2 = S.Context.getCanonicalType(T2); 4197 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4198 Qualifiers T1Quals, T2Quals; 4199 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4200 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4201 4202 // If the types are the same, we won't learn anything by unwrapping 4203 // them. 4204 if (UnqualT1 == UnqualT2) 4205 return ImplicitConversionSequence::Indistinguishable; 4206 4207 ImplicitConversionSequence::CompareKind Result 4208 = ImplicitConversionSequence::Indistinguishable; 4209 4210 // Objective-C++ ARC: 4211 // Prefer qualification conversions not involving a change in lifetime 4212 // to qualification conversions that do not change lifetime. 4213 if (SCS1.QualificationIncludesObjCLifetime != 4214 SCS2.QualificationIncludesObjCLifetime) { 4215 Result = SCS1.QualificationIncludesObjCLifetime 4216 ? ImplicitConversionSequence::Worse 4217 : ImplicitConversionSequence::Better; 4218 } 4219 4220 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4221 // Within each iteration of the loop, we check the qualifiers to 4222 // determine if this still looks like a qualification 4223 // conversion. Then, if all is well, we unwrap one more level of 4224 // pointers or pointers-to-members and do it all again 4225 // until there are no more pointers or pointers-to-members left 4226 // to unwrap. This essentially mimics what 4227 // IsQualificationConversion does, but here we're checking for a 4228 // strict subset of qualifiers. 4229 if (T1.getQualifiers().withoutObjCLifetime() == 4230 T2.getQualifiers().withoutObjCLifetime()) 4231 // The qualifiers are the same, so this doesn't tell us anything 4232 // about how the sequences rank. 4233 // ObjC ownership quals are omitted above as they interfere with 4234 // the ARC overload rule. 4235 ; 4236 else if (T2.isMoreQualifiedThan(T1)) { 4237 // T1 has fewer qualifiers, so it could be the better sequence. 4238 if (Result == ImplicitConversionSequence::Worse) 4239 // Neither has qualifiers that are a subset of the other's 4240 // qualifiers. 4241 return ImplicitConversionSequence::Indistinguishable; 4242 4243 Result = ImplicitConversionSequence::Better; 4244 } else if (T1.isMoreQualifiedThan(T2)) { 4245 // T2 has fewer qualifiers, so it could be the better sequence. 4246 if (Result == ImplicitConversionSequence::Better) 4247 // Neither has qualifiers that are a subset of the other's 4248 // qualifiers. 4249 return ImplicitConversionSequence::Indistinguishable; 4250 4251 Result = ImplicitConversionSequence::Worse; 4252 } else { 4253 // Qualifiers are disjoint. 4254 return ImplicitConversionSequence::Indistinguishable; 4255 } 4256 4257 // If the types after this point are equivalent, we're done. 4258 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4259 break; 4260 } 4261 4262 // Check that the winning standard conversion sequence isn't using 4263 // the deprecated string literal array to pointer conversion. 4264 switch (Result) { 4265 case ImplicitConversionSequence::Better: 4266 if (SCS1.DeprecatedStringLiteralToCharPtr) 4267 Result = ImplicitConversionSequence::Indistinguishable; 4268 break; 4269 4270 case ImplicitConversionSequence::Indistinguishable: 4271 break; 4272 4273 case ImplicitConversionSequence::Worse: 4274 if (SCS2.DeprecatedStringLiteralToCharPtr) 4275 Result = ImplicitConversionSequence::Indistinguishable; 4276 break; 4277 } 4278 4279 return Result; 4280 } 4281 4282 /// CompareDerivedToBaseConversions - Compares two standard conversion 4283 /// sequences to determine whether they can be ranked based on their 4284 /// various kinds of derived-to-base conversions (C++ 4285 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4286 /// conversions between Objective-C interface types. 4287 static ImplicitConversionSequence::CompareKind 4288 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4289 const StandardConversionSequence& SCS1, 4290 const StandardConversionSequence& SCS2) { 4291 QualType FromType1 = SCS1.getFromType(); 4292 QualType ToType1 = SCS1.getToType(1); 4293 QualType FromType2 = SCS2.getFromType(); 4294 QualType ToType2 = SCS2.getToType(1); 4295 4296 // Adjust the types we're converting from via the array-to-pointer 4297 // conversion, if we need to. 4298 if (SCS1.First == ICK_Array_To_Pointer) 4299 FromType1 = S.Context.getArrayDecayedType(FromType1); 4300 if (SCS2.First == ICK_Array_To_Pointer) 4301 FromType2 = S.Context.getArrayDecayedType(FromType2); 4302 4303 // Canonicalize all of the types. 4304 FromType1 = S.Context.getCanonicalType(FromType1); 4305 ToType1 = S.Context.getCanonicalType(ToType1); 4306 FromType2 = S.Context.getCanonicalType(FromType2); 4307 ToType2 = S.Context.getCanonicalType(ToType2); 4308 4309 // C++ [over.ics.rank]p4b3: 4310 // 4311 // If class B is derived directly or indirectly from class A and 4312 // class C is derived directly or indirectly from B, 4313 // 4314 // Compare based on pointer conversions. 4315 if (SCS1.Second == ICK_Pointer_Conversion && 4316 SCS2.Second == ICK_Pointer_Conversion && 4317 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4318 FromType1->isPointerType() && FromType2->isPointerType() && 4319 ToType1->isPointerType() && ToType2->isPointerType()) { 4320 QualType FromPointee1 = 4321 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4322 QualType ToPointee1 = 4323 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4324 QualType FromPointee2 = 4325 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4326 QualType ToPointee2 = 4327 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4328 4329 // -- conversion of C* to B* is better than conversion of C* to A*, 4330 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4331 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4332 return ImplicitConversionSequence::Better; 4333 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4334 return ImplicitConversionSequence::Worse; 4335 } 4336 4337 // -- conversion of B* to A* is better than conversion of C* to A*, 4338 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4339 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4340 return ImplicitConversionSequence::Better; 4341 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4342 return ImplicitConversionSequence::Worse; 4343 } 4344 } else if (SCS1.Second == ICK_Pointer_Conversion && 4345 SCS2.Second == ICK_Pointer_Conversion) { 4346 const ObjCObjectPointerType *FromPtr1 4347 = FromType1->getAs<ObjCObjectPointerType>(); 4348 const ObjCObjectPointerType *FromPtr2 4349 = FromType2->getAs<ObjCObjectPointerType>(); 4350 const ObjCObjectPointerType *ToPtr1 4351 = ToType1->getAs<ObjCObjectPointerType>(); 4352 const ObjCObjectPointerType *ToPtr2 4353 = ToType2->getAs<ObjCObjectPointerType>(); 4354 4355 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4356 // Apply the same conversion ranking rules for Objective-C pointer types 4357 // that we do for C++ pointers to class types. However, we employ the 4358 // Objective-C pseudo-subtyping relationship used for assignment of 4359 // Objective-C pointer types. 4360 bool FromAssignLeft 4361 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4362 bool FromAssignRight 4363 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4364 bool ToAssignLeft 4365 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4366 bool ToAssignRight 4367 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4368 4369 // A conversion to an a non-id object pointer type or qualified 'id' 4370 // type is better than a conversion to 'id'. 4371 if (ToPtr1->isObjCIdType() && 4372 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4373 return ImplicitConversionSequence::Worse; 4374 if (ToPtr2->isObjCIdType() && 4375 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4376 return ImplicitConversionSequence::Better; 4377 4378 // A conversion to a non-id object pointer type is better than a 4379 // conversion to a qualified 'id' type 4380 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4381 return ImplicitConversionSequence::Worse; 4382 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4383 return ImplicitConversionSequence::Better; 4384 4385 // A conversion to an a non-Class object pointer type or qualified 'Class' 4386 // type is better than a conversion to 'Class'. 4387 if (ToPtr1->isObjCClassType() && 4388 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4389 return ImplicitConversionSequence::Worse; 4390 if (ToPtr2->isObjCClassType() && 4391 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4392 return ImplicitConversionSequence::Better; 4393 4394 // A conversion to a non-Class object pointer type is better than a 4395 // conversion to a qualified 'Class' type. 4396 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4397 return ImplicitConversionSequence::Worse; 4398 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4399 return ImplicitConversionSequence::Better; 4400 4401 // -- "conversion of C* to B* is better than conversion of C* to A*," 4402 if (S.Context.hasSameType(FromType1, FromType2) && 4403 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4404 (ToAssignLeft != ToAssignRight)) { 4405 if (FromPtr1->isSpecialized()) { 4406 // "conversion of B<A> * to B * is better than conversion of B * to 4407 // C *. 4408 bool IsFirstSame = 4409 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4410 bool IsSecondSame = 4411 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4412 if (IsFirstSame) { 4413 if (!IsSecondSame) 4414 return ImplicitConversionSequence::Better; 4415 } else if (IsSecondSame) 4416 return ImplicitConversionSequence::Worse; 4417 } 4418 return ToAssignLeft? ImplicitConversionSequence::Worse 4419 : ImplicitConversionSequence::Better; 4420 } 4421 4422 // -- "conversion of B* to A* is better than conversion of C* to A*," 4423 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4424 (FromAssignLeft != FromAssignRight)) 4425 return FromAssignLeft? ImplicitConversionSequence::Better 4426 : ImplicitConversionSequence::Worse; 4427 } 4428 } 4429 4430 // Ranking of member-pointer types. 4431 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4432 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4433 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4434 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4435 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4436 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4437 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4438 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4439 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4440 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4441 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4442 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4443 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4444 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4445 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4446 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4447 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4448 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4449 return ImplicitConversionSequence::Worse; 4450 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4451 return ImplicitConversionSequence::Better; 4452 } 4453 // conversion of B::* to C::* is better than conversion of A::* to C::* 4454 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4455 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4456 return ImplicitConversionSequence::Better; 4457 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4458 return ImplicitConversionSequence::Worse; 4459 } 4460 } 4461 4462 if (SCS1.Second == ICK_Derived_To_Base) { 4463 // -- conversion of C to B is better than conversion of C to A, 4464 // -- binding of an expression of type C to a reference of type 4465 // B& is better than binding an expression of type C to a 4466 // reference of type A&, 4467 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4468 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4469 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4470 return ImplicitConversionSequence::Better; 4471 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4472 return ImplicitConversionSequence::Worse; 4473 } 4474 4475 // -- conversion of B to A is better than conversion of C to A. 4476 // -- binding of an expression of type B to a reference of type 4477 // A& is better than binding an expression of type C to a 4478 // reference of type A&, 4479 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4480 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4481 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4482 return ImplicitConversionSequence::Better; 4483 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4484 return ImplicitConversionSequence::Worse; 4485 } 4486 } 4487 4488 return ImplicitConversionSequence::Indistinguishable; 4489 } 4490 4491 /// Determine whether the given type is valid, e.g., it is not an invalid 4492 /// C++ class. 4493 static bool isTypeValid(QualType T) { 4494 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4495 return !Record->isInvalidDecl(); 4496 4497 return true; 4498 } 4499 4500 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4501 if (!T.getQualifiers().hasUnaligned()) 4502 return T; 4503 4504 Qualifiers Q; 4505 T = Ctx.getUnqualifiedArrayType(T, Q); 4506 Q.removeUnaligned(); 4507 return Ctx.getQualifiedType(T, Q); 4508 } 4509 4510 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4511 /// determine whether they are reference-compatible, 4512 /// reference-related, or incompatible, for use in C++ initialization by 4513 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4514 /// type, and the first type (T1) is the pointee type of the reference 4515 /// type being initialized. 4516 Sema::ReferenceCompareResult 4517 Sema::CompareReferenceRelationship(SourceLocation Loc, 4518 QualType OrigT1, QualType OrigT2, 4519 ReferenceConversions *ConvOut) { 4520 assert(!OrigT1->isReferenceType() && 4521 "T1 must be the pointee type of the reference type"); 4522 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4523 4524 QualType T1 = Context.getCanonicalType(OrigT1); 4525 QualType T2 = Context.getCanonicalType(OrigT2); 4526 Qualifiers T1Quals, T2Quals; 4527 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4528 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4529 4530 ReferenceConversions ConvTmp; 4531 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4532 Conv = ReferenceConversions(); 4533 4534 // C++2a [dcl.init.ref]p4: 4535 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4536 // reference-related to "cv2 T2" if T1 is similar to T2, or 4537 // T1 is a base class of T2. 4538 // "cv1 T1" is reference-compatible with "cv2 T2" if 4539 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4540 // "pointer to cv1 T1" via a standard conversion sequence. 4541 4542 // Check for standard conversions we can apply to pointers: derived-to-base 4543 // conversions, ObjC pointer conversions, and function pointer conversions. 4544 // (Qualification conversions are checked last.) 4545 QualType ConvertedT2; 4546 if (UnqualT1 == UnqualT2) { 4547 // Nothing to do. 4548 } else if (isCompleteType(Loc, OrigT2) && 4549 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4550 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4551 Conv |= ReferenceConversions::DerivedToBase; 4552 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4553 UnqualT2->isObjCObjectOrInterfaceType() && 4554 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4555 Conv |= ReferenceConversions::ObjC; 4556 else if (UnqualT2->isFunctionType() && 4557 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4558 Conv |= ReferenceConversions::Function; 4559 // No need to check qualifiers; function types don't have them. 4560 return Ref_Compatible; 4561 } 4562 bool ConvertedReferent = Conv != 0; 4563 4564 // We can have a qualification conversion. Compute whether the types are 4565 // similar at the same time. 4566 bool PreviousToQualsIncludeConst = true; 4567 bool TopLevel = true; 4568 do { 4569 if (T1 == T2) 4570 break; 4571 4572 // We will need a qualification conversion. 4573 Conv |= ReferenceConversions::Qualification; 4574 4575 // Track whether we performed a qualification conversion anywhere other 4576 // than the top level. This matters for ranking reference bindings in 4577 // overload resolution. 4578 if (!TopLevel) 4579 Conv |= ReferenceConversions::NestedQualification; 4580 4581 // MS compiler ignores __unaligned qualifier for references; do the same. 4582 T1 = withoutUnaligned(Context, T1); 4583 T2 = withoutUnaligned(Context, T2); 4584 4585 // If we find a qualifier mismatch, the types are not reference-compatible, 4586 // but are still be reference-related if they're similar. 4587 bool ObjCLifetimeConversion = false; 4588 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4589 PreviousToQualsIncludeConst, 4590 ObjCLifetimeConversion)) 4591 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4592 ? Ref_Related 4593 : Ref_Incompatible; 4594 4595 // FIXME: Should we track this for any level other than the first? 4596 if (ObjCLifetimeConversion) 4597 Conv |= ReferenceConversions::ObjCLifetime; 4598 4599 TopLevel = false; 4600 } while (Context.UnwrapSimilarTypes(T1, T2)); 4601 4602 // At this point, if the types are reference-related, we must either have the 4603 // same inner type (ignoring qualifiers), or must have already worked out how 4604 // to convert the referent. 4605 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4606 ? Ref_Compatible 4607 : Ref_Incompatible; 4608 } 4609 4610 /// Look for a user-defined conversion to a value reference-compatible 4611 /// with DeclType. Return true if something definite is found. 4612 static bool 4613 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4614 QualType DeclType, SourceLocation DeclLoc, 4615 Expr *Init, QualType T2, bool AllowRvalues, 4616 bool AllowExplicit) { 4617 assert(T2->isRecordType() && "Can only find conversions of record types."); 4618 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4619 4620 OverloadCandidateSet CandidateSet( 4621 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4622 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4623 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4624 NamedDecl *D = *I; 4625 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4626 if (isa<UsingShadowDecl>(D)) 4627 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4628 4629 FunctionTemplateDecl *ConvTemplate 4630 = dyn_cast<FunctionTemplateDecl>(D); 4631 CXXConversionDecl *Conv; 4632 if (ConvTemplate) 4633 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4634 else 4635 Conv = cast<CXXConversionDecl>(D); 4636 4637 if (AllowRvalues) { 4638 // If we are initializing an rvalue reference, don't permit conversion 4639 // functions that return lvalues. 4640 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4641 const ReferenceType *RefType 4642 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4643 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4644 continue; 4645 } 4646 4647 if (!ConvTemplate && 4648 S.CompareReferenceRelationship( 4649 DeclLoc, 4650 Conv->getConversionType() 4651 .getNonReferenceType() 4652 .getUnqualifiedType(), 4653 DeclType.getNonReferenceType().getUnqualifiedType()) == 4654 Sema::Ref_Incompatible) 4655 continue; 4656 } else { 4657 // If the conversion function doesn't return a reference type, 4658 // it can't be considered for this conversion. An rvalue reference 4659 // is only acceptable if its referencee is a function type. 4660 4661 const ReferenceType *RefType = 4662 Conv->getConversionType()->getAs<ReferenceType>(); 4663 if (!RefType || 4664 (!RefType->isLValueReferenceType() && 4665 !RefType->getPointeeType()->isFunctionType())) 4666 continue; 4667 } 4668 4669 if (ConvTemplate) 4670 S.AddTemplateConversionCandidate( 4671 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4672 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4673 else 4674 S.AddConversionCandidate( 4675 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4676 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4677 } 4678 4679 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4680 4681 OverloadCandidateSet::iterator Best; 4682 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4683 case OR_Success: 4684 // C++ [over.ics.ref]p1: 4685 // 4686 // [...] If the parameter binds directly to the result of 4687 // applying a conversion function to the argument 4688 // expression, the implicit conversion sequence is a 4689 // user-defined conversion sequence (13.3.3.1.2), with the 4690 // second standard conversion sequence either an identity 4691 // conversion or, if the conversion function returns an 4692 // entity of a type that is a derived class of the parameter 4693 // type, a derived-to-base Conversion. 4694 if (!Best->FinalConversion.DirectBinding) 4695 return false; 4696 4697 ICS.setUserDefined(); 4698 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4699 ICS.UserDefined.After = Best->FinalConversion; 4700 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4701 ICS.UserDefined.ConversionFunction = Best->Function; 4702 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4703 ICS.UserDefined.EllipsisConversion = false; 4704 assert(ICS.UserDefined.After.ReferenceBinding && 4705 ICS.UserDefined.After.DirectBinding && 4706 "Expected a direct reference binding!"); 4707 return true; 4708 4709 case OR_Ambiguous: 4710 ICS.setAmbiguous(); 4711 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4712 Cand != CandidateSet.end(); ++Cand) 4713 if (Cand->Best) 4714 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4715 return true; 4716 4717 case OR_No_Viable_Function: 4718 case OR_Deleted: 4719 // There was no suitable conversion, or we found a deleted 4720 // conversion; continue with other checks. 4721 return false; 4722 } 4723 4724 llvm_unreachable("Invalid OverloadResult!"); 4725 } 4726 4727 /// Compute an implicit conversion sequence for reference 4728 /// initialization. 4729 static ImplicitConversionSequence 4730 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4731 SourceLocation DeclLoc, 4732 bool SuppressUserConversions, 4733 bool AllowExplicit) { 4734 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4735 4736 // Most paths end in a failed conversion. 4737 ImplicitConversionSequence ICS; 4738 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4739 4740 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4741 QualType T2 = Init->getType(); 4742 4743 // If the initializer is the address of an overloaded function, try 4744 // to resolve the overloaded function. If all goes well, T2 is the 4745 // type of the resulting function. 4746 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4747 DeclAccessPair Found; 4748 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4749 false, Found)) 4750 T2 = Fn->getType(); 4751 } 4752 4753 // Compute some basic properties of the types and the initializer. 4754 bool isRValRef = DeclType->isRValueReferenceType(); 4755 Expr::Classification InitCategory = Init->Classify(S.Context); 4756 4757 Sema::ReferenceConversions RefConv; 4758 Sema::ReferenceCompareResult RefRelationship = 4759 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4760 4761 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4762 ICS.setStandard(); 4763 ICS.Standard.First = ICK_Identity; 4764 // FIXME: A reference binding can be a function conversion too. We should 4765 // consider that when ordering reference-to-function bindings. 4766 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4767 ? ICK_Derived_To_Base 4768 : (RefConv & Sema::ReferenceConversions::ObjC) 4769 ? ICK_Compatible_Conversion 4770 : ICK_Identity; 4771 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4772 // a reference binding that performs a non-top-level qualification 4773 // conversion as a qualification conversion, not as an identity conversion. 4774 ICS.Standard.Third = (RefConv & 4775 Sema::ReferenceConversions::NestedQualification) 4776 ? ICK_Qualification 4777 : ICK_Identity; 4778 ICS.Standard.setFromType(T2); 4779 ICS.Standard.setToType(0, T2); 4780 ICS.Standard.setToType(1, T1); 4781 ICS.Standard.setToType(2, T1); 4782 ICS.Standard.ReferenceBinding = true; 4783 ICS.Standard.DirectBinding = BindsDirectly; 4784 ICS.Standard.IsLvalueReference = !isRValRef; 4785 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4786 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4787 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4788 ICS.Standard.ObjCLifetimeConversionBinding = 4789 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4790 ICS.Standard.CopyConstructor = nullptr; 4791 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4792 }; 4793 4794 // C++0x [dcl.init.ref]p5: 4795 // A reference to type "cv1 T1" is initialized by an expression 4796 // of type "cv2 T2" as follows: 4797 4798 // -- If reference is an lvalue reference and the initializer expression 4799 if (!isRValRef) { 4800 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4801 // reference-compatible with "cv2 T2," or 4802 // 4803 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4804 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4805 // C++ [over.ics.ref]p1: 4806 // When a parameter of reference type binds directly (8.5.3) 4807 // to an argument expression, the implicit conversion sequence 4808 // is the identity conversion, unless the argument expression 4809 // has a type that is a derived class of the parameter type, 4810 // in which case the implicit conversion sequence is a 4811 // derived-to-base Conversion (13.3.3.1). 4812 SetAsReferenceBinding(/*BindsDirectly=*/true); 4813 4814 // Nothing more to do: the inaccessibility/ambiguity check for 4815 // derived-to-base conversions is suppressed when we're 4816 // computing the implicit conversion sequence (C++ 4817 // [over.best.ics]p2). 4818 return ICS; 4819 } 4820 4821 // -- has a class type (i.e., T2 is a class type), where T1 is 4822 // not reference-related to T2, and can be implicitly 4823 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4824 // is reference-compatible with "cv3 T3" 92) (this 4825 // conversion is selected by enumerating the applicable 4826 // conversion functions (13.3.1.6) and choosing the best 4827 // one through overload resolution (13.3)), 4828 if (!SuppressUserConversions && T2->isRecordType() && 4829 S.isCompleteType(DeclLoc, T2) && 4830 RefRelationship == Sema::Ref_Incompatible) { 4831 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4832 Init, T2, /*AllowRvalues=*/false, 4833 AllowExplicit)) 4834 return ICS; 4835 } 4836 } 4837 4838 // -- Otherwise, the reference shall be an lvalue reference to a 4839 // non-volatile const type (i.e., cv1 shall be const), or the reference 4840 // shall be an rvalue reference. 4841 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4842 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4843 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4844 return ICS; 4845 } 4846 4847 // -- If the initializer expression 4848 // 4849 // -- is an xvalue, class prvalue, array prvalue or function 4850 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4851 if (RefRelationship == Sema::Ref_Compatible && 4852 (InitCategory.isXValue() || 4853 (InitCategory.isPRValue() && 4854 (T2->isRecordType() || T2->isArrayType())) || 4855 (InitCategory.isLValue() && T2->isFunctionType()))) { 4856 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4857 // binding unless we're binding to a class prvalue. 4858 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4859 // allow the use of rvalue references in C++98/03 for the benefit of 4860 // standard library implementors; therefore, we need the xvalue check here. 4861 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4862 !(InitCategory.isPRValue() || T2->isRecordType())); 4863 return ICS; 4864 } 4865 4866 // -- has a class type (i.e., T2 is a class type), where T1 is not 4867 // reference-related to T2, and can be implicitly converted to 4868 // an xvalue, class prvalue, or function lvalue of type 4869 // "cv3 T3", where "cv1 T1" is reference-compatible with 4870 // "cv3 T3", 4871 // 4872 // then the reference is bound to the value of the initializer 4873 // expression in the first case and to the result of the conversion 4874 // in the second case (or, in either case, to an appropriate base 4875 // class subobject). 4876 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4877 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4878 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4879 Init, T2, /*AllowRvalues=*/true, 4880 AllowExplicit)) { 4881 // In the second case, if the reference is an rvalue reference 4882 // and the second standard conversion sequence of the 4883 // user-defined conversion sequence includes an lvalue-to-rvalue 4884 // conversion, the program is ill-formed. 4885 if (ICS.isUserDefined() && isRValRef && 4886 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4887 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4888 4889 return ICS; 4890 } 4891 4892 // A temporary of function type cannot be created; don't even try. 4893 if (T1->isFunctionType()) 4894 return ICS; 4895 4896 // -- Otherwise, a temporary of type "cv1 T1" is created and 4897 // initialized from the initializer expression using the 4898 // rules for a non-reference copy initialization (8.5). The 4899 // reference is then bound to the temporary. If T1 is 4900 // reference-related to T2, cv1 must be the same 4901 // cv-qualification as, or greater cv-qualification than, 4902 // cv2; otherwise, the program is ill-formed. 4903 if (RefRelationship == Sema::Ref_Related) { 4904 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4905 // we would be reference-compatible or reference-compatible with 4906 // added qualification. But that wasn't the case, so the reference 4907 // initialization fails. 4908 // 4909 // Note that we only want to check address spaces and cvr-qualifiers here. 4910 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4911 Qualifiers T1Quals = T1.getQualifiers(); 4912 Qualifiers T2Quals = T2.getQualifiers(); 4913 T1Quals.removeObjCGCAttr(); 4914 T1Quals.removeObjCLifetime(); 4915 T2Quals.removeObjCGCAttr(); 4916 T2Quals.removeObjCLifetime(); 4917 // MS compiler ignores __unaligned qualifier for references; do the same. 4918 T1Quals.removeUnaligned(); 4919 T2Quals.removeUnaligned(); 4920 if (!T1Quals.compatiblyIncludes(T2Quals)) 4921 return ICS; 4922 } 4923 4924 // If at least one of the types is a class type, the types are not 4925 // related, and we aren't allowed any user conversions, the 4926 // reference binding fails. This case is important for breaking 4927 // recursion, since TryImplicitConversion below will attempt to 4928 // create a temporary through the use of a copy constructor. 4929 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4930 (T1->isRecordType() || T2->isRecordType())) 4931 return ICS; 4932 4933 // If T1 is reference-related to T2 and the reference is an rvalue 4934 // reference, the initializer expression shall not be an lvalue. 4935 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4936 Init->Classify(S.Context).isLValue()) { 4937 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4938 return ICS; 4939 } 4940 4941 // C++ [over.ics.ref]p2: 4942 // When a parameter of reference type is not bound directly to 4943 // an argument expression, the conversion sequence is the one 4944 // required to convert the argument expression to the 4945 // underlying type of the reference according to 4946 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4947 // to copy-initializing a temporary of the underlying type with 4948 // the argument expression. Any difference in top-level 4949 // cv-qualification is subsumed by the initialization itself 4950 // and does not constitute a conversion. 4951 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4952 AllowedExplicit::None, 4953 /*InOverloadResolution=*/false, 4954 /*CStyle=*/false, 4955 /*AllowObjCWritebackConversion=*/false, 4956 /*AllowObjCConversionOnExplicit=*/false); 4957 4958 // Of course, that's still a reference binding. 4959 if (ICS.isStandard()) { 4960 ICS.Standard.ReferenceBinding = true; 4961 ICS.Standard.IsLvalueReference = !isRValRef; 4962 ICS.Standard.BindsToFunctionLvalue = false; 4963 ICS.Standard.BindsToRvalue = true; 4964 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4965 ICS.Standard.ObjCLifetimeConversionBinding = false; 4966 } else if (ICS.isUserDefined()) { 4967 const ReferenceType *LValRefType = 4968 ICS.UserDefined.ConversionFunction->getReturnType() 4969 ->getAs<LValueReferenceType>(); 4970 4971 // C++ [over.ics.ref]p3: 4972 // Except for an implicit object parameter, for which see 13.3.1, a 4973 // standard conversion sequence cannot be formed if it requires [...] 4974 // binding an rvalue reference to an lvalue other than a function 4975 // lvalue. 4976 // Note that the function case is not possible here. 4977 if (isRValRef && LValRefType) { 4978 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4979 return ICS; 4980 } 4981 4982 ICS.UserDefined.After.ReferenceBinding = true; 4983 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4984 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4985 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4986 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4987 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4988 } 4989 4990 return ICS; 4991 } 4992 4993 static ImplicitConversionSequence 4994 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4995 bool SuppressUserConversions, 4996 bool InOverloadResolution, 4997 bool AllowObjCWritebackConversion, 4998 bool AllowExplicit = false); 4999 5000 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5001 /// initializer list From. 5002 static ImplicitConversionSequence 5003 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5004 bool SuppressUserConversions, 5005 bool InOverloadResolution, 5006 bool AllowObjCWritebackConversion) { 5007 // C++11 [over.ics.list]p1: 5008 // When an argument is an initializer list, it is not an expression and 5009 // special rules apply for converting it to a parameter type. 5010 5011 ImplicitConversionSequence Result; 5012 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5013 5014 // We need a complete type for what follows. Incomplete types can never be 5015 // initialized from init lists. 5016 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 5017 return Result; 5018 5019 // Per DR1467: 5020 // If the parameter type is a class X and the initializer list has a single 5021 // element of type cv U, where U is X or a class derived from X, the 5022 // implicit conversion sequence is the one required to convert the element 5023 // to the parameter type. 5024 // 5025 // Otherwise, if the parameter type is a character array [... ] 5026 // and the initializer list has a single element that is an 5027 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5028 // implicit conversion sequence is the identity conversion. 5029 if (From->getNumInits() == 1) { 5030 if (ToType->isRecordType()) { 5031 QualType InitType = From->getInit(0)->getType(); 5032 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5033 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5034 return TryCopyInitialization(S, From->getInit(0), ToType, 5035 SuppressUserConversions, 5036 InOverloadResolution, 5037 AllowObjCWritebackConversion); 5038 } 5039 5040 if (const auto *AT = S.Context.getAsArrayType(ToType)) { 5041 if (S.IsStringInit(From->getInit(0), AT)) { 5042 InitializedEntity Entity = 5043 InitializedEntity::InitializeParameter(S.Context, ToType, 5044 /*Consumed=*/false); 5045 if (S.CanPerformCopyInitialization(Entity, From)) { 5046 Result.setStandard(); 5047 Result.Standard.setAsIdentityConversion(); 5048 Result.Standard.setFromType(ToType); 5049 Result.Standard.setAllToTypes(ToType); 5050 return Result; 5051 } 5052 } 5053 } 5054 } 5055 5056 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5057 // C++11 [over.ics.list]p2: 5058 // If the parameter type is std::initializer_list<X> or "array of X" and 5059 // all the elements can be implicitly converted to X, the implicit 5060 // conversion sequence is the worst conversion necessary to convert an 5061 // element of the list to X. 5062 // 5063 // C++14 [over.ics.list]p3: 5064 // Otherwise, if the parameter type is "array of N X", if the initializer 5065 // list has exactly N elements or if it has fewer than N elements and X is 5066 // default-constructible, and if all the elements of the initializer list 5067 // can be implicitly converted to X, the implicit conversion sequence is 5068 // the worst conversion necessary to convert an element of the list to X. 5069 // 5070 // FIXME: We're missing a lot of these checks. 5071 bool toStdInitializerList = false; 5072 QualType X; 5073 if (ToType->isArrayType()) 5074 X = S.Context.getAsArrayType(ToType)->getElementType(); 5075 else 5076 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5077 if (!X.isNull()) { 5078 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5079 Expr *Init = From->getInit(i); 5080 ImplicitConversionSequence ICS = 5081 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5082 InOverloadResolution, 5083 AllowObjCWritebackConversion); 5084 // If a single element isn't convertible, fail. 5085 if (ICS.isBad()) { 5086 Result = ICS; 5087 break; 5088 } 5089 // Otherwise, look for the worst conversion. 5090 if (Result.isBad() || CompareImplicitConversionSequences( 5091 S, From->getBeginLoc(), ICS, Result) == 5092 ImplicitConversionSequence::Worse) 5093 Result = ICS; 5094 } 5095 5096 // For an empty list, we won't have computed any conversion sequence. 5097 // Introduce the identity conversion sequence. 5098 if (From->getNumInits() == 0) { 5099 Result.setStandard(); 5100 Result.Standard.setAsIdentityConversion(); 5101 Result.Standard.setFromType(ToType); 5102 Result.Standard.setAllToTypes(ToType); 5103 } 5104 5105 Result.setStdInitializerListElement(toStdInitializerList); 5106 return Result; 5107 } 5108 5109 // C++14 [over.ics.list]p4: 5110 // C++11 [over.ics.list]p3: 5111 // Otherwise, if the parameter is a non-aggregate class X and overload 5112 // resolution chooses a single best constructor [...] the implicit 5113 // conversion sequence is a user-defined conversion sequence. If multiple 5114 // constructors are viable but none is better than the others, the 5115 // implicit conversion sequence is a user-defined conversion sequence. 5116 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5117 // This function can deal with initializer lists. 5118 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5119 AllowedExplicit::None, 5120 InOverloadResolution, /*CStyle=*/false, 5121 AllowObjCWritebackConversion, 5122 /*AllowObjCConversionOnExplicit=*/false); 5123 } 5124 5125 // C++14 [over.ics.list]p5: 5126 // C++11 [over.ics.list]p4: 5127 // Otherwise, if the parameter has an aggregate type which can be 5128 // initialized from the initializer list [...] the implicit conversion 5129 // sequence is a user-defined conversion sequence. 5130 if (ToType->isAggregateType()) { 5131 // Type is an aggregate, argument is an init list. At this point it comes 5132 // down to checking whether the initialization works. 5133 // FIXME: Find out whether this parameter is consumed or not. 5134 InitializedEntity Entity = 5135 InitializedEntity::InitializeParameter(S.Context, ToType, 5136 /*Consumed=*/false); 5137 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5138 From)) { 5139 Result.setUserDefined(); 5140 Result.UserDefined.Before.setAsIdentityConversion(); 5141 // Initializer lists don't have a type. 5142 Result.UserDefined.Before.setFromType(QualType()); 5143 Result.UserDefined.Before.setAllToTypes(QualType()); 5144 5145 Result.UserDefined.After.setAsIdentityConversion(); 5146 Result.UserDefined.After.setFromType(ToType); 5147 Result.UserDefined.After.setAllToTypes(ToType); 5148 Result.UserDefined.ConversionFunction = nullptr; 5149 } 5150 return Result; 5151 } 5152 5153 // C++14 [over.ics.list]p6: 5154 // C++11 [over.ics.list]p5: 5155 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5156 if (ToType->isReferenceType()) { 5157 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5158 // mention initializer lists in any way. So we go by what list- 5159 // initialization would do and try to extrapolate from that. 5160 5161 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5162 5163 // If the initializer list has a single element that is reference-related 5164 // to the parameter type, we initialize the reference from that. 5165 if (From->getNumInits() == 1) { 5166 Expr *Init = From->getInit(0); 5167 5168 QualType T2 = Init->getType(); 5169 5170 // If the initializer is the address of an overloaded function, try 5171 // to resolve the overloaded function. If all goes well, T2 is the 5172 // type of the resulting function. 5173 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5174 DeclAccessPair Found; 5175 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5176 Init, ToType, false, Found)) 5177 T2 = Fn->getType(); 5178 } 5179 5180 // Compute some basic properties of the types and the initializer. 5181 Sema::ReferenceCompareResult RefRelationship = 5182 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5183 5184 if (RefRelationship >= Sema::Ref_Related) { 5185 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5186 SuppressUserConversions, 5187 /*AllowExplicit=*/false); 5188 } 5189 } 5190 5191 // Otherwise, we bind the reference to a temporary created from the 5192 // initializer list. 5193 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5194 InOverloadResolution, 5195 AllowObjCWritebackConversion); 5196 if (Result.isFailure()) 5197 return Result; 5198 assert(!Result.isEllipsis() && 5199 "Sub-initialization cannot result in ellipsis conversion."); 5200 5201 // Can we even bind to a temporary? 5202 if (ToType->isRValueReferenceType() || 5203 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5204 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5205 Result.UserDefined.After; 5206 SCS.ReferenceBinding = true; 5207 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5208 SCS.BindsToRvalue = true; 5209 SCS.BindsToFunctionLvalue = false; 5210 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5211 SCS.ObjCLifetimeConversionBinding = false; 5212 } else 5213 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5214 From, ToType); 5215 return Result; 5216 } 5217 5218 // C++14 [over.ics.list]p7: 5219 // C++11 [over.ics.list]p6: 5220 // Otherwise, if the parameter type is not a class: 5221 if (!ToType->isRecordType()) { 5222 // - if the initializer list has one element that is not itself an 5223 // initializer list, the implicit conversion sequence is the one 5224 // required to convert the element to the parameter type. 5225 unsigned NumInits = From->getNumInits(); 5226 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5227 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5228 SuppressUserConversions, 5229 InOverloadResolution, 5230 AllowObjCWritebackConversion); 5231 // - if the initializer list has no elements, the implicit conversion 5232 // sequence is the identity conversion. 5233 else if (NumInits == 0) { 5234 Result.setStandard(); 5235 Result.Standard.setAsIdentityConversion(); 5236 Result.Standard.setFromType(ToType); 5237 Result.Standard.setAllToTypes(ToType); 5238 } 5239 return Result; 5240 } 5241 5242 // C++14 [over.ics.list]p8: 5243 // C++11 [over.ics.list]p7: 5244 // In all cases other than those enumerated above, no conversion is possible 5245 return Result; 5246 } 5247 5248 /// TryCopyInitialization - Try to copy-initialize a value of type 5249 /// ToType from the expression From. Return the implicit conversion 5250 /// sequence required to pass this argument, which may be a bad 5251 /// conversion sequence (meaning that the argument cannot be passed to 5252 /// a parameter of this type). If @p SuppressUserConversions, then we 5253 /// do not permit any user-defined conversion sequences. 5254 static ImplicitConversionSequence 5255 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5256 bool SuppressUserConversions, 5257 bool InOverloadResolution, 5258 bool AllowObjCWritebackConversion, 5259 bool AllowExplicit) { 5260 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5261 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5262 InOverloadResolution,AllowObjCWritebackConversion); 5263 5264 if (ToType->isReferenceType()) 5265 return TryReferenceInit(S, From, ToType, 5266 /*FIXME:*/ From->getBeginLoc(), 5267 SuppressUserConversions, AllowExplicit); 5268 5269 return TryImplicitConversion(S, From, ToType, 5270 SuppressUserConversions, 5271 AllowedExplicit::None, 5272 InOverloadResolution, 5273 /*CStyle=*/false, 5274 AllowObjCWritebackConversion, 5275 /*AllowObjCConversionOnExplicit=*/false); 5276 } 5277 5278 static bool TryCopyInitialization(const CanQualType FromQTy, 5279 const CanQualType ToQTy, 5280 Sema &S, 5281 SourceLocation Loc, 5282 ExprValueKind FromVK) { 5283 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5284 ImplicitConversionSequence ICS = 5285 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5286 5287 return !ICS.isBad(); 5288 } 5289 5290 /// TryObjectArgumentInitialization - Try to initialize the object 5291 /// parameter of the given member function (@c Method) from the 5292 /// expression @p From. 5293 static ImplicitConversionSequence 5294 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5295 Expr::Classification FromClassification, 5296 CXXMethodDecl *Method, 5297 CXXRecordDecl *ActingContext) { 5298 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5299 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5300 // const volatile object. 5301 Qualifiers Quals = Method->getMethodQualifiers(); 5302 if (isa<CXXDestructorDecl>(Method)) { 5303 Quals.addConst(); 5304 Quals.addVolatile(); 5305 } 5306 5307 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5308 5309 // Set up the conversion sequence as a "bad" conversion, to allow us 5310 // to exit early. 5311 ImplicitConversionSequence ICS; 5312 5313 // We need to have an object of class type. 5314 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5315 FromType = PT->getPointeeType(); 5316 5317 // When we had a pointer, it's implicitly dereferenced, so we 5318 // better have an lvalue. 5319 assert(FromClassification.isLValue()); 5320 } 5321 5322 assert(FromType->isRecordType()); 5323 5324 // C++0x [over.match.funcs]p4: 5325 // For non-static member functions, the type of the implicit object 5326 // parameter is 5327 // 5328 // - "lvalue reference to cv X" for functions declared without a 5329 // ref-qualifier or with the & ref-qualifier 5330 // - "rvalue reference to cv X" for functions declared with the && 5331 // ref-qualifier 5332 // 5333 // where X is the class of which the function is a member and cv is the 5334 // cv-qualification on the member function declaration. 5335 // 5336 // However, when finding an implicit conversion sequence for the argument, we 5337 // are not allowed to perform user-defined conversions 5338 // (C++ [over.match.funcs]p5). We perform a simplified version of 5339 // reference binding here, that allows class rvalues to bind to 5340 // non-constant references. 5341 5342 // First check the qualifiers. 5343 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5344 if (ImplicitParamType.getCVRQualifiers() 5345 != FromTypeCanon.getLocalCVRQualifiers() && 5346 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5347 ICS.setBad(BadConversionSequence::bad_qualifiers, 5348 FromType, ImplicitParamType); 5349 return ICS; 5350 } 5351 5352 if (FromTypeCanon.hasAddressSpace()) { 5353 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5354 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5355 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5356 ICS.setBad(BadConversionSequence::bad_qualifiers, 5357 FromType, ImplicitParamType); 5358 return ICS; 5359 } 5360 } 5361 5362 // Check that we have either the same type or a derived type. It 5363 // affects the conversion rank. 5364 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5365 ImplicitConversionKind SecondKind; 5366 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5367 SecondKind = ICK_Identity; 5368 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5369 SecondKind = ICK_Derived_To_Base; 5370 else { 5371 ICS.setBad(BadConversionSequence::unrelated_class, 5372 FromType, ImplicitParamType); 5373 return ICS; 5374 } 5375 5376 // Check the ref-qualifier. 5377 switch (Method->getRefQualifier()) { 5378 case RQ_None: 5379 // Do nothing; we don't care about lvalueness or rvalueness. 5380 break; 5381 5382 case RQ_LValue: 5383 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5384 // non-const lvalue reference cannot bind to an rvalue 5385 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5386 ImplicitParamType); 5387 return ICS; 5388 } 5389 break; 5390 5391 case RQ_RValue: 5392 if (!FromClassification.isRValue()) { 5393 // rvalue reference cannot bind to an lvalue 5394 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5395 ImplicitParamType); 5396 return ICS; 5397 } 5398 break; 5399 } 5400 5401 // Success. Mark this as a reference binding. 5402 ICS.setStandard(); 5403 ICS.Standard.setAsIdentityConversion(); 5404 ICS.Standard.Second = SecondKind; 5405 ICS.Standard.setFromType(FromType); 5406 ICS.Standard.setAllToTypes(ImplicitParamType); 5407 ICS.Standard.ReferenceBinding = true; 5408 ICS.Standard.DirectBinding = true; 5409 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5410 ICS.Standard.BindsToFunctionLvalue = false; 5411 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5412 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5413 = (Method->getRefQualifier() == RQ_None); 5414 return ICS; 5415 } 5416 5417 /// PerformObjectArgumentInitialization - Perform initialization of 5418 /// the implicit object parameter for the given Method with the given 5419 /// expression. 5420 ExprResult 5421 Sema::PerformObjectArgumentInitialization(Expr *From, 5422 NestedNameSpecifier *Qualifier, 5423 NamedDecl *FoundDecl, 5424 CXXMethodDecl *Method) { 5425 QualType FromRecordType, DestType; 5426 QualType ImplicitParamRecordType = 5427 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5428 5429 Expr::Classification FromClassification; 5430 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5431 FromRecordType = PT->getPointeeType(); 5432 DestType = Method->getThisType(); 5433 FromClassification = Expr::Classification::makeSimpleLValue(); 5434 } else { 5435 FromRecordType = From->getType(); 5436 DestType = ImplicitParamRecordType; 5437 FromClassification = From->Classify(Context); 5438 5439 // When performing member access on a prvalue, materialize a temporary. 5440 if (From->isPRValue()) { 5441 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5442 Method->getRefQualifier() != 5443 RefQualifierKind::RQ_RValue); 5444 } 5445 } 5446 5447 // Note that we always use the true parent context when performing 5448 // the actual argument initialization. 5449 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5450 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5451 Method->getParent()); 5452 if (ICS.isBad()) { 5453 switch (ICS.Bad.Kind) { 5454 case BadConversionSequence::bad_qualifiers: { 5455 Qualifiers FromQs = FromRecordType.getQualifiers(); 5456 Qualifiers ToQs = DestType.getQualifiers(); 5457 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5458 if (CVR) { 5459 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5460 << Method->getDeclName() << FromRecordType << (CVR - 1) 5461 << From->getSourceRange(); 5462 Diag(Method->getLocation(), diag::note_previous_decl) 5463 << Method->getDeclName(); 5464 return ExprError(); 5465 } 5466 break; 5467 } 5468 5469 case BadConversionSequence::lvalue_ref_to_rvalue: 5470 case BadConversionSequence::rvalue_ref_to_lvalue: { 5471 bool IsRValueQualified = 5472 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5473 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5474 << Method->getDeclName() << FromClassification.isRValue() 5475 << IsRValueQualified; 5476 Diag(Method->getLocation(), diag::note_previous_decl) 5477 << Method->getDeclName(); 5478 return ExprError(); 5479 } 5480 5481 case BadConversionSequence::no_conversion: 5482 case BadConversionSequence::unrelated_class: 5483 break; 5484 } 5485 5486 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5487 << ImplicitParamRecordType << FromRecordType 5488 << From->getSourceRange(); 5489 } 5490 5491 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5492 ExprResult FromRes = 5493 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5494 if (FromRes.isInvalid()) 5495 return ExprError(); 5496 From = FromRes.get(); 5497 } 5498 5499 if (!Context.hasSameType(From->getType(), DestType)) { 5500 CastKind CK; 5501 QualType PteeTy = DestType->getPointeeType(); 5502 LangAS DestAS = 5503 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5504 if (FromRecordType.getAddressSpace() != DestAS) 5505 CK = CK_AddressSpaceConversion; 5506 else 5507 CK = CK_NoOp; 5508 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5509 } 5510 return From; 5511 } 5512 5513 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5514 /// expression From to bool (C++0x [conv]p3). 5515 static ImplicitConversionSequence 5516 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5517 // C++ [dcl.init]/17.8: 5518 // - Otherwise, if the initialization is direct-initialization, the source 5519 // type is std::nullptr_t, and the destination type is bool, the initial 5520 // value of the object being initialized is false. 5521 if (From->getType()->isNullPtrType()) 5522 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5523 S.Context.BoolTy, 5524 From->isGLValue()); 5525 5526 // All other direct-initialization of bool is equivalent to an implicit 5527 // conversion to bool in which explicit conversions are permitted. 5528 return TryImplicitConversion(S, From, S.Context.BoolTy, 5529 /*SuppressUserConversions=*/false, 5530 AllowedExplicit::Conversions, 5531 /*InOverloadResolution=*/false, 5532 /*CStyle=*/false, 5533 /*AllowObjCWritebackConversion=*/false, 5534 /*AllowObjCConversionOnExplicit=*/false); 5535 } 5536 5537 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5538 /// of the expression From to bool (C++0x [conv]p3). 5539 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5540 if (checkPlaceholderForOverload(*this, From)) 5541 return ExprError(); 5542 5543 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5544 if (!ICS.isBad()) 5545 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5546 5547 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5548 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5549 << From->getType() << From->getSourceRange(); 5550 return ExprError(); 5551 } 5552 5553 /// Check that the specified conversion is permitted in a converted constant 5554 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5555 /// is acceptable. 5556 static bool CheckConvertedConstantConversions(Sema &S, 5557 StandardConversionSequence &SCS) { 5558 // Since we know that the target type is an integral or unscoped enumeration 5559 // type, most conversion kinds are impossible. All possible First and Third 5560 // conversions are fine. 5561 switch (SCS.Second) { 5562 case ICK_Identity: 5563 case ICK_Integral_Promotion: 5564 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5565 case ICK_Zero_Queue_Conversion: 5566 return true; 5567 5568 case ICK_Boolean_Conversion: 5569 // Conversion from an integral or unscoped enumeration type to bool is 5570 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5571 // conversion, so we allow it in a converted constant expression. 5572 // 5573 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5574 // a lot of popular code. We should at least add a warning for this 5575 // (non-conforming) extension. 5576 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5577 SCS.getToType(2)->isBooleanType(); 5578 5579 case ICK_Pointer_Conversion: 5580 case ICK_Pointer_Member: 5581 // C++1z: null pointer conversions and null member pointer conversions are 5582 // only permitted if the source type is std::nullptr_t. 5583 return SCS.getFromType()->isNullPtrType(); 5584 5585 case ICK_Floating_Promotion: 5586 case ICK_Complex_Promotion: 5587 case ICK_Floating_Conversion: 5588 case ICK_Complex_Conversion: 5589 case ICK_Floating_Integral: 5590 case ICK_Compatible_Conversion: 5591 case ICK_Derived_To_Base: 5592 case ICK_Vector_Conversion: 5593 case ICK_SVE_Vector_Conversion: 5594 case ICK_Vector_Splat: 5595 case ICK_Complex_Real: 5596 case ICK_Block_Pointer_Conversion: 5597 case ICK_TransparentUnionConversion: 5598 case ICK_Writeback_Conversion: 5599 case ICK_Zero_Event_Conversion: 5600 case ICK_C_Only_Conversion: 5601 case ICK_Incompatible_Pointer_Conversion: 5602 return false; 5603 5604 case ICK_Lvalue_To_Rvalue: 5605 case ICK_Array_To_Pointer: 5606 case ICK_Function_To_Pointer: 5607 llvm_unreachable("found a first conversion kind in Second"); 5608 5609 case ICK_Function_Conversion: 5610 case ICK_Qualification: 5611 llvm_unreachable("found a third conversion kind in Second"); 5612 5613 case ICK_Num_Conversion_Kinds: 5614 break; 5615 } 5616 5617 llvm_unreachable("unknown conversion kind"); 5618 } 5619 5620 /// CheckConvertedConstantExpression - Check that the expression From is a 5621 /// converted constant expression of type T, perform the conversion and produce 5622 /// the converted expression, per C++11 [expr.const]p3. 5623 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5624 QualType T, APValue &Value, 5625 Sema::CCEKind CCE, 5626 bool RequireInt, 5627 NamedDecl *Dest) { 5628 assert(S.getLangOpts().CPlusPlus11 && 5629 "converted constant expression outside C++11"); 5630 5631 if (checkPlaceholderForOverload(S, From)) 5632 return ExprError(); 5633 5634 // C++1z [expr.const]p3: 5635 // A converted constant expression of type T is an expression, 5636 // implicitly converted to type T, where the converted 5637 // expression is a constant expression and the implicit conversion 5638 // sequence contains only [... list of conversions ...]. 5639 ImplicitConversionSequence ICS = 5640 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 5641 ? TryContextuallyConvertToBool(S, From) 5642 : TryCopyInitialization(S, From, T, 5643 /*SuppressUserConversions=*/false, 5644 /*InOverloadResolution=*/false, 5645 /*AllowObjCWritebackConversion=*/false, 5646 /*AllowExplicit=*/false); 5647 StandardConversionSequence *SCS = nullptr; 5648 switch (ICS.getKind()) { 5649 case ImplicitConversionSequence::StandardConversion: 5650 SCS = &ICS.Standard; 5651 break; 5652 case ImplicitConversionSequence::UserDefinedConversion: 5653 if (T->isRecordType()) 5654 SCS = &ICS.UserDefined.Before; 5655 else 5656 SCS = &ICS.UserDefined.After; 5657 break; 5658 case ImplicitConversionSequence::AmbiguousConversion: 5659 case ImplicitConversionSequence::BadConversion: 5660 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5661 return S.Diag(From->getBeginLoc(), 5662 diag::err_typecheck_converted_constant_expression) 5663 << From->getType() << From->getSourceRange() << T; 5664 return ExprError(); 5665 5666 case ImplicitConversionSequence::EllipsisConversion: 5667 llvm_unreachable("ellipsis conversion in converted constant expression"); 5668 } 5669 5670 // Check that we would only use permitted conversions. 5671 if (!CheckConvertedConstantConversions(S, *SCS)) { 5672 return S.Diag(From->getBeginLoc(), 5673 diag::err_typecheck_converted_constant_expression_disallowed) 5674 << From->getType() << From->getSourceRange() << T; 5675 } 5676 // [...] and where the reference binding (if any) binds directly. 5677 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5678 return S.Diag(From->getBeginLoc(), 5679 diag::err_typecheck_converted_constant_expression_indirect) 5680 << From->getType() << From->getSourceRange() << T; 5681 } 5682 5683 // Usually we can simply apply the ImplicitConversionSequence we formed 5684 // earlier, but that's not guaranteed to work when initializing an object of 5685 // class type. 5686 ExprResult Result; 5687 if (T->isRecordType()) { 5688 assert(CCE == Sema::CCEK_TemplateArg && 5689 "unexpected class type converted constant expr"); 5690 Result = S.PerformCopyInitialization( 5691 InitializedEntity::InitializeTemplateParameter( 5692 T, cast<NonTypeTemplateParmDecl>(Dest)), 5693 SourceLocation(), From); 5694 } else { 5695 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5696 } 5697 if (Result.isInvalid()) 5698 return Result; 5699 5700 // C++2a [intro.execution]p5: 5701 // A full-expression is [...] a constant-expression [...] 5702 Result = 5703 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5704 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5705 if (Result.isInvalid()) 5706 return Result; 5707 5708 // Check for a narrowing implicit conversion. 5709 bool ReturnPreNarrowingValue = false; 5710 APValue PreNarrowingValue; 5711 QualType PreNarrowingType; 5712 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5713 PreNarrowingType)) { 5714 case NK_Dependent_Narrowing: 5715 // Implicit conversion to a narrower type, but the expression is 5716 // value-dependent so we can't tell whether it's actually narrowing. 5717 case NK_Variable_Narrowing: 5718 // Implicit conversion to a narrower type, and the value is not a constant 5719 // expression. We'll diagnose this in a moment. 5720 case NK_Not_Narrowing: 5721 break; 5722 5723 case NK_Constant_Narrowing: 5724 if (CCE == Sema::CCEK_ArrayBound && 5725 PreNarrowingType->isIntegralOrEnumerationType() && 5726 PreNarrowingValue.isInt()) { 5727 // Don't diagnose array bound narrowing here; we produce more precise 5728 // errors by allowing the un-narrowed value through. 5729 ReturnPreNarrowingValue = true; 5730 break; 5731 } 5732 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5733 << CCE << /*Constant*/ 1 5734 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5735 break; 5736 5737 case NK_Type_Narrowing: 5738 // FIXME: It would be better to diagnose that the expression is not a 5739 // constant expression. 5740 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5741 << CCE << /*Constant*/ 0 << From->getType() << T; 5742 break; 5743 } 5744 5745 if (Result.get()->isValueDependent()) { 5746 Value = APValue(); 5747 return Result; 5748 } 5749 5750 // Check the expression is a constant expression. 5751 SmallVector<PartialDiagnosticAt, 8> Notes; 5752 Expr::EvalResult Eval; 5753 Eval.Diag = &Notes; 5754 5755 ConstantExprKind Kind; 5756 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5757 Kind = ConstantExprKind::ClassTemplateArgument; 5758 else if (CCE == Sema::CCEK_TemplateArg) 5759 Kind = ConstantExprKind::NonClassTemplateArgument; 5760 else 5761 Kind = ConstantExprKind::Normal; 5762 5763 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5764 (RequireInt && !Eval.Val.isInt())) { 5765 // The expression can't be folded, so we can't keep it at this position in 5766 // the AST. 5767 Result = ExprError(); 5768 } else { 5769 Value = Eval.Val; 5770 5771 if (Notes.empty()) { 5772 // It's a constant expression. 5773 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5774 if (ReturnPreNarrowingValue) 5775 Value = std::move(PreNarrowingValue); 5776 return E; 5777 } 5778 } 5779 5780 // It's not a constant expression. Produce an appropriate diagnostic. 5781 if (Notes.size() == 1 && 5782 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5783 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5784 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5785 diag::note_constexpr_invalid_template_arg) { 5786 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5787 for (unsigned I = 0; I < Notes.size(); ++I) 5788 S.Diag(Notes[I].first, Notes[I].second); 5789 } else { 5790 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5791 << CCE << From->getSourceRange(); 5792 for (unsigned I = 0; I < Notes.size(); ++I) 5793 S.Diag(Notes[I].first, Notes[I].second); 5794 } 5795 return ExprError(); 5796 } 5797 5798 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5799 APValue &Value, CCEKind CCE, 5800 NamedDecl *Dest) { 5801 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5802 Dest); 5803 } 5804 5805 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5806 llvm::APSInt &Value, 5807 CCEKind CCE) { 5808 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5809 5810 APValue V; 5811 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5812 /*Dest=*/nullptr); 5813 if (!R.isInvalid() && !R.get()->isValueDependent()) 5814 Value = V.getInt(); 5815 return R; 5816 } 5817 5818 5819 /// dropPointerConversions - If the given standard conversion sequence 5820 /// involves any pointer conversions, remove them. This may change 5821 /// the result type of the conversion sequence. 5822 static void dropPointerConversion(StandardConversionSequence &SCS) { 5823 if (SCS.Second == ICK_Pointer_Conversion) { 5824 SCS.Second = ICK_Identity; 5825 SCS.Third = ICK_Identity; 5826 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5827 } 5828 } 5829 5830 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5831 /// convert the expression From to an Objective-C pointer type. 5832 static ImplicitConversionSequence 5833 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5834 // Do an implicit conversion to 'id'. 5835 QualType Ty = S.Context.getObjCIdType(); 5836 ImplicitConversionSequence ICS 5837 = TryImplicitConversion(S, From, Ty, 5838 // FIXME: Are these flags correct? 5839 /*SuppressUserConversions=*/false, 5840 AllowedExplicit::Conversions, 5841 /*InOverloadResolution=*/false, 5842 /*CStyle=*/false, 5843 /*AllowObjCWritebackConversion=*/false, 5844 /*AllowObjCConversionOnExplicit=*/true); 5845 5846 // Strip off any final conversions to 'id'. 5847 switch (ICS.getKind()) { 5848 case ImplicitConversionSequence::BadConversion: 5849 case ImplicitConversionSequence::AmbiguousConversion: 5850 case ImplicitConversionSequence::EllipsisConversion: 5851 break; 5852 5853 case ImplicitConversionSequence::UserDefinedConversion: 5854 dropPointerConversion(ICS.UserDefined.After); 5855 break; 5856 5857 case ImplicitConversionSequence::StandardConversion: 5858 dropPointerConversion(ICS.Standard); 5859 break; 5860 } 5861 5862 return ICS; 5863 } 5864 5865 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5866 /// conversion of the expression From to an Objective-C pointer type. 5867 /// Returns a valid but null ExprResult if no conversion sequence exists. 5868 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5869 if (checkPlaceholderForOverload(*this, From)) 5870 return ExprError(); 5871 5872 QualType Ty = Context.getObjCIdType(); 5873 ImplicitConversionSequence ICS = 5874 TryContextuallyConvertToObjCPointer(*this, From); 5875 if (!ICS.isBad()) 5876 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5877 return ExprResult(); 5878 } 5879 5880 /// Determine whether the provided type is an integral type, or an enumeration 5881 /// type of a permitted flavor. 5882 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5883 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5884 : T->isIntegralOrUnscopedEnumerationType(); 5885 } 5886 5887 static ExprResult 5888 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5889 Sema::ContextualImplicitConverter &Converter, 5890 QualType T, UnresolvedSetImpl &ViableConversions) { 5891 5892 if (Converter.Suppress) 5893 return ExprError(); 5894 5895 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5896 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5897 CXXConversionDecl *Conv = 5898 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5899 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5900 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5901 } 5902 return From; 5903 } 5904 5905 static bool 5906 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5907 Sema::ContextualImplicitConverter &Converter, 5908 QualType T, bool HadMultipleCandidates, 5909 UnresolvedSetImpl &ExplicitConversions) { 5910 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5911 DeclAccessPair Found = ExplicitConversions[0]; 5912 CXXConversionDecl *Conversion = 5913 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5914 5915 // The user probably meant to invoke the given explicit 5916 // conversion; use it. 5917 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5918 std::string TypeStr; 5919 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5920 5921 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5922 << FixItHint::CreateInsertion(From->getBeginLoc(), 5923 "static_cast<" + TypeStr + ">(") 5924 << FixItHint::CreateInsertion( 5925 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5926 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5927 5928 // If we aren't in a SFINAE context, build a call to the 5929 // explicit conversion function. 5930 if (SemaRef.isSFINAEContext()) 5931 return true; 5932 5933 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5934 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5935 HadMultipleCandidates); 5936 if (Result.isInvalid()) 5937 return true; 5938 // Record usage of conversion in an implicit cast. 5939 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5940 CK_UserDefinedConversion, Result.get(), 5941 nullptr, Result.get()->getValueKind(), 5942 SemaRef.CurFPFeatureOverrides()); 5943 } 5944 return false; 5945 } 5946 5947 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5948 Sema::ContextualImplicitConverter &Converter, 5949 QualType T, bool HadMultipleCandidates, 5950 DeclAccessPair &Found) { 5951 CXXConversionDecl *Conversion = 5952 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5953 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5954 5955 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5956 if (!Converter.SuppressConversion) { 5957 if (SemaRef.isSFINAEContext()) 5958 return true; 5959 5960 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5961 << From->getSourceRange(); 5962 } 5963 5964 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5965 HadMultipleCandidates); 5966 if (Result.isInvalid()) 5967 return true; 5968 // Record usage of conversion in an implicit cast. 5969 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5970 CK_UserDefinedConversion, Result.get(), 5971 nullptr, Result.get()->getValueKind(), 5972 SemaRef.CurFPFeatureOverrides()); 5973 return false; 5974 } 5975 5976 static ExprResult finishContextualImplicitConversion( 5977 Sema &SemaRef, SourceLocation Loc, Expr *From, 5978 Sema::ContextualImplicitConverter &Converter) { 5979 if (!Converter.match(From->getType()) && !Converter.Suppress) 5980 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5981 << From->getSourceRange(); 5982 5983 return SemaRef.DefaultLvalueConversion(From); 5984 } 5985 5986 static void 5987 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5988 UnresolvedSetImpl &ViableConversions, 5989 OverloadCandidateSet &CandidateSet) { 5990 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5991 DeclAccessPair FoundDecl = ViableConversions[I]; 5992 NamedDecl *D = FoundDecl.getDecl(); 5993 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5994 if (isa<UsingShadowDecl>(D)) 5995 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5996 5997 CXXConversionDecl *Conv; 5998 FunctionTemplateDecl *ConvTemplate; 5999 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6000 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6001 else 6002 Conv = cast<CXXConversionDecl>(D); 6003 6004 if (ConvTemplate) 6005 SemaRef.AddTemplateConversionCandidate( 6006 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6007 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6008 else 6009 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6010 ToType, CandidateSet, 6011 /*AllowObjCConversionOnExplicit=*/false, 6012 /*AllowExplicit*/ true); 6013 } 6014 } 6015 6016 /// Attempt to convert the given expression to a type which is accepted 6017 /// by the given converter. 6018 /// 6019 /// This routine will attempt to convert an expression of class type to a 6020 /// type accepted by the specified converter. In C++11 and before, the class 6021 /// must have a single non-explicit conversion function converting to a matching 6022 /// type. In C++1y, there can be multiple such conversion functions, but only 6023 /// one target type. 6024 /// 6025 /// \param Loc The source location of the construct that requires the 6026 /// conversion. 6027 /// 6028 /// \param From The expression we're converting from. 6029 /// 6030 /// \param Converter Used to control and diagnose the conversion process. 6031 /// 6032 /// \returns The expression, converted to an integral or enumeration type if 6033 /// successful. 6034 ExprResult Sema::PerformContextualImplicitConversion( 6035 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6036 // We can't perform any more checking for type-dependent expressions. 6037 if (From->isTypeDependent()) 6038 return From; 6039 6040 // Process placeholders immediately. 6041 if (From->hasPlaceholderType()) { 6042 ExprResult result = CheckPlaceholderExpr(From); 6043 if (result.isInvalid()) 6044 return result; 6045 From = result.get(); 6046 } 6047 6048 // If the expression already has a matching type, we're golden. 6049 QualType T = From->getType(); 6050 if (Converter.match(T)) 6051 return DefaultLvalueConversion(From); 6052 6053 // FIXME: Check for missing '()' if T is a function type? 6054 6055 // We can only perform contextual implicit conversions on objects of class 6056 // type. 6057 const RecordType *RecordTy = T->getAs<RecordType>(); 6058 if (!RecordTy || !getLangOpts().CPlusPlus) { 6059 if (!Converter.Suppress) 6060 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6061 return From; 6062 } 6063 6064 // We must have a complete class type. 6065 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6066 ContextualImplicitConverter &Converter; 6067 Expr *From; 6068 6069 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6070 : Converter(Converter), From(From) {} 6071 6072 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6073 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6074 } 6075 } IncompleteDiagnoser(Converter, From); 6076 6077 if (Converter.Suppress ? !isCompleteType(Loc, T) 6078 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6079 return From; 6080 6081 // Look for a conversion to an integral or enumeration type. 6082 UnresolvedSet<4> 6083 ViableConversions; // These are *potentially* viable in C++1y. 6084 UnresolvedSet<4> ExplicitConversions; 6085 const auto &Conversions = 6086 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6087 6088 bool HadMultipleCandidates = 6089 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6090 6091 // To check that there is only one target type, in C++1y: 6092 QualType ToType; 6093 bool HasUniqueTargetType = true; 6094 6095 // Collect explicit or viable (potentially in C++1y) conversions. 6096 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6097 NamedDecl *D = (*I)->getUnderlyingDecl(); 6098 CXXConversionDecl *Conversion; 6099 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6100 if (ConvTemplate) { 6101 if (getLangOpts().CPlusPlus14) 6102 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6103 else 6104 continue; // C++11 does not consider conversion operator templates(?). 6105 } else 6106 Conversion = cast<CXXConversionDecl>(D); 6107 6108 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6109 "Conversion operator templates are considered potentially " 6110 "viable in C++1y"); 6111 6112 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6113 if (Converter.match(CurToType) || ConvTemplate) { 6114 6115 if (Conversion->isExplicit()) { 6116 // FIXME: For C++1y, do we need this restriction? 6117 // cf. diagnoseNoViableConversion() 6118 if (!ConvTemplate) 6119 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6120 } else { 6121 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6122 if (ToType.isNull()) 6123 ToType = CurToType.getUnqualifiedType(); 6124 else if (HasUniqueTargetType && 6125 (CurToType.getUnqualifiedType() != ToType)) 6126 HasUniqueTargetType = false; 6127 } 6128 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6129 } 6130 } 6131 } 6132 6133 if (getLangOpts().CPlusPlus14) { 6134 // C++1y [conv]p6: 6135 // ... An expression e of class type E appearing in such a context 6136 // is said to be contextually implicitly converted to a specified 6137 // type T and is well-formed if and only if e can be implicitly 6138 // converted to a type T that is determined as follows: E is searched 6139 // for conversion functions whose return type is cv T or reference to 6140 // cv T such that T is allowed by the context. There shall be 6141 // exactly one such T. 6142 6143 // If no unique T is found: 6144 if (ToType.isNull()) { 6145 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6146 HadMultipleCandidates, 6147 ExplicitConversions)) 6148 return ExprError(); 6149 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6150 } 6151 6152 // If more than one unique Ts are found: 6153 if (!HasUniqueTargetType) 6154 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6155 ViableConversions); 6156 6157 // If one unique T is found: 6158 // First, build a candidate set from the previously recorded 6159 // potentially viable conversions. 6160 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6161 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6162 CandidateSet); 6163 6164 // Then, perform overload resolution over the candidate set. 6165 OverloadCandidateSet::iterator Best; 6166 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6167 case OR_Success: { 6168 // Apply this conversion. 6169 DeclAccessPair Found = 6170 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6171 if (recordConversion(*this, Loc, From, Converter, T, 6172 HadMultipleCandidates, Found)) 6173 return ExprError(); 6174 break; 6175 } 6176 case OR_Ambiguous: 6177 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6178 ViableConversions); 6179 case OR_No_Viable_Function: 6180 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6181 HadMultipleCandidates, 6182 ExplicitConversions)) 6183 return ExprError(); 6184 LLVM_FALLTHROUGH; 6185 case OR_Deleted: 6186 // We'll complain below about a non-integral condition type. 6187 break; 6188 } 6189 } else { 6190 switch (ViableConversions.size()) { 6191 case 0: { 6192 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6193 HadMultipleCandidates, 6194 ExplicitConversions)) 6195 return ExprError(); 6196 6197 // We'll complain below about a non-integral condition type. 6198 break; 6199 } 6200 case 1: { 6201 // Apply this conversion. 6202 DeclAccessPair Found = ViableConversions[0]; 6203 if (recordConversion(*this, Loc, From, Converter, T, 6204 HadMultipleCandidates, Found)) 6205 return ExprError(); 6206 break; 6207 } 6208 default: 6209 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6210 ViableConversions); 6211 } 6212 } 6213 6214 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6215 } 6216 6217 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6218 /// an acceptable non-member overloaded operator for a call whose 6219 /// arguments have types T1 (and, if non-empty, T2). This routine 6220 /// implements the check in C++ [over.match.oper]p3b2 concerning 6221 /// enumeration types. 6222 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6223 FunctionDecl *Fn, 6224 ArrayRef<Expr *> Args) { 6225 QualType T1 = Args[0]->getType(); 6226 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6227 6228 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6229 return true; 6230 6231 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6232 return true; 6233 6234 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6235 if (Proto->getNumParams() < 1) 6236 return false; 6237 6238 if (T1->isEnumeralType()) { 6239 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6240 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6241 return true; 6242 } 6243 6244 if (Proto->getNumParams() < 2) 6245 return false; 6246 6247 if (!T2.isNull() && T2->isEnumeralType()) { 6248 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6249 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6250 return true; 6251 } 6252 6253 return false; 6254 } 6255 6256 /// AddOverloadCandidate - Adds the given function to the set of 6257 /// candidate functions, using the given function call arguments. If 6258 /// @p SuppressUserConversions, then don't allow user-defined 6259 /// conversions via constructors or conversion operators. 6260 /// 6261 /// \param PartialOverloading true if we are performing "partial" overloading 6262 /// based on an incomplete set of function arguments. This feature is used by 6263 /// code completion. 6264 void Sema::AddOverloadCandidate( 6265 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6266 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6267 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6268 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6269 OverloadCandidateParamOrder PO) { 6270 const FunctionProtoType *Proto 6271 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6272 assert(Proto && "Functions without a prototype cannot be overloaded"); 6273 assert(!Function->getDescribedFunctionTemplate() && 6274 "Use AddTemplateOverloadCandidate for function templates"); 6275 6276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6277 if (!isa<CXXConstructorDecl>(Method)) { 6278 // If we get here, it's because we're calling a member function 6279 // that is named without a member access expression (e.g., 6280 // "this->f") that was either written explicitly or created 6281 // implicitly. This can happen with a qualified call to a member 6282 // function, e.g., X::f(). We use an empty type for the implied 6283 // object argument (C++ [over.call.func]p3), and the acting context 6284 // is irrelevant. 6285 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6286 Expr::Classification::makeSimpleLValue(), Args, 6287 CandidateSet, SuppressUserConversions, 6288 PartialOverloading, EarlyConversions, PO); 6289 return; 6290 } 6291 // We treat a constructor like a non-member function, since its object 6292 // argument doesn't participate in overload resolution. 6293 } 6294 6295 if (!CandidateSet.isNewCandidate(Function, PO)) 6296 return; 6297 6298 // C++11 [class.copy]p11: [DR1402] 6299 // A defaulted move constructor that is defined as deleted is ignored by 6300 // overload resolution. 6301 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6302 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6303 Constructor->isMoveConstructor()) 6304 return; 6305 6306 // Overload resolution is always an unevaluated context. 6307 EnterExpressionEvaluationContext Unevaluated( 6308 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6309 6310 // C++ [over.match.oper]p3: 6311 // if no operand has a class type, only those non-member functions in the 6312 // lookup set that have a first parameter of type T1 or "reference to 6313 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6314 // is a right operand) a second parameter of type T2 or "reference to 6315 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6316 // candidate functions. 6317 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6318 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6319 return; 6320 6321 // Add this candidate 6322 OverloadCandidate &Candidate = 6323 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6324 Candidate.FoundDecl = FoundDecl; 6325 Candidate.Function = Function; 6326 Candidate.Viable = true; 6327 Candidate.RewriteKind = 6328 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6329 Candidate.IsSurrogate = false; 6330 Candidate.IsADLCandidate = IsADLCandidate; 6331 Candidate.IgnoreObjectArgument = false; 6332 Candidate.ExplicitCallArguments = Args.size(); 6333 6334 // Explicit functions are not actually candidates at all if we're not 6335 // allowing them in this context, but keep them around so we can point 6336 // to them in diagnostics. 6337 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6338 Candidate.Viable = false; 6339 Candidate.FailureKind = ovl_fail_explicit; 6340 return; 6341 } 6342 6343 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6344 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6345 Candidate.Viable = false; 6346 Candidate.FailureKind = ovl_non_default_multiversion_function; 6347 return; 6348 } 6349 6350 if (Constructor) { 6351 // C++ [class.copy]p3: 6352 // A member function template is never instantiated to perform the copy 6353 // of a class object to an object of its class type. 6354 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6355 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6356 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6357 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6358 ClassType))) { 6359 Candidate.Viable = false; 6360 Candidate.FailureKind = ovl_fail_illegal_constructor; 6361 return; 6362 } 6363 6364 // C++ [over.match.funcs]p8: (proposed DR resolution) 6365 // A constructor inherited from class type C that has a first parameter 6366 // of type "reference to P" (including such a constructor instantiated 6367 // from a template) is excluded from the set of candidate functions when 6368 // constructing an object of type cv D if the argument list has exactly 6369 // one argument and D is reference-related to P and P is reference-related 6370 // to C. 6371 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6372 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6373 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6374 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6375 QualType C = Context.getRecordType(Constructor->getParent()); 6376 QualType D = Context.getRecordType(Shadow->getParent()); 6377 SourceLocation Loc = Args.front()->getExprLoc(); 6378 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6379 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6380 Candidate.Viable = false; 6381 Candidate.FailureKind = ovl_fail_inhctor_slice; 6382 return; 6383 } 6384 } 6385 6386 // Check that the constructor is capable of constructing an object in the 6387 // destination address space. 6388 if (!Qualifiers::isAddressSpaceSupersetOf( 6389 Constructor->getMethodQualifiers().getAddressSpace(), 6390 CandidateSet.getDestAS())) { 6391 Candidate.Viable = false; 6392 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6393 } 6394 } 6395 6396 unsigned NumParams = Proto->getNumParams(); 6397 6398 // (C++ 13.3.2p2): A candidate function having fewer than m 6399 // parameters is viable only if it has an ellipsis in its parameter 6400 // list (8.3.5). 6401 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6402 !Proto->isVariadic()) { 6403 Candidate.Viable = false; 6404 Candidate.FailureKind = ovl_fail_too_many_arguments; 6405 return; 6406 } 6407 6408 // (C++ 13.3.2p2): A candidate function having more than m parameters 6409 // is viable only if the (m+1)st parameter has a default argument 6410 // (8.3.6). For the purposes of overload resolution, the 6411 // parameter list is truncated on the right, so that there are 6412 // exactly m parameters. 6413 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6414 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6415 // Not enough arguments. 6416 Candidate.Viable = false; 6417 Candidate.FailureKind = ovl_fail_too_few_arguments; 6418 return; 6419 } 6420 6421 // (CUDA B.1): Check for invalid calls between targets. 6422 if (getLangOpts().CUDA) 6423 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6424 // Skip the check for callers that are implicit members, because in this 6425 // case we may not yet know what the member's target is; the target is 6426 // inferred for the member automatically, based on the bases and fields of 6427 // the class. 6428 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6429 Candidate.Viable = false; 6430 Candidate.FailureKind = ovl_fail_bad_target; 6431 return; 6432 } 6433 6434 if (Function->getTrailingRequiresClause()) { 6435 ConstraintSatisfaction Satisfaction; 6436 if (CheckFunctionConstraints(Function, Satisfaction) || 6437 !Satisfaction.IsSatisfied) { 6438 Candidate.Viable = false; 6439 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6440 return; 6441 } 6442 } 6443 6444 // Determine the implicit conversion sequences for each of the 6445 // arguments. 6446 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6447 unsigned ConvIdx = 6448 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6449 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6450 // We already formed a conversion sequence for this parameter during 6451 // template argument deduction. 6452 } else if (ArgIdx < NumParams) { 6453 // (C++ 13.3.2p3): for F to be a viable function, there shall 6454 // exist for each argument an implicit conversion sequence 6455 // (13.3.3.1) that converts that argument to the corresponding 6456 // parameter of F. 6457 QualType ParamType = Proto->getParamType(ArgIdx); 6458 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6459 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6460 /*InOverloadResolution=*/true, 6461 /*AllowObjCWritebackConversion=*/ 6462 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6463 if (Candidate.Conversions[ConvIdx].isBad()) { 6464 Candidate.Viable = false; 6465 Candidate.FailureKind = ovl_fail_bad_conversion; 6466 return; 6467 } 6468 } else { 6469 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6470 // argument for which there is no corresponding parameter is 6471 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6472 Candidate.Conversions[ConvIdx].setEllipsis(); 6473 } 6474 } 6475 6476 if (EnableIfAttr *FailedAttr = 6477 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6478 Candidate.Viable = false; 6479 Candidate.FailureKind = ovl_fail_enable_if; 6480 Candidate.DeductionFailure.Data = FailedAttr; 6481 return; 6482 } 6483 } 6484 6485 ObjCMethodDecl * 6486 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6487 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6488 if (Methods.size() <= 1) 6489 return nullptr; 6490 6491 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6492 bool Match = true; 6493 ObjCMethodDecl *Method = Methods[b]; 6494 unsigned NumNamedArgs = Sel.getNumArgs(); 6495 // Method might have more arguments than selector indicates. This is due 6496 // to addition of c-style arguments in method. 6497 if (Method->param_size() > NumNamedArgs) 6498 NumNamedArgs = Method->param_size(); 6499 if (Args.size() < NumNamedArgs) 6500 continue; 6501 6502 for (unsigned i = 0; i < NumNamedArgs; i++) { 6503 // We can't do any type-checking on a type-dependent argument. 6504 if (Args[i]->isTypeDependent()) { 6505 Match = false; 6506 break; 6507 } 6508 6509 ParmVarDecl *param = Method->parameters()[i]; 6510 Expr *argExpr = Args[i]; 6511 assert(argExpr && "SelectBestMethod(): missing expression"); 6512 6513 // Strip the unbridged-cast placeholder expression off unless it's 6514 // a consumed argument. 6515 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6516 !param->hasAttr<CFConsumedAttr>()) 6517 argExpr = stripARCUnbridgedCast(argExpr); 6518 6519 // If the parameter is __unknown_anytype, move on to the next method. 6520 if (param->getType() == Context.UnknownAnyTy) { 6521 Match = false; 6522 break; 6523 } 6524 6525 ImplicitConversionSequence ConversionState 6526 = TryCopyInitialization(*this, argExpr, param->getType(), 6527 /*SuppressUserConversions*/false, 6528 /*InOverloadResolution=*/true, 6529 /*AllowObjCWritebackConversion=*/ 6530 getLangOpts().ObjCAutoRefCount, 6531 /*AllowExplicit*/false); 6532 // This function looks for a reasonably-exact match, so we consider 6533 // incompatible pointer conversions to be a failure here. 6534 if (ConversionState.isBad() || 6535 (ConversionState.isStandard() && 6536 ConversionState.Standard.Second == 6537 ICK_Incompatible_Pointer_Conversion)) { 6538 Match = false; 6539 break; 6540 } 6541 } 6542 // Promote additional arguments to variadic methods. 6543 if (Match && Method->isVariadic()) { 6544 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6545 if (Args[i]->isTypeDependent()) { 6546 Match = false; 6547 break; 6548 } 6549 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6550 nullptr); 6551 if (Arg.isInvalid()) { 6552 Match = false; 6553 break; 6554 } 6555 } 6556 } else { 6557 // Check for extra arguments to non-variadic methods. 6558 if (Args.size() != NumNamedArgs) 6559 Match = false; 6560 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6561 // Special case when selectors have no argument. In this case, select 6562 // one with the most general result type of 'id'. 6563 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6564 QualType ReturnT = Methods[b]->getReturnType(); 6565 if (ReturnT->isObjCIdType()) 6566 return Methods[b]; 6567 } 6568 } 6569 } 6570 6571 if (Match) 6572 return Method; 6573 } 6574 return nullptr; 6575 } 6576 6577 static bool convertArgsForAvailabilityChecks( 6578 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6579 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6580 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6581 if (ThisArg) { 6582 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6583 assert(!isa<CXXConstructorDecl>(Method) && 6584 "Shouldn't have `this` for ctors!"); 6585 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6586 ExprResult R = S.PerformObjectArgumentInitialization( 6587 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6588 if (R.isInvalid()) 6589 return false; 6590 ConvertedThis = R.get(); 6591 } else { 6592 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6593 (void)MD; 6594 assert((MissingImplicitThis || MD->isStatic() || 6595 isa<CXXConstructorDecl>(MD)) && 6596 "Expected `this` for non-ctor instance methods"); 6597 } 6598 ConvertedThis = nullptr; 6599 } 6600 6601 // Ignore any variadic arguments. Converting them is pointless, since the 6602 // user can't refer to them in the function condition. 6603 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6604 6605 // Convert the arguments. 6606 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6607 ExprResult R; 6608 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6609 S.Context, Function->getParamDecl(I)), 6610 SourceLocation(), Args[I]); 6611 6612 if (R.isInvalid()) 6613 return false; 6614 6615 ConvertedArgs.push_back(R.get()); 6616 } 6617 6618 if (Trap.hasErrorOccurred()) 6619 return false; 6620 6621 // Push default arguments if needed. 6622 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6623 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6624 ParmVarDecl *P = Function->getParamDecl(i); 6625 if (!P->hasDefaultArg()) 6626 return false; 6627 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6628 if (R.isInvalid()) 6629 return false; 6630 ConvertedArgs.push_back(R.get()); 6631 } 6632 6633 if (Trap.hasErrorOccurred()) 6634 return false; 6635 } 6636 return true; 6637 } 6638 6639 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6640 SourceLocation CallLoc, 6641 ArrayRef<Expr *> Args, 6642 bool MissingImplicitThis) { 6643 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6644 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6645 return nullptr; 6646 6647 SFINAETrap Trap(*this); 6648 SmallVector<Expr *, 16> ConvertedArgs; 6649 // FIXME: We should look into making enable_if late-parsed. 6650 Expr *DiscardedThis; 6651 if (!convertArgsForAvailabilityChecks( 6652 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6653 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6654 return *EnableIfAttrs.begin(); 6655 6656 for (auto *EIA : EnableIfAttrs) { 6657 APValue Result; 6658 // FIXME: This doesn't consider value-dependent cases, because doing so is 6659 // very difficult. Ideally, we should handle them more gracefully. 6660 if (EIA->getCond()->isValueDependent() || 6661 !EIA->getCond()->EvaluateWithSubstitution( 6662 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6663 return EIA; 6664 6665 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6666 return EIA; 6667 } 6668 return nullptr; 6669 } 6670 6671 template <typename CheckFn> 6672 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6673 bool ArgDependent, SourceLocation Loc, 6674 CheckFn &&IsSuccessful) { 6675 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6676 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6677 if (ArgDependent == DIA->getArgDependent()) 6678 Attrs.push_back(DIA); 6679 } 6680 6681 // Common case: No diagnose_if attributes, so we can quit early. 6682 if (Attrs.empty()) 6683 return false; 6684 6685 auto WarningBegin = std::stable_partition( 6686 Attrs.begin(), Attrs.end(), 6687 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6688 6689 // Note that diagnose_if attributes are late-parsed, so they appear in the 6690 // correct order (unlike enable_if attributes). 6691 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6692 IsSuccessful); 6693 if (ErrAttr != WarningBegin) { 6694 const DiagnoseIfAttr *DIA = *ErrAttr; 6695 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6696 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6697 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6698 return true; 6699 } 6700 6701 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6702 if (IsSuccessful(DIA)) { 6703 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6704 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6705 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6706 } 6707 6708 return false; 6709 } 6710 6711 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6712 const Expr *ThisArg, 6713 ArrayRef<const Expr *> Args, 6714 SourceLocation Loc) { 6715 return diagnoseDiagnoseIfAttrsWith( 6716 *this, Function, /*ArgDependent=*/true, Loc, 6717 [&](const DiagnoseIfAttr *DIA) { 6718 APValue Result; 6719 // It's sane to use the same Args for any redecl of this function, since 6720 // EvaluateWithSubstitution only cares about the position of each 6721 // argument in the arg list, not the ParmVarDecl* it maps to. 6722 if (!DIA->getCond()->EvaluateWithSubstitution( 6723 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6724 return false; 6725 return Result.isInt() && Result.getInt().getBoolValue(); 6726 }); 6727 } 6728 6729 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6730 SourceLocation Loc) { 6731 return diagnoseDiagnoseIfAttrsWith( 6732 *this, ND, /*ArgDependent=*/false, Loc, 6733 [&](const DiagnoseIfAttr *DIA) { 6734 bool Result; 6735 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6736 Result; 6737 }); 6738 } 6739 6740 /// Add all of the function declarations in the given function set to 6741 /// the overload candidate set. 6742 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6743 ArrayRef<Expr *> Args, 6744 OverloadCandidateSet &CandidateSet, 6745 TemplateArgumentListInfo *ExplicitTemplateArgs, 6746 bool SuppressUserConversions, 6747 bool PartialOverloading, 6748 bool FirstArgumentIsBase) { 6749 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6750 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6751 ArrayRef<Expr *> FunctionArgs = Args; 6752 6753 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6754 FunctionDecl *FD = 6755 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6756 6757 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6758 QualType ObjectType; 6759 Expr::Classification ObjectClassification; 6760 if (Args.size() > 0) { 6761 if (Expr *E = Args[0]) { 6762 // Use the explicit base to restrict the lookup: 6763 ObjectType = E->getType(); 6764 // Pointers in the object arguments are implicitly dereferenced, so we 6765 // always classify them as l-values. 6766 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6767 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6768 else 6769 ObjectClassification = E->Classify(Context); 6770 } // .. else there is an implicit base. 6771 FunctionArgs = Args.slice(1); 6772 } 6773 if (FunTmpl) { 6774 AddMethodTemplateCandidate( 6775 FunTmpl, F.getPair(), 6776 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6777 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6778 FunctionArgs, CandidateSet, SuppressUserConversions, 6779 PartialOverloading); 6780 } else { 6781 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6782 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6783 ObjectClassification, FunctionArgs, CandidateSet, 6784 SuppressUserConversions, PartialOverloading); 6785 } 6786 } else { 6787 // This branch handles both standalone functions and static methods. 6788 6789 // Slice the first argument (which is the base) when we access 6790 // static method as non-static. 6791 if (Args.size() > 0 && 6792 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6793 !isa<CXXConstructorDecl>(FD)))) { 6794 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6795 FunctionArgs = Args.slice(1); 6796 } 6797 if (FunTmpl) { 6798 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6799 ExplicitTemplateArgs, FunctionArgs, 6800 CandidateSet, SuppressUserConversions, 6801 PartialOverloading); 6802 } else { 6803 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6804 SuppressUserConversions, PartialOverloading); 6805 } 6806 } 6807 } 6808 } 6809 6810 /// AddMethodCandidate - Adds a named decl (which is some kind of 6811 /// method) as a method candidate to the given overload set. 6812 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6813 Expr::Classification ObjectClassification, 6814 ArrayRef<Expr *> Args, 6815 OverloadCandidateSet &CandidateSet, 6816 bool SuppressUserConversions, 6817 OverloadCandidateParamOrder PO) { 6818 NamedDecl *Decl = FoundDecl.getDecl(); 6819 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6820 6821 if (isa<UsingShadowDecl>(Decl)) 6822 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6823 6824 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6825 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6826 "Expected a member function template"); 6827 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6828 /*ExplicitArgs*/ nullptr, ObjectType, 6829 ObjectClassification, Args, CandidateSet, 6830 SuppressUserConversions, false, PO); 6831 } else { 6832 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6833 ObjectType, ObjectClassification, Args, CandidateSet, 6834 SuppressUserConversions, false, None, PO); 6835 } 6836 } 6837 6838 /// AddMethodCandidate - Adds the given C++ member function to the set 6839 /// of candidate functions, using the given function call arguments 6840 /// and the object argument (@c Object). For example, in a call 6841 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6842 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6843 /// allow user-defined conversions via constructors or conversion 6844 /// operators. 6845 void 6846 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6847 CXXRecordDecl *ActingContext, QualType ObjectType, 6848 Expr::Classification ObjectClassification, 6849 ArrayRef<Expr *> Args, 6850 OverloadCandidateSet &CandidateSet, 6851 bool SuppressUserConversions, 6852 bool PartialOverloading, 6853 ConversionSequenceList EarlyConversions, 6854 OverloadCandidateParamOrder PO) { 6855 const FunctionProtoType *Proto 6856 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6857 assert(Proto && "Methods without a prototype cannot be overloaded"); 6858 assert(!isa<CXXConstructorDecl>(Method) && 6859 "Use AddOverloadCandidate for constructors"); 6860 6861 if (!CandidateSet.isNewCandidate(Method, PO)) 6862 return; 6863 6864 // C++11 [class.copy]p23: [DR1402] 6865 // A defaulted move assignment operator that is defined as deleted is 6866 // ignored by overload resolution. 6867 if (Method->isDefaulted() && Method->isDeleted() && 6868 Method->isMoveAssignmentOperator()) 6869 return; 6870 6871 // Overload resolution is always an unevaluated context. 6872 EnterExpressionEvaluationContext Unevaluated( 6873 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6874 6875 // Add this candidate 6876 OverloadCandidate &Candidate = 6877 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6878 Candidate.FoundDecl = FoundDecl; 6879 Candidate.Function = Method; 6880 Candidate.RewriteKind = 6881 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6882 Candidate.IsSurrogate = false; 6883 Candidate.IgnoreObjectArgument = false; 6884 Candidate.ExplicitCallArguments = Args.size(); 6885 6886 unsigned NumParams = Proto->getNumParams(); 6887 6888 // (C++ 13.3.2p2): A candidate function having fewer than m 6889 // parameters is viable only if it has an ellipsis in its parameter 6890 // list (8.3.5). 6891 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6892 !Proto->isVariadic()) { 6893 Candidate.Viable = false; 6894 Candidate.FailureKind = ovl_fail_too_many_arguments; 6895 return; 6896 } 6897 6898 // (C++ 13.3.2p2): A candidate function having more than m parameters 6899 // is viable only if the (m+1)st parameter has a default argument 6900 // (8.3.6). For the purposes of overload resolution, the 6901 // parameter list is truncated on the right, so that there are 6902 // exactly m parameters. 6903 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6904 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6905 // Not enough arguments. 6906 Candidate.Viable = false; 6907 Candidate.FailureKind = ovl_fail_too_few_arguments; 6908 return; 6909 } 6910 6911 Candidate.Viable = true; 6912 6913 if (Method->isStatic() || ObjectType.isNull()) 6914 // The implicit object argument is ignored. 6915 Candidate.IgnoreObjectArgument = true; 6916 else { 6917 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6918 // Determine the implicit conversion sequence for the object 6919 // parameter. 6920 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6921 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6922 Method, ActingContext); 6923 if (Candidate.Conversions[ConvIdx].isBad()) { 6924 Candidate.Viable = false; 6925 Candidate.FailureKind = ovl_fail_bad_conversion; 6926 return; 6927 } 6928 } 6929 6930 // (CUDA B.1): Check for invalid calls between targets. 6931 if (getLangOpts().CUDA) 6932 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6933 if (!IsAllowedCUDACall(Caller, Method)) { 6934 Candidate.Viable = false; 6935 Candidate.FailureKind = ovl_fail_bad_target; 6936 return; 6937 } 6938 6939 if (Method->getTrailingRequiresClause()) { 6940 ConstraintSatisfaction Satisfaction; 6941 if (CheckFunctionConstraints(Method, Satisfaction) || 6942 !Satisfaction.IsSatisfied) { 6943 Candidate.Viable = false; 6944 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6945 return; 6946 } 6947 } 6948 6949 // Determine the implicit conversion sequences for each of the 6950 // arguments. 6951 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6952 unsigned ConvIdx = 6953 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6954 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6955 // We already formed a conversion sequence for this parameter during 6956 // template argument deduction. 6957 } else if (ArgIdx < NumParams) { 6958 // (C++ 13.3.2p3): for F to be a viable function, there shall 6959 // exist for each argument an implicit conversion sequence 6960 // (13.3.3.1) that converts that argument to the corresponding 6961 // parameter of F. 6962 QualType ParamType = Proto->getParamType(ArgIdx); 6963 Candidate.Conversions[ConvIdx] 6964 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6965 SuppressUserConversions, 6966 /*InOverloadResolution=*/true, 6967 /*AllowObjCWritebackConversion=*/ 6968 getLangOpts().ObjCAutoRefCount); 6969 if (Candidate.Conversions[ConvIdx].isBad()) { 6970 Candidate.Viable = false; 6971 Candidate.FailureKind = ovl_fail_bad_conversion; 6972 return; 6973 } 6974 } else { 6975 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6976 // argument for which there is no corresponding parameter is 6977 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6978 Candidate.Conversions[ConvIdx].setEllipsis(); 6979 } 6980 } 6981 6982 if (EnableIfAttr *FailedAttr = 6983 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6984 Candidate.Viable = false; 6985 Candidate.FailureKind = ovl_fail_enable_if; 6986 Candidate.DeductionFailure.Data = FailedAttr; 6987 return; 6988 } 6989 6990 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6991 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6992 Candidate.Viable = false; 6993 Candidate.FailureKind = ovl_non_default_multiversion_function; 6994 } 6995 } 6996 6997 /// Add a C++ member function template as a candidate to the candidate 6998 /// set, using template argument deduction to produce an appropriate member 6999 /// function template specialization. 7000 void Sema::AddMethodTemplateCandidate( 7001 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7002 CXXRecordDecl *ActingContext, 7003 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7004 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7005 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7006 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7007 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7008 return; 7009 7010 // C++ [over.match.funcs]p7: 7011 // In each case where a candidate is a function template, candidate 7012 // function template specializations are generated using template argument 7013 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7014 // candidate functions in the usual way.113) A given name can refer to one 7015 // or more function templates and also to a set of overloaded non-template 7016 // functions. In such a case, the candidate functions generated from each 7017 // function template are combined with the set of non-template candidate 7018 // functions. 7019 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7020 FunctionDecl *Specialization = nullptr; 7021 ConversionSequenceList Conversions; 7022 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7023 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7024 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7025 return CheckNonDependentConversions( 7026 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7027 SuppressUserConversions, ActingContext, ObjectType, 7028 ObjectClassification, PO); 7029 })) { 7030 OverloadCandidate &Candidate = 7031 CandidateSet.addCandidate(Conversions.size(), Conversions); 7032 Candidate.FoundDecl = FoundDecl; 7033 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7034 Candidate.Viable = false; 7035 Candidate.RewriteKind = 7036 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7037 Candidate.IsSurrogate = false; 7038 Candidate.IgnoreObjectArgument = 7039 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7040 ObjectType.isNull(); 7041 Candidate.ExplicitCallArguments = Args.size(); 7042 if (Result == TDK_NonDependentConversionFailure) 7043 Candidate.FailureKind = ovl_fail_bad_conversion; 7044 else { 7045 Candidate.FailureKind = ovl_fail_bad_deduction; 7046 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7047 Info); 7048 } 7049 return; 7050 } 7051 7052 // Add the function template specialization produced by template argument 7053 // deduction as a candidate. 7054 assert(Specialization && "Missing member function template specialization?"); 7055 assert(isa<CXXMethodDecl>(Specialization) && 7056 "Specialization is not a member function?"); 7057 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7058 ActingContext, ObjectType, ObjectClassification, Args, 7059 CandidateSet, SuppressUserConversions, PartialOverloading, 7060 Conversions, PO); 7061 } 7062 7063 /// Determine whether a given function template has a simple explicit specifier 7064 /// or a non-value-dependent explicit-specification that evaluates to true. 7065 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7066 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7067 } 7068 7069 /// Add a C++ function template specialization as a candidate 7070 /// in the candidate set, using template argument deduction to produce 7071 /// an appropriate function template specialization. 7072 void Sema::AddTemplateOverloadCandidate( 7073 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7074 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7075 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7076 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7077 OverloadCandidateParamOrder PO) { 7078 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7079 return; 7080 7081 // If the function template has a non-dependent explicit specification, 7082 // exclude it now if appropriate; we are not permitted to perform deduction 7083 // and substitution in this case. 7084 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7085 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7086 Candidate.FoundDecl = FoundDecl; 7087 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7088 Candidate.Viable = false; 7089 Candidate.FailureKind = ovl_fail_explicit; 7090 return; 7091 } 7092 7093 // C++ [over.match.funcs]p7: 7094 // In each case where a candidate is a function template, candidate 7095 // function template specializations are generated using template argument 7096 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7097 // candidate functions in the usual way.113) A given name can refer to one 7098 // or more function templates and also to a set of overloaded non-template 7099 // functions. In such a case, the candidate functions generated from each 7100 // function template are combined with the set of non-template candidate 7101 // functions. 7102 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7103 FunctionDecl *Specialization = nullptr; 7104 ConversionSequenceList Conversions; 7105 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7106 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7107 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7108 return CheckNonDependentConversions( 7109 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7110 SuppressUserConversions, nullptr, QualType(), {}, PO); 7111 })) { 7112 OverloadCandidate &Candidate = 7113 CandidateSet.addCandidate(Conversions.size(), Conversions); 7114 Candidate.FoundDecl = FoundDecl; 7115 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7116 Candidate.Viable = false; 7117 Candidate.RewriteKind = 7118 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7119 Candidate.IsSurrogate = false; 7120 Candidate.IsADLCandidate = IsADLCandidate; 7121 // Ignore the object argument if there is one, since we don't have an object 7122 // type. 7123 Candidate.IgnoreObjectArgument = 7124 isa<CXXMethodDecl>(Candidate.Function) && 7125 !isa<CXXConstructorDecl>(Candidate.Function); 7126 Candidate.ExplicitCallArguments = Args.size(); 7127 if (Result == TDK_NonDependentConversionFailure) 7128 Candidate.FailureKind = ovl_fail_bad_conversion; 7129 else { 7130 Candidate.FailureKind = ovl_fail_bad_deduction; 7131 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7132 Info); 7133 } 7134 return; 7135 } 7136 7137 // Add the function template specialization produced by template argument 7138 // deduction as a candidate. 7139 assert(Specialization && "Missing function template specialization?"); 7140 AddOverloadCandidate( 7141 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7142 PartialOverloading, AllowExplicit, 7143 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7144 } 7145 7146 /// Check that implicit conversion sequences can be formed for each argument 7147 /// whose corresponding parameter has a non-dependent type, per DR1391's 7148 /// [temp.deduct.call]p10. 7149 bool Sema::CheckNonDependentConversions( 7150 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7151 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7152 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7153 CXXRecordDecl *ActingContext, QualType ObjectType, 7154 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7155 // FIXME: The cases in which we allow explicit conversions for constructor 7156 // arguments never consider calling a constructor template. It's not clear 7157 // that is correct. 7158 const bool AllowExplicit = false; 7159 7160 auto *FD = FunctionTemplate->getTemplatedDecl(); 7161 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7162 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7163 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7164 7165 Conversions = 7166 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7167 7168 // Overload resolution is always an unevaluated context. 7169 EnterExpressionEvaluationContext Unevaluated( 7170 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7171 7172 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7173 // require that, but this check should never result in a hard error, and 7174 // overload resolution is permitted to sidestep instantiations. 7175 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7176 !ObjectType.isNull()) { 7177 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7178 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7179 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7180 Method, ActingContext); 7181 if (Conversions[ConvIdx].isBad()) 7182 return true; 7183 } 7184 7185 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7186 ++I) { 7187 QualType ParamType = ParamTypes[I]; 7188 if (!ParamType->isDependentType()) { 7189 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7190 ? 0 7191 : (ThisConversions + I); 7192 Conversions[ConvIdx] 7193 = TryCopyInitialization(*this, Args[I], ParamType, 7194 SuppressUserConversions, 7195 /*InOverloadResolution=*/true, 7196 /*AllowObjCWritebackConversion=*/ 7197 getLangOpts().ObjCAutoRefCount, 7198 AllowExplicit); 7199 if (Conversions[ConvIdx].isBad()) 7200 return true; 7201 } 7202 } 7203 7204 return false; 7205 } 7206 7207 /// Determine whether this is an allowable conversion from the result 7208 /// of an explicit conversion operator to the expected type, per C++ 7209 /// [over.match.conv]p1 and [over.match.ref]p1. 7210 /// 7211 /// \param ConvType The return type of the conversion function. 7212 /// 7213 /// \param ToType The type we are converting to. 7214 /// 7215 /// \param AllowObjCPointerConversion Allow a conversion from one 7216 /// Objective-C pointer to another. 7217 /// 7218 /// \returns true if the conversion is allowable, false otherwise. 7219 static bool isAllowableExplicitConversion(Sema &S, 7220 QualType ConvType, QualType ToType, 7221 bool AllowObjCPointerConversion) { 7222 QualType ToNonRefType = ToType.getNonReferenceType(); 7223 7224 // Easy case: the types are the same. 7225 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7226 return true; 7227 7228 // Allow qualification conversions. 7229 bool ObjCLifetimeConversion; 7230 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7231 ObjCLifetimeConversion)) 7232 return true; 7233 7234 // If we're not allowed to consider Objective-C pointer conversions, 7235 // we're done. 7236 if (!AllowObjCPointerConversion) 7237 return false; 7238 7239 // Is this an Objective-C pointer conversion? 7240 bool IncompatibleObjC = false; 7241 QualType ConvertedType; 7242 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7243 IncompatibleObjC); 7244 } 7245 7246 /// AddConversionCandidate - Add a C++ conversion function as a 7247 /// candidate in the candidate set (C++ [over.match.conv], 7248 /// C++ [over.match.copy]). From is the expression we're converting from, 7249 /// and ToType is the type that we're eventually trying to convert to 7250 /// (which may or may not be the same type as the type that the 7251 /// conversion function produces). 7252 void Sema::AddConversionCandidate( 7253 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7254 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7255 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7256 bool AllowExplicit, bool AllowResultConversion) { 7257 assert(!Conversion->getDescribedFunctionTemplate() && 7258 "Conversion function templates use AddTemplateConversionCandidate"); 7259 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7260 if (!CandidateSet.isNewCandidate(Conversion)) 7261 return; 7262 7263 // If the conversion function has an undeduced return type, trigger its 7264 // deduction now. 7265 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7266 if (DeduceReturnType(Conversion, From->getExprLoc())) 7267 return; 7268 ConvType = Conversion->getConversionType().getNonReferenceType(); 7269 } 7270 7271 // If we don't allow any conversion of the result type, ignore conversion 7272 // functions that don't convert to exactly (possibly cv-qualified) T. 7273 if (!AllowResultConversion && 7274 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7275 return; 7276 7277 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7278 // operator is only a candidate if its return type is the target type or 7279 // can be converted to the target type with a qualification conversion. 7280 // 7281 // FIXME: Include such functions in the candidate list and explain why we 7282 // can't select them. 7283 if (Conversion->isExplicit() && 7284 !isAllowableExplicitConversion(*this, ConvType, ToType, 7285 AllowObjCConversionOnExplicit)) 7286 return; 7287 7288 // Overload resolution is always an unevaluated context. 7289 EnterExpressionEvaluationContext Unevaluated( 7290 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7291 7292 // Add this candidate 7293 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7294 Candidate.FoundDecl = FoundDecl; 7295 Candidate.Function = Conversion; 7296 Candidate.IsSurrogate = false; 7297 Candidate.IgnoreObjectArgument = false; 7298 Candidate.FinalConversion.setAsIdentityConversion(); 7299 Candidate.FinalConversion.setFromType(ConvType); 7300 Candidate.FinalConversion.setAllToTypes(ToType); 7301 Candidate.Viable = true; 7302 Candidate.ExplicitCallArguments = 1; 7303 7304 // Explicit functions are not actually candidates at all if we're not 7305 // allowing them in this context, but keep them around so we can point 7306 // to them in diagnostics. 7307 if (!AllowExplicit && Conversion->isExplicit()) { 7308 Candidate.Viable = false; 7309 Candidate.FailureKind = ovl_fail_explicit; 7310 return; 7311 } 7312 7313 // C++ [over.match.funcs]p4: 7314 // For conversion functions, the function is considered to be a member of 7315 // the class of the implicit implied object argument for the purpose of 7316 // defining the type of the implicit object parameter. 7317 // 7318 // Determine the implicit conversion sequence for the implicit 7319 // object parameter. 7320 QualType ImplicitParamType = From->getType(); 7321 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7322 ImplicitParamType = FromPtrType->getPointeeType(); 7323 CXXRecordDecl *ConversionContext 7324 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7325 7326 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7327 *this, CandidateSet.getLocation(), From->getType(), 7328 From->Classify(Context), Conversion, ConversionContext); 7329 7330 if (Candidate.Conversions[0].isBad()) { 7331 Candidate.Viable = false; 7332 Candidate.FailureKind = ovl_fail_bad_conversion; 7333 return; 7334 } 7335 7336 if (Conversion->getTrailingRequiresClause()) { 7337 ConstraintSatisfaction Satisfaction; 7338 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7339 !Satisfaction.IsSatisfied) { 7340 Candidate.Viable = false; 7341 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7342 return; 7343 } 7344 } 7345 7346 // We won't go through a user-defined type conversion function to convert a 7347 // derived to base as such conversions are given Conversion Rank. They only 7348 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7349 QualType FromCanon 7350 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7351 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7352 if (FromCanon == ToCanon || 7353 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7354 Candidate.Viable = false; 7355 Candidate.FailureKind = ovl_fail_trivial_conversion; 7356 return; 7357 } 7358 7359 // To determine what the conversion from the result of calling the 7360 // conversion function to the type we're eventually trying to 7361 // convert to (ToType), we need to synthesize a call to the 7362 // conversion function and attempt copy initialization from it. This 7363 // makes sure that we get the right semantics with respect to 7364 // lvalues/rvalues and the type. Fortunately, we can allocate this 7365 // call on the stack and we don't need its arguments to be 7366 // well-formed. 7367 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7368 VK_LValue, From->getBeginLoc()); 7369 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7370 Context.getPointerType(Conversion->getType()), 7371 CK_FunctionToPointerDecay, &ConversionRef, 7372 VK_PRValue, FPOptionsOverride()); 7373 7374 QualType ConversionType = Conversion->getConversionType(); 7375 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7376 Candidate.Viable = false; 7377 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7378 return; 7379 } 7380 7381 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7382 7383 // Note that it is safe to allocate CallExpr on the stack here because 7384 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7385 // allocator). 7386 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7387 7388 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7389 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7390 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7391 7392 ImplicitConversionSequence ICS = 7393 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7394 /*SuppressUserConversions=*/true, 7395 /*InOverloadResolution=*/false, 7396 /*AllowObjCWritebackConversion=*/false); 7397 7398 switch (ICS.getKind()) { 7399 case ImplicitConversionSequence::StandardConversion: 7400 Candidate.FinalConversion = ICS.Standard; 7401 7402 // C++ [over.ics.user]p3: 7403 // If the user-defined conversion is specified by a specialization of a 7404 // conversion function template, the second standard conversion sequence 7405 // shall have exact match rank. 7406 if (Conversion->getPrimaryTemplate() && 7407 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7408 Candidate.Viable = false; 7409 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7410 return; 7411 } 7412 7413 // C++0x [dcl.init.ref]p5: 7414 // In the second case, if the reference is an rvalue reference and 7415 // the second standard conversion sequence of the user-defined 7416 // conversion sequence includes an lvalue-to-rvalue conversion, the 7417 // program is ill-formed. 7418 if (ToType->isRValueReferenceType() && 7419 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7420 Candidate.Viable = false; 7421 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7422 return; 7423 } 7424 break; 7425 7426 case ImplicitConversionSequence::BadConversion: 7427 Candidate.Viable = false; 7428 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7429 return; 7430 7431 default: 7432 llvm_unreachable( 7433 "Can only end up with a standard conversion sequence or failure"); 7434 } 7435 7436 if (EnableIfAttr *FailedAttr = 7437 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7438 Candidate.Viable = false; 7439 Candidate.FailureKind = ovl_fail_enable_if; 7440 Candidate.DeductionFailure.Data = FailedAttr; 7441 return; 7442 } 7443 7444 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7445 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7446 Candidate.Viable = false; 7447 Candidate.FailureKind = ovl_non_default_multiversion_function; 7448 } 7449 } 7450 7451 /// Adds a conversion function template specialization 7452 /// candidate to the overload set, using template argument deduction 7453 /// to deduce the template arguments of the conversion function 7454 /// template from the type that we are converting to (C++ 7455 /// [temp.deduct.conv]). 7456 void Sema::AddTemplateConversionCandidate( 7457 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7458 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7459 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7460 bool AllowExplicit, bool AllowResultConversion) { 7461 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7462 "Only conversion function templates permitted here"); 7463 7464 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7465 return; 7466 7467 // If the function template has a non-dependent explicit specification, 7468 // exclude it now if appropriate; we are not permitted to perform deduction 7469 // and substitution in this case. 7470 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7471 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7472 Candidate.FoundDecl = FoundDecl; 7473 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7474 Candidate.Viable = false; 7475 Candidate.FailureKind = ovl_fail_explicit; 7476 return; 7477 } 7478 7479 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7480 CXXConversionDecl *Specialization = nullptr; 7481 if (TemplateDeductionResult Result 7482 = DeduceTemplateArguments(FunctionTemplate, ToType, 7483 Specialization, Info)) { 7484 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7485 Candidate.FoundDecl = FoundDecl; 7486 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7487 Candidate.Viable = false; 7488 Candidate.FailureKind = ovl_fail_bad_deduction; 7489 Candidate.IsSurrogate = false; 7490 Candidate.IgnoreObjectArgument = false; 7491 Candidate.ExplicitCallArguments = 1; 7492 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7493 Info); 7494 return; 7495 } 7496 7497 // Add the conversion function template specialization produced by 7498 // template argument deduction as a candidate. 7499 assert(Specialization && "Missing function template specialization?"); 7500 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7501 CandidateSet, AllowObjCConversionOnExplicit, 7502 AllowExplicit, AllowResultConversion); 7503 } 7504 7505 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7506 /// converts the given @c Object to a function pointer via the 7507 /// conversion function @c Conversion, and then attempts to call it 7508 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7509 /// the type of function that we'll eventually be calling. 7510 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7511 DeclAccessPair FoundDecl, 7512 CXXRecordDecl *ActingContext, 7513 const FunctionProtoType *Proto, 7514 Expr *Object, 7515 ArrayRef<Expr *> Args, 7516 OverloadCandidateSet& CandidateSet) { 7517 if (!CandidateSet.isNewCandidate(Conversion)) 7518 return; 7519 7520 // Overload resolution is always an unevaluated context. 7521 EnterExpressionEvaluationContext Unevaluated( 7522 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7523 7524 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7525 Candidate.FoundDecl = FoundDecl; 7526 Candidate.Function = nullptr; 7527 Candidate.Surrogate = Conversion; 7528 Candidate.Viable = true; 7529 Candidate.IsSurrogate = true; 7530 Candidate.IgnoreObjectArgument = false; 7531 Candidate.ExplicitCallArguments = Args.size(); 7532 7533 // Determine the implicit conversion sequence for the implicit 7534 // object parameter. 7535 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7536 *this, CandidateSet.getLocation(), Object->getType(), 7537 Object->Classify(Context), Conversion, ActingContext); 7538 if (ObjectInit.isBad()) { 7539 Candidate.Viable = false; 7540 Candidate.FailureKind = ovl_fail_bad_conversion; 7541 Candidate.Conversions[0] = ObjectInit; 7542 return; 7543 } 7544 7545 // The first conversion is actually a user-defined conversion whose 7546 // first conversion is ObjectInit's standard conversion (which is 7547 // effectively a reference binding). Record it as such. 7548 Candidate.Conversions[0].setUserDefined(); 7549 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7550 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7551 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7552 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7553 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7554 Candidate.Conversions[0].UserDefined.After 7555 = Candidate.Conversions[0].UserDefined.Before; 7556 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7557 7558 // Find the 7559 unsigned NumParams = Proto->getNumParams(); 7560 7561 // (C++ 13.3.2p2): A candidate function having fewer than m 7562 // parameters is viable only if it has an ellipsis in its parameter 7563 // list (8.3.5). 7564 if (Args.size() > NumParams && !Proto->isVariadic()) { 7565 Candidate.Viable = false; 7566 Candidate.FailureKind = ovl_fail_too_many_arguments; 7567 return; 7568 } 7569 7570 // Function types don't have any default arguments, so just check if 7571 // we have enough arguments. 7572 if (Args.size() < NumParams) { 7573 // Not enough arguments. 7574 Candidate.Viable = false; 7575 Candidate.FailureKind = ovl_fail_too_few_arguments; 7576 return; 7577 } 7578 7579 // Determine the implicit conversion sequences for each of the 7580 // arguments. 7581 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7582 if (ArgIdx < NumParams) { 7583 // (C++ 13.3.2p3): for F to be a viable function, there shall 7584 // exist for each argument an implicit conversion sequence 7585 // (13.3.3.1) that converts that argument to the corresponding 7586 // parameter of F. 7587 QualType ParamType = Proto->getParamType(ArgIdx); 7588 Candidate.Conversions[ArgIdx + 1] 7589 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7590 /*SuppressUserConversions=*/false, 7591 /*InOverloadResolution=*/false, 7592 /*AllowObjCWritebackConversion=*/ 7593 getLangOpts().ObjCAutoRefCount); 7594 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7595 Candidate.Viable = false; 7596 Candidate.FailureKind = ovl_fail_bad_conversion; 7597 return; 7598 } 7599 } else { 7600 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7601 // argument for which there is no corresponding parameter is 7602 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7603 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7604 } 7605 } 7606 7607 if (EnableIfAttr *FailedAttr = 7608 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7609 Candidate.Viable = false; 7610 Candidate.FailureKind = ovl_fail_enable_if; 7611 Candidate.DeductionFailure.Data = FailedAttr; 7612 return; 7613 } 7614 } 7615 7616 /// Add all of the non-member operator function declarations in the given 7617 /// function set to the overload candidate set. 7618 void Sema::AddNonMemberOperatorCandidates( 7619 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7620 OverloadCandidateSet &CandidateSet, 7621 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7622 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7623 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7624 ArrayRef<Expr *> FunctionArgs = Args; 7625 7626 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7627 FunctionDecl *FD = 7628 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7629 7630 // Don't consider rewritten functions if we're not rewriting. 7631 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7632 continue; 7633 7634 assert(!isa<CXXMethodDecl>(FD) && 7635 "unqualified operator lookup found a member function"); 7636 7637 if (FunTmpl) { 7638 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7639 FunctionArgs, CandidateSet); 7640 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7641 AddTemplateOverloadCandidate( 7642 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7643 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7644 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7645 } else { 7646 if (ExplicitTemplateArgs) 7647 continue; 7648 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7649 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7650 AddOverloadCandidate(FD, F.getPair(), 7651 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7652 false, false, true, false, ADLCallKind::NotADL, 7653 None, OverloadCandidateParamOrder::Reversed); 7654 } 7655 } 7656 } 7657 7658 /// Add overload candidates for overloaded operators that are 7659 /// member functions. 7660 /// 7661 /// Add the overloaded operator candidates that are member functions 7662 /// for the operator Op that was used in an operator expression such 7663 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7664 /// CandidateSet will store the added overload candidates. (C++ 7665 /// [over.match.oper]). 7666 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7667 SourceLocation OpLoc, 7668 ArrayRef<Expr *> Args, 7669 OverloadCandidateSet &CandidateSet, 7670 OverloadCandidateParamOrder PO) { 7671 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7672 7673 // C++ [over.match.oper]p3: 7674 // For a unary operator @ with an operand of a type whose 7675 // cv-unqualified version is T1, and for a binary operator @ with 7676 // a left operand of a type whose cv-unqualified version is T1 and 7677 // a right operand of a type whose cv-unqualified version is T2, 7678 // three sets of candidate functions, designated member 7679 // candidates, non-member candidates and built-in candidates, are 7680 // constructed as follows: 7681 QualType T1 = Args[0]->getType(); 7682 7683 // -- If T1 is a complete class type or a class currently being 7684 // defined, the set of member candidates is the result of the 7685 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7686 // the set of member candidates is empty. 7687 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7688 // Complete the type if it can be completed. 7689 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7690 return; 7691 // If the type is neither complete nor being defined, bail out now. 7692 if (!T1Rec->getDecl()->getDefinition()) 7693 return; 7694 7695 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7696 LookupQualifiedName(Operators, T1Rec->getDecl()); 7697 Operators.suppressDiagnostics(); 7698 7699 for (LookupResult::iterator Oper = Operators.begin(), 7700 OperEnd = Operators.end(); 7701 Oper != OperEnd; 7702 ++Oper) 7703 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7704 Args[0]->Classify(Context), Args.slice(1), 7705 CandidateSet, /*SuppressUserConversion=*/false, PO); 7706 } 7707 } 7708 7709 /// AddBuiltinCandidate - Add a candidate for a built-in 7710 /// operator. ResultTy and ParamTys are the result and parameter types 7711 /// of the built-in candidate, respectively. Args and NumArgs are the 7712 /// arguments being passed to the candidate. IsAssignmentOperator 7713 /// should be true when this built-in candidate is an assignment 7714 /// operator. NumContextualBoolArguments is the number of arguments 7715 /// (at the beginning of the argument list) that will be contextually 7716 /// converted to bool. 7717 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7718 OverloadCandidateSet& CandidateSet, 7719 bool IsAssignmentOperator, 7720 unsigned NumContextualBoolArguments) { 7721 // Overload resolution is always an unevaluated context. 7722 EnterExpressionEvaluationContext Unevaluated( 7723 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7724 7725 // Add this candidate 7726 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7727 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7728 Candidate.Function = nullptr; 7729 Candidate.IsSurrogate = false; 7730 Candidate.IgnoreObjectArgument = false; 7731 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7732 7733 // Determine the implicit conversion sequences for each of the 7734 // arguments. 7735 Candidate.Viable = true; 7736 Candidate.ExplicitCallArguments = Args.size(); 7737 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7738 // C++ [over.match.oper]p4: 7739 // For the built-in assignment operators, conversions of the 7740 // left operand are restricted as follows: 7741 // -- no temporaries are introduced to hold the left operand, and 7742 // -- no user-defined conversions are applied to the left 7743 // operand to achieve a type match with the left-most 7744 // parameter of a built-in candidate. 7745 // 7746 // We block these conversions by turning off user-defined 7747 // conversions, since that is the only way that initialization of 7748 // a reference to a non-class type can occur from something that 7749 // is not of the same type. 7750 if (ArgIdx < NumContextualBoolArguments) { 7751 assert(ParamTys[ArgIdx] == Context.BoolTy && 7752 "Contextual conversion to bool requires bool type"); 7753 Candidate.Conversions[ArgIdx] 7754 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7755 } else { 7756 Candidate.Conversions[ArgIdx] 7757 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7758 ArgIdx == 0 && IsAssignmentOperator, 7759 /*InOverloadResolution=*/false, 7760 /*AllowObjCWritebackConversion=*/ 7761 getLangOpts().ObjCAutoRefCount); 7762 } 7763 if (Candidate.Conversions[ArgIdx].isBad()) { 7764 Candidate.Viable = false; 7765 Candidate.FailureKind = ovl_fail_bad_conversion; 7766 break; 7767 } 7768 } 7769 } 7770 7771 namespace { 7772 7773 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7774 /// candidate operator functions for built-in operators (C++ 7775 /// [over.built]). The types are separated into pointer types and 7776 /// enumeration types. 7777 class BuiltinCandidateTypeSet { 7778 /// TypeSet - A set of types. 7779 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7780 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7781 7782 /// PointerTypes - The set of pointer types that will be used in the 7783 /// built-in candidates. 7784 TypeSet PointerTypes; 7785 7786 /// MemberPointerTypes - The set of member pointer types that will be 7787 /// used in the built-in candidates. 7788 TypeSet MemberPointerTypes; 7789 7790 /// EnumerationTypes - The set of enumeration types that will be 7791 /// used in the built-in candidates. 7792 TypeSet EnumerationTypes; 7793 7794 /// The set of vector types that will be used in the built-in 7795 /// candidates. 7796 TypeSet VectorTypes; 7797 7798 /// The set of matrix types that will be used in the built-in 7799 /// candidates. 7800 TypeSet MatrixTypes; 7801 7802 /// A flag indicating non-record types are viable candidates 7803 bool HasNonRecordTypes; 7804 7805 /// A flag indicating whether either arithmetic or enumeration types 7806 /// were present in the candidate set. 7807 bool HasArithmeticOrEnumeralTypes; 7808 7809 /// A flag indicating whether the nullptr type was present in the 7810 /// candidate set. 7811 bool HasNullPtrType; 7812 7813 /// Sema - The semantic analysis instance where we are building the 7814 /// candidate type set. 7815 Sema &SemaRef; 7816 7817 /// Context - The AST context in which we will build the type sets. 7818 ASTContext &Context; 7819 7820 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7821 const Qualifiers &VisibleQuals); 7822 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7823 7824 public: 7825 /// iterator - Iterates through the types that are part of the set. 7826 typedef TypeSet::iterator iterator; 7827 7828 BuiltinCandidateTypeSet(Sema &SemaRef) 7829 : HasNonRecordTypes(false), 7830 HasArithmeticOrEnumeralTypes(false), 7831 HasNullPtrType(false), 7832 SemaRef(SemaRef), 7833 Context(SemaRef.Context) { } 7834 7835 void AddTypesConvertedFrom(QualType Ty, 7836 SourceLocation Loc, 7837 bool AllowUserConversions, 7838 bool AllowExplicitConversions, 7839 const Qualifiers &VisibleTypeConversionsQuals); 7840 7841 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7842 llvm::iterator_range<iterator> member_pointer_types() { 7843 return MemberPointerTypes; 7844 } 7845 llvm::iterator_range<iterator> enumeration_types() { 7846 return EnumerationTypes; 7847 } 7848 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7849 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7850 7851 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7852 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7853 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7854 bool hasNullPtrType() const { return HasNullPtrType; } 7855 }; 7856 7857 } // end anonymous namespace 7858 7859 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7860 /// the set of pointer types along with any more-qualified variants of 7861 /// that type. For example, if @p Ty is "int const *", this routine 7862 /// will add "int const *", "int const volatile *", "int const 7863 /// restrict *", and "int const volatile restrict *" to the set of 7864 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7865 /// false otherwise. 7866 /// 7867 /// FIXME: what to do about extended qualifiers? 7868 bool 7869 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7870 const Qualifiers &VisibleQuals) { 7871 7872 // Insert this type. 7873 if (!PointerTypes.insert(Ty)) 7874 return false; 7875 7876 QualType PointeeTy; 7877 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7878 bool buildObjCPtr = false; 7879 if (!PointerTy) { 7880 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7881 PointeeTy = PTy->getPointeeType(); 7882 buildObjCPtr = true; 7883 } else { 7884 PointeeTy = PointerTy->getPointeeType(); 7885 } 7886 7887 // Don't add qualified variants of arrays. For one, they're not allowed 7888 // (the qualifier would sink to the element type), and for another, the 7889 // only overload situation where it matters is subscript or pointer +- int, 7890 // and those shouldn't have qualifier variants anyway. 7891 if (PointeeTy->isArrayType()) 7892 return true; 7893 7894 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7895 bool hasVolatile = VisibleQuals.hasVolatile(); 7896 bool hasRestrict = VisibleQuals.hasRestrict(); 7897 7898 // Iterate through all strict supersets of BaseCVR. 7899 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7900 if ((CVR | BaseCVR) != CVR) continue; 7901 // Skip over volatile if no volatile found anywhere in the types. 7902 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7903 7904 // Skip over restrict if no restrict found anywhere in the types, or if 7905 // the type cannot be restrict-qualified. 7906 if ((CVR & Qualifiers::Restrict) && 7907 (!hasRestrict || 7908 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7909 continue; 7910 7911 // Build qualified pointee type. 7912 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7913 7914 // Build qualified pointer type. 7915 QualType QPointerTy; 7916 if (!buildObjCPtr) 7917 QPointerTy = Context.getPointerType(QPointeeTy); 7918 else 7919 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7920 7921 // Insert qualified pointer type. 7922 PointerTypes.insert(QPointerTy); 7923 } 7924 7925 return true; 7926 } 7927 7928 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7929 /// to the set of pointer types along with any more-qualified variants of 7930 /// that type. For example, if @p Ty is "int const *", this routine 7931 /// will add "int const *", "int const volatile *", "int const 7932 /// restrict *", and "int const volatile restrict *" to the set of 7933 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7934 /// false otherwise. 7935 /// 7936 /// FIXME: what to do about extended qualifiers? 7937 bool 7938 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7939 QualType Ty) { 7940 // Insert this type. 7941 if (!MemberPointerTypes.insert(Ty)) 7942 return false; 7943 7944 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7945 assert(PointerTy && "type was not a member pointer type!"); 7946 7947 QualType PointeeTy = PointerTy->getPointeeType(); 7948 // Don't add qualified variants of arrays. For one, they're not allowed 7949 // (the qualifier would sink to the element type), and for another, the 7950 // only overload situation where it matters is subscript or pointer +- int, 7951 // and those shouldn't have qualifier variants anyway. 7952 if (PointeeTy->isArrayType()) 7953 return true; 7954 const Type *ClassTy = PointerTy->getClass(); 7955 7956 // Iterate through all strict supersets of the pointee type's CVR 7957 // qualifiers. 7958 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7959 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7960 if ((CVR | BaseCVR) != CVR) continue; 7961 7962 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7963 MemberPointerTypes.insert( 7964 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7965 } 7966 7967 return true; 7968 } 7969 7970 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7971 /// Ty can be implicit converted to the given set of @p Types. We're 7972 /// primarily interested in pointer types and enumeration types. We also 7973 /// take member pointer types, for the conditional operator. 7974 /// AllowUserConversions is true if we should look at the conversion 7975 /// functions of a class type, and AllowExplicitConversions if we 7976 /// should also include the explicit conversion functions of a class 7977 /// type. 7978 void 7979 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7980 SourceLocation Loc, 7981 bool AllowUserConversions, 7982 bool AllowExplicitConversions, 7983 const Qualifiers &VisibleQuals) { 7984 // Only deal with canonical types. 7985 Ty = Context.getCanonicalType(Ty); 7986 7987 // Look through reference types; they aren't part of the type of an 7988 // expression for the purposes of conversions. 7989 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7990 Ty = RefTy->getPointeeType(); 7991 7992 // If we're dealing with an array type, decay to the pointer. 7993 if (Ty->isArrayType()) 7994 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7995 7996 // Otherwise, we don't care about qualifiers on the type. 7997 Ty = Ty.getLocalUnqualifiedType(); 7998 7999 // Flag if we ever add a non-record type. 8000 const RecordType *TyRec = Ty->getAs<RecordType>(); 8001 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8002 8003 // Flag if we encounter an arithmetic type. 8004 HasArithmeticOrEnumeralTypes = 8005 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8006 8007 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8008 PointerTypes.insert(Ty); 8009 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8010 // Insert our type, and its more-qualified variants, into the set 8011 // of types. 8012 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8013 return; 8014 } else if (Ty->isMemberPointerType()) { 8015 // Member pointers are far easier, since the pointee can't be converted. 8016 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8017 return; 8018 } else if (Ty->isEnumeralType()) { 8019 HasArithmeticOrEnumeralTypes = true; 8020 EnumerationTypes.insert(Ty); 8021 } else if (Ty->isVectorType()) { 8022 // We treat vector types as arithmetic types in many contexts as an 8023 // extension. 8024 HasArithmeticOrEnumeralTypes = true; 8025 VectorTypes.insert(Ty); 8026 } else if (Ty->isMatrixType()) { 8027 // Similar to vector types, we treat vector types as arithmetic types in 8028 // many contexts as an extension. 8029 HasArithmeticOrEnumeralTypes = true; 8030 MatrixTypes.insert(Ty); 8031 } else if (Ty->isNullPtrType()) { 8032 HasNullPtrType = true; 8033 } else if (AllowUserConversions && TyRec) { 8034 // No conversion functions in incomplete types. 8035 if (!SemaRef.isCompleteType(Loc, Ty)) 8036 return; 8037 8038 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8039 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8040 if (isa<UsingShadowDecl>(D)) 8041 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8042 8043 // Skip conversion function templates; they don't tell us anything 8044 // about which builtin types we can convert to. 8045 if (isa<FunctionTemplateDecl>(D)) 8046 continue; 8047 8048 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8049 if (AllowExplicitConversions || !Conv->isExplicit()) { 8050 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8051 VisibleQuals); 8052 } 8053 } 8054 } 8055 } 8056 /// Helper function for adjusting address spaces for the pointer or reference 8057 /// operands of builtin operators depending on the argument. 8058 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8059 Expr *Arg) { 8060 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8061 } 8062 8063 /// Helper function for AddBuiltinOperatorCandidates() that adds 8064 /// the volatile- and non-volatile-qualified assignment operators for the 8065 /// given type to the candidate set. 8066 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8067 QualType T, 8068 ArrayRef<Expr *> Args, 8069 OverloadCandidateSet &CandidateSet) { 8070 QualType ParamTypes[2]; 8071 8072 // T& operator=(T&, T) 8073 ParamTypes[0] = S.Context.getLValueReferenceType( 8074 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8075 ParamTypes[1] = T; 8076 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8077 /*IsAssignmentOperator=*/true); 8078 8079 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8080 // volatile T& operator=(volatile T&, T) 8081 ParamTypes[0] = S.Context.getLValueReferenceType( 8082 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8083 Args[0])); 8084 ParamTypes[1] = T; 8085 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8086 /*IsAssignmentOperator=*/true); 8087 } 8088 } 8089 8090 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8091 /// if any, found in visible type conversion functions found in ArgExpr's type. 8092 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8093 Qualifiers VRQuals; 8094 const RecordType *TyRec; 8095 if (const MemberPointerType *RHSMPType = 8096 ArgExpr->getType()->getAs<MemberPointerType>()) 8097 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8098 else 8099 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8100 if (!TyRec) { 8101 // Just to be safe, assume the worst case. 8102 VRQuals.addVolatile(); 8103 VRQuals.addRestrict(); 8104 return VRQuals; 8105 } 8106 8107 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8108 if (!ClassDecl->hasDefinition()) 8109 return VRQuals; 8110 8111 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8112 if (isa<UsingShadowDecl>(D)) 8113 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8114 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8115 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8116 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8117 CanTy = ResTypeRef->getPointeeType(); 8118 // Need to go down the pointer/mempointer chain and add qualifiers 8119 // as see them. 8120 bool done = false; 8121 while (!done) { 8122 if (CanTy.isRestrictQualified()) 8123 VRQuals.addRestrict(); 8124 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8125 CanTy = ResTypePtr->getPointeeType(); 8126 else if (const MemberPointerType *ResTypeMPtr = 8127 CanTy->getAs<MemberPointerType>()) 8128 CanTy = ResTypeMPtr->getPointeeType(); 8129 else 8130 done = true; 8131 if (CanTy.isVolatileQualified()) 8132 VRQuals.addVolatile(); 8133 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8134 return VRQuals; 8135 } 8136 } 8137 } 8138 return VRQuals; 8139 } 8140 8141 namespace { 8142 8143 /// Helper class to manage the addition of builtin operator overload 8144 /// candidates. It provides shared state and utility methods used throughout 8145 /// the process, as well as a helper method to add each group of builtin 8146 /// operator overloads from the standard to a candidate set. 8147 class BuiltinOperatorOverloadBuilder { 8148 // Common instance state available to all overload candidate addition methods. 8149 Sema &S; 8150 ArrayRef<Expr *> Args; 8151 Qualifiers VisibleTypeConversionsQuals; 8152 bool HasArithmeticOrEnumeralCandidateType; 8153 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8154 OverloadCandidateSet &CandidateSet; 8155 8156 static constexpr int ArithmeticTypesCap = 24; 8157 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8158 8159 // Define some indices used to iterate over the arithmetic types in 8160 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8161 // types are that preserved by promotion (C++ [over.built]p2). 8162 unsigned FirstIntegralType, 8163 LastIntegralType; 8164 unsigned FirstPromotedIntegralType, 8165 LastPromotedIntegralType; 8166 unsigned FirstPromotedArithmeticType, 8167 LastPromotedArithmeticType; 8168 unsigned NumArithmeticTypes; 8169 8170 void InitArithmeticTypes() { 8171 // Start of promoted types. 8172 FirstPromotedArithmeticType = 0; 8173 ArithmeticTypes.push_back(S.Context.FloatTy); 8174 ArithmeticTypes.push_back(S.Context.DoubleTy); 8175 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8176 if (S.Context.getTargetInfo().hasFloat128Type()) 8177 ArithmeticTypes.push_back(S.Context.Float128Ty); 8178 if (S.Context.getTargetInfo().hasIbm128Type()) 8179 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8180 8181 // Start of integral types. 8182 FirstIntegralType = ArithmeticTypes.size(); 8183 FirstPromotedIntegralType = ArithmeticTypes.size(); 8184 ArithmeticTypes.push_back(S.Context.IntTy); 8185 ArithmeticTypes.push_back(S.Context.LongTy); 8186 ArithmeticTypes.push_back(S.Context.LongLongTy); 8187 if (S.Context.getTargetInfo().hasInt128Type() || 8188 (S.Context.getAuxTargetInfo() && 8189 S.Context.getAuxTargetInfo()->hasInt128Type())) 8190 ArithmeticTypes.push_back(S.Context.Int128Ty); 8191 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8192 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8193 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8194 if (S.Context.getTargetInfo().hasInt128Type() || 8195 (S.Context.getAuxTargetInfo() && 8196 S.Context.getAuxTargetInfo()->hasInt128Type())) 8197 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8198 LastPromotedIntegralType = ArithmeticTypes.size(); 8199 LastPromotedArithmeticType = ArithmeticTypes.size(); 8200 // End of promoted types. 8201 8202 ArithmeticTypes.push_back(S.Context.BoolTy); 8203 ArithmeticTypes.push_back(S.Context.CharTy); 8204 ArithmeticTypes.push_back(S.Context.WCharTy); 8205 if (S.Context.getLangOpts().Char8) 8206 ArithmeticTypes.push_back(S.Context.Char8Ty); 8207 ArithmeticTypes.push_back(S.Context.Char16Ty); 8208 ArithmeticTypes.push_back(S.Context.Char32Ty); 8209 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8210 ArithmeticTypes.push_back(S.Context.ShortTy); 8211 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8212 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8213 LastIntegralType = ArithmeticTypes.size(); 8214 NumArithmeticTypes = ArithmeticTypes.size(); 8215 // End of integral types. 8216 // FIXME: What about complex? What about half? 8217 8218 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8219 "Enough inline storage for all arithmetic types."); 8220 } 8221 8222 /// Helper method to factor out the common pattern of adding overloads 8223 /// for '++' and '--' builtin operators. 8224 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8225 bool HasVolatile, 8226 bool HasRestrict) { 8227 QualType ParamTypes[2] = { 8228 S.Context.getLValueReferenceType(CandidateTy), 8229 S.Context.IntTy 8230 }; 8231 8232 // Non-volatile version. 8233 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8234 8235 // Use a heuristic to reduce number of builtin candidates in the set: 8236 // add volatile version only if there are conversions to a volatile type. 8237 if (HasVolatile) { 8238 ParamTypes[0] = 8239 S.Context.getLValueReferenceType( 8240 S.Context.getVolatileType(CandidateTy)); 8241 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8242 } 8243 8244 // Add restrict version only if there are conversions to a restrict type 8245 // and our candidate type is a non-restrict-qualified pointer. 8246 if (HasRestrict && CandidateTy->isAnyPointerType() && 8247 !CandidateTy.isRestrictQualified()) { 8248 ParamTypes[0] 8249 = S.Context.getLValueReferenceType( 8250 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8251 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8252 8253 if (HasVolatile) { 8254 ParamTypes[0] 8255 = S.Context.getLValueReferenceType( 8256 S.Context.getCVRQualifiedType(CandidateTy, 8257 (Qualifiers::Volatile | 8258 Qualifiers::Restrict))); 8259 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8260 } 8261 } 8262 8263 } 8264 8265 /// Helper to add an overload candidate for a binary builtin with types \p L 8266 /// and \p R. 8267 void AddCandidate(QualType L, QualType R) { 8268 QualType LandR[2] = {L, R}; 8269 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8270 } 8271 8272 public: 8273 BuiltinOperatorOverloadBuilder( 8274 Sema &S, ArrayRef<Expr *> Args, 8275 Qualifiers VisibleTypeConversionsQuals, 8276 bool HasArithmeticOrEnumeralCandidateType, 8277 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8278 OverloadCandidateSet &CandidateSet) 8279 : S(S), Args(Args), 8280 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8281 HasArithmeticOrEnumeralCandidateType( 8282 HasArithmeticOrEnumeralCandidateType), 8283 CandidateTypes(CandidateTypes), 8284 CandidateSet(CandidateSet) { 8285 8286 InitArithmeticTypes(); 8287 } 8288 8289 // Increment is deprecated for bool since C++17. 8290 // 8291 // C++ [over.built]p3: 8292 // 8293 // For every pair (T, VQ), where T is an arithmetic type other 8294 // than bool, and VQ is either volatile or empty, there exist 8295 // candidate operator functions of the form 8296 // 8297 // VQ T& operator++(VQ T&); 8298 // T operator++(VQ T&, int); 8299 // 8300 // C++ [over.built]p4: 8301 // 8302 // For every pair (T, VQ), where T is an arithmetic type other 8303 // than bool, and VQ is either volatile or empty, there exist 8304 // candidate operator functions of the form 8305 // 8306 // VQ T& operator--(VQ T&); 8307 // T operator--(VQ T&, int); 8308 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8309 if (!HasArithmeticOrEnumeralCandidateType) 8310 return; 8311 8312 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8313 const auto TypeOfT = ArithmeticTypes[Arith]; 8314 if (TypeOfT == S.Context.BoolTy) { 8315 if (Op == OO_MinusMinus) 8316 continue; 8317 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8318 continue; 8319 } 8320 addPlusPlusMinusMinusStyleOverloads( 8321 TypeOfT, 8322 VisibleTypeConversionsQuals.hasVolatile(), 8323 VisibleTypeConversionsQuals.hasRestrict()); 8324 } 8325 } 8326 8327 // C++ [over.built]p5: 8328 // 8329 // For every pair (T, VQ), where T is a cv-qualified or 8330 // cv-unqualified object type, and VQ is either volatile or 8331 // empty, there exist candidate operator functions of the form 8332 // 8333 // T*VQ& operator++(T*VQ&); 8334 // T*VQ& operator--(T*VQ&); 8335 // T* operator++(T*VQ&, int); 8336 // T* operator--(T*VQ&, int); 8337 void addPlusPlusMinusMinusPointerOverloads() { 8338 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8339 // Skip pointer types that aren't pointers to object types. 8340 if (!PtrTy->getPointeeType()->isObjectType()) 8341 continue; 8342 8343 addPlusPlusMinusMinusStyleOverloads( 8344 PtrTy, 8345 (!PtrTy.isVolatileQualified() && 8346 VisibleTypeConversionsQuals.hasVolatile()), 8347 (!PtrTy.isRestrictQualified() && 8348 VisibleTypeConversionsQuals.hasRestrict())); 8349 } 8350 } 8351 8352 // C++ [over.built]p6: 8353 // For every cv-qualified or cv-unqualified object type T, there 8354 // exist candidate operator functions of the form 8355 // 8356 // T& operator*(T*); 8357 // 8358 // C++ [over.built]p7: 8359 // For every function type T that does not have cv-qualifiers or a 8360 // ref-qualifier, there exist candidate operator functions of the form 8361 // T& operator*(T*); 8362 void addUnaryStarPointerOverloads() { 8363 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8364 QualType PointeeTy = ParamTy->getPointeeType(); 8365 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8366 continue; 8367 8368 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8369 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8370 continue; 8371 8372 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8373 } 8374 } 8375 8376 // C++ [over.built]p9: 8377 // For every promoted arithmetic type T, there exist candidate 8378 // operator functions of the form 8379 // 8380 // T operator+(T); 8381 // T operator-(T); 8382 void addUnaryPlusOrMinusArithmeticOverloads() { 8383 if (!HasArithmeticOrEnumeralCandidateType) 8384 return; 8385 8386 for (unsigned Arith = FirstPromotedArithmeticType; 8387 Arith < LastPromotedArithmeticType; ++Arith) { 8388 QualType ArithTy = ArithmeticTypes[Arith]; 8389 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8390 } 8391 8392 // Extension: We also add these operators for vector types. 8393 for (QualType VecTy : CandidateTypes[0].vector_types()) 8394 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8395 } 8396 8397 // C++ [over.built]p8: 8398 // For every type T, there exist candidate operator functions of 8399 // the form 8400 // 8401 // T* operator+(T*); 8402 void addUnaryPlusPointerOverloads() { 8403 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8404 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8405 } 8406 8407 // C++ [over.built]p10: 8408 // For every promoted integral type T, there exist candidate 8409 // operator functions of the form 8410 // 8411 // T operator~(T); 8412 void addUnaryTildePromotedIntegralOverloads() { 8413 if (!HasArithmeticOrEnumeralCandidateType) 8414 return; 8415 8416 for (unsigned Int = FirstPromotedIntegralType; 8417 Int < LastPromotedIntegralType; ++Int) { 8418 QualType IntTy = ArithmeticTypes[Int]; 8419 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8420 } 8421 8422 // Extension: We also add this operator for vector types. 8423 for (QualType VecTy : CandidateTypes[0].vector_types()) 8424 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8425 } 8426 8427 // C++ [over.match.oper]p16: 8428 // For every pointer to member type T or type std::nullptr_t, there 8429 // exist candidate operator functions of the form 8430 // 8431 // bool operator==(T,T); 8432 // bool operator!=(T,T); 8433 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8434 /// Set of (canonical) types that we've already handled. 8435 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8436 8437 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8438 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8439 // Don't add the same builtin candidate twice. 8440 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8441 continue; 8442 8443 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8444 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8445 } 8446 8447 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8448 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8449 if (AddedTypes.insert(NullPtrTy).second) { 8450 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8451 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8452 } 8453 } 8454 } 8455 } 8456 8457 // C++ [over.built]p15: 8458 // 8459 // For every T, where T is an enumeration type or a pointer type, 8460 // there exist candidate operator functions of the form 8461 // 8462 // bool operator<(T, T); 8463 // bool operator>(T, T); 8464 // bool operator<=(T, T); 8465 // bool operator>=(T, T); 8466 // bool operator==(T, T); 8467 // bool operator!=(T, T); 8468 // R operator<=>(T, T) 8469 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 8470 // C++ [over.match.oper]p3: 8471 // [...]the built-in candidates include all of the candidate operator 8472 // functions defined in 13.6 that, compared to the given operator, [...] 8473 // do not have the same parameter-type-list as any non-template non-member 8474 // candidate. 8475 // 8476 // Note that in practice, this only affects enumeration types because there 8477 // aren't any built-in candidates of record type, and a user-defined operator 8478 // must have an operand of record or enumeration type. Also, the only other 8479 // overloaded operator with enumeration arguments, operator=, 8480 // cannot be overloaded for enumeration types, so this is the only place 8481 // where we must suppress candidates like this. 8482 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8483 UserDefinedBinaryOperators; 8484 8485 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8486 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8487 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8488 CEnd = CandidateSet.end(); 8489 C != CEnd; ++C) { 8490 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8491 continue; 8492 8493 if (C->Function->isFunctionTemplateSpecialization()) 8494 continue; 8495 8496 // We interpret "same parameter-type-list" as applying to the 8497 // "synthesized candidate, with the order of the two parameters 8498 // reversed", not to the original function. 8499 bool Reversed = C->isReversed(); 8500 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8501 ->getType() 8502 .getUnqualifiedType(); 8503 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8504 ->getType() 8505 .getUnqualifiedType(); 8506 8507 // Skip if either parameter isn't of enumeral type. 8508 if (!FirstParamType->isEnumeralType() || 8509 !SecondParamType->isEnumeralType()) 8510 continue; 8511 8512 // Add this operator to the set of known user-defined operators. 8513 UserDefinedBinaryOperators.insert( 8514 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8515 S.Context.getCanonicalType(SecondParamType))); 8516 } 8517 } 8518 } 8519 8520 /// Set of (canonical) types that we've already handled. 8521 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8522 8523 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8524 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8525 // Don't add the same builtin candidate twice. 8526 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8527 continue; 8528 if (IsSpaceship && PtrTy->isFunctionPointerType()) 8529 continue; 8530 8531 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8532 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8533 } 8534 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8535 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8536 8537 // Don't add the same builtin candidate twice, or if a user defined 8538 // candidate exists. 8539 if (!AddedTypes.insert(CanonType).second || 8540 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8541 CanonType))) 8542 continue; 8543 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8544 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8545 } 8546 } 8547 } 8548 8549 // C++ [over.built]p13: 8550 // 8551 // For every cv-qualified or cv-unqualified object type T 8552 // there exist candidate operator functions of the form 8553 // 8554 // T* operator+(T*, ptrdiff_t); 8555 // T& operator[](T*, ptrdiff_t); [BELOW] 8556 // T* operator-(T*, ptrdiff_t); 8557 // T* operator+(ptrdiff_t, T*); 8558 // T& operator[](ptrdiff_t, T*); [BELOW] 8559 // 8560 // C++ [over.built]p14: 8561 // 8562 // For every T, where T is a pointer to object type, there 8563 // exist candidate operator functions of the form 8564 // 8565 // ptrdiff_t operator-(T, T); 8566 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8567 /// Set of (canonical) types that we've already handled. 8568 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8569 8570 for (int Arg = 0; Arg < 2; ++Arg) { 8571 QualType AsymmetricParamTypes[2] = { 8572 S.Context.getPointerDiffType(), 8573 S.Context.getPointerDiffType(), 8574 }; 8575 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8576 QualType PointeeTy = PtrTy->getPointeeType(); 8577 if (!PointeeTy->isObjectType()) 8578 continue; 8579 8580 AsymmetricParamTypes[Arg] = PtrTy; 8581 if (Arg == 0 || Op == OO_Plus) { 8582 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8583 // T* operator+(ptrdiff_t, T*); 8584 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8585 } 8586 if (Op == OO_Minus) { 8587 // ptrdiff_t operator-(T, T); 8588 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8589 continue; 8590 8591 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8592 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8593 } 8594 } 8595 } 8596 } 8597 8598 // C++ [over.built]p12: 8599 // 8600 // For every pair of promoted arithmetic types L and R, there 8601 // exist candidate operator functions of the form 8602 // 8603 // LR operator*(L, R); 8604 // LR operator/(L, R); 8605 // LR operator+(L, R); 8606 // LR operator-(L, R); 8607 // bool operator<(L, R); 8608 // bool operator>(L, R); 8609 // bool operator<=(L, R); 8610 // bool operator>=(L, R); 8611 // bool operator==(L, R); 8612 // bool operator!=(L, R); 8613 // 8614 // where LR is the result of the usual arithmetic conversions 8615 // between types L and R. 8616 // 8617 // C++ [over.built]p24: 8618 // 8619 // For every pair of promoted arithmetic types L and R, there exist 8620 // candidate operator functions of the form 8621 // 8622 // LR operator?(bool, L, R); 8623 // 8624 // where LR is the result of the usual arithmetic conversions 8625 // between types L and R. 8626 // Our candidates ignore the first parameter. 8627 void addGenericBinaryArithmeticOverloads() { 8628 if (!HasArithmeticOrEnumeralCandidateType) 8629 return; 8630 8631 for (unsigned Left = FirstPromotedArithmeticType; 8632 Left < LastPromotedArithmeticType; ++Left) { 8633 for (unsigned Right = FirstPromotedArithmeticType; 8634 Right < LastPromotedArithmeticType; ++Right) { 8635 QualType LandR[2] = { ArithmeticTypes[Left], 8636 ArithmeticTypes[Right] }; 8637 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8638 } 8639 } 8640 8641 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8642 // conditional operator for vector types. 8643 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8644 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8645 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8646 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8647 } 8648 } 8649 8650 /// Add binary operator overloads for each candidate matrix type M1, M2: 8651 /// * (M1, M1) -> M1 8652 /// * (M1, M1.getElementType()) -> M1 8653 /// * (M2.getElementType(), M2) -> M2 8654 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8655 void addMatrixBinaryArithmeticOverloads() { 8656 if (!HasArithmeticOrEnumeralCandidateType) 8657 return; 8658 8659 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8660 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8661 AddCandidate(M1, M1); 8662 } 8663 8664 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8665 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8666 if (!CandidateTypes[0].containsMatrixType(M2)) 8667 AddCandidate(M2, M2); 8668 } 8669 } 8670 8671 // C++2a [over.built]p14: 8672 // 8673 // For every integral type T there exists a candidate operator function 8674 // of the form 8675 // 8676 // std::strong_ordering operator<=>(T, T) 8677 // 8678 // C++2a [over.built]p15: 8679 // 8680 // For every pair of floating-point types L and R, there exists a candidate 8681 // operator function of the form 8682 // 8683 // std::partial_ordering operator<=>(L, R); 8684 // 8685 // FIXME: The current specification for integral types doesn't play nice with 8686 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8687 // comparisons. Under the current spec this can lead to ambiguity during 8688 // overload resolution. For example: 8689 // 8690 // enum A : int {a}; 8691 // auto x = (a <=> (long)42); 8692 // 8693 // error: call is ambiguous for arguments 'A' and 'long'. 8694 // note: candidate operator<=>(int, int) 8695 // note: candidate operator<=>(long, long) 8696 // 8697 // To avoid this error, this function deviates from the specification and adds 8698 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8699 // arithmetic types (the same as the generic relational overloads). 8700 // 8701 // For now this function acts as a placeholder. 8702 void addThreeWayArithmeticOverloads() { 8703 addGenericBinaryArithmeticOverloads(); 8704 } 8705 8706 // C++ [over.built]p17: 8707 // 8708 // For every pair of promoted integral types L and R, there 8709 // exist candidate operator functions of the form 8710 // 8711 // LR operator%(L, R); 8712 // LR operator&(L, R); 8713 // LR operator^(L, R); 8714 // LR operator|(L, R); 8715 // L operator<<(L, R); 8716 // L operator>>(L, R); 8717 // 8718 // where LR is the result of the usual arithmetic conversions 8719 // between types L and R. 8720 void addBinaryBitwiseArithmeticOverloads() { 8721 if (!HasArithmeticOrEnumeralCandidateType) 8722 return; 8723 8724 for (unsigned Left = FirstPromotedIntegralType; 8725 Left < LastPromotedIntegralType; ++Left) { 8726 for (unsigned Right = FirstPromotedIntegralType; 8727 Right < LastPromotedIntegralType; ++Right) { 8728 QualType LandR[2] = { ArithmeticTypes[Left], 8729 ArithmeticTypes[Right] }; 8730 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8731 } 8732 } 8733 } 8734 8735 // C++ [over.built]p20: 8736 // 8737 // For every pair (T, VQ), where T is an enumeration or 8738 // pointer to member type and VQ is either volatile or 8739 // empty, there exist candidate operator functions of the form 8740 // 8741 // VQ T& operator=(VQ T&, T); 8742 void addAssignmentMemberPointerOrEnumeralOverloads() { 8743 /// Set of (canonical) types that we've already handled. 8744 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8745 8746 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8747 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8748 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8749 continue; 8750 8751 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8752 } 8753 8754 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8755 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8756 continue; 8757 8758 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8759 } 8760 } 8761 } 8762 8763 // C++ [over.built]p19: 8764 // 8765 // For every pair (T, VQ), where T is any type and VQ is either 8766 // volatile or empty, there exist candidate operator functions 8767 // of the form 8768 // 8769 // T*VQ& operator=(T*VQ&, T*); 8770 // 8771 // C++ [over.built]p21: 8772 // 8773 // For every pair (T, VQ), where T is a cv-qualified or 8774 // cv-unqualified object type and VQ is either volatile or 8775 // empty, there exist candidate operator functions of the form 8776 // 8777 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8778 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8779 void addAssignmentPointerOverloads(bool isEqualOp) { 8780 /// Set of (canonical) types that we've already handled. 8781 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8782 8783 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8784 // If this is operator=, keep track of the builtin candidates we added. 8785 if (isEqualOp) 8786 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8787 else if (!PtrTy->getPointeeType()->isObjectType()) 8788 continue; 8789 8790 // non-volatile version 8791 QualType ParamTypes[2] = { 8792 S.Context.getLValueReferenceType(PtrTy), 8793 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8794 }; 8795 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8796 /*IsAssignmentOperator=*/ isEqualOp); 8797 8798 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8799 VisibleTypeConversionsQuals.hasVolatile(); 8800 if (NeedVolatile) { 8801 // volatile version 8802 ParamTypes[0] = 8803 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8804 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8805 /*IsAssignmentOperator=*/isEqualOp); 8806 } 8807 8808 if (!PtrTy.isRestrictQualified() && 8809 VisibleTypeConversionsQuals.hasRestrict()) { 8810 // restrict version 8811 ParamTypes[0] = 8812 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8813 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8814 /*IsAssignmentOperator=*/isEqualOp); 8815 8816 if (NeedVolatile) { 8817 // volatile restrict version 8818 ParamTypes[0] = 8819 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8820 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8821 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8822 /*IsAssignmentOperator=*/isEqualOp); 8823 } 8824 } 8825 } 8826 8827 if (isEqualOp) { 8828 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8829 // Make sure we don't add the same candidate twice. 8830 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8831 continue; 8832 8833 QualType ParamTypes[2] = { 8834 S.Context.getLValueReferenceType(PtrTy), 8835 PtrTy, 8836 }; 8837 8838 // non-volatile version 8839 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8840 /*IsAssignmentOperator=*/true); 8841 8842 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8843 VisibleTypeConversionsQuals.hasVolatile(); 8844 if (NeedVolatile) { 8845 // volatile version 8846 ParamTypes[0] = S.Context.getLValueReferenceType( 8847 S.Context.getVolatileType(PtrTy)); 8848 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8849 /*IsAssignmentOperator=*/true); 8850 } 8851 8852 if (!PtrTy.isRestrictQualified() && 8853 VisibleTypeConversionsQuals.hasRestrict()) { 8854 // restrict version 8855 ParamTypes[0] = S.Context.getLValueReferenceType( 8856 S.Context.getRestrictType(PtrTy)); 8857 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8858 /*IsAssignmentOperator=*/true); 8859 8860 if (NeedVolatile) { 8861 // volatile restrict version 8862 ParamTypes[0] = 8863 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8864 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8865 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8866 /*IsAssignmentOperator=*/true); 8867 } 8868 } 8869 } 8870 } 8871 } 8872 8873 // C++ [over.built]p18: 8874 // 8875 // For every triple (L, VQ, R), where L is an arithmetic type, 8876 // VQ is either volatile or empty, and R is a promoted 8877 // arithmetic type, there exist candidate operator functions of 8878 // the form 8879 // 8880 // VQ L& operator=(VQ L&, R); 8881 // VQ L& operator*=(VQ L&, R); 8882 // VQ L& operator/=(VQ L&, R); 8883 // VQ L& operator+=(VQ L&, R); 8884 // VQ L& operator-=(VQ L&, R); 8885 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8886 if (!HasArithmeticOrEnumeralCandidateType) 8887 return; 8888 8889 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8890 for (unsigned Right = FirstPromotedArithmeticType; 8891 Right < LastPromotedArithmeticType; ++Right) { 8892 QualType ParamTypes[2]; 8893 ParamTypes[1] = ArithmeticTypes[Right]; 8894 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8895 S, ArithmeticTypes[Left], Args[0]); 8896 // Add this built-in operator as a candidate (VQ is empty). 8897 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8898 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8899 /*IsAssignmentOperator=*/isEqualOp); 8900 8901 // Add this built-in operator as a candidate (VQ is 'volatile'). 8902 if (VisibleTypeConversionsQuals.hasVolatile()) { 8903 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8904 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8905 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8906 /*IsAssignmentOperator=*/isEqualOp); 8907 } 8908 } 8909 } 8910 8911 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8912 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8913 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8914 QualType ParamTypes[2]; 8915 ParamTypes[1] = Vec2Ty; 8916 // Add this built-in operator as a candidate (VQ is empty). 8917 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8918 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8919 /*IsAssignmentOperator=*/isEqualOp); 8920 8921 // Add this built-in operator as a candidate (VQ is 'volatile'). 8922 if (VisibleTypeConversionsQuals.hasVolatile()) { 8923 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8924 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8925 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8926 /*IsAssignmentOperator=*/isEqualOp); 8927 } 8928 } 8929 } 8930 8931 // C++ [over.built]p22: 8932 // 8933 // For every triple (L, VQ, R), where L is an integral type, VQ 8934 // is either volatile or empty, and R is a promoted integral 8935 // type, there exist candidate operator functions of the form 8936 // 8937 // VQ L& operator%=(VQ L&, R); 8938 // VQ L& operator<<=(VQ L&, R); 8939 // VQ L& operator>>=(VQ L&, R); 8940 // VQ L& operator&=(VQ L&, R); 8941 // VQ L& operator^=(VQ L&, R); 8942 // VQ L& operator|=(VQ L&, R); 8943 void addAssignmentIntegralOverloads() { 8944 if (!HasArithmeticOrEnumeralCandidateType) 8945 return; 8946 8947 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8948 for (unsigned Right = FirstPromotedIntegralType; 8949 Right < LastPromotedIntegralType; ++Right) { 8950 QualType ParamTypes[2]; 8951 ParamTypes[1] = ArithmeticTypes[Right]; 8952 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8953 S, ArithmeticTypes[Left], Args[0]); 8954 // Add this built-in operator as a candidate (VQ is empty). 8955 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8956 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8957 if (VisibleTypeConversionsQuals.hasVolatile()) { 8958 // Add this built-in operator as a candidate (VQ is 'volatile'). 8959 ParamTypes[0] = LeftBaseTy; 8960 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8961 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8963 } 8964 } 8965 } 8966 } 8967 8968 // C++ [over.operator]p23: 8969 // 8970 // There also exist candidate operator functions of the form 8971 // 8972 // bool operator!(bool); 8973 // bool operator&&(bool, bool); 8974 // bool operator||(bool, bool); 8975 void addExclaimOverload() { 8976 QualType ParamTy = S.Context.BoolTy; 8977 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8978 /*IsAssignmentOperator=*/false, 8979 /*NumContextualBoolArguments=*/1); 8980 } 8981 void addAmpAmpOrPipePipeOverload() { 8982 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8983 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8984 /*IsAssignmentOperator=*/false, 8985 /*NumContextualBoolArguments=*/2); 8986 } 8987 8988 // C++ [over.built]p13: 8989 // 8990 // For every cv-qualified or cv-unqualified object type T there 8991 // exist candidate operator functions of the form 8992 // 8993 // T* operator+(T*, ptrdiff_t); [ABOVE] 8994 // T& operator[](T*, ptrdiff_t); 8995 // T* operator-(T*, ptrdiff_t); [ABOVE] 8996 // T* operator+(ptrdiff_t, T*); [ABOVE] 8997 // T& operator[](ptrdiff_t, T*); 8998 void addSubscriptOverloads() { 8999 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9000 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9001 QualType PointeeType = PtrTy->getPointeeType(); 9002 if (!PointeeType->isObjectType()) 9003 continue; 9004 9005 // T& operator[](T*, ptrdiff_t) 9006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9007 } 9008 9009 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9010 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9011 QualType PointeeType = PtrTy->getPointeeType(); 9012 if (!PointeeType->isObjectType()) 9013 continue; 9014 9015 // T& operator[](ptrdiff_t, T*) 9016 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9017 } 9018 } 9019 9020 // C++ [over.built]p11: 9021 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9022 // C1 is the same type as C2 or is a derived class of C2, T is an object 9023 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9024 // there exist candidate operator functions of the form 9025 // 9026 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9027 // 9028 // where CV12 is the union of CV1 and CV2. 9029 void addArrowStarOverloads() { 9030 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9031 QualType C1Ty = PtrTy; 9032 QualType C1; 9033 QualifierCollector Q1; 9034 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9035 if (!isa<RecordType>(C1)) 9036 continue; 9037 // heuristic to reduce number of builtin candidates in the set. 9038 // Add volatile/restrict version only if there are conversions to a 9039 // volatile/restrict type. 9040 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9041 continue; 9042 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9043 continue; 9044 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9045 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9046 QualType C2 = QualType(mptr->getClass(), 0); 9047 C2 = C2.getUnqualifiedType(); 9048 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9049 break; 9050 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9051 // build CV12 T& 9052 QualType T = mptr->getPointeeType(); 9053 if (!VisibleTypeConversionsQuals.hasVolatile() && 9054 T.isVolatileQualified()) 9055 continue; 9056 if (!VisibleTypeConversionsQuals.hasRestrict() && 9057 T.isRestrictQualified()) 9058 continue; 9059 T = Q1.apply(S.Context, T); 9060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9061 } 9062 } 9063 } 9064 9065 // Note that we don't consider the first argument, since it has been 9066 // contextually converted to bool long ago. The candidates below are 9067 // therefore added as binary. 9068 // 9069 // C++ [over.built]p25: 9070 // For every type T, where T is a pointer, pointer-to-member, or scoped 9071 // enumeration type, there exist candidate operator functions of the form 9072 // 9073 // T operator?(bool, T, T); 9074 // 9075 void addConditionalOperatorOverloads() { 9076 /// Set of (canonical) types that we've already handled. 9077 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9078 9079 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9080 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9081 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9082 continue; 9083 9084 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9085 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9086 } 9087 9088 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9089 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9090 continue; 9091 9092 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9093 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9094 } 9095 9096 if (S.getLangOpts().CPlusPlus11) { 9097 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9098 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9099 continue; 9100 9101 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9102 continue; 9103 9104 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9105 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9106 } 9107 } 9108 } 9109 } 9110 }; 9111 9112 } // end anonymous namespace 9113 9114 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9115 /// operator overloads to the candidate set (C++ [over.built]), based 9116 /// on the operator @p Op and the arguments given. For example, if the 9117 /// operator is a binary '+', this routine might add "int 9118 /// operator+(int, int)" to cover integer addition. 9119 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9120 SourceLocation OpLoc, 9121 ArrayRef<Expr *> Args, 9122 OverloadCandidateSet &CandidateSet) { 9123 // Find all of the types that the arguments can convert to, but only 9124 // if the operator we're looking at has built-in operator candidates 9125 // that make use of these types. Also record whether we encounter non-record 9126 // candidate types or either arithmetic or enumeral candidate types. 9127 Qualifiers VisibleTypeConversionsQuals; 9128 VisibleTypeConversionsQuals.addConst(); 9129 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9130 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9131 9132 bool HasNonRecordCandidateType = false; 9133 bool HasArithmeticOrEnumeralCandidateType = false; 9134 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9135 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9136 CandidateTypes.emplace_back(*this); 9137 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9138 OpLoc, 9139 true, 9140 (Op == OO_Exclaim || 9141 Op == OO_AmpAmp || 9142 Op == OO_PipePipe), 9143 VisibleTypeConversionsQuals); 9144 HasNonRecordCandidateType = HasNonRecordCandidateType || 9145 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9146 HasArithmeticOrEnumeralCandidateType = 9147 HasArithmeticOrEnumeralCandidateType || 9148 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9149 } 9150 9151 // Exit early when no non-record types have been added to the candidate set 9152 // for any of the arguments to the operator. 9153 // 9154 // We can't exit early for !, ||, or &&, since there we have always have 9155 // 'bool' overloads. 9156 if (!HasNonRecordCandidateType && 9157 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9158 return; 9159 9160 // Setup an object to manage the common state for building overloads. 9161 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9162 VisibleTypeConversionsQuals, 9163 HasArithmeticOrEnumeralCandidateType, 9164 CandidateTypes, CandidateSet); 9165 9166 // Dispatch over the operation to add in only those overloads which apply. 9167 switch (Op) { 9168 case OO_None: 9169 case NUM_OVERLOADED_OPERATORS: 9170 llvm_unreachable("Expected an overloaded operator"); 9171 9172 case OO_New: 9173 case OO_Delete: 9174 case OO_Array_New: 9175 case OO_Array_Delete: 9176 case OO_Call: 9177 llvm_unreachable( 9178 "Special operators don't use AddBuiltinOperatorCandidates"); 9179 9180 case OO_Comma: 9181 case OO_Arrow: 9182 case OO_Coawait: 9183 // C++ [over.match.oper]p3: 9184 // -- For the operator ',', the unary operator '&', the 9185 // operator '->', or the operator 'co_await', the 9186 // built-in candidates set is empty. 9187 break; 9188 9189 case OO_Plus: // '+' is either unary or binary 9190 if (Args.size() == 1) 9191 OpBuilder.addUnaryPlusPointerOverloads(); 9192 LLVM_FALLTHROUGH; 9193 9194 case OO_Minus: // '-' is either unary or binary 9195 if (Args.size() == 1) { 9196 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9197 } else { 9198 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9199 OpBuilder.addGenericBinaryArithmeticOverloads(); 9200 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9201 } 9202 break; 9203 9204 case OO_Star: // '*' is either unary or binary 9205 if (Args.size() == 1) 9206 OpBuilder.addUnaryStarPointerOverloads(); 9207 else { 9208 OpBuilder.addGenericBinaryArithmeticOverloads(); 9209 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9210 } 9211 break; 9212 9213 case OO_Slash: 9214 OpBuilder.addGenericBinaryArithmeticOverloads(); 9215 break; 9216 9217 case OO_PlusPlus: 9218 case OO_MinusMinus: 9219 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9220 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9221 break; 9222 9223 case OO_EqualEqual: 9224 case OO_ExclaimEqual: 9225 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9226 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9227 OpBuilder.addGenericBinaryArithmeticOverloads(); 9228 break; 9229 9230 case OO_Less: 9231 case OO_Greater: 9232 case OO_LessEqual: 9233 case OO_GreaterEqual: 9234 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9235 OpBuilder.addGenericBinaryArithmeticOverloads(); 9236 break; 9237 9238 case OO_Spaceship: 9239 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9240 OpBuilder.addThreeWayArithmeticOverloads(); 9241 break; 9242 9243 case OO_Percent: 9244 case OO_Caret: 9245 case OO_Pipe: 9246 case OO_LessLess: 9247 case OO_GreaterGreater: 9248 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9249 break; 9250 9251 case OO_Amp: // '&' is either unary or binary 9252 if (Args.size() == 1) 9253 // C++ [over.match.oper]p3: 9254 // -- For the operator ',', the unary operator '&', or the 9255 // operator '->', the built-in candidates set is empty. 9256 break; 9257 9258 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9259 break; 9260 9261 case OO_Tilde: 9262 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9263 break; 9264 9265 case OO_Equal: 9266 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9267 LLVM_FALLTHROUGH; 9268 9269 case OO_PlusEqual: 9270 case OO_MinusEqual: 9271 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9272 LLVM_FALLTHROUGH; 9273 9274 case OO_StarEqual: 9275 case OO_SlashEqual: 9276 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9277 break; 9278 9279 case OO_PercentEqual: 9280 case OO_LessLessEqual: 9281 case OO_GreaterGreaterEqual: 9282 case OO_AmpEqual: 9283 case OO_CaretEqual: 9284 case OO_PipeEqual: 9285 OpBuilder.addAssignmentIntegralOverloads(); 9286 break; 9287 9288 case OO_Exclaim: 9289 OpBuilder.addExclaimOverload(); 9290 break; 9291 9292 case OO_AmpAmp: 9293 case OO_PipePipe: 9294 OpBuilder.addAmpAmpOrPipePipeOverload(); 9295 break; 9296 9297 case OO_Subscript: 9298 OpBuilder.addSubscriptOverloads(); 9299 break; 9300 9301 case OO_ArrowStar: 9302 OpBuilder.addArrowStarOverloads(); 9303 break; 9304 9305 case OO_Conditional: 9306 OpBuilder.addConditionalOperatorOverloads(); 9307 OpBuilder.addGenericBinaryArithmeticOverloads(); 9308 break; 9309 } 9310 } 9311 9312 /// Add function candidates found via argument-dependent lookup 9313 /// to the set of overloading candidates. 9314 /// 9315 /// This routine performs argument-dependent name lookup based on the 9316 /// given function name (which may also be an operator name) and adds 9317 /// all of the overload candidates found by ADL to the overload 9318 /// candidate set (C++ [basic.lookup.argdep]). 9319 void 9320 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9321 SourceLocation Loc, 9322 ArrayRef<Expr *> Args, 9323 TemplateArgumentListInfo *ExplicitTemplateArgs, 9324 OverloadCandidateSet& CandidateSet, 9325 bool PartialOverloading) { 9326 ADLResult Fns; 9327 9328 // FIXME: This approach for uniquing ADL results (and removing 9329 // redundant candidates from the set) relies on pointer-equality, 9330 // which means we need to key off the canonical decl. However, 9331 // always going back to the canonical decl might not get us the 9332 // right set of default arguments. What default arguments are 9333 // we supposed to consider on ADL candidates, anyway? 9334 9335 // FIXME: Pass in the explicit template arguments? 9336 ArgumentDependentLookup(Name, Loc, Args, Fns); 9337 9338 // Erase all of the candidates we already knew about. 9339 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9340 CandEnd = CandidateSet.end(); 9341 Cand != CandEnd; ++Cand) 9342 if (Cand->Function) { 9343 Fns.erase(Cand->Function); 9344 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9345 Fns.erase(FunTmpl); 9346 } 9347 9348 // For each of the ADL candidates we found, add it to the overload 9349 // set. 9350 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9351 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9352 9353 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9354 if (ExplicitTemplateArgs) 9355 continue; 9356 9357 AddOverloadCandidate( 9358 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9359 PartialOverloading, /*AllowExplicit=*/true, 9360 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9361 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9362 AddOverloadCandidate( 9363 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9364 /*SuppressUserConversions=*/false, PartialOverloading, 9365 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9366 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9367 } 9368 } else { 9369 auto *FTD = cast<FunctionTemplateDecl>(*I); 9370 AddTemplateOverloadCandidate( 9371 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9372 /*SuppressUserConversions=*/false, PartialOverloading, 9373 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9374 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9375 Context, FTD->getTemplatedDecl())) { 9376 AddTemplateOverloadCandidate( 9377 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9378 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9379 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9380 OverloadCandidateParamOrder::Reversed); 9381 } 9382 } 9383 } 9384 } 9385 9386 namespace { 9387 enum class Comparison { Equal, Better, Worse }; 9388 } 9389 9390 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9391 /// overload resolution. 9392 /// 9393 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9394 /// Cand1's first N enable_if attributes have precisely the same conditions as 9395 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9396 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9397 /// 9398 /// Note that you can have a pair of candidates such that Cand1's enable_if 9399 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9400 /// worse than Cand1's. 9401 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9402 const FunctionDecl *Cand2) { 9403 // Common case: One (or both) decls don't have enable_if attrs. 9404 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9405 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9406 if (!Cand1Attr || !Cand2Attr) { 9407 if (Cand1Attr == Cand2Attr) 9408 return Comparison::Equal; 9409 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9410 } 9411 9412 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9413 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9414 9415 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9416 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9417 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9418 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9419 9420 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9421 // has fewer enable_if attributes than Cand2, and vice versa. 9422 if (!Cand1A) 9423 return Comparison::Worse; 9424 if (!Cand2A) 9425 return Comparison::Better; 9426 9427 Cand1ID.clear(); 9428 Cand2ID.clear(); 9429 9430 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9431 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9432 if (Cand1ID != Cand2ID) 9433 return Comparison::Worse; 9434 } 9435 9436 return Comparison::Equal; 9437 } 9438 9439 static Comparison 9440 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9441 const OverloadCandidate &Cand2) { 9442 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9443 !Cand2.Function->isMultiVersion()) 9444 return Comparison::Equal; 9445 9446 // If both are invalid, they are equal. If one of them is invalid, the other 9447 // is better. 9448 if (Cand1.Function->isInvalidDecl()) { 9449 if (Cand2.Function->isInvalidDecl()) 9450 return Comparison::Equal; 9451 return Comparison::Worse; 9452 } 9453 if (Cand2.Function->isInvalidDecl()) 9454 return Comparison::Better; 9455 9456 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9457 // cpu_dispatch, else arbitrarily based on the identifiers. 9458 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9459 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9460 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9461 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9462 9463 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9464 return Comparison::Equal; 9465 9466 if (Cand1CPUDisp && !Cand2CPUDisp) 9467 return Comparison::Better; 9468 if (Cand2CPUDisp && !Cand1CPUDisp) 9469 return Comparison::Worse; 9470 9471 if (Cand1CPUSpec && Cand2CPUSpec) { 9472 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9473 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9474 ? Comparison::Better 9475 : Comparison::Worse; 9476 9477 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9478 FirstDiff = std::mismatch( 9479 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9480 Cand2CPUSpec->cpus_begin(), 9481 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9482 return LHS->getName() == RHS->getName(); 9483 }); 9484 9485 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9486 "Two different cpu-specific versions should not have the same " 9487 "identifier list, otherwise they'd be the same decl!"); 9488 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9489 ? Comparison::Better 9490 : Comparison::Worse; 9491 } 9492 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9493 } 9494 9495 /// Compute the type of the implicit object parameter for the given function, 9496 /// if any. Returns None if there is no implicit object parameter, and a null 9497 /// QualType if there is a 'matches anything' implicit object parameter. 9498 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9499 const FunctionDecl *F) { 9500 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9501 return llvm::None; 9502 9503 auto *M = cast<CXXMethodDecl>(F); 9504 // Static member functions' object parameters match all types. 9505 if (M->isStatic()) 9506 return QualType(); 9507 9508 QualType T = M->getThisObjectType(); 9509 if (M->getRefQualifier() == RQ_RValue) 9510 return Context.getRValueReferenceType(T); 9511 return Context.getLValueReferenceType(T); 9512 } 9513 9514 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9515 const FunctionDecl *F2, unsigned NumParams) { 9516 if (declaresSameEntity(F1, F2)) 9517 return true; 9518 9519 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9520 if (First) { 9521 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9522 return *T; 9523 } 9524 assert(I < F->getNumParams()); 9525 return F->getParamDecl(I++)->getType(); 9526 }; 9527 9528 unsigned I1 = 0, I2 = 0; 9529 for (unsigned I = 0; I != NumParams; ++I) { 9530 QualType T1 = NextParam(F1, I1, I == 0); 9531 QualType T2 = NextParam(F2, I2, I == 0); 9532 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9533 return false; 9534 } 9535 return true; 9536 } 9537 9538 /// isBetterOverloadCandidate - Determines whether the first overload 9539 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9540 bool clang::isBetterOverloadCandidate( 9541 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9542 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9543 // Define viable functions to be better candidates than non-viable 9544 // functions. 9545 if (!Cand2.Viable) 9546 return Cand1.Viable; 9547 else if (!Cand1.Viable) 9548 return false; 9549 9550 // [CUDA] A function with 'never' preference is marked not viable, therefore 9551 // is never shown up here. The worst preference shown up here is 'wrong side', 9552 // e.g. an H function called by a HD function in device compilation. This is 9553 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9554 // function which is called only by an H function. A deferred diagnostic will 9555 // be triggered if it is emitted. However a wrong-sided function is still 9556 // a viable candidate here. 9557 // 9558 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9559 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9560 // can be emitted, Cand1 is not better than Cand2. This rule should have 9561 // precedence over other rules. 9562 // 9563 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9564 // other rules should be used to determine which is better. This is because 9565 // host/device based overloading resolution is mostly for determining 9566 // viability of a function. If two functions are both viable, other factors 9567 // should take precedence in preference, e.g. the standard-defined preferences 9568 // like argument conversion ranks or enable_if partial-ordering. The 9569 // preference for pass-object-size parameters is probably most similar to a 9570 // type-based-overloading decision and so should take priority. 9571 // 9572 // If other rules cannot determine which is better, CUDA preference will be 9573 // used again to determine which is better. 9574 // 9575 // TODO: Currently IdentifyCUDAPreference does not return correct values 9576 // for functions called in global variable initializers due to missing 9577 // correct context about device/host. Therefore we can only enforce this 9578 // rule when there is a caller. We should enforce this rule for functions 9579 // in global variable initializers once proper context is added. 9580 // 9581 // TODO: We can only enable the hostness based overloading resolution when 9582 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9583 // overloading resolution diagnostics. 9584 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9585 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9586 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9587 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9588 bool IsCand1ImplicitHD = 9589 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9590 bool IsCand2ImplicitHD = 9591 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9592 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9593 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9594 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9595 // The implicit HD function may be a function in a system header which 9596 // is forced by pragma. In device compilation, if we prefer HD candidates 9597 // over wrong-sided candidates, overloading resolution may change, which 9598 // may result in non-deferrable diagnostics. As a workaround, we let 9599 // implicit HD candidates take equal preference as wrong-sided candidates. 9600 // This will preserve the overloading resolution. 9601 // TODO: We still need special handling of implicit HD functions since 9602 // they may incur other diagnostics to be deferred. We should make all 9603 // host/device related diagnostics deferrable and remove special handling 9604 // of implicit HD functions. 9605 auto EmitThreshold = 9606 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9607 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9608 ? Sema::CFP_Never 9609 : Sema::CFP_WrongSide; 9610 auto Cand1Emittable = P1 > EmitThreshold; 9611 auto Cand2Emittable = P2 > EmitThreshold; 9612 if (Cand1Emittable && !Cand2Emittable) 9613 return true; 9614 if (!Cand1Emittable && Cand2Emittable) 9615 return false; 9616 } 9617 } 9618 9619 // C++ [over.match.best]p1: 9620 // 9621 // -- if F is a static member function, ICS1(F) is defined such 9622 // that ICS1(F) is neither better nor worse than ICS1(G) for 9623 // any function G, and, symmetrically, ICS1(G) is neither 9624 // better nor worse than ICS1(F). 9625 unsigned StartArg = 0; 9626 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9627 StartArg = 1; 9628 9629 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9630 // We don't allow incompatible pointer conversions in C++. 9631 if (!S.getLangOpts().CPlusPlus) 9632 return ICS.isStandard() && 9633 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9634 9635 // The only ill-formed conversion we allow in C++ is the string literal to 9636 // char* conversion, which is only considered ill-formed after C++11. 9637 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9638 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9639 }; 9640 9641 // Define functions that don't require ill-formed conversions for a given 9642 // argument to be better candidates than functions that do. 9643 unsigned NumArgs = Cand1.Conversions.size(); 9644 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9645 bool HasBetterConversion = false; 9646 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9647 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9648 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9649 if (Cand1Bad != Cand2Bad) { 9650 if (Cand1Bad) 9651 return false; 9652 HasBetterConversion = true; 9653 } 9654 } 9655 9656 if (HasBetterConversion) 9657 return true; 9658 9659 // C++ [over.match.best]p1: 9660 // A viable function F1 is defined to be a better function than another 9661 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9662 // conversion sequence than ICSi(F2), and then... 9663 bool HasWorseConversion = false; 9664 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9665 switch (CompareImplicitConversionSequences(S, Loc, 9666 Cand1.Conversions[ArgIdx], 9667 Cand2.Conversions[ArgIdx])) { 9668 case ImplicitConversionSequence::Better: 9669 // Cand1 has a better conversion sequence. 9670 HasBetterConversion = true; 9671 break; 9672 9673 case ImplicitConversionSequence::Worse: 9674 if (Cand1.Function && Cand2.Function && 9675 Cand1.isReversed() != Cand2.isReversed() && 9676 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9677 NumArgs)) { 9678 // Work around large-scale breakage caused by considering reversed 9679 // forms of operator== in C++20: 9680 // 9681 // When comparing a function against a reversed function with the same 9682 // parameter types, if we have a better conversion for one argument and 9683 // a worse conversion for the other, the implicit conversion sequences 9684 // are treated as being equally good. 9685 // 9686 // This prevents a comparison function from being considered ambiguous 9687 // with a reversed form that is written in the same way. 9688 // 9689 // We diagnose this as an extension from CreateOverloadedBinOp. 9690 HasWorseConversion = true; 9691 break; 9692 } 9693 9694 // Cand1 can't be better than Cand2. 9695 return false; 9696 9697 case ImplicitConversionSequence::Indistinguishable: 9698 // Do nothing. 9699 break; 9700 } 9701 } 9702 9703 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9704 // ICSj(F2), or, if not that, 9705 if (HasBetterConversion && !HasWorseConversion) 9706 return true; 9707 9708 // -- the context is an initialization by user-defined conversion 9709 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9710 // from the return type of F1 to the destination type (i.e., 9711 // the type of the entity being initialized) is a better 9712 // conversion sequence than the standard conversion sequence 9713 // from the return type of F2 to the destination type. 9714 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9715 Cand1.Function && Cand2.Function && 9716 isa<CXXConversionDecl>(Cand1.Function) && 9717 isa<CXXConversionDecl>(Cand2.Function)) { 9718 // First check whether we prefer one of the conversion functions over the 9719 // other. This only distinguishes the results in non-standard, extension 9720 // cases such as the conversion from a lambda closure type to a function 9721 // pointer or block. 9722 ImplicitConversionSequence::CompareKind Result = 9723 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9724 if (Result == ImplicitConversionSequence::Indistinguishable) 9725 Result = CompareStandardConversionSequences(S, Loc, 9726 Cand1.FinalConversion, 9727 Cand2.FinalConversion); 9728 9729 if (Result != ImplicitConversionSequence::Indistinguishable) 9730 return Result == ImplicitConversionSequence::Better; 9731 9732 // FIXME: Compare kind of reference binding if conversion functions 9733 // convert to a reference type used in direct reference binding, per 9734 // C++14 [over.match.best]p1 section 2 bullet 3. 9735 } 9736 9737 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9738 // as combined with the resolution to CWG issue 243. 9739 // 9740 // When the context is initialization by constructor ([over.match.ctor] or 9741 // either phase of [over.match.list]), a constructor is preferred over 9742 // a conversion function. 9743 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9744 Cand1.Function && Cand2.Function && 9745 isa<CXXConstructorDecl>(Cand1.Function) != 9746 isa<CXXConstructorDecl>(Cand2.Function)) 9747 return isa<CXXConstructorDecl>(Cand1.Function); 9748 9749 // -- F1 is a non-template function and F2 is a function template 9750 // specialization, or, if not that, 9751 bool Cand1IsSpecialization = Cand1.Function && 9752 Cand1.Function->getPrimaryTemplate(); 9753 bool Cand2IsSpecialization = Cand2.Function && 9754 Cand2.Function->getPrimaryTemplate(); 9755 if (Cand1IsSpecialization != Cand2IsSpecialization) 9756 return Cand2IsSpecialization; 9757 9758 // -- F1 and F2 are function template specializations, and the function 9759 // template for F1 is more specialized than the template for F2 9760 // according to the partial ordering rules described in 14.5.5.2, or, 9761 // if not that, 9762 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9763 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9764 Cand1.Function->getPrimaryTemplate(), 9765 Cand2.Function->getPrimaryTemplate(), Loc, 9766 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9767 : TPOC_Call, 9768 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9769 Cand1.isReversed() ^ Cand2.isReversed())) 9770 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9771 } 9772 9773 // -— F1 and F2 are non-template functions with the same 9774 // parameter-type-lists, and F1 is more constrained than F2 [...], 9775 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9776 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9777 Cand2.Function->hasPrototype()) { 9778 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9779 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9780 if (PT1->getNumParams() == PT2->getNumParams() && 9781 PT1->isVariadic() == PT2->isVariadic() && 9782 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9783 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9784 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9785 if (RC1 && RC2) { 9786 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9787 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9788 {RC2}, AtLeastAsConstrained1) || 9789 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9790 {RC1}, AtLeastAsConstrained2)) 9791 return false; 9792 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9793 return AtLeastAsConstrained1; 9794 } else if (RC1 || RC2) { 9795 return RC1 != nullptr; 9796 } 9797 } 9798 } 9799 9800 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9801 // class B of D, and for all arguments the corresponding parameters of 9802 // F1 and F2 have the same type. 9803 // FIXME: Implement the "all parameters have the same type" check. 9804 bool Cand1IsInherited = 9805 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9806 bool Cand2IsInherited = 9807 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9808 if (Cand1IsInherited != Cand2IsInherited) 9809 return Cand2IsInherited; 9810 else if (Cand1IsInherited) { 9811 assert(Cand2IsInherited); 9812 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9813 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9814 if (Cand1Class->isDerivedFrom(Cand2Class)) 9815 return true; 9816 if (Cand2Class->isDerivedFrom(Cand1Class)) 9817 return false; 9818 // Inherited from sibling base classes: still ambiguous. 9819 } 9820 9821 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9822 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9823 // with reversed order of parameters and F1 is not 9824 // 9825 // We rank reversed + different operator as worse than just reversed, but 9826 // that comparison can never happen, because we only consider reversing for 9827 // the maximally-rewritten operator (== or <=>). 9828 if (Cand1.RewriteKind != Cand2.RewriteKind) 9829 return Cand1.RewriteKind < Cand2.RewriteKind; 9830 9831 // Check C++17 tie-breakers for deduction guides. 9832 { 9833 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9834 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9835 if (Guide1 && Guide2) { 9836 // -- F1 is generated from a deduction-guide and F2 is not 9837 if (Guide1->isImplicit() != Guide2->isImplicit()) 9838 return Guide2->isImplicit(); 9839 9840 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9841 if (Guide1->isCopyDeductionCandidate()) 9842 return true; 9843 } 9844 } 9845 9846 // Check for enable_if value-based overload resolution. 9847 if (Cand1.Function && Cand2.Function) { 9848 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9849 if (Cmp != Comparison::Equal) 9850 return Cmp == Comparison::Better; 9851 } 9852 9853 bool HasPS1 = Cand1.Function != nullptr && 9854 functionHasPassObjectSizeParams(Cand1.Function); 9855 bool HasPS2 = Cand2.Function != nullptr && 9856 functionHasPassObjectSizeParams(Cand2.Function); 9857 if (HasPS1 != HasPS2 && HasPS1) 9858 return true; 9859 9860 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9861 if (MV == Comparison::Better) 9862 return true; 9863 if (MV == Comparison::Worse) 9864 return false; 9865 9866 // If other rules cannot determine which is better, CUDA preference is used 9867 // to determine which is better. 9868 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9869 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9870 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9871 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9872 } 9873 9874 // General member function overloading is handled above, so this only handles 9875 // constructors with address spaces. 9876 // This only handles address spaces since C++ has no other 9877 // qualifier that can be used with constructors. 9878 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 9879 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 9880 if (CD1 && CD2) { 9881 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 9882 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 9883 if (AS1 != AS2) { 9884 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 9885 return true; 9886 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 9887 return false; 9888 } 9889 } 9890 9891 return false; 9892 } 9893 9894 /// Determine whether two declarations are "equivalent" for the purposes of 9895 /// name lookup and overload resolution. This applies when the same internal/no 9896 /// linkage entity is defined by two modules (probably by textually including 9897 /// the same header). In such a case, we don't consider the declarations to 9898 /// declare the same entity, but we also don't want lookups with both 9899 /// declarations visible to be ambiguous in some cases (this happens when using 9900 /// a modularized libstdc++). 9901 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9902 const NamedDecl *B) { 9903 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9904 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9905 if (!VA || !VB) 9906 return false; 9907 9908 // The declarations must be declaring the same name as an internal linkage 9909 // entity in different modules. 9910 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9911 VB->getDeclContext()->getRedeclContext()) || 9912 getOwningModule(VA) == getOwningModule(VB) || 9913 VA->isExternallyVisible() || VB->isExternallyVisible()) 9914 return false; 9915 9916 // Check that the declarations appear to be equivalent. 9917 // 9918 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9919 // For constants and functions, we should check the initializer or body is 9920 // the same. For non-constant variables, we shouldn't allow it at all. 9921 if (Context.hasSameType(VA->getType(), VB->getType())) 9922 return true; 9923 9924 // Enum constants within unnamed enumerations will have different types, but 9925 // may still be similar enough to be interchangeable for our purposes. 9926 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9927 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9928 // Only handle anonymous enums. If the enumerations were named and 9929 // equivalent, they would have been merged to the same type. 9930 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9931 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9932 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9933 !Context.hasSameType(EnumA->getIntegerType(), 9934 EnumB->getIntegerType())) 9935 return false; 9936 // Allow this only if the value is the same for both enumerators. 9937 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9938 } 9939 } 9940 9941 // Nothing else is sufficiently similar. 9942 return false; 9943 } 9944 9945 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9946 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9947 assert(D && "Unknown declaration"); 9948 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9949 9950 Module *M = getOwningModule(D); 9951 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9952 << !M << (M ? M->getFullModuleName() : ""); 9953 9954 for (auto *E : Equiv) { 9955 Module *M = getOwningModule(E); 9956 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9957 << !M << (M ? M->getFullModuleName() : ""); 9958 } 9959 } 9960 9961 /// Computes the best viable function (C++ 13.3.3) 9962 /// within an overload candidate set. 9963 /// 9964 /// \param Loc The location of the function name (or operator symbol) for 9965 /// which overload resolution occurs. 9966 /// 9967 /// \param Best If overload resolution was successful or found a deleted 9968 /// function, \p Best points to the candidate function found. 9969 /// 9970 /// \returns The result of overload resolution. 9971 OverloadingResult 9972 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9973 iterator &Best) { 9974 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9975 std::transform(begin(), end(), std::back_inserter(Candidates), 9976 [](OverloadCandidate &Cand) { return &Cand; }); 9977 9978 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9979 // are accepted by both clang and NVCC. However, during a particular 9980 // compilation mode only one call variant is viable. We need to 9981 // exclude non-viable overload candidates from consideration based 9982 // only on their host/device attributes. Specifically, if one 9983 // candidate call is WrongSide and the other is SameSide, we ignore 9984 // the WrongSide candidate. 9985 // We only need to remove wrong-sided candidates here if 9986 // -fgpu-exclude-wrong-side-overloads is off. When 9987 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 9988 // uniformly in isBetterOverloadCandidate. 9989 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 9990 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9991 bool ContainsSameSideCandidate = 9992 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9993 // Check viable function only. 9994 return Cand->Viable && Cand->Function && 9995 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9996 Sema::CFP_SameSide; 9997 }); 9998 if (ContainsSameSideCandidate) { 9999 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10000 // Check viable function only to avoid unnecessary data copying/moving. 10001 return Cand->Viable && Cand->Function && 10002 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10003 Sema::CFP_WrongSide; 10004 }; 10005 llvm::erase_if(Candidates, IsWrongSideCandidate); 10006 } 10007 } 10008 10009 // Find the best viable function. 10010 Best = end(); 10011 for (auto *Cand : Candidates) { 10012 Cand->Best = false; 10013 if (Cand->Viable) 10014 if (Best == end() || 10015 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10016 Best = Cand; 10017 } 10018 10019 // If we didn't find any viable functions, abort. 10020 if (Best == end()) 10021 return OR_No_Viable_Function; 10022 10023 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10024 10025 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10026 PendingBest.push_back(&*Best); 10027 Best->Best = true; 10028 10029 // Make sure that this function is better than every other viable 10030 // function. If not, we have an ambiguity. 10031 while (!PendingBest.empty()) { 10032 auto *Curr = PendingBest.pop_back_val(); 10033 for (auto *Cand : Candidates) { 10034 if (Cand->Viable && !Cand->Best && 10035 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10036 PendingBest.push_back(Cand); 10037 Cand->Best = true; 10038 10039 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10040 Curr->Function)) 10041 EquivalentCands.push_back(Cand->Function); 10042 else 10043 Best = end(); 10044 } 10045 } 10046 } 10047 10048 // If we found more than one best candidate, this is ambiguous. 10049 if (Best == end()) 10050 return OR_Ambiguous; 10051 10052 // Best is the best viable function. 10053 if (Best->Function && Best->Function->isDeleted()) 10054 return OR_Deleted; 10055 10056 if (!EquivalentCands.empty()) 10057 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10058 EquivalentCands); 10059 10060 return OR_Success; 10061 } 10062 10063 namespace { 10064 10065 enum OverloadCandidateKind { 10066 oc_function, 10067 oc_method, 10068 oc_reversed_binary_operator, 10069 oc_constructor, 10070 oc_implicit_default_constructor, 10071 oc_implicit_copy_constructor, 10072 oc_implicit_move_constructor, 10073 oc_implicit_copy_assignment, 10074 oc_implicit_move_assignment, 10075 oc_implicit_equality_comparison, 10076 oc_inherited_constructor 10077 }; 10078 10079 enum OverloadCandidateSelect { 10080 ocs_non_template, 10081 ocs_template, 10082 ocs_described_template, 10083 }; 10084 10085 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10086 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10087 OverloadCandidateRewriteKind CRK, 10088 std::string &Description) { 10089 10090 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10091 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10092 isTemplate = true; 10093 Description = S.getTemplateArgumentBindingsText( 10094 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10095 } 10096 10097 OverloadCandidateSelect Select = [&]() { 10098 if (!Description.empty()) 10099 return ocs_described_template; 10100 return isTemplate ? ocs_template : ocs_non_template; 10101 }(); 10102 10103 OverloadCandidateKind Kind = [&]() { 10104 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10105 return oc_implicit_equality_comparison; 10106 10107 if (CRK & CRK_Reversed) 10108 return oc_reversed_binary_operator; 10109 10110 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10111 if (!Ctor->isImplicit()) { 10112 if (isa<ConstructorUsingShadowDecl>(Found)) 10113 return oc_inherited_constructor; 10114 else 10115 return oc_constructor; 10116 } 10117 10118 if (Ctor->isDefaultConstructor()) 10119 return oc_implicit_default_constructor; 10120 10121 if (Ctor->isMoveConstructor()) 10122 return oc_implicit_move_constructor; 10123 10124 assert(Ctor->isCopyConstructor() && 10125 "unexpected sort of implicit constructor"); 10126 return oc_implicit_copy_constructor; 10127 } 10128 10129 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10130 // This actually gets spelled 'candidate function' for now, but 10131 // it doesn't hurt to split it out. 10132 if (!Meth->isImplicit()) 10133 return oc_method; 10134 10135 if (Meth->isMoveAssignmentOperator()) 10136 return oc_implicit_move_assignment; 10137 10138 if (Meth->isCopyAssignmentOperator()) 10139 return oc_implicit_copy_assignment; 10140 10141 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10142 return oc_method; 10143 } 10144 10145 return oc_function; 10146 }(); 10147 10148 return std::make_pair(Kind, Select); 10149 } 10150 10151 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10152 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10153 // set. 10154 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10155 S.Diag(FoundDecl->getLocation(), 10156 diag::note_ovl_candidate_inherited_constructor) 10157 << Shadow->getNominatedBaseClass(); 10158 } 10159 10160 } // end anonymous namespace 10161 10162 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10163 const FunctionDecl *FD) { 10164 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10165 bool AlwaysTrue; 10166 if (EnableIf->getCond()->isValueDependent() || 10167 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10168 return false; 10169 if (!AlwaysTrue) 10170 return false; 10171 } 10172 return true; 10173 } 10174 10175 /// Returns true if we can take the address of the function. 10176 /// 10177 /// \param Complain - If true, we'll emit a diagnostic 10178 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10179 /// we in overload resolution? 10180 /// \param Loc - The location of the statement we're complaining about. Ignored 10181 /// if we're not complaining, or if we're in overload resolution. 10182 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10183 bool Complain, 10184 bool InOverloadResolution, 10185 SourceLocation Loc) { 10186 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10187 if (Complain) { 10188 if (InOverloadResolution) 10189 S.Diag(FD->getBeginLoc(), 10190 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10191 else 10192 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10193 } 10194 return false; 10195 } 10196 10197 if (FD->getTrailingRequiresClause()) { 10198 ConstraintSatisfaction Satisfaction; 10199 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10200 return false; 10201 if (!Satisfaction.IsSatisfied) { 10202 if (Complain) { 10203 if (InOverloadResolution) 10204 S.Diag(FD->getBeginLoc(), 10205 diag::note_ovl_candidate_unsatisfied_constraints); 10206 else 10207 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10208 << FD; 10209 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10210 } 10211 return false; 10212 } 10213 } 10214 10215 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10216 return P->hasAttr<PassObjectSizeAttr>(); 10217 }); 10218 if (I == FD->param_end()) 10219 return true; 10220 10221 if (Complain) { 10222 // Add one to ParamNo because it's user-facing 10223 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10224 if (InOverloadResolution) 10225 S.Diag(FD->getLocation(), 10226 diag::note_ovl_candidate_has_pass_object_size_params) 10227 << ParamNo; 10228 else 10229 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10230 << FD << ParamNo; 10231 } 10232 return false; 10233 } 10234 10235 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10236 const FunctionDecl *FD) { 10237 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10238 /*InOverloadResolution=*/true, 10239 /*Loc=*/SourceLocation()); 10240 } 10241 10242 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10243 bool Complain, 10244 SourceLocation Loc) { 10245 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10246 /*InOverloadResolution=*/false, 10247 Loc); 10248 } 10249 10250 // Don't print candidates other than the one that matches the calling 10251 // convention of the call operator, since that is guaranteed to exist. 10252 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10253 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10254 10255 if (!ConvD) 10256 return false; 10257 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10258 if (!RD->isLambda()) 10259 return false; 10260 10261 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10262 CallingConv CallOpCC = 10263 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10264 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10265 CallingConv ConvToCC = 10266 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10267 10268 return ConvToCC != CallOpCC; 10269 } 10270 10271 // Notes the location of an overload candidate. 10272 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10273 OverloadCandidateRewriteKind RewriteKind, 10274 QualType DestType, bool TakingAddress) { 10275 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10276 return; 10277 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10278 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10279 return; 10280 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10281 return; 10282 10283 std::string FnDesc; 10284 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10285 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10286 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10287 << (unsigned)KSPair.first << (unsigned)KSPair.second 10288 << Fn << FnDesc; 10289 10290 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10291 Diag(Fn->getLocation(), PD); 10292 MaybeEmitInheritedConstructorNote(*this, Found); 10293 } 10294 10295 static void 10296 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10297 // Perhaps the ambiguity was caused by two atomic constraints that are 10298 // 'identical' but not equivalent: 10299 // 10300 // void foo() requires (sizeof(T) > 4) { } // #1 10301 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10302 // 10303 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10304 // #2 to subsume #1, but these constraint are not considered equivalent 10305 // according to the subsumption rules because they are not the same 10306 // source-level construct. This behavior is quite confusing and we should try 10307 // to help the user figure out what happened. 10308 10309 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10310 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10311 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10312 if (!I->Function) 10313 continue; 10314 SmallVector<const Expr *, 3> AC; 10315 if (auto *Template = I->Function->getPrimaryTemplate()) 10316 Template->getAssociatedConstraints(AC); 10317 else 10318 I->Function->getAssociatedConstraints(AC); 10319 if (AC.empty()) 10320 continue; 10321 if (FirstCand == nullptr) { 10322 FirstCand = I->Function; 10323 FirstAC = AC; 10324 } else if (SecondCand == nullptr) { 10325 SecondCand = I->Function; 10326 SecondAC = AC; 10327 } else { 10328 // We have more than one pair of constrained functions - this check is 10329 // expensive and we'd rather not try to diagnose it. 10330 return; 10331 } 10332 } 10333 if (!SecondCand) 10334 return; 10335 // The diagnostic can only happen if there are associated constraints on 10336 // both sides (there needs to be some identical atomic constraint). 10337 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10338 SecondCand, SecondAC)) 10339 // Just show the user one diagnostic, they'll probably figure it out 10340 // from here. 10341 return; 10342 } 10343 10344 // Notes the location of all overload candidates designated through 10345 // OverloadedExpr 10346 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10347 bool TakingAddress) { 10348 assert(OverloadedExpr->getType() == Context.OverloadTy); 10349 10350 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10351 OverloadExpr *OvlExpr = Ovl.Expression; 10352 10353 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10354 IEnd = OvlExpr->decls_end(); 10355 I != IEnd; ++I) { 10356 if (FunctionTemplateDecl *FunTmpl = 10357 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10358 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10359 TakingAddress); 10360 } else if (FunctionDecl *Fun 10361 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10362 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10363 } 10364 } 10365 } 10366 10367 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10368 /// "lead" diagnostic; it will be given two arguments, the source and 10369 /// target types of the conversion. 10370 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10371 Sema &S, 10372 SourceLocation CaretLoc, 10373 const PartialDiagnostic &PDiag) const { 10374 S.Diag(CaretLoc, PDiag) 10375 << Ambiguous.getFromType() << Ambiguous.getToType(); 10376 unsigned CandsShown = 0; 10377 AmbiguousConversionSequence::const_iterator I, E; 10378 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10379 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10380 break; 10381 ++CandsShown; 10382 S.NoteOverloadCandidate(I->first, I->second); 10383 } 10384 S.Diags.overloadCandidatesShown(CandsShown); 10385 if (I != E) 10386 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10387 } 10388 10389 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10390 unsigned I, bool TakingCandidateAddress) { 10391 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10392 assert(Conv.isBad()); 10393 assert(Cand->Function && "for now, candidate must be a function"); 10394 FunctionDecl *Fn = Cand->Function; 10395 10396 // There's a conversion slot for the object argument if this is a 10397 // non-constructor method. Note that 'I' corresponds the 10398 // conversion-slot index. 10399 bool isObjectArgument = false; 10400 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10401 if (I == 0) 10402 isObjectArgument = true; 10403 else 10404 I--; 10405 } 10406 10407 std::string FnDesc; 10408 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10409 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10410 FnDesc); 10411 10412 Expr *FromExpr = Conv.Bad.FromExpr; 10413 QualType FromTy = Conv.Bad.getFromType(); 10414 QualType ToTy = Conv.Bad.getToType(); 10415 10416 if (FromTy == S.Context.OverloadTy) { 10417 assert(FromExpr && "overload set argument came from implicit argument?"); 10418 Expr *E = FromExpr->IgnoreParens(); 10419 if (isa<UnaryOperator>(E)) 10420 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10421 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10422 10423 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10424 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10425 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10426 << Name << I + 1; 10427 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10428 return; 10429 } 10430 10431 // Do some hand-waving analysis to see if the non-viability is due 10432 // to a qualifier mismatch. 10433 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10434 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10435 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10436 CToTy = RT->getPointeeType(); 10437 else { 10438 // TODO: detect and diagnose the full richness of const mismatches. 10439 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10440 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10441 CFromTy = FromPT->getPointeeType(); 10442 CToTy = ToPT->getPointeeType(); 10443 } 10444 } 10445 10446 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10447 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10448 Qualifiers FromQs = CFromTy.getQualifiers(); 10449 Qualifiers ToQs = CToTy.getQualifiers(); 10450 10451 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10452 if (isObjectArgument) 10453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10454 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10455 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10456 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10457 else 10458 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10459 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10460 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10461 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10462 << ToTy->isReferenceType() << I + 1; 10463 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10464 return; 10465 } 10466 10467 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10468 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10469 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10470 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10471 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10472 << (unsigned)isObjectArgument << I + 1; 10473 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10474 return; 10475 } 10476 10477 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10478 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10479 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10480 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10481 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10482 << (unsigned)isObjectArgument << I + 1; 10483 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10484 return; 10485 } 10486 10487 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10488 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10489 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10490 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10491 << FromQs.hasUnaligned() << I + 1; 10492 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10493 return; 10494 } 10495 10496 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10497 assert(CVR && "expected qualifiers mismatch"); 10498 10499 if (isObjectArgument) { 10500 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10501 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10502 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10503 << (CVR - 1); 10504 } else { 10505 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10506 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10507 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10508 << (CVR - 1) << I + 1; 10509 } 10510 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10511 return; 10512 } 10513 10514 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10515 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10517 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10518 << (unsigned)isObjectArgument << I + 1 10519 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10521 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10522 return; 10523 } 10524 10525 // Special diagnostic for failure to convert an initializer list, since 10526 // telling the user that it has type void is not useful. 10527 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10529 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10531 << ToTy << (unsigned)isObjectArgument << I + 1; 10532 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10533 return; 10534 } 10535 10536 // Diagnose references or pointers to incomplete types differently, 10537 // since it's far from impossible that the incompleteness triggered 10538 // the failure. 10539 QualType TempFromTy = FromTy.getNonReferenceType(); 10540 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10541 TempFromTy = PTy->getPointeeType(); 10542 if (TempFromTy->isIncompleteType()) { 10543 // Emit the generic diagnostic and, optionally, add the hints to it. 10544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10545 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10546 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10547 << ToTy << (unsigned)isObjectArgument << I + 1 10548 << (unsigned)(Cand->Fix.Kind); 10549 10550 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10551 return; 10552 } 10553 10554 // Diagnose base -> derived pointer conversions. 10555 unsigned BaseToDerivedConversion = 0; 10556 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10557 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10558 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10559 FromPtrTy->getPointeeType()) && 10560 !FromPtrTy->getPointeeType()->isIncompleteType() && 10561 !ToPtrTy->getPointeeType()->isIncompleteType() && 10562 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10563 FromPtrTy->getPointeeType())) 10564 BaseToDerivedConversion = 1; 10565 } 10566 } else if (const ObjCObjectPointerType *FromPtrTy 10567 = FromTy->getAs<ObjCObjectPointerType>()) { 10568 if (const ObjCObjectPointerType *ToPtrTy 10569 = ToTy->getAs<ObjCObjectPointerType>()) 10570 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10571 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10572 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10573 FromPtrTy->getPointeeType()) && 10574 FromIface->isSuperClassOf(ToIface)) 10575 BaseToDerivedConversion = 2; 10576 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10577 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10578 !FromTy->isIncompleteType() && 10579 !ToRefTy->getPointeeType()->isIncompleteType() && 10580 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10581 BaseToDerivedConversion = 3; 10582 } 10583 } 10584 10585 if (BaseToDerivedConversion) { 10586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10587 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10588 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10589 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10590 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10591 return; 10592 } 10593 10594 if (isa<ObjCObjectPointerType>(CFromTy) && 10595 isa<PointerType>(CToTy)) { 10596 Qualifiers FromQs = CFromTy.getQualifiers(); 10597 Qualifiers ToQs = CToTy.getQualifiers(); 10598 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10599 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10600 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10601 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10602 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10603 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10604 return; 10605 } 10606 } 10607 10608 if (TakingCandidateAddress && 10609 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10610 return; 10611 10612 // Emit the generic diagnostic and, optionally, add the hints to it. 10613 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10614 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10615 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10616 << ToTy << (unsigned)isObjectArgument << I + 1 10617 << (unsigned)(Cand->Fix.Kind); 10618 10619 // If we can fix the conversion, suggest the FixIts. 10620 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10621 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10622 FDiag << *HI; 10623 S.Diag(Fn->getLocation(), FDiag); 10624 10625 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10626 } 10627 10628 /// Additional arity mismatch diagnosis specific to a function overload 10629 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10630 /// over a candidate in any candidate set. 10631 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10632 unsigned NumArgs) { 10633 FunctionDecl *Fn = Cand->Function; 10634 unsigned MinParams = Fn->getMinRequiredArguments(); 10635 10636 // With invalid overloaded operators, it's possible that we think we 10637 // have an arity mismatch when in fact it looks like we have the 10638 // right number of arguments, because only overloaded operators have 10639 // the weird behavior of overloading member and non-member functions. 10640 // Just don't report anything. 10641 if (Fn->isInvalidDecl() && 10642 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10643 return true; 10644 10645 if (NumArgs < MinParams) { 10646 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10647 (Cand->FailureKind == ovl_fail_bad_deduction && 10648 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10649 } else { 10650 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10651 (Cand->FailureKind == ovl_fail_bad_deduction && 10652 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10653 } 10654 10655 return false; 10656 } 10657 10658 /// General arity mismatch diagnosis over a candidate in a candidate set. 10659 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10660 unsigned NumFormalArgs) { 10661 assert(isa<FunctionDecl>(D) && 10662 "The templated declaration should at least be a function" 10663 " when diagnosing bad template argument deduction due to too many" 10664 " or too few arguments"); 10665 10666 FunctionDecl *Fn = cast<FunctionDecl>(D); 10667 10668 // TODO: treat calls to a missing default constructor as a special case 10669 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10670 unsigned MinParams = Fn->getMinRequiredArguments(); 10671 10672 // at least / at most / exactly 10673 unsigned mode, modeCount; 10674 if (NumFormalArgs < MinParams) { 10675 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10676 FnTy->isTemplateVariadic()) 10677 mode = 0; // "at least" 10678 else 10679 mode = 2; // "exactly" 10680 modeCount = MinParams; 10681 } else { 10682 if (MinParams != FnTy->getNumParams()) 10683 mode = 1; // "at most" 10684 else 10685 mode = 2; // "exactly" 10686 modeCount = FnTy->getNumParams(); 10687 } 10688 10689 std::string Description; 10690 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10691 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10692 10693 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10694 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10695 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10696 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10697 else 10698 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10699 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10700 << Description << mode << modeCount << NumFormalArgs; 10701 10702 MaybeEmitInheritedConstructorNote(S, Found); 10703 } 10704 10705 /// Arity mismatch diagnosis specific to a function overload candidate. 10706 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10707 unsigned NumFormalArgs) { 10708 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10709 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10710 } 10711 10712 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10713 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10714 return TD; 10715 llvm_unreachable("Unsupported: Getting the described template declaration" 10716 " for bad deduction diagnosis"); 10717 } 10718 10719 /// Diagnose a failed template-argument deduction. 10720 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10721 DeductionFailureInfo &DeductionFailure, 10722 unsigned NumArgs, 10723 bool TakingCandidateAddress) { 10724 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10725 NamedDecl *ParamD; 10726 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10727 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10728 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10729 switch (DeductionFailure.Result) { 10730 case Sema::TDK_Success: 10731 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10732 10733 case Sema::TDK_Incomplete: { 10734 assert(ParamD && "no parameter found for incomplete deduction result"); 10735 S.Diag(Templated->getLocation(), 10736 diag::note_ovl_candidate_incomplete_deduction) 10737 << ParamD->getDeclName(); 10738 MaybeEmitInheritedConstructorNote(S, Found); 10739 return; 10740 } 10741 10742 case Sema::TDK_IncompletePack: { 10743 assert(ParamD && "no parameter found for incomplete deduction result"); 10744 S.Diag(Templated->getLocation(), 10745 diag::note_ovl_candidate_incomplete_deduction_pack) 10746 << ParamD->getDeclName() 10747 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10748 << *DeductionFailure.getFirstArg(); 10749 MaybeEmitInheritedConstructorNote(S, Found); 10750 return; 10751 } 10752 10753 case Sema::TDK_Underqualified: { 10754 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10755 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10756 10757 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10758 10759 // Param will have been canonicalized, but it should just be a 10760 // qualified version of ParamD, so move the qualifiers to that. 10761 QualifierCollector Qs; 10762 Qs.strip(Param); 10763 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10764 assert(S.Context.hasSameType(Param, NonCanonParam)); 10765 10766 // Arg has also been canonicalized, but there's nothing we can do 10767 // about that. It also doesn't matter as much, because it won't 10768 // have any template parameters in it (because deduction isn't 10769 // done on dependent types). 10770 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10771 10772 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10773 << ParamD->getDeclName() << Arg << NonCanonParam; 10774 MaybeEmitInheritedConstructorNote(S, Found); 10775 return; 10776 } 10777 10778 case Sema::TDK_Inconsistent: { 10779 assert(ParamD && "no parameter found for inconsistent deduction result"); 10780 int which = 0; 10781 if (isa<TemplateTypeParmDecl>(ParamD)) 10782 which = 0; 10783 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10784 // Deduction might have failed because we deduced arguments of two 10785 // different types for a non-type template parameter. 10786 // FIXME: Use a different TDK value for this. 10787 QualType T1 = 10788 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10789 QualType T2 = 10790 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10791 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10792 S.Diag(Templated->getLocation(), 10793 diag::note_ovl_candidate_inconsistent_deduction_types) 10794 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10795 << *DeductionFailure.getSecondArg() << T2; 10796 MaybeEmitInheritedConstructorNote(S, Found); 10797 return; 10798 } 10799 10800 which = 1; 10801 } else { 10802 which = 2; 10803 } 10804 10805 // Tweak the diagnostic if the problem is that we deduced packs of 10806 // different arities. We'll print the actual packs anyway in case that 10807 // includes additional useful information. 10808 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10809 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10810 DeductionFailure.getFirstArg()->pack_size() != 10811 DeductionFailure.getSecondArg()->pack_size()) { 10812 which = 3; 10813 } 10814 10815 S.Diag(Templated->getLocation(), 10816 diag::note_ovl_candidate_inconsistent_deduction) 10817 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10818 << *DeductionFailure.getSecondArg(); 10819 MaybeEmitInheritedConstructorNote(S, Found); 10820 return; 10821 } 10822 10823 case Sema::TDK_InvalidExplicitArguments: 10824 assert(ParamD && "no parameter found for invalid explicit arguments"); 10825 if (ParamD->getDeclName()) 10826 S.Diag(Templated->getLocation(), 10827 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10828 << ParamD->getDeclName(); 10829 else { 10830 int index = 0; 10831 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10832 index = TTP->getIndex(); 10833 else if (NonTypeTemplateParmDecl *NTTP 10834 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10835 index = NTTP->getIndex(); 10836 else 10837 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10838 S.Diag(Templated->getLocation(), 10839 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10840 << (index + 1); 10841 } 10842 MaybeEmitInheritedConstructorNote(S, Found); 10843 return; 10844 10845 case Sema::TDK_ConstraintsNotSatisfied: { 10846 // Format the template argument list into the argument string. 10847 SmallString<128> TemplateArgString; 10848 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10849 TemplateArgString = " "; 10850 TemplateArgString += S.getTemplateArgumentBindingsText( 10851 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10852 if (TemplateArgString.size() == 1) 10853 TemplateArgString.clear(); 10854 S.Diag(Templated->getLocation(), 10855 diag::note_ovl_candidate_unsatisfied_constraints) 10856 << TemplateArgString; 10857 10858 S.DiagnoseUnsatisfiedConstraint( 10859 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10860 return; 10861 } 10862 case Sema::TDK_TooManyArguments: 10863 case Sema::TDK_TooFewArguments: 10864 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10865 return; 10866 10867 case Sema::TDK_InstantiationDepth: 10868 S.Diag(Templated->getLocation(), 10869 diag::note_ovl_candidate_instantiation_depth); 10870 MaybeEmitInheritedConstructorNote(S, Found); 10871 return; 10872 10873 case Sema::TDK_SubstitutionFailure: { 10874 // Format the template argument list into the argument string. 10875 SmallString<128> TemplateArgString; 10876 if (TemplateArgumentList *Args = 10877 DeductionFailure.getTemplateArgumentList()) { 10878 TemplateArgString = " "; 10879 TemplateArgString += S.getTemplateArgumentBindingsText( 10880 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10881 if (TemplateArgString.size() == 1) 10882 TemplateArgString.clear(); 10883 } 10884 10885 // If this candidate was disabled by enable_if, say so. 10886 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10887 if (PDiag && PDiag->second.getDiagID() == 10888 diag::err_typename_nested_not_found_enable_if) { 10889 // FIXME: Use the source range of the condition, and the fully-qualified 10890 // name of the enable_if template. These are both present in PDiag. 10891 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10892 << "'enable_if'" << TemplateArgString; 10893 return; 10894 } 10895 10896 // We found a specific requirement that disabled the enable_if. 10897 if (PDiag && PDiag->second.getDiagID() == 10898 diag::err_typename_nested_not_found_requirement) { 10899 S.Diag(Templated->getLocation(), 10900 diag::note_ovl_candidate_disabled_by_requirement) 10901 << PDiag->second.getStringArg(0) << TemplateArgString; 10902 return; 10903 } 10904 10905 // Format the SFINAE diagnostic into the argument string. 10906 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10907 // formatted message in another diagnostic. 10908 SmallString<128> SFINAEArgString; 10909 SourceRange R; 10910 if (PDiag) { 10911 SFINAEArgString = ": "; 10912 R = SourceRange(PDiag->first, PDiag->first); 10913 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10914 } 10915 10916 S.Diag(Templated->getLocation(), 10917 diag::note_ovl_candidate_substitution_failure) 10918 << TemplateArgString << SFINAEArgString << R; 10919 MaybeEmitInheritedConstructorNote(S, Found); 10920 return; 10921 } 10922 10923 case Sema::TDK_DeducedMismatch: 10924 case Sema::TDK_DeducedMismatchNested: { 10925 // Format the template argument list into the argument string. 10926 SmallString<128> TemplateArgString; 10927 if (TemplateArgumentList *Args = 10928 DeductionFailure.getTemplateArgumentList()) { 10929 TemplateArgString = " "; 10930 TemplateArgString += S.getTemplateArgumentBindingsText( 10931 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10932 if (TemplateArgString.size() == 1) 10933 TemplateArgString.clear(); 10934 } 10935 10936 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10937 << (*DeductionFailure.getCallArgIndex() + 1) 10938 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10939 << TemplateArgString 10940 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10941 break; 10942 } 10943 10944 case Sema::TDK_NonDeducedMismatch: { 10945 // FIXME: Provide a source location to indicate what we couldn't match. 10946 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10947 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10948 if (FirstTA.getKind() == TemplateArgument::Template && 10949 SecondTA.getKind() == TemplateArgument::Template) { 10950 TemplateName FirstTN = FirstTA.getAsTemplate(); 10951 TemplateName SecondTN = SecondTA.getAsTemplate(); 10952 if (FirstTN.getKind() == TemplateName::Template && 10953 SecondTN.getKind() == TemplateName::Template) { 10954 if (FirstTN.getAsTemplateDecl()->getName() == 10955 SecondTN.getAsTemplateDecl()->getName()) { 10956 // FIXME: This fixes a bad diagnostic where both templates are named 10957 // the same. This particular case is a bit difficult since: 10958 // 1) It is passed as a string to the diagnostic printer. 10959 // 2) The diagnostic printer only attempts to find a better 10960 // name for types, not decls. 10961 // Ideally, this should folded into the diagnostic printer. 10962 S.Diag(Templated->getLocation(), 10963 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10964 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10965 return; 10966 } 10967 } 10968 } 10969 10970 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10971 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10972 return; 10973 10974 // FIXME: For generic lambda parameters, check if the function is a lambda 10975 // call operator, and if so, emit a prettier and more informative 10976 // diagnostic that mentions 'auto' and lambda in addition to 10977 // (or instead of?) the canonical template type parameters. 10978 S.Diag(Templated->getLocation(), 10979 diag::note_ovl_candidate_non_deduced_mismatch) 10980 << FirstTA << SecondTA; 10981 return; 10982 } 10983 // TODO: diagnose these individually, then kill off 10984 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10985 case Sema::TDK_MiscellaneousDeductionFailure: 10986 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10987 MaybeEmitInheritedConstructorNote(S, Found); 10988 return; 10989 case Sema::TDK_CUDATargetMismatch: 10990 S.Diag(Templated->getLocation(), 10991 diag::note_cuda_ovl_candidate_target_mismatch); 10992 return; 10993 } 10994 } 10995 10996 /// Diagnose a failed template-argument deduction, for function calls. 10997 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10998 unsigned NumArgs, 10999 bool TakingCandidateAddress) { 11000 unsigned TDK = Cand->DeductionFailure.Result; 11001 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11002 if (CheckArityMismatch(S, Cand, NumArgs)) 11003 return; 11004 } 11005 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11006 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11007 } 11008 11009 /// CUDA: diagnose an invalid call across targets. 11010 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11011 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 11012 FunctionDecl *Callee = Cand->Function; 11013 11014 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11015 CalleeTarget = S.IdentifyCUDATarget(Callee); 11016 11017 std::string FnDesc; 11018 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11019 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11020 Cand->getRewriteKind(), FnDesc); 11021 11022 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11023 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11024 << FnDesc /* Ignored */ 11025 << CalleeTarget << CallerTarget; 11026 11027 // This could be an implicit constructor for which we could not infer the 11028 // target due to a collsion. Diagnose that case. 11029 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11030 if (Meth != nullptr && Meth->isImplicit()) { 11031 CXXRecordDecl *ParentClass = Meth->getParent(); 11032 Sema::CXXSpecialMember CSM; 11033 11034 switch (FnKindPair.first) { 11035 default: 11036 return; 11037 case oc_implicit_default_constructor: 11038 CSM = Sema::CXXDefaultConstructor; 11039 break; 11040 case oc_implicit_copy_constructor: 11041 CSM = Sema::CXXCopyConstructor; 11042 break; 11043 case oc_implicit_move_constructor: 11044 CSM = Sema::CXXMoveConstructor; 11045 break; 11046 case oc_implicit_copy_assignment: 11047 CSM = Sema::CXXCopyAssignment; 11048 break; 11049 case oc_implicit_move_assignment: 11050 CSM = Sema::CXXMoveAssignment; 11051 break; 11052 }; 11053 11054 bool ConstRHS = false; 11055 if (Meth->getNumParams()) { 11056 if (const ReferenceType *RT = 11057 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11058 ConstRHS = RT->getPointeeType().isConstQualified(); 11059 } 11060 } 11061 11062 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11063 /* ConstRHS */ ConstRHS, 11064 /* Diagnose */ true); 11065 } 11066 } 11067 11068 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11069 FunctionDecl *Callee = Cand->Function; 11070 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11071 11072 S.Diag(Callee->getLocation(), 11073 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11074 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11075 } 11076 11077 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11078 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11079 assert(ES.isExplicit() && "not an explicit candidate"); 11080 11081 unsigned Kind; 11082 switch (Cand->Function->getDeclKind()) { 11083 case Decl::Kind::CXXConstructor: 11084 Kind = 0; 11085 break; 11086 case Decl::Kind::CXXConversion: 11087 Kind = 1; 11088 break; 11089 case Decl::Kind::CXXDeductionGuide: 11090 Kind = Cand->Function->isImplicit() ? 0 : 2; 11091 break; 11092 default: 11093 llvm_unreachable("invalid Decl"); 11094 } 11095 11096 // Note the location of the first (in-class) declaration; a redeclaration 11097 // (particularly an out-of-class definition) will typically lack the 11098 // 'explicit' specifier. 11099 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11100 FunctionDecl *First = Cand->Function->getFirstDecl(); 11101 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11102 First = Pattern->getFirstDecl(); 11103 11104 S.Diag(First->getLocation(), 11105 diag::note_ovl_candidate_explicit) 11106 << Kind << (ES.getExpr() ? 1 : 0) 11107 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11108 } 11109 11110 /// Generates a 'note' diagnostic for an overload candidate. We've 11111 /// already generated a primary error at the call site. 11112 /// 11113 /// It really does need to be a single diagnostic with its caret 11114 /// pointed at the candidate declaration. Yes, this creates some 11115 /// major challenges of technical writing. Yes, this makes pointing 11116 /// out problems with specific arguments quite awkward. It's still 11117 /// better than generating twenty screens of text for every failed 11118 /// overload. 11119 /// 11120 /// It would be great to be able to express per-candidate problems 11121 /// more richly for those diagnostic clients that cared, but we'd 11122 /// still have to be just as careful with the default diagnostics. 11123 /// \param CtorDestAS Addr space of object being constructed (for ctor 11124 /// candidates only). 11125 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11126 unsigned NumArgs, 11127 bool TakingCandidateAddress, 11128 LangAS CtorDestAS = LangAS::Default) { 11129 FunctionDecl *Fn = Cand->Function; 11130 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11131 return; 11132 11133 // Note deleted candidates, but only if they're viable. 11134 if (Cand->Viable) { 11135 if (Fn->isDeleted()) { 11136 std::string FnDesc; 11137 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11138 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11139 Cand->getRewriteKind(), FnDesc); 11140 11141 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11142 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11143 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11144 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11145 return; 11146 } 11147 11148 // We don't really have anything else to say about viable candidates. 11149 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11150 return; 11151 } 11152 11153 switch (Cand->FailureKind) { 11154 case ovl_fail_too_many_arguments: 11155 case ovl_fail_too_few_arguments: 11156 return DiagnoseArityMismatch(S, Cand, NumArgs); 11157 11158 case ovl_fail_bad_deduction: 11159 return DiagnoseBadDeduction(S, Cand, NumArgs, 11160 TakingCandidateAddress); 11161 11162 case ovl_fail_illegal_constructor: { 11163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11164 << (Fn->getPrimaryTemplate() ? 1 : 0); 11165 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11166 return; 11167 } 11168 11169 case ovl_fail_object_addrspace_mismatch: { 11170 Qualifiers QualsForPrinting; 11171 QualsForPrinting.setAddressSpace(CtorDestAS); 11172 S.Diag(Fn->getLocation(), 11173 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11174 << QualsForPrinting; 11175 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11176 return; 11177 } 11178 11179 case ovl_fail_trivial_conversion: 11180 case ovl_fail_bad_final_conversion: 11181 case ovl_fail_final_conversion_not_exact: 11182 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11183 11184 case ovl_fail_bad_conversion: { 11185 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11186 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11187 if (Cand->Conversions[I].isBad()) 11188 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11189 11190 // FIXME: this currently happens when we're called from SemaInit 11191 // when user-conversion overload fails. Figure out how to handle 11192 // those conditions and diagnose them well. 11193 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11194 } 11195 11196 case ovl_fail_bad_target: 11197 return DiagnoseBadTarget(S, Cand); 11198 11199 case ovl_fail_enable_if: 11200 return DiagnoseFailedEnableIfAttr(S, Cand); 11201 11202 case ovl_fail_explicit: 11203 return DiagnoseFailedExplicitSpec(S, Cand); 11204 11205 case ovl_fail_inhctor_slice: 11206 // It's generally not interesting to note copy/move constructors here. 11207 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11208 return; 11209 S.Diag(Fn->getLocation(), 11210 diag::note_ovl_candidate_inherited_constructor_slice) 11211 << (Fn->getPrimaryTemplate() ? 1 : 0) 11212 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11213 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11214 return; 11215 11216 case ovl_fail_addr_not_available: { 11217 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11218 (void)Available; 11219 assert(!Available); 11220 break; 11221 } 11222 case ovl_non_default_multiversion_function: 11223 // Do nothing, these should simply be ignored. 11224 break; 11225 11226 case ovl_fail_constraints_not_satisfied: { 11227 std::string FnDesc; 11228 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11229 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11230 Cand->getRewriteKind(), FnDesc); 11231 11232 S.Diag(Fn->getLocation(), 11233 diag::note_ovl_candidate_constraints_not_satisfied) 11234 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11235 << FnDesc /* Ignored */; 11236 ConstraintSatisfaction Satisfaction; 11237 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11238 break; 11239 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11240 } 11241 } 11242 } 11243 11244 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11245 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11246 return; 11247 11248 // Desugar the type of the surrogate down to a function type, 11249 // retaining as many typedefs as possible while still showing 11250 // the function type (and, therefore, its parameter types). 11251 QualType FnType = Cand->Surrogate->getConversionType(); 11252 bool isLValueReference = false; 11253 bool isRValueReference = false; 11254 bool isPointer = false; 11255 if (const LValueReferenceType *FnTypeRef = 11256 FnType->getAs<LValueReferenceType>()) { 11257 FnType = FnTypeRef->getPointeeType(); 11258 isLValueReference = true; 11259 } else if (const RValueReferenceType *FnTypeRef = 11260 FnType->getAs<RValueReferenceType>()) { 11261 FnType = FnTypeRef->getPointeeType(); 11262 isRValueReference = true; 11263 } 11264 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11265 FnType = FnTypePtr->getPointeeType(); 11266 isPointer = true; 11267 } 11268 // Desugar down to a function type. 11269 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11270 // Reconstruct the pointer/reference as appropriate. 11271 if (isPointer) FnType = S.Context.getPointerType(FnType); 11272 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11273 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11274 11275 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11276 << FnType; 11277 } 11278 11279 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11280 SourceLocation OpLoc, 11281 OverloadCandidate *Cand) { 11282 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11283 std::string TypeStr("operator"); 11284 TypeStr += Opc; 11285 TypeStr += "("; 11286 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11287 if (Cand->Conversions.size() == 1) { 11288 TypeStr += ")"; 11289 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11290 } else { 11291 TypeStr += ", "; 11292 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11293 TypeStr += ")"; 11294 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11295 } 11296 } 11297 11298 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11299 OverloadCandidate *Cand) { 11300 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11301 if (ICS.isBad()) break; // all meaningless after first invalid 11302 if (!ICS.isAmbiguous()) continue; 11303 11304 ICS.DiagnoseAmbiguousConversion( 11305 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11306 } 11307 } 11308 11309 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11310 if (Cand->Function) 11311 return Cand->Function->getLocation(); 11312 if (Cand->IsSurrogate) 11313 return Cand->Surrogate->getLocation(); 11314 return SourceLocation(); 11315 } 11316 11317 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11318 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11319 case Sema::TDK_Success: 11320 case Sema::TDK_NonDependentConversionFailure: 11321 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11322 11323 case Sema::TDK_Invalid: 11324 case Sema::TDK_Incomplete: 11325 case Sema::TDK_IncompletePack: 11326 return 1; 11327 11328 case Sema::TDK_Underqualified: 11329 case Sema::TDK_Inconsistent: 11330 return 2; 11331 11332 case Sema::TDK_SubstitutionFailure: 11333 case Sema::TDK_DeducedMismatch: 11334 case Sema::TDK_ConstraintsNotSatisfied: 11335 case Sema::TDK_DeducedMismatchNested: 11336 case Sema::TDK_NonDeducedMismatch: 11337 case Sema::TDK_MiscellaneousDeductionFailure: 11338 case Sema::TDK_CUDATargetMismatch: 11339 return 3; 11340 11341 case Sema::TDK_InstantiationDepth: 11342 return 4; 11343 11344 case Sema::TDK_InvalidExplicitArguments: 11345 return 5; 11346 11347 case Sema::TDK_TooManyArguments: 11348 case Sema::TDK_TooFewArguments: 11349 return 6; 11350 } 11351 llvm_unreachable("Unhandled deduction result"); 11352 } 11353 11354 namespace { 11355 struct CompareOverloadCandidatesForDisplay { 11356 Sema &S; 11357 SourceLocation Loc; 11358 size_t NumArgs; 11359 OverloadCandidateSet::CandidateSetKind CSK; 11360 11361 CompareOverloadCandidatesForDisplay( 11362 Sema &S, SourceLocation Loc, size_t NArgs, 11363 OverloadCandidateSet::CandidateSetKind CSK) 11364 : S(S), NumArgs(NArgs), CSK(CSK) {} 11365 11366 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11367 // If there are too many or too few arguments, that's the high-order bit we 11368 // want to sort by, even if the immediate failure kind was something else. 11369 if (C->FailureKind == ovl_fail_too_many_arguments || 11370 C->FailureKind == ovl_fail_too_few_arguments) 11371 return static_cast<OverloadFailureKind>(C->FailureKind); 11372 11373 if (C->Function) { 11374 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11375 return ovl_fail_too_many_arguments; 11376 if (NumArgs < C->Function->getMinRequiredArguments()) 11377 return ovl_fail_too_few_arguments; 11378 } 11379 11380 return static_cast<OverloadFailureKind>(C->FailureKind); 11381 } 11382 11383 bool operator()(const OverloadCandidate *L, 11384 const OverloadCandidate *R) { 11385 // Fast-path this check. 11386 if (L == R) return false; 11387 11388 // Order first by viability. 11389 if (L->Viable) { 11390 if (!R->Viable) return true; 11391 11392 // TODO: introduce a tri-valued comparison for overload 11393 // candidates. Would be more worthwhile if we had a sort 11394 // that could exploit it. 11395 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11396 return true; 11397 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11398 return false; 11399 } else if (R->Viable) 11400 return false; 11401 11402 assert(L->Viable == R->Viable); 11403 11404 // Criteria by which we can sort non-viable candidates: 11405 if (!L->Viable) { 11406 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11407 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11408 11409 // 1. Arity mismatches come after other candidates. 11410 if (LFailureKind == ovl_fail_too_many_arguments || 11411 LFailureKind == ovl_fail_too_few_arguments) { 11412 if (RFailureKind == ovl_fail_too_many_arguments || 11413 RFailureKind == ovl_fail_too_few_arguments) { 11414 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11415 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11416 if (LDist == RDist) { 11417 if (LFailureKind == RFailureKind) 11418 // Sort non-surrogates before surrogates. 11419 return !L->IsSurrogate && R->IsSurrogate; 11420 // Sort candidates requiring fewer parameters than there were 11421 // arguments given after candidates requiring more parameters 11422 // than there were arguments given. 11423 return LFailureKind == ovl_fail_too_many_arguments; 11424 } 11425 return LDist < RDist; 11426 } 11427 return false; 11428 } 11429 if (RFailureKind == ovl_fail_too_many_arguments || 11430 RFailureKind == ovl_fail_too_few_arguments) 11431 return true; 11432 11433 // 2. Bad conversions come first and are ordered by the number 11434 // of bad conversions and quality of good conversions. 11435 if (LFailureKind == ovl_fail_bad_conversion) { 11436 if (RFailureKind != ovl_fail_bad_conversion) 11437 return true; 11438 11439 // The conversion that can be fixed with a smaller number of changes, 11440 // comes first. 11441 unsigned numLFixes = L->Fix.NumConversionsFixed; 11442 unsigned numRFixes = R->Fix.NumConversionsFixed; 11443 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11444 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11445 if (numLFixes != numRFixes) { 11446 return numLFixes < numRFixes; 11447 } 11448 11449 // If there's any ordering between the defined conversions... 11450 // FIXME: this might not be transitive. 11451 assert(L->Conversions.size() == R->Conversions.size()); 11452 11453 int leftBetter = 0; 11454 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11455 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11456 switch (CompareImplicitConversionSequences(S, Loc, 11457 L->Conversions[I], 11458 R->Conversions[I])) { 11459 case ImplicitConversionSequence::Better: 11460 leftBetter++; 11461 break; 11462 11463 case ImplicitConversionSequence::Worse: 11464 leftBetter--; 11465 break; 11466 11467 case ImplicitConversionSequence::Indistinguishable: 11468 break; 11469 } 11470 } 11471 if (leftBetter > 0) return true; 11472 if (leftBetter < 0) return false; 11473 11474 } else if (RFailureKind == ovl_fail_bad_conversion) 11475 return false; 11476 11477 if (LFailureKind == ovl_fail_bad_deduction) { 11478 if (RFailureKind != ovl_fail_bad_deduction) 11479 return true; 11480 11481 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11482 return RankDeductionFailure(L->DeductionFailure) 11483 < RankDeductionFailure(R->DeductionFailure); 11484 } else if (RFailureKind == ovl_fail_bad_deduction) 11485 return false; 11486 11487 // TODO: others? 11488 } 11489 11490 // Sort everything else by location. 11491 SourceLocation LLoc = GetLocationForCandidate(L); 11492 SourceLocation RLoc = GetLocationForCandidate(R); 11493 11494 // Put candidates without locations (e.g. builtins) at the end. 11495 if (LLoc.isInvalid()) return false; 11496 if (RLoc.isInvalid()) return true; 11497 11498 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11499 } 11500 }; 11501 } 11502 11503 /// CompleteNonViableCandidate - Normally, overload resolution only 11504 /// computes up to the first bad conversion. Produces the FixIt set if 11505 /// possible. 11506 static void 11507 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11508 ArrayRef<Expr *> Args, 11509 OverloadCandidateSet::CandidateSetKind CSK) { 11510 assert(!Cand->Viable); 11511 11512 // Don't do anything on failures other than bad conversion. 11513 if (Cand->FailureKind != ovl_fail_bad_conversion) 11514 return; 11515 11516 // We only want the FixIts if all the arguments can be corrected. 11517 bool Unfixable = false; 11518 // Use a implicit copy initialization to check conversion fixes. 11519 Cand->Fix.setConversionChecker(TryCopyInitialization); 11520 11521 // Attempt to fix the bad conversion. 11522 unsigned ConvCount = Cand->Conversions.size(); 11523 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11524 ++ConvIdx) { 11525 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11526 if (Cand->Conversions[ConvIdx].isInitialized() && 11527 Cand->Conversions[ConvIdx].isBad()) { 11528 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11529 break; 11530 } 11531 } 11532 11533 // FIXME: this should probably be preserved from the overload 11534 // operation somehow. 11535 bool SuppressUserConversions = false; 11536 11537 unsigned ConvIdx = 0; 11538 unsigned ArgIdx = 0; 11539 ArrayRef<QualType> ParamTypes; 11540 bool Reversed = Cand->isReversed(); 11541 11542 if (Cand->IsSurrogate) { 11543 QualType ConvType 11544 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11545 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11546 ConvType = ConvPtrType->getPointeeType(); 11547 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11548 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11549 ConvIdx = 1; 11550 } else if (Cand->Function) { 11551 ParamTypes = 11552 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11553 if (isa<CXXMethodDecl>(Cand->Function) && 11554 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11555 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11556 ConvIdx = 1; 11557 if (CSK == OverloadCandidateSet::CSK_Operator && 11558 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11559 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11560 ArgIdx = 1; 11561 } 11562 } else { 11563 // Builtin operator. 11564 assert(ConvCount <= 3); 11565 ParamTypes = Cand->BuiltinParamTypes; 11566 } 11567 11568 // Fill in the rest of the conversions. 11569 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11570 ConvIdx != ConvCount; 11571 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11572 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11573 if (Cand->Conversions[ConvIdx].isInitialized()) { 11574 // We've already checked this conversion. 11575 } else if (ParamIdx < ParamTypes.size()) { 11576 if (ParamTypes[ParamIdx]->isDependentType()) 11577 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11578 Args[ArgIdx]->getType()); 11579 else { 11580 Cand->Conversions[ConvIdx] = 11581 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11582 SuppressUserConversions, 11583 /*InOverloadResolution=*/true, 11584 /*AllowObjCWritebackConversion=*/ 11585 S.getLangOpts().ObjCAutoRefCount); 11586 // Store the FixIt in the candidate if it exists. 11587 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11588 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11589 } 11590 } else 11591 Cand->Conversions[ConvIdx].setEllipsis(); 11592 } 11593 } 11594 11595 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11596 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11597 SourceLocation OpLoc, 11598 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11599 // Sort the candidates by viability and position. Sorting directly would 11600 // be prohibitive, so we make a set of pointers and sort those. 11601 SmallVector<OverloadCandidate*, 32> Cands; 11602 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11603 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11604 if (!Filter(*Cand)) 11605 continue; 11606 switch (OCD) { 11607 case OCD_AllCandidates: 11608 if (!Cand->Viable) { 11609 if (!Cand->Function && !Cand->IsSurrogate) { 11610 // This a non-viable builtin candidate. We do not, in general, 11611 // want to list every possible builtin candidate. 11612 continue; 11613 } 11614 CompleteNonViableCandidate(S, Cand, Args, Kind); 11615 } 11616 break; 11617 11618 case OCD_ViableCandidates: 11619 if (!Cand->Viable) 11620 continue; 11621 break; 11622 11623 case OCD_AmbiguousCandidates: 11624 if (!Cand->Best) 11625 continue; 11626 break; 11627 } 11628 11629 Cands.push_back(Cand); 11630 } 11631 11632 llvm::stable_sort( 11633 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11634 11635 return Cands; 11636 } 11637 11638 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11639 SourceLocation OpLoc) { 11640 bool DeferHint = false; 11641 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11642 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11643 // host device candidates. 11644 auto WrongSidedCands = 11645 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11646 return (Cand.Viable == false && 11647 Cand.FailureKind == ovl_fail_bad_target) || 11648 (Cand.Function && 11649 Cand.Function->template hasAttr<CUDAHostAttr>() && 11650 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11651 }); 11652 DeferHint = !WrongSidedCands.empty(); 11653 } 11654 return DeferHint; 11655 } 11656 11657 /// When overload resolution fails, prints diagnostic messages containing the 11658 /// candidates in the candidate set. 11659 void OverloadCandidateSet::NoteCandidates( 11660 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11661 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11662 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11663 11664 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11665 11666 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11667 11668 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11669 11670 if (OCD == OCD_AmbiguousCandidates) 11671 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11672 } 11673 11674 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11675 ArrayRef<OverloadCandidate *> Cands, 11676 StringRef Opc, SourceLocation OpLoc) { 11677 bool ReportedAmbiguousConversions = false; 11678 11679 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11680 unsigned CandsShown = 0; 11681 auto I = Cands.begin(), E = Cands.end(); 11682 for (; I != E; ++I) { 11683 OverloadCandidate *Cand = *I; 11684 11685 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11686 ShowOverloads == Ovl_Best) { 11687 break; 11688 } 11689 ++CandsShown; 11690 11691 if (Cand->Function) 11692 NoteFunctionCandidate(S, Cand, Args.size(), 11693 /*TakingCandidateAddress=*/false, DestAS); 11694 else if (Cand->IsSurrogate) 11695 NoteSurrogateCandidate(S, Cand); 11696 else { 11697 assert(Cand->Viable && 11698 "Non-viable built-in candidates are not added to Cands."); 11699 // Generally we only see ambiguities including viable builtin 11700 // operators if overload resolution got screwed up by an 11701 // ambiguous user-defined conversion. 11702 // 11703 // FIXME: It's quite possible for different conversions to see 11704 // different ambiguities, though. 11705 if (!ReportedAmbiguousConversions) { 11706 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11707 ReportedAmbiguousConversions = true; 11708 } 11709 11710 // If this is a viable builtin, print it. 11711 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11712 } 11713 } 11714 11715 // Inform S.Diags that we've shown an overload set with N elements. This may 11716 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11717 S.Diags.overloadCandidatesShown(CandsShown); 11718 11719 if (I != E) 11720 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11721 shouldDeferDiags(S, Args, OpLoc)) 11722 << int(E - I); 11723 } 11724 11725 static SourceLocation 11726 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11727 return Cand->Specialization ? Cand->Specialization->getLocation() 11728 : SourceLocation(); 11729 } 11730 11731 namespace { 11732 struct CompareTemplateSpecCandidatesForDisplay { 11733 Sema &S; 11734 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11735 11736 bool operator()(const TemplateSpecCandidate *L, 11737 const TemplateSpecCandidate *R) { 11738 // Fast-path this check. 11739 if (L == R) 11740 return false; 11741 11742 // Assuming that both candidates are not matches... 11743 11744 // Sort by the ranking of deduction failures. 11745 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11746 return RankDeductionFailure(L->DeductionFailure) < 11747 RankDeductionFailure(R->DeductionFailure); 11748 11749 // Sort everything else by location. 11750 SourceLocation LLoc = GetLocationForCandidate(L); 11751 SourceLocation RLoc = GetLocationForCandidate(R); 11752 11753 // Put candidates without locations (e.g. builtins) at the end. 11754 if (LLoc.isInvalid()) 11755 return false; 11756 if (RLoc.isInvalid()) 11757 return true; 11758 11759 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11760 } 11761 }; 11762 } 11763 11764 /// Diagnose a template argument deduction failure. 11765 /// We are treating these failures as overload failures due to bad 11766 /// deductions. 11767 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11768 bool ForTakingAddress) { 11769 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11770 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11771 } 11772 11773 void TemplateSpecCandidateSet::destroyCandidates() { 11774 for (iterator i = begin(), e = end(); i != e; ++i) { 11775 i->DeductionFailure.Destroy(); 11776 } 11777 } 11778 11779 void TemplateSpecCandidateSet::clear() { 11780 destroyCandidates(); 11781 Candidates.clear(); 11782 } 11783 11784 /// NoteCandidates - When no template specialization match is found, prints 11785 /// diagnostic messages containing the non-matching specializations that form 11786 /// the candidate set. 11787 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11788 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11789 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11790 // Sort the candidates by position (assuming no candidate is a match). 11791 // Sorting directly would be prohibitive, so we make a set of pointers 11792 // and sort those. 11793 SmallVector<TemplateSpecCandidate *, 32> Cands; 11794 Cands.reserve(size()); 11795 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11796 if (Cand->Specialization) 11797 Cands.push_back(Cand); 11798 // Otherwise, this is a non-matching builtin candidate. We do not, 11799 // in general, want to list every possible builtin candidate. 11800 } 11801 11802 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11803 11804 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11805 // for generalization purposes (?). 11806 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11807 11808 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11809 unsigned CandsShown = 0; 11810 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11811 TemplateSpecCandidate *Cand = *I; 11812 11813 // Set an arbitrary limit on the number of candidates we'll spam 11814 // the user with. FIXME: This limit should depend on details of the 11815 // candidate list. 11816 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11817 break; 11818 ++CandsShown; 11819 11820 assert(Cand->Specialization && 11821 "Non-matching built-in candidates are not added to Cands."); 11822 Cand->NoteDeductionFailure(S, ForTakingAddress); 11823 } 11824 11825 if (I != E) 11826 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11827 } 11828 11829 // [PossiblyAFunctionType] --> [Return] 11830 // NonFunctionType --> NonFunctionType 11831 // R (A) --> R(A) 11832 // R (*)(A) --> R (A) 11833 // R (&)(A) --> R (A) 11834 // R (S::*)(A) --> R (A) 11835 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11836 QualType Ret = PossiblyAFunctionType; 11837 if (const PointerType *ToTypePtr = 11838 PossiblyAFunctionType->getAs<PointerType>()) 11839 Ret = ToTypePtr->getPointeeType(); 11840 else if (const ReferenceType *ToTypeRef = 11841 PossiblyAFunctionType->getAs<ReferenceType>()) 11842 Ret = ToTypeRef->getPointeeType(); 11843 else if (const MemberPointerType *MemTypePtr = 11844 PossiblyAFunctionType->getAs<MemberPointerType>()) 11845 Ret = MemTypePtr->getPointeeType(); 11846 Ret = 11847 Context.getCanonicalType(Ret).getUnqualifiedType(); 11848 return Ret; 11849 } 11850 11851 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11852 bool Complain = true) { 11853 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11854 S.DeduceReturnType(FD, Loc, Complain)) 11855 return true; 11856 11857 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11858 if (S.getLangOpts().CPlusPlus17 && 11859 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11860 !S.ResolveExceptionSpec(Loc, FPT)) 11861 return true; 11862 11863 return false; 11864 } 11865 11866 namespace { 11867 // A helper class to help with address of function resolution 11868 // - allows us to avoid passing around all those ugly parameters 11869 class AddressOfFunctionResolver { 11870 Sema& S; 11871 Expr* SourceExpr; 11872 const QualType& TargetType; 11873 QualType TargetFunctionType; // Extracted function type from target type 11874 11875 bool Complain; 11876 //DeclAccessPair& ResultFunctionAccessPair; 11877 ASTContext& Context; 11878 11879 bool TargetTypeIsNonStaticMemberFunction; 11880 bool FoundNonTemplateFunction; 11881 bool StaticMemberFunctionFromBoundPointer; 11882 bool HasComplained; 11883 11884 OverloadExpr::FindResult OvlExprInfo; 11885 OverloadExpr *OvlExpr; 11886 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11887 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11888 TemplateSpecCandidateSet FailedCandidates; 11889 11890 public: 11891 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11892 const QualType &TargetType, bool Complain) 11893 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11894 Complain(Complain), Context(S.getASTContext()), 11895 TargetTypeIsNonStaticMemberFunction( 11896 !!TargetType->getAs<MemberPointerType>()), 11897 FoundNonTemplateFunction(false), 11898 StaticMemberFunctionFromBoundPointer(false), 11899 HasComplained(false), 11900 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11901 OvlExpr(OvlExprInfo.Expression), 11902 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11903 ExtractUnqualifiedFunctionTypeFromTargetType(); 11904 11905 if (TargetFunctionType->isFunctionType()) { 11906 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11907 if (!UME->isImplicitAccess() && 11908 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11909 StaticMemberFunctionFromBoundPointer = true; 11910 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11911 DeclAccessPair dap; 11912 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11913 OvlExpr, false, &dap)) { 11914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11915 if (!Method->isStatic()) { 11916 // If the target type is a non-function type and the function found 11917 // is a non-static member function, pretend as if that was the 11918 // target, it's the only possible type to end up with. 11919 TargetTypeIsNonStaticMemberFunction = true; 11920 11921 // And skip adding the function if its not in the proper form. 11922 // We'll diagnose this due to an empty set of functions. 11923 if (!OvlExprInfo.HasFormOfMemberPointer) 11924 return; 11925 } 11926 11927 Matches.push_back(std::make_pair(dap, Fn)); 11928 } 11929 return; 11930 } 11931 11932 if (OvlExpr->hasExplicitTemplateArgs()) 11933 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11934 11935 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11936 // C++ [over.over]p4: 11937 // If more than one function is selected, [...] 11938 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11939 if (FoundNonTemplateFunction) 11940 EliminateAllTemplateMatches(); 11941 else 11942 EliminateAllExceptMostSpecializedTemplate(); 11943 } 11944 } 11945 11946 if (S.getLangOpts().CUDA && Matches.size() > 1) 11947 EliminateSuboptimalCudaMatches(); 11948 } 11949 11950 bool hasComplained() const { return HasComplained; } 11951 11952 private: 11953 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11954 QualType Discard; 11955 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11956 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11957 } 11958 11959 /// \return true if A is considered a better overload candidate for the 11960 /// desired type than B. 11961 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11962 // If A doesn't have exactly the correct type, we don't want to classify it 11963 // as "better" than anything else. This way, the user is required to 11964 // disambiguate for us if there are multiple candidates and no exact match. 11965 return candidateHasExactlyCorrectType(A) && 11966 (!candidateHasExactlyCorrectType(B) || 11967 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11968 } 11969 11970 /// \return true if we were able to eliminate all but one overload candidate, 11971 /// false otherwise. 11972 bool eliminiateSuboptimalOverloadCandidates() { 11973 // Same algorithm as overload resolution -- one pass to pick the "best", 11974 // another pass to be sure that nothing is better than the best. 11975 auto Best = Matches.begin(); 11976 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11977 if (isBetterCandidate(I->second, Best->second)) 11978 Best = I; 11979 11980 const FunctionDecl *BestFn = Best->second; 11981 auto IsBestOrInferiorToBest = [this, BestFn]( 11982 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11983 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11984 }; 11985 11986 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11987 // option, so we can potentially give the user a better error 11988 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11989 return false; 11990 Matches[0] = *Best; 11991 Matches.resize(1); 11992 return true; 11993 } 11994 11995 bool isTargetTypeAFunction() const { 11996 return TargetFunctionType->isFunctionType(); 11997 } 11998 11999 // [ToType] [Return] 12000 12001 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12002 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12003 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12004 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12005 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12006 } 12007 12008 // return true if any matching specializations were found 12009 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12010 const DeclAccessPair& CurAccessFunPair) { 12011 if (CXXMethodDecl *Method 12012 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12013 // Skip non-static function templates when converting to pointer, and 12014 // static when converting to member pointer. 12015 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12016 return false; 12017 } 12018 else if (TargetTypeIsNonStaticMemberFunction) 12019 return false; 12020 12021 // C++ [over.over]p2: 12022 // If the name is a function template, template argument deduction is 12023 // done (14.8.2.2), and if the argument deduction succeeds, the 12024 // resulting template argument list is used to generate a single 12025 // function template specialization, which is added to the set of 12026 // overloaded functions considered. 12027 FunctionDecl *Specialization = nullptr; 12028 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12029 if (Sema::TemplateDeductionResult Result 12030 = S.DeduceTemplateArguments(FunctionTemplate, 12031 &OvlExplicitTemplateArgs, 12032 TargetFunctionType, Specialization, 12033 Info, /*IsAddressOfFunction*/true)) { 12034 // Make a note of the failed deduction for diagnostics. 12035 FailedCandidates.addCandidate() 12036 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12037 MakeDeductionFailureInfo(Context, Result, Info)); 12038 return false; 12039 } 12040 12041 // Template argument deduction ensures that we have an exact match or 12042 // compatible pointer-to-function arguments that would be adjusted by ICS. 12043 // This function template specicalization works. 12044 assert(S.isSameOrCompatibleFunctionType( 12045 Context.getCanonicalType(Specialization->getType()), 12046 Context.getCanonicalType(TargetFunctionType))); 12047 12048 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12049 return false; 12050 12051 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12052 return true; 12053 } 12054 12055 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12056 const DeclAccessPair& CurAccessFunPair) { 12057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12058 // Skip non-static functions when converting to pointer, and static 12059 // when converting to member pointer. 12060 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12061 return false; 12062 } 12063 else if (TargetTypeIsNonStaticMemberFunction) 12064 return false; 12065 12066 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12067 if (S.getLangOpts().CUDA) 12068 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12069 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12070 return false; 12071 if (FunDecl->isMultiVersion()) { 12072 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12073 if (TA && !TA->isDefaultVersion()) 12074 return false; 12075 } 12076 12077 // If any candidate has a placeholder return type, trigger its deduction 12078 // now. 12079 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12080 Complain)) { 12081 HasComplained |= Complain; 12082 return false; 12083 } 12084 12085 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12086 return false; 12087 12088 // If we're in C, we need to support types that aren't exactly identical. 12089 if (!S.getLangOpts().CPlusPlus || 12090 candidateHasExactlyCorrectType(FunDecl)) { 12091 Matches.push_back(std::make_pair( 12092 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12093 FoundNonTemplateFunction = true; 12094 return true; 12095 } 12096 } 12097 12098 return false; 12099 } 12100 12101 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12102 bool Ret = false; 12103 12104 // If the overload expression doesn't have the form of a pointer to 12105 // member, don't try to convert it to a pointer-to-member type. 12106 if (IsInvalidFormOfPointerToMemberFunction()) 12107 return false; 12108 12109 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12110 E = OvlExpr->decls_end(); 12111 I != E; ++I) { 12112 // Look through any using declarations to find the underlying function. 12113 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12114 12115 // C++ [over.over]p3: 12116 // Non-member functions and static member functions match 12117 // targets of type "pointer-to-function" or "reference-to-function." 12118 // Nonstatic member functions match targets of 12119 // type "pointer-to-member-function." 12120 // Note that according to DR 247, the containing class does not matter. 12121 if (FunctionTemplateDecl *FunctionTemplate 12122 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12123 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12124 Ret = true; 12125 } 12126 // If we have explicit template arguments supplied, skip non-templates. 12127 else if (!OvlExpr->hasExplicitTemplateArgs() && 12128 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12129 Ret = true; 12130 } 12131 assert(Ret || Matches.empty()); 12132 return Ret; 12133 } 12134 12135 void EliminateAllExceptMostSpecializedTemplate() { 12136 // [...] and any given function template specialization F1 is 12137 // eliminated if the set contains a second function template 12138 // specialization whose function template is more specialized 12139 // than the function template of F1 according to the partial 12140 // ordering rules of 14.5.5.2. 12141 12142 // The algorithm specified above is quadratic. We instead use a 12143 // two-pass algorithm (similar to the one used to identify the 12144 // best viable function in an overload set) that identifies the 12145 // best function template (if it exists). 12146 12147 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12148 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12149 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12150 12151 // TODO: It looks like FailedCandidates does not serve much purpose 12152 // here, since the no_viable diagnostic has index 0. 12153 UnresolvedSetIterator Result = S.getMostSpecialized( 12154 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12155 SourceExpr->getBeginLoc(), S.PDiag(), 12156 S.PDiag(diag::err_addr_ovl_ambiguous) 12157 << Matches[0].second->getDeclName(), 12158 S.PDiag(diag::note_ovl_candidate) 12159 << (unsigned)oc_function << (unsigned)ocs_described_template, 12160 Complain, TargetFunctionType); 12161 12162 if (Result != MatchesCopy.end()) { 12163 // Make it the first and only element 12164 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12165 Matches[0].second = cast<FunctionDecl>(*Result); 12166 Matches.resize(1); 12167 } else 12168 HasComplained |= Complain; 12169 } 12170 12171 void EliminateAllTemplateMatches() { 12172 // [...] any function template specializations in the set are 12173 // eliminated if the set also contains a non-template function, [...] 12174 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12175 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12176 ++I; 12177 else { 12178 Matches[I] = Matches[--N]; 12179 Matches.resize(N); 12180 } 12181 } 12182 } 12183 12184 void EliminateSuboptimalCudaMatches() { 12185 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12186 } 12187 12188 public: 12189 void ComplainNoMatchesFound() const { 12190 assert(Matches.empty()); 12191 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12192 << OvlExpr->getName() << TargetFunctionType 12193 << OvlExpr->getSourceRange(); 12194 if (FailedCandidates.empty()) 12195 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12196 /*TakingAddress=*/true); 12197 else { 12198 // We have some deduction failure messages. Use them to diagnose 12199 // the function templates, and diagnose the non-template candidates 12200 // normally. 12201 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12202 IEnd = OvlExpr->decls_end(); 12203 I != IEnd; ++I) 12204 if (FunctionDecl *Fun = 12205 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12206 if (!functionHasPassObjectSizeParams(Fun)) 12207 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12208 /*TakingAddress=*/true); 12209 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12210 } 12211 } 12212 12213 bool IsInvalidFormOfPointerToMemberFunction() const { 12214 return TargetTypeIsNonStaticMemberFunction && 12215 !OvlExprInfo.HasFormOfMemberPointer; 12216 } 12217 12218 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12219 // TODO: Should we condition this on whether any functions might 12220 // have matched, or is it more appropriate to do that in callers? 12221 // TODO: a fixit wouldn't hurt. 12222 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12223 << TargetType << OvlExpr->getSourceRange(); 12224 } 12225 12226 bool IsStaticMemberFunctionFromBoundPointer() const { 12227 return StaticMemberFunctionFromBoundPointer; 12228 } 12229 12230 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12231 S.Diag(OvlExpr->getBeginLoc(), 12232 diag::err_invalid_form_pointer_member_function) 12233 << OvlExpr->getSourceRange(); 12234 } 12235 12236 void ComplainOfInvalidConversion() const { 12237 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12238 << OvlExpr->getName() << TargetType; 12239 } 12240 12241 void ComplainMultipleMatchesFound() const { 12242 assert(Matches.size() > 1); 12243 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12244 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12245 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12246 /*TakingAddress=*/true); 12247 } 12248 12249 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12250 12251 int getNumMatches() const { return Matches.size(); } 12252 12253 FunctionDecl* getMatchingFunctionDecl() const { 12254 if (Matches.size() != 1) return nullptr; 12255 return Matches[0].second; 12256 } 12257 12258 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12259 if (Matches.size() != 1) return nullptr; 12260 return &Matches[0].first; 12261 } 12262 }; 12263 } 12264 12265 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12266 /// an overloaded function (C++ [over.over]), where @p From is an 12267 /// expression with overloaded function type and @p ToType is the type 12268 /// we're trying to resolve to. For example: 12269 /// 12270 /// @code 12271 /// int f(double); 12272 /// int f(int); 12273 /// 12274 /// int (*pfd)(double) = f; // selects f(double) 12275 /// @endcode 12276 /// 12277 /// This routine returns the resulting FunctionDecl if it could be 12278 /// resolved, and NULL otherwise. When @p Complain is true, this 12279 /// routine will emit diagnostics if there is an error. 12280 FunctionDecl * 12281 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12282 QualType TargetType, 12283 bool Complain, 12284 DeclAccessPair &FoundResult, 12285 bool *pHadMultipleCandidates) { 12286 assert(AddressOfExpr->getType() == Context.OverloadTy); 12287 12288 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12289 Complain); 12290 int NumMatches = Resolver.getNumMatches(); 12291 FunctionDecl *Fn = nullptr; 12292 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12293 if (NumMatches == 0 && ShouldComplain) { 12294 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12295 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12296 else 12297 Resolver.ComplainNoMatchesFound(); 12298 } 12299 else if (NumMatches > 1 && ShouldComplain) 12300 Resolver.ComplainMultipleMatchesFound(); 12301 else if (NumMatches == 1) { 12302 Fn = Resolver.getMatchingFunctionDecl(); 12303 assert(Fn); 12304 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12305 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12306 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12307 if (Complain) { 12308 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12309 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12310 else 12311 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12312 } 12313 } 12314 12315 if (pHadMultipleCandidates) 12316 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12317 return Fn; 12318 } 12319 12320 /// Given an expression that refers to an overloaded function, try to 12321 /// resolve that function to a single function that can have its address taken. 12322 /// This will modify `Pair` iff it returns non-null. 12323 /// 12324 /// This routine can only succeed if from all of the candidates in the overload 12325 /// set for SrcExpr that can have their addresses taken, there is one candidate 12326 /// that is more constrained than the rest. 12327 FunctionDecl * 12328 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12329 OverloadExpr::FindResult R = OverloadExpr::find(E); 12330 OverloadExpr *Ovl = R.Expression; 12331 bool IsResultAmbiguous = false; 12332 FunctionDecl *Result = nullptr; 12333 DeclAccessPair DAP; 12334 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12335 12336 auto CheckMoreConstrained = 12337 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12338 SmallVector<const Expr *, 1> AC1, AC2; 12339 FD1->getAssociatedConstraints(AC1); 12340 FD2->getAssociatedConstraints(AC2); 12341 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12342 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12343 return None; 12344 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12345 return None; 12346 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12347 return None; 12348 return AtLeastAsConstrained1; 12349 }; 12350 12351 // Don't use the AddressOfResolver because we're specifically looking for 12352 // cases where we have one overload candidate that lacks 12353 // enable_if/pass_object_size/... 12354 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12355 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12356 if (!FD) 12357 return nullptr; 12358 12359 if (!checkAddressOfFunctionIsAvailable(FD)) 12360 continue; 12361 12362 // We have more than one result - see if it is more constrained than the 12363 // previous one. 12364 if (Result) { 12365 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12366 Result); 12367 if (!MoreConstrainedThanPrevious) { 12368 IsResultAmbiguous = true; 12369 AmbiguousDecls.push_back(FD); 12370 continue; 12371 } 12372 if (!*MoreConstrainedThanPrevious) 12373 continue; 12374 // FD is more constrained - replace Result with it. 12375 } 12376 IsResultAmbiguous = false; 12377 DAP = I.getPair(); 12378 Result = FD; 12379 } 12380 12381 if (IsResultAmbiguous) 12382 return nullptr; 12383 12384 if (Result) { 12385 SmallVector<const Expr *, 1> ResultAC; 12386 // We skipped over some ambiguous declarations which might be ambiguous with 12387 // the selected result. 12388 for (FunctionDecl *Skipped : AmbiguousDecls) 12389 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12390 return nullptr; 12391 Pair = DAP; 12392 } 12393 return Result; 12394 } 12395 12396 /// Given an overloaded function, tries to turn it into a non-overloaded 12397 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12398 /// will perform access checks, diagnose the use of the resultant decl, and, if 12399 /// requested, potentially perform a function-to-pointer decay. 12400 /// 12401 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12402 /// Otherwise, returns true. This may emit diagnostics and return true. 12403 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12404 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12405 Expr *E = SrcExpr.get(); 12406 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12407 12408 DeclAccessPair DAP; 12409 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12410 if (!Found || Found->isCPUDispatchMultiVersion() || 12411 Found->isCPUSpecificMultiVersion()) 12412 return false; 12413 12414 // Emitting multiple diagnostics for a function that is both inaccessible and 12415 // unavailable is consistent with our behavior elsewhere. So, always check 12416 // for both. 12417 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12418 CheckAddressOfMemberAccess(E, DAP); 12419 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12420 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12421 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12422 else 12423 SrcExpr = Fixed; 12424 return true; 12425 } 12426 12427 /// Given an expression that refers to an overloaded function, try to 12428 /// resolve that overloaded function expression down to a single function. 12429 /// 12430 /// This routine can only resolve template-ids that refer to a single function 12431 /// template, where that template-id refers to a single template whose template 12432 /// arguments are either provided by the template-id or have defaults, 12433 /// as described in C++0x [temp.arg.explicit]p3. 12434 /// 12435 /// If no template-ids are found, no diagnostics are emitted and NULL is 12436 /// returned. 12437 FunctionDecl * 12438 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12439 bool Complain, 12440 DeclAccessPair *FoundResult) { 12441 // C++ [over.over]p1: 12442 // [...] [Note: any redundant set of parentheses surrounding the 12443 // overloaded function name is ignored (5.1). ] 12444 // C++ [over.over]p1: 12445 // [...] The overloaded function name can be preceded by the & 12446 // operator. 12447 12448 // If we didn't actually find any template-ids, we're done. 12449 if (!ovl->hasExplicitTemplateArgs()) 12450 return nullptr; 12451 12452 TemplateArgumentListInfo ExplicitTemplateArgs; 12453 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12454 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12455 12456 // Look through all of the overloaded functions, searching for one 12457 // whose type matches exactly. 12458 FunctionDecl *Matched = nullptr; 12459 for (UnresolvedSetIterator I = ovl->decls_begin(), 12460 E = ovl->decls_end(); I != E; ++I) { 12461 // C++0x [temp.arg.explicit]p3: 12462 // [...] In contexts where deduction is done and fails, or in contexts 12463 // where deduction is not done, if a template argument list is 12464 // specified and it, along with any default template arguments, 12465 // identifies a single function template specialization, then the 12466 // template-id is an lvalue for the function template specialization. 12467 FunctionTemplateDecl *FunctionTemplate 12468 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12469 12470 // C++ [over.over]p2: 12471 // If the name is a function template, template argument deduction is 12472 // done (14.8.2.2), and if the argument deduction succeeds, the 12473 // resulting template argument list is used to generate a single 12474 // function template specialization, which is added to the set of 12475 // overloaded functions considered. 12476 FunctionDecl *Specialization = nullptr; 12477 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12478 if (TemplateDeductionResult Result 12479 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12480 Specialization, Info, 12481 /*IsAddressOfFunction*/true)) { 12482 // Make a note of the failed deduction for diagnostics. 12483 // TODO: Actually use the failed-deduction info? 12484 FailedCandidates.addCandidate() 12485 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12486 MakeDeductionFailureInfo(Context, Result, Info)); 12487 continue; 12488 } 12489 12490 assert(Specialization && "no specialization and no error?"); 12491 12492 // Multiple matches; we can't resolve to a single declaration. 12493 if (Matched) { 12494 if (Complain) { 12495 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12496 << ovl->getName(); 12497 NoteAllOverloadCandidates(ovl); 12498 } 12499 return nullptr; 12500 } 12501 12502 Matched = Specialization; 12503 if (FoundResult) *FoundResult = I.getPair(); 12504 } 12505 12506 if (Matched && 12507 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12508 return nullptr; 12509 12510 return Matched; 12511 } 12512 12513 // Resolve and fix an overloaded expression that can be resolved 12514 // because it identifies a single function template specialization. 12515 // 12516 // Last three arguments should only be supplied if Complain = true 12517 // 12518 // Return true if it was logically possible to so resolve the 12519 // expression, regardless of whether or not it succeeded. Always 12520 // returns true if 'complain' is set. 12521 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12522 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12523 bool complain, SourceRange OpRangeForComplaining, 12524 QualType DestTypeForComplaining, 12525 unsigned DiagIDForComplaining) { 12526 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12527 12528 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12529 12530 DeclAccessPair found; 12531 ExprResult SingleFunctionExpression; 12532 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12533 ovl.Expression, /*complain*/ false, &found)) { 12534 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12535 SrcExpr = ExprError(); 12536 return true; 12537 } 12538 12539 // It is only correct to resolve to an instance method if we're 12540 // resolving a form that's permitted to be a pointer to member. 12541 // Otherwise we'll end up making a bound member expression, which 12542 // is illegal in all the contexts we resolve like this. 12543 if (!ovl.HasFormOfMemberPointer && 12544 isa<CXXMethodDecl>(fn) && 12545 cast<CXXMethodDecl>(fn)->isInstance()) { 12546 if (!complain) return false; 12547 12548 Diag(ovl.Expression->getExprLoc(), 12549 diag::err_bound_member_function) 12550 << 0 << ovl.Expression->getSourceRange(); 12551 12552 // TODO: I believe we only end up here if there's a mix of 12553 // static and non-static candidates (otherwise the expression 12554 // would have 'bound member' type, not 'overload' type). 12555 // Ideally we would note which candidate was chosen and why 12556 // the static candidates were rejected. 12557 SrcExpr = ExprError(); 12558 return true; 12559 } 12560 12561 // Fix the expression to refer to 'fn'. 12562 SingleFunctionExpression = 12563 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12564 12565 // If desired, do function-to-pointer decay. 12566 if (doFunctionPointerConverion) { 12567 SingleFunctionExpression = 12568 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12569 if (SingleFunctionExpression.isInvalid()) { 12570 SrcExpr = ExprError(); 12571 return true; 12572 } 12573 } 12574 } 12575 12576 if (!SingleFunctionExpression.isUsable()) { 12577 if (complain) { 12578 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12579 << ovl.Expression->getName() 12580 << DestTypeForComplaining 12581 << OpRangeForComplaining 12582 << ovl.Expression->getQualifierLoc().getSourceRange(); 12583 NoteAllOverloadCandidates(SrcExpr.get()); 12584 12585 SrcExpr = ExprError(); 12586 return true; 12587 } 12588 12589 return false; 12590 } 12591 12592 SrcExpr = SingleFunctionExpression; 12593 return true; 12594 } 12595 12596 /// Add a single candidate to the overload set. 12597 static void AddOverloadedCallCandidate(Sema &S, 12598 DeclAccessPair FoundDecl, 12599 TemplateArgumentListInfo *ExplicitTemplateArgs, 12600 ArrayRef<Expr *> Args, 12601 OverloadCandidateSet &CandidateSet, 12602 bool PartialOverloading, 12603 bool KnownValid) { 12604 NamedDecl *Callee = FoundDecl.getDecl(); 12605 if (isa<UsingShadowDecl>(Callee)) 12606 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12607 12608 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12609 if (ExplicitTemplateArgs) { 12610 assert(!KnownValid && "Explicit template arguments?"); 12611 return; 12612 } 12613 // Prevent ill-formed function decls to be added as overload candidates. 12614 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12615 return; 12616 12617 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12618 /*SuppressUserConversions=*/false, 12619 PartialOverloading); 12620 return; 12621 } 12622 12623 if (FunctionTemplateDecl *FuncTemplate 12624 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12625 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12626 ExplicitTemplateArgs, Args, CandidateSet, 12627 /*SuppressUserConversions=*/false, 12628 PartialOverloading); 12629 return; 12630 } 12631 12632 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12633 } 12634 12635 /// Add the overload candidates named by callee and/or found by argument 12636 /// dependent lookup to the given overload set. 12637 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12638 ArrayRef<Expr *> Args, 12639 OverloadCandidateSet &CandidateSet, 12640 bool PartialOverloading) { 12641 12642 #ifndef NDEBUG 12643 // Verify that ArgumentDependentLookup is consistent with the rules 12644 // in C++0x [basic.lookup.argdep]p3: 12645 // 12646 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12647 // and let Y be the lookup set produced by argument dependent 12648 // lookup (defined as follows). If X contains 12649 // 12650 // -- a declaration of a class member, or 12651 // 12652 // -- a block-scope function declaration that is not a 12653 // using-declaration, or 12654 // 12655 // -- a declaration that is neither a function or a function 12656 // template 12657 // 12658 // then Y is empty. 12659 12660 if (ULE->requiresADL()) { 12661 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12662 E = ULE->decls_end(); I != E; ++I) { 12663 assert(!(*I)->getDeclContext()->isRecord()); 12664 assert(isa<UsingShadowDecl>(*I) || 12665 !(*I)->getDeclContext()->isFunctionOrMethod()); 12666 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12667 } 12668 } 12669 #endif 12670 12671 // It would be nice to avoid this copy. 12672 TemplateArgumentListInfo TABuffer; 12673 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12674 if (ULE->hasExplicitTemplateArgs()) { 12675 ULE->copyTemplateArgumentsInto(TABuffer); 12676 ExplicitTemplateArgs = &TABuffer; 12677 } 12678 12679 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12680 E = ULE->decls_end(); I != E; ++I) 12681 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12682 CandidateSet, PartialOverloading, 12683 /*KnownValid*/ true); 12684 12685 if (ULE->requiresADL()) 12686 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12687 Args, ExplicitTemplateArgs, 12688 CandidateSet, PartialOverloading); 12689 } 12690 12691 /// Add the call candidates from the given set of lookup results to the given 12692 /// overload set. Non-function lookup results are ignored. 12693 void Sema::AddOverloadedCallCandidates( 12694 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12695 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12696 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12697 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12698 CandidateSet, false, /*KnownValid*/ false); 12699 } 12700 12701 /// Determine whether a declaration with the specified name could be moved into 12702 /// a different namespace. 12703 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12704 switch (Name.getCXXOverloadedOperator()) { 12705 case OO_New: case OO_Array_New: 12706 case OO_Delete: case OO_Array_Delete: 12707 return false; 12708 12709 default: 12710 return true; 12711 } 12712 } 12713 12714 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12715 /// template, where the non-dependent name was declared after the template 12716 /// was defined. This is common in code written for a compilers which do not 12717 /// correctly implement two-stage name lookup. 12718 /// 12719 /// Returns true if a viable candidate was found and a diagnostic was issued. 12720 static bool DiagnoseTwoPhaseLookup( 12721 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12722 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12723 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12724 CXXRecordDecl **FoundInClass = nullptr) { 12725 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12726 return false; 12727 12728 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12729 if (DC->isTransparentContext()) 12730 continue; 12731 12732 SemaRef.LookupQualifiedName(R, DC); 12733 12734 if (!R.empty()) { 12735 R.suppressDiagnostics(); 12736 12737 OverloadCandidateSet Candidates(FnLoc, CSK); 12738 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12739 Candidates); 12740 12741 OverloadCandidateSet::iterator Best; 12742 OverloadingResult OR = 12743 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12744 12745 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12746 // We either found non-function declarations or a best viable function 12747 // at class scope. A class-scope lookup result disables ADL. Don't 12748 // look past this, but let the caller know that we found something that 12749 // either is, or might be, usable in this class. 12750 if (FoundInClass) { 12751 *FoundInClass = RD; 12752 if (OR == OR_Success) { 12753 R.clear(); 12754 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12755 R.resolveKind(); 12756 } 12757 } 12758 return false; 12759 } 12760 12761 if (OR != OR_Success) { 12762 // There wasn't a unique best function or function template. 12763 return false; 12764 } 12765 12766 // Find the namespaces where ADL would have looked, and suggest 12767 // declaring the function there instead. 12768 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12769 Sema::AssociatedClassSet AssociatedClasses; 12770 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12771 AssociatedNamespaces, 12772 AssociatedClasses); 12773 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12774 if (canBeDeclaredInNamespace(R.getLookupName())) { 12775 DeclContext *Std = SemaRef.getStdNamespace(); 12776 for (Sema::AssociatedNamespaceSet::iterator 12777 it = AssociatedNamespaces.begin(), 12778 end = AssociatedNamespaces.end(); it != end; ++it) { 12779 // Never suggest declaring a function within namespace 'std'. 12780 if (Std && Std->Encloses(*it)) 12781 continue; 12782 12783 // Never suggest declaring a function within a namespace with a 12784 // reserved name, like __gnu_cxx. 12785 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12786 if (NS && 12787 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12788 continue; 12789 12790 SuggestedNamespaces.insert(*it); 12791 } 12792 } 12793 12794 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12795 << R.getLookupName(); 12796 if (SuggestedNamespaces.empty()) { 12797 SemaRef.Diag(Best->Function->getLocation(), 12798 diag::note_not_found_by_two_phase_lookup) 12799 << R.getLookupName() << 0; 12800 } else if (SuggestedNamespaces.size() == 1) { 12801 SemaRef.Diag(Best->Function->getLocation(), 12802 diag::note_not_found_by_two_phase_lookup) 12803 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12804 } else { 12805 // FIXME: It would be useful to list the associated namespaces here, 12806 // but the diagnostics infrastructure doesn't provide a way to produce 12807 // a localized representation of a list of items. 12808 SemaRef.Diag(Best->Function->getLocation(), 12809 diag::note_not_found_by_two_phase_lookup) 12810 << R.getLookupName() << 2; 12811 } 12812 12813 // Try to recover by calling this function. 12814 return true; 12815 } 12816 12817 R.clear(); 12818 } 12819 12820 return false; 12821 } 12822 12823 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12824 /// template, where the non-dependent operator was declared after the template 12825 /// was defined. 12826 /// 12827 /// Returns true if a viable candidate was found and a diagnostic was issued. 12828 static bool 12829 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12830 SourceLocation OpLoc, 12831 ArrayRef<Expr *> Args) { 12832 DeclarationName OpName = 12833 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12834 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12835 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12836 OverloadCandidateSet::CSK_Operator, 12837 /*ExplicitTemplateArgs=*/nullptr, Args); 12838 } 12839 12840 namespace { 12841 class BuildRecoveryCallExprRAII { 12842 Sema &SemaRef; 12843 public: 12844 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12845 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12846 SemaRef.IsBuildingRecoveryCallExpr = true; 12847 } 12848 12849 ~BuildRecoveryCallExprRAII() { 12850 SemaRef.IsBuildingRecoveryCallExpr = false; 12851 } 12852 }; 12853 12854 } 12855 12856 /// Attempts to recover from a call where no functions were found. 12857 /// 12858 /// This function will do one of three things: 12859 /// * Diagnose, recover, and return a recovery expression. 12860 /// * Diagnose, fail to recover, and return ExprError(). 12861 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 12862 /// expected to diagnose as appropriate. 12863 static ExprResult 12864 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12865 UnresolvedLookupExpr *ULE, 12866 SourceLocation LParenLoc, 12867 MutableArrayRef<Expr *> Args, 12868 SourceLocation RParenLoc, 12869 bool EmptyLookup, bool AllowTypoCorrection) { 12870 // Do not try to recover if it is already building a recovery call. 12871 // This stops infinite loops for template instantiations like 12872 // 12873 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12874 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12875 if (SemaRef.IsBuildingRecoveryCallExpr) 12876 return ExprResult(); 12877 BuildRecoveryCallExprRAII RCE(SemaRef); 12878 12879 CXXScopeSpec SS; 12880 SS.Adopt(ULE->getQualifierLoc()); 12881 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12882 12883 TemplateArgumentListInfo TABuffer; 12884 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12885 if (ULE->hasExplicitTemplateArgs()) { 12886 ULE->copyTemplateArgumentsInto(TABuffer); 12887 ExplicitTemplateArgs = &TABuffer; 12888 } 12889 12890 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12891 Sema::LookupOrdinaryName); 12892 CXXRecordDecl *FoundInClass = nullptr; 12893 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 12894 OverloadCandidateSet::CSK_Normal, 12895 ExplicitTemplateArgs, Args, &FoundInClass)) { 12896 // OK, diagnosed a two-phase lookup issue. 12897 } else if (EmptyLookup) { 12898 // Try to recover from an empty lookup with typo correction. 12899 R.clear(); 12900 NoTypoCorrectionCCC NoTypoValidator{}; 12901 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12902 ExplicitTemplateArgs != nullptr, 12903 dyn_cast<MemberExpr>(Fn)); 12904 CorrectionCandidateCallback &Validator = 12905 AllowTypoCorrection 12906 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12907 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12908 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12909 Args)) 12910 return ExprError(); 12911 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 12912 // We found a usable declaration of the name in a dependent base of some 12913 // enclosing class. 12914 // FIXME: We should also explain why the candidates found by name lookup 12915 // were not viable. 12916 if (SemaRef.DiagnoseDependentMemberLookup(R)) 12917 return ExprError(); 12918 } else { 12919 // We had viable candidates and couldn't recover; let the caller diagnose 12920 // this. 12921 return ExprResult(); 12922 } 12923 12924 // If we get here, we should have issued a diagnostic and formed a recovery 12925 // lookup result. 12926 assert(!R.empty() && "lookup results empty despite recovery"); 12927 12928 // If recovery created an ambiguity, just bail out. 12929 if (R.isAmbiguous()) { 12930 R.suppressDiagnostics(); 12931 return ExprError(); 12932 } 12933 12934 // Build an implicit member call if appropriate. Just drop the 12935 // casts and such from the call, we don't really care. 12936 ExprResult NewFn = ExprError(); 12937 if ((*R.begin())->isCXXClassMember()) 12938 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12939 ExplicitTemplateArgs, S); 12940 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12941 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12942 ExplicitTemplateArgs); 12943 else 12944 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12945 12946 if (NewFn.isInvalid()) 12947 return ExprError(); 12948 12949 // This shouldn't cause an infinite loop because we're giving it 12950 // an expression with viable lookup results, which should never 12951 // end up here. 12952 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12953 MultiExprArg(Args.data(), Args.size()), 12954 RParenLoc); 12955 } 12956 12957 /// Constructs and populates an OverloadedCandidateSet from 12958 /// the given function. 12959 /// \returns true when an the ExprResult output parameter has been set. 12960 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12961 UnresolvedLookupExpr *ULE, 12962 MultiExprArg Args, 12963 SourceLocation RParenLoc, 12964 OverloadCandidateSet *CandidateSet, 12965 ExprResult *Result) { 12966 #ifndef NDEBUG 12967 if (ULE->requiresADL()) { 12968 // To do ADL, we must have found an unqualified name. 12969 assert(!ULE->getQualifier() && "qualified name with ADL"); 12970 12971 // We don't perform ADL for implicit declarations of builtins. 12972 // Verify that this was correctly set up. 12973 FunctionDecl *F; 12974 if (ULE->decls_begin() != ULE->decls_end() && 12975 ULE->decls_begin() + 1 == ULE->decls_end() && 12976 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12977 F->getBuiltinID() && F->isImplicit()) 12978 llvm_unreachable("performing ADL for builtin"); 12979 12980 // We don't perform ADL in C. 12981 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12982 } 12983 #endif 12984 12985 UnbridgedCastsSet UnbridgedCasts; 12986 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12987 *Result = ExprError(); 12988 return true; 12989 } 12990 12991 // Add the functions denoted by the callee to the set of candidate 12992 // functions, including those from argument-dependent lookup. 12993 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12994 12995 if (getLangOpts().MSVCCompat && 12996 CurContext->isDependentContext() && !isSFINAEContext() && 12997 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12998 12999 OverloadCandidateSet::iterator Best; 13000 if (CandidateSet->empty() || 13001 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13002 OR_No_Viable_Function) { 13003 // In Microsoft mode, if we are inside a template class member function 13004 // then create a type dependent CallExpr. The goal is to postpone name 13005 // lookup to instantiation time to be able to search into type dependent 13006 // base classes. 13007 CallExpr *CE = 13008 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13009 RParenLoc, CurFPFeatureOverrides()); 13010 CE->markDependentForPostponedNameLookup(); 13011 *Result = CE; 13012 return true; 13013 } 13014 } 13015 13016 if (CandidateSet->empty()) 13017 return false; 13018 13019 UnbridgedCasts.restore(); 13020 return false; 13021 } 13022 13023 // Guess at what the return type for an unresolvable overload should be. 13024 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13025 OverloadCandidateSet::iterator *Best) { 13026 llvm::Optional<QualType> Result; 13027 // Adjust Type after seeing a candidate. 13028 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13029 if (!Candidate.Function) 13030 return; 13031 if (Candidate.Function->isInvalidDecl()) 13032 return; 13033 QualType T = Candidate.Function->getReturnType(); 13034 if (T.isNull()) 13035 return; 13036 if (!Result) 13037 Result = T; 13038 else if (Result != T) 13039 Result = QualType(); 13040 }; 13041 13042 // Look for an unambiguous type from a progressively larger subset. 13043 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13044 // 13045 // First, consider only the best candidate. 13046 if (Best && *Best != CS.end()) 13047 ConsiderCandidate(**Best); 13048 // Next, consider only viable candidates. 13049 if (!Result) 13050 for (const auto &C : CS) 13051 if (C.Viable) 13052 ConsiderCandidate(C); 13053 // Finally, consider all candidates. 13054 if (!Result) 13055 for (const auto &C : CS) 13056 ConsiderCandidate(C); 13057 13058 if (!Result) 13059 return QualType(); 13060 auto Value = Result.getValue(); 13061 if (Value.isNull() || Value->isUndeducedType()) 13062 return QualType(); 13063 return Value; 13064 } 13065 13066 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13067 /// the completed call expression. If overload resolution fails, emits 13068 /// diagnostics and returns ExprError() 13069 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13070 UnresolvedLookupExpr *ULE, 13071 SourceLocation LParenLoc, 13072 MultiExprArg Args, 13073 SourceLocation RParenLoc, 13074 Expr *ExecConfig, 13075 OverloadCandidateSet *CandidateSet, 13076 OverloadCandidateSet::iterator *Best, 13077 OverloadingResult OverloadResult, 13078 bool AllowTypoCorrection) { 13079 switch (OverloadResult) { 13080 case OR_Success: { 13081 FunctionDecl *FDecl = (*Best)->Function; 13082 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13083 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13084 return ExprError(); 13085 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13086 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13087 ExecConfig, /*IsExecConfig=*/false, 13088 (*Best)->IsADLCandidate); 13089 } 13090 13091 case OR_No_Viable_Function: { 13092 // Try to recover by looking for viable functions which the user might 13093 // have meant to call. 13094 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13095 Args, RParenLoc, 13096 CandidateSet->empty(), 13097 AllowTypoCorrection); 13098 if (Recovery.isInvalid() || Recovery.isUsable()) 13099 return Recovery; 13100 13101 // If the user passes in a function that we can't take the address of, we 13102 // generally end up emitting really bad error messages. Here, we attempt to 13103 // emit better ones. 13104 for (const Expr *Arg : Args) { 13105 if (!Arg->getType()->isFunctionType()) 13106 continue; 13107 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13108 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13109 if (FD && 13110 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13111 Arg->getExprLoc())) 13112 return ExprError(); 13113 } 13114 } 13115 13116 CandidateSet->NoteCandidates( 13117 PartialDiagnosticAt( 13118 Fn->getBeginLoc(), 13119 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13120 << ULE->getName() << Fn->getSourceRange()), 13121 SemaRef, OCD_AllCandidates, Args); 13122 break; 13123 } 13124 13125 case OR_Ambiguous: 13126 CandidateSet->NoteCandidates( 13127 PartialDiagnosticAt(Fn->getBeginLoc(), 13128 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13129 << ULE->getName() << Fn->getSourceRange()), 13130 SemaRef, OCD_AmbiguousCandidates, Args); 13131 break; 13132 13133 case OR_Deleted: { 13134 CandidateSet->NoteCandidates( 13135 PartialDiagnosticAt(Fn->getBeginLoc(), 13136 SemaRef.PDiag(diag::err_ovl_deleted_call) 13137 << ULE->getName() << Fn->getSourceRange()), 13138 SemaRef, OCD_AllCandidates, Args); 13139 13140 // We emitted an error for the unavailable/deleted function call but keep 13141 // the call in the AST. 13142 FunctionDecl *FDecl = (*Best)->Function; 13143 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13144 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13145 ExecConfig, /*IsExecConfig=*/false, 13146 (*Best)->IsADLCandidate); 13147 } 13148 } 13149 13150 // Overload resolution failed, try to recover. 13151 SmallVector<Expr *, 8> SubExprs = {Fn}; 13152 SubExprs.append(Args.begin(), Args.end()); 13153 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13154 chooseRecoveryType(*CandidateSet, Best)); 13155 } 13156 13157 static void markUnaddressableCandidatesUnviable(Sema &S, 13158 OverloadCandidateSet &CS) { 13159 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13160 if (I->Viable && 13161 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13162 I->Viable = false; 13163 I->FailureKind = ovl_fail_addr_not_available; 13164 } 13165 } 13166 } 13167 13168 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13169 /// (which eventually refers to the declaration Func) and the call 13170 /// arguments Args/NumArgs, attempt to resolve the function call down 13171 /// to a specific function. If overload resolution succeeds, returns 13172 /// the call expression produced by overload resolution. 13173 /// Otherwise, emits diagnostics and returns ExprError. 13174 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13175 UnresolvedLookupExpr *ULE, 13176 SourceLocation LParenLoc, 13177 MultiExprArg Args, 13178 SourceLocation RParenLoc, 13179 Expr *ExecConfig, 13180 bool AllowTypoCorrection, 13181 bool CalleesAddressIsTaken) { 13182 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13183 OverloadCandidateSet::CSK_Normal); 13184 ExprResult result; 13185 13186 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13187 &result)) 13188 return result; 13189 13190 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13191 // functions that aren't addressible are considered unviable. 13192 if (CalleesAddressIsTaken) 13193 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13194 13195 OverloadCandidateSet::iterator Best; 13196 OverloadingResult OverloadResult = 13197 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13198 13199 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13200 ExecConfig, &CandidateSet, &Best, 13201 OverloadResult, AllowTypoCorrection); 13202 } 13203 13204 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13205 return Functions.size() > 1 || 13206 (Functions.size() == 1 && 13207 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13208 } 13209 13210 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13211 NestedNameSpecifierLoc NNSLoc, 13212 DeclarationNameInfo DNI, 13213 const UnresolvedSetImpl &Fns, 13214 bool PerformADL) { 13215 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13216 PerformADL, IsOverloaded(Fns), 13217 Fns.begin(), Fns.end()); 13218 } 13219 13220 /// Create a unary operation that may resolve to an overloaded 13221 /// operator. 13222 /// 13223 /// \param OpLoc The location of the operator itself (e.g., '*'). 13224 /// 13225 /// \param Opc The UnaryOperatorKind that describes this operator. 13226 /// 13227 /// \param Fns The set of non-member functions that will be 13228 /// considered by overload resolution. The caller needs to build this 13229 /// set based on the context using, e.g., 13230 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13231 /// set should not contain any member functions; those will be added 13232 /// by CreateOverloadedUnaryOp(). 13233 /// 13234 /// \param Input The input argument. 13235 ExprResult 13236 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13237 const UnresolvedSetImpl &Fns, 13238 Expr *Input, bool PerformADL) { 13239 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13240 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13241 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13242 // TODO: provide better source location info. 13243 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13244 13245 if (checkPlaceholderForOverload(*this, Input)) 13246 return ExprError(); 13247 13248 Expr *Args[2] = { Input, nullptr }; 13249 unsigned NumArgs = 1; 13250 13251 // For post-increment and post-decrement, add the implicit '0' as 13252 // the second argument, so that we know this is a post-increment or 13253 // post-decrement. 13254 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13255 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13256 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13257 SourceLocation()); 13258 NumArgs = 2; 13259 } 13260 13261 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13262 13263 if (Input->isTypeDependent()) { 13264 if (Fns.empty()) 13265 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13266 VK_PRValue, OK_Ordinary, OpLoc, false, 13267 CurFPFeatureOverrides()); 13268 13269 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13270 ExprResult Fn = CreateUnresolvedLookupExpr( 13271 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13272 if (Fn.isInvalid()) 13273 return ExprError(); 13274 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13275 Context.DependentTy, VK_PRValue, OpLoc, 13276 CurFPFeatureOverrides()); 13277 } 13278 13279 // Build an empty overload set. 13280 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13281 13282 // Add the candidates from the given function set. 13283 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13284 13285 // Add operator candidates that are member functions. 13286 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13287 13288 // Add candidates from ADL. 13289 if (PerformADL) { 13290 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13291 /*ExplicitTemplateArgs*/nullptr, 13292 CandidateSet); 13293 } 13294 13295 // Add builtin operator candidates. 13296 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13297 13298 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13299 13300 // Perform overload resolution. 13301 OverloadCandidateSet::iterator Best; 13302 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13303 case OR_Success: { 13304 // We found a built-in operator or an overloaded operator. 13305 FunctionDecl *FnDecl = Best->Function; 13306 13307 if (FnDecl) { 13308 Expr *Base = nullptr; 13309 // We matched an overloaded operator. Build a call to that 13310 // operator. 13311 13312 // Convert the arguments. 13313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13314 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13315 13316 ExprResult InputRes = 13317 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13318 Best->FoundDecl, Method); 13319 if (InputRes.isInvalid()) 13320 return ExprError(); 13321 Base = Input = InputRes.get(); 13322 } else { 13323 // Convert the arguments. 13324 ExprResult InputInit 13325 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13326 Context, 13327 FnDecl->getParamDecl(0)), 13328 SourceLocation(), 13329 Input); 13330 if (InputInit.isInvalid()) 13331 return ExprError(); 13332 Input = InputInit.get(); 13333 } 13334 13335 // Build the actual expression node. 13336 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13337 Base, HadMultipleCandidates, 13338 OpLoc); 13339 if (FnExpr.isInvalid()) 13340 return ExprError(); 13341 13342 // Determine the result type. 13343 QualType ResultTy = FnDecl->getReturnType(); 13344 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13345 ResultTy = ResultTy.getNonLValueExprType(Context); 13346 13347 Args[0] = Input; 13348 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13349 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13350 CurFPFeatureOverrides(), Best->IsADLCandidate); 13351 13352 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13353 return ExprError(); 13354 13355 if (CheckFunctionCall(FnDecl, TheCall, 13356 FnDecl->getType()->castAs<FunctionProtoType>())) 13357 return ExprError(); 13358 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13359 } else { 13360 // We matched a built-in operator. Convert the arguments, then 13361 // break out so that we will build the appropriate built-in 13362 // operator node. 13363 ExprResult InputRes = PerformImplicitConversion( 13364 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13365 CCK_ForBuiltinOverloadedOp); 13366 if (InputRes.isInvalid()) 13367 return ExprError(); 13368 Input = InputRes.get(); 13369 break; 13370 } 13371 } 13372 13373 case OR_No_Viable_Function: 13374 // This is an erroneous use of an operator which can be overloaded by 13375 // a non-member function. Check for non-member operators which were 13376 // defined too late to be candidates. 13377 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13378 // FIXME: Recover by calling the found function. 13379 return ExprError(); 13380 13381 // No viable function; fall through to handling this as a 13382 // built-in operator, which will produce an error message for us. 13383 break; 13384 13385 case OR_Ambiguous: 13386 CandidateSet.NoteCandidates( 13387 PartialDiagnosticAt(OpLoc, 13388 PDiag(diag::err_ovl_ambiguous_oper_unary) 13389 << UnaryOperator::getOpcodeStr(Opc) 13390 << Input->getType() << Input->getSourceRange()), 13391 *this, OCD_AmbiguousCandidates, ArgsArray, 13392 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13393 return ExprError(); 13394 13395 case OR_Deleted: 13396 CandidateSet.NoteCandidates( 13397 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13398 << UnaryOperator::getOpcodeStr(Opc) 13399 << Input->getSourceRange()), 13400 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13401 OpLoc); 13402 return ExprError(); 13403 } 13404 13405 // Either we found no viable overloaded operator or we matched a 13406 // built-in operator. In either case, fall through to trying to 13407 // build a built-in operation. 13408 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13409 } 13410 13411 /// Perform lookup for an overloaded binary operator. 13412 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13413 OverloadedOperatorKind Op, 13414 const UnresolvedSetImpl &Fns, 13415 ArrayRef<Expr *> Args, bool PerformADL) { 13416 SourceLocation OpLoc = CandidateSet.getLocation(); 13417 13418 OverloadedOperatorKind ExtraOp = 13419 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13420 ? getRewrittenOverloadedOperator(Op) 13421 : OO_None; 13422 13423 // Add the candidates from the given function set. This also adds the 13424 // rewritten candidates using these functions if necessary. 13425 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13426 13427 // Add operator candidates that are member functions. 13428 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13429 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13430 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13431 OverloadCandidateParamOrder::Reversed); 13432 13433 // In C++20, also add any rewritten member candidates. 13434 if (ExtraOp) { 13435 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13436 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13437 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13438 CandidateSet, 13439 OverloadCandidateParamOrder::Reversed); 13440 } 13441 13442 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13443 // performed for an assignment operator (nor for operator[] nor operator->, 13444 // which don't get here). 13445 if (Op != OO_Equal && PerformADL) { 13446 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13447 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13448 /*ExplicitTemplateArgs*/ nullptr, 13449 CandidateSet); 13450 if (ExtraOp) { 13451 DeclarationName ExtraOpName = 13452 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13453 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13454 /*ExplicitTemplateArgs*/ nullptr, 13455 CandidateSet); 13456 } 13457 } 13458 13459 // Add builtin operator candidates. 13460 // 13461 // FIXME: We don't add any rewritten candidates here. This is strictly 13462 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13463 // resulting in our selecting a rewritten builtin candidate. For example: 13464 // 13465 // enum class E { e }; 13466 // bool operator!=(E, E) requires false; 13467 // bool k = E::e != E::e; 13468 // 13469 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13470 // it seems unreasonable to consider rewritten builtin candidates. A core 13471 // issue has been filed proposing to removed this requirement. 13472 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13473 } 13474 13475 /// Create a binary operation that may resolve to an overloaded 13476 /// operator. 13477 /// 13478 /// \param OpLoc The location of the operator itself (e.g., '+'). 13479 /// 13480 /// \param Opc The BinaryOperatorKind that describes this operator. 13481 /// 13482 /// \param Fns The set of non-member functions that will be 13483 /// considered by overload resolution. The caller needs to build this 13484 /// set based on the context using, e.g., 13485 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13486 /// set should not contain any member functions; those will be added 13487 /// by CreateOverloadedBinOp(). 13488 /// 13489 /// \param LHS Left-hand argument. 13490 /// \param RHS Right-hand argument. 13491 /// \param PerformADL Whether to consider operator candidates found by ADL. 13492 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13493 /// C++20 operator rewrites. 13494 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13495 /// the function in question. Such a function is never a candidate in 13496 /// our overload resolution. This also enables synthesizing a three-way 13497 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13498 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13499 BinaryOperatorKind Opc, 13500 const UnresolvedSetImpl &Fns, Expr *LHS, 13501 Expr *RHS, bool PerformADL, 13502 bool AllowRewrittenCandidates, 13503 FunctionDecl *DefaultedFn) { 13504 Expr *Args[2] = { LHS, RHS }; 13505 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13506 13507 if (!getLangOpts().CPlusPlus20) 13508 AllowRewrittenCandidates = false; 13509 13510 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13511 13512 // If either side is type-dependent, create an appropriate dependent 13513 // expression. 13514 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13515 if (Fns.empty()) { 13516 // If there are no functions to store, just build a dependent 13517 // BinaryOperator or CompoundAssignment. 13518 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13519 return CompoundAssignOperator::Create( 13520 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13521 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13522 Context.DependentTy); 13523 return BinaryOperator::Create( 13524 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 13525 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13526 } 13527 13528 // FIXME: save results of ADL from here? 13529 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13530 // TODO: provide better source location info in DNLoc component. 13531 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13532 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13533 ExprResult Fn = CreateUnresolvedLookupExpr( 13534 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13535 if (Fn.isInvalid()) 13536 return ExprError(); 13537 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13538 Context.DependentTy, VK_PRValue, OpLoc, 13539 CurFPFeatureOverrides()); 13540 } 13541 13542 // Always do placeholder-like conversions on the RHS. 13543 if (checkPlaceholderForOverload(*this, Args[1])) 13544 return ExprError(); 13545 13546 // Do placeholder-like conversion on the LHS; note that we should 13547 // not get here with a PseudoObject LHS. 13548 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13549 if (checkPlaceholderForOverload(*this, Args[0])) 13550 return ExprError(); 13551 13552 // If this is the assignment operator, we only perform overload resolution 13553 // if the left-hand side is a class or enumeration type. This is actually 13554 // a hack. The standard requires that we do overload resolution between the 13555 // various built-in candidates, but as DR507 points out, this can lead to 13556 // problems. So we do it this way, which pretty much follows what GCC does. 13557 // Note that we go the traditional code path for compound assignment forms. 13558 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13559 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13560 13561 // If this is the .* operator, which is not overloadable, just 13562 // create a built-in binary operator. 13563 if (Opc == BO_PtrMemD) 13564 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13565 13566 // Build the overload set. 13567 OverloadCandidateSet CandidateSet( 13568 OpLoc, OverloadCandidateSet::CSK_Operator, 13569 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13570 if (DefaultedFn) 13571 CandidateSet.exclude(DefaultedFn); 13572 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13573 13574 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13575 13576 // Perform overload resolution. 13577 OverloadCandidateSet::iterator Best; 13578 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13579 case OR_Success: { 13580 // We found a built-in operator or an overloaded operator. 13581 FunctionDecl *FnDecl = Best->Function; 13582 13583 bool IsReversed = Best->isReversed(); 13584 if (IsReversed) 13585 std::swap(Args[0], Args[1]); 13586 13587 if (FnDecl) { 13588 Expr *Base = nullptr; 13589 // We matched an overloaded operator. Build a call to that 13590 // operator. 13591 13592 OverloadedOperatorKind ChosenOp = 13593 FnDecl->getDeclName().getCXXOverloadedOperator(); 13594 13595 // C++2a [over.match.oper]p9: 13596 // If a rewritten operator== candidate is selected by overload 13597 // resolution for an operator@, its return type shall be cv bool 13598 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13599 !FnDecl->getReturnType()->isBooleanType()) { 13600 bool IsExtension = 13601 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13602 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13603 : diag::err_ovl_rewrite_equalequal_not_bool) 13604 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13605 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13606 Diag(FnDecl->getLocation(), diag::note_declared_at); 13607 if (!IsExtension) 13608 return ExprError(); 13609 } 13610 13611 if (AllowRewrittenCandidates && !IsReversed && 13612 CandidateSet.getRewriteInfo().isReversible()) { 13613 // We could have reversed this operator, but didn't. Check if some 13614 // reversed form was a viable candidate, and if so, if it had a 13615 // better conversion for either parameter. If so, this call is 13616 // formally ambiguous, and allowing it is an extension. 13617 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13618 for (OverloadCandidate &Cand : CandidateSet) { 13619 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13620 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13621 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13622 if (CompareImplicitConversionSequences( 13623 *this, OpLoc, Cand.Conversions[ArgIdx], 13624 Best->Conversions[ArgIdx]) == 13625 ImplicitConversionSequence::Better) { 13626 AmbiguousWith.push_back(Cand.Function); 13627 break; 13628 } 13629 } 13630 } 13631 } 13632 13633 if (!AmbiguousWith.empty()) { 13634 bool AmbiguousWithSelf = 13635 AmbiguousWith.size() == 1 && 13636 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13637 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13638 << BinaryOperator::getOpcodeStr(Opc) 13639 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13640 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13641 if (AmbiguousWithSelf) { 13642 Diag(FnDecl->getLocation(), 13643 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13644 } else { 13645 Diag(FnDecl->getLocation(), 13646 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13647 for (auto *F : AmbiguousWith) 13648 Diag(F->getLocation(), 13649 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13650 } 13651 } 13652 } 13653 13654 // Convert the arguments. 13655 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13656 // Best->Access is only meaningful for class members. 13657 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13658 13659 ExprResult Arg1 = 13660 PerformCopyInitialization( 13661 InitializedEntity::InitializeParameter(Context, 13662 FnDecl->getParamDecl(0)), 13663 SourceLocation(), Args[1]); 13664 if (Arg1.isInvalid()) 13665 return ExprError(); 13666 13667 ExprResult Arg0 = 13668 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13669 Best->FoundDecl, Method); 13670 if (Arg0.isInvalid()) 13671 return ExprError(); 13672 Base = Args[0] = Arg0.getAs<Expr>(); 13673 Args[1] = RHS = Arg1.getAs<Expr>(); 13674 } else { 13675 // Convert the arguments. 13676 ExprResult Arg0 = PerformCopyInitialization( 13677 InitializedEntity::InitializeParameter(Context, 13678 FnDecl->getParamDecl(0)), 13679 SourceLocation(), Args[0]); 13680 if (Arg0.isInvalid()) 13681 return ExprError(); 13682 13683 ExprResult Arg1 = 13684 PerformCopyInitialization( 13685 InitializedEntity::InitializeParameter(Context, 13686 FnDecl->getParamDecl(1)), 13687 SourceLocation(), Args[1]); 13688 if (Arg1.isInvalid()) 13689 return ExprError(); 13690 Args[0] = LHS = Arg0.getAs<Expr>(); 13691 Args[1] = RHS = Arg1.getAs<Expr>(); 13692 } 13693 13694 // Build the actual expression node. 13695 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13696 Best->FoundDecl, Base, 13697 HadMultipleCandidates, OpLoc); 13698 if (FnExpr.isInvalid()) 13699 return ExprError(); 13700 13701 // Determine the result type. 13702 QualType ResultTy = FnDecl->getReturnType(); 13703 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13704 ResultTy = ResultTy.getNonLValueExprType(Context); 13705 13706 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13707 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13708 CurFPFeatureOverrides(), Best->IsADLCandidate); 13709 13710 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13711 FnDecl)) 13712 return ExprError(); 13713 13714 ArrayRef<const Expr *> ArgsArray(Args, 2); 13715 const Expr *ImplicitThis = nullptr; 13716 // Cut off the implicit 'this'. 13717 if (isa<CXXMethodDecl>(FnDecl)) { 13718 ImplicitThis = ArgsArray[0]; 13719 ArgsArray = ArgsArray.slice(1); 13720 } 13721 13722 // Check for a self move. 13723 if (Op == OO_Equal) 13724 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13725 13726 if (ImplicitThis) { 13727 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13728 QualType ThisTypeFromDecl = Context.getPointerType( 13729 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13730 13731 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13732 ThisTypeFromDecl); 13733 } 13734 13735 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13736 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13737 VariadicDoesNotApply); 13738 13739 ExprResult R = MaybeBindToTemporary(TheCall); 13740 if (R.isInvalid()) 13741 return ExprError(); 13742 13743 R = CheckForImmediateInvocation(R, FnDecl); 13744 if (R.isInvalid()) 13745 return ExprError(); 13746 13747 // For a rewritten candidate, we've already reversed the arguments 13748 // if needed. Perform the rest of the rewrite now. 13749 if ((Best->RewriteKind & CRK_DifferentOperator) || 13750 (Op == OO_Spaceship && IsReversed)) { 13751 if (Op == OO_ExclaimEqual) { 13752 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13753 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13754 } else { 13755 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13756 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13757 Expr *ZeroLiteral = 13758 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13759 13760 Sema::CodeSynthesisContext Ctx; 13761 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13762 Ctx.Entity = FnDecl; 13763 pushCodeSynthesisContext(Ctx); 13764 13765 R = CreateOverloadedBinOp( 13766 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13767 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13768 /*AllowRewrittenCandidates=*/false); 13769 13770 popCodeSynthesisContext(); 13771 } 13772 if (R.isInvalid()) 13773 return ExprError(); 13774 } else { 13775 assert(ChosenOp == Op && "unexpected operator name"); 13776 } 13777 13778 // Make a note in the AST if we did any rewriting. 13779 if (Best->RewriteKind != CRK_None) 13780 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13781 13782 return R; 13783 } else { 13784 // We matched a built-in operator. Convert the arguments, then 13785 // break out so that we will build the appropriate built-in 13786 // operator node. 13787 ExprResult ArgsRes0 = PerformImplicitConversion( 13788 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13789 AA_Passing, CCK_ForBuiltinOverloadedOp); 13790 if (ArgsRes0.isInvalid()) 13791 return ExprError(); 13792 Args[0] = ArgsRes0.get(); 13793 13794 ExprResult ArgsRes1 = PerformImplicitConversion( 13795 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13796 AA_Passing, CCK_ForBuiltinOverloadedOp); 13797 if (ArgsRes1.isInvalid()) 13798 return ExprError(); 13799 Args[1] = ArgsRes1.get(); 13800 break; 13801 } 13802 } 13803 13804 case OR_No_Viable_Function: { 13805 // C++ [over.match.oper]p9: 13806 // If the operator is the operator , [...] and there are no 13807 // viable functions, then the operator is assumed to be the 13808 // built-in operator and interpreted according to clause 5. 13809 if (Opc == BO_Comma) 13810 break; 13811 13812 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13813 // compare result using '==' and '<'. 13814 if (DefaultedFn && Opc == BO_Cmp) { 13815 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13816 Args[1], DefaultedFn); 13817 if (E.isInvalid() || E.isUsable()) 13818 return E; 13819 } 13820 13821 // For class as left operand for assignment or compound assignment 13822 // operator do not fall through to handling in built-in, but report that 13823 // no overloaded assignment operator found 13824 ExprResult Result = ExprError(); 13825 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13826 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13827 Args, OpLoc); 13828 DeferDiagsRAII DDR(*this, 13829 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 13830 if (Args[0]->getType()->isRecordType() && 13831 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13832 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13833 << BinaryOperator::getOpcodeStr(Opc) 13834 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13835 if (Args[0]->getType()->isIncompleteType()) { 13836 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13837 << Args[0]->getType() 13838 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13839 } 13840 } else { 13841 // This is an erroneous use of an operator which can be overloaded by 13842 // a non-member function. Check for non-member operators which were 13843 // defined too late to be candidates. 13844 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13845 // FIXME: Recover by calling the found function. 13846 return ExprError(); 13847 13848 // No viable function; try to create a built-in operation, which will 13849 // produce an error. Then, show the non-viable candidates. 13850 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13851 } 13852 assert(Result.isInvalid() && 13853 "C++ binary operator overloading is missing candidates!"); 13854 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13855 return Result; 13856 } 13857 13858 case OR_Ambiguous: 13859 CandidateSet.NoteCandidates( 13860 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13861 << BinaryOperator::getOpcodeStr(Opc) 13862 << Args[0]->getType() 13863 << Args[1]->getType() 13864 << Args[0]->getSourceRange() 13865 << Args[1]->getSourceRange()), 13866 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13867 OpLoc); 13868 return ExprError(); 13869 13870 case OR_Deleted: 13871 if (isImplicitlyDeleted(Best->Function)) { 13872 FunctionDecl *DeletedFD = Best->Function; 13873 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13874 if (DFK.isSpecialMember()) { 13875 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13876 << Args[0]->getType() << DFK.asSpecialMember(); 13877 } else { 13878 assert(DFK.isComparison()); 13879 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13880 << Args[0]->getType() << DeletedFD; 13881 } 13882 13883 // The user probably meant to call this special member. Just 13884 // explain why it's deleted. 13885 NoteDeletedFunction(DeletedFD); 13886 return ExprError(); 13887 } 13888 CandidateSet.NoteCandidates( 13889 PartialDiagnosticAt( 13890 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13891 << getOperatorSpelling(Best->Function->getDeclName() 13892 .getCXXOverloadedOperator()) 13893 << Args[0]->getSourceRange() 13894 << Args[1]->getSourceRange()), 13895 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13896 OpLoc); 13897 return ExprError(); 13898 } 13899 13900 // We matched a built-in operator; build it. 13901 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13902 } 13903 13904 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13905 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13906 FunctionDecl *DefaultedFn) { 13907 const ComparisonCategoryInfo *Info = 13908 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13909 // If we're not producing a known comparison category type, we can't 13910 // synthesize a three-way comparison. Let the caller diagnose this. 13911 if (!Info) 13912 return ExprResult((Expr*)nullptr); 13913 13914 // If we ever want to perform this synthesis more generally, we will need to 13915 // apply the temporary materialization conversion to the operands. 13916 assert(LHS->isGLValue() && RHS->isGLValue() && 13917 "cannot use prvalue expressions more than once"); 13918 Expr *OrigLHS = LHS; 13919 Expr *OrigRHS = RHS; 13920 13921 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13922 // each of them multiple times below. 13923 LHS = new (Context) 13924 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13925 LHS->getObjectKind(), LHS); 13926 RHS = new (Context) 13927 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13928 RHS->getObjectKind(), RHS); 13929 13930 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13931 DefaultedFn); 13932 if (Eq.isInvalid()) 13933 return ExprError(); 13934 13935 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13936 true, DefaultedFn); 13937 if (Less.isInvalid()) 13938 return ExprError(); 13939 13940 ExprResult Greater; 13941 if (Info->isPartial()) { 13942 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13943 DefaultedFn); 13944 if (Greater.isInvalid()) 13945 return ExprError(); 13946 } 13947 13948 // Form the list of comparisons we're going to perform. 13949 struct Comparison { 13950 ExprResult Cmp; 13951 ComparisonCategoryResult Result; 13952 } Comparisons[4] = 13953 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13954 : ComparisonCategoryResult::Equivalent}, 13955 {Less, ComparisonCategoryResult::Less}, 13956 {Greater, ComparisonCategoryResult::Greater}, 13957 {ExprResult(), ComparisonCategoryResult::Unordered}, 13958 }; 13959 13960 int I = Info->isPartial() ? 3 : 2; 13961 13962 // Combine the comparisons with suitable conditional expressions. 13963 ExprResult Result; 13964 for (; I >= 0; --I) { 13965 // Build a reference to the comparison category constant. 13966 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13967 // FIXME: Missing a constant for a comparison category. Diagnose this? 13968 if (!VI) 13969 return ExprResult((Expr*)nullptr); 13970 ExprResult ThisResult = 13971 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13972 if (ThisResult.isInvalid()) 13973 return ExprError(); 13974 13975 // Build a conditional unless this is the final case. 13976 if (Result.get()) { 13977 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13978 ThisResult.get(), Result.get()); 13979 if (Result.isInvalid()) 13980 return ExprError(); 13981 } else { 13982 Result = ThisResult; 13983 } 13984 } 13985 13986 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13987 // bind the OpaqueValueExprs before they're (repeatedly) used. 13988 Expr *SyntacticForm = BinaryOperator::Create( 13989 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13990 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13991 CurFPFeatureOverrides()); 13992 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13993 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13994 } 13995 13996 ExprResult 13997 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13998 SourceLocation RLoc, 13999 Expr *Base, Expr *Idx) { 14000 Expr *Args[2] = { Base, Idx }; 14001 DeclarationName OpName = 14002 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14003 14004 // If either side is type-dependent, create an appropriate dependent 14005 // expression. 14006 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 14007 14008 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14009 // CHECKME: no 'operator' keyword? 14010 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14011 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14012 ExprResult Fn = CreateUnresolvedLookupExpr( 14013 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14014 if (Fn.isInvalid()) 14015 return ExprError(); 14016 // Can't add any actual overloads yet 14017 14018 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14019 Context.DependentTy, VK_PRValue, RLoc, 14020 CurFPFeatureOverrides()); 14021 } 14022 14023 // Handle placeholders on both operands. 14024 if (checkPlaceholderForOverload(*this, Args[0])) 14025 return ExprError(); 14026 if (checkPlaceholderForOverload(*this, Args[1])) 14027 return ExprError(); 14028 14029 // Build an empty overload set. 14030 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14031 14032 // Subscript can only be overloaded as a member function. 14033 14034 // Add operator candidates that are member functions. 14035 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14036 14037 // Add builtin operator candidates. 14038 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14039 14040 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14041 14042 // Perform overload resolution. 14043 OverloadCandidateSet::iterator Best; 14044 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14045 case OR_Success: { 14046 // We found a built-in operator or an overloaded operator. 14047 FunctionDecl *FnDecl = Best->Function; 14048 14049 if (FnDecl) { 14050 // We matched an overloaded operator. Build a call to that 14051 // operator. 14052 14053 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 14054 14055 // Convert the arguments. 14056 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14057 ExprResult Arg0 = 14058 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 14059 Best->FoundDecl, Method); 14060 if (Arg0.isInvalid()) 14061 return ExprError(); 14062 Args[0] = Arg0.get(); 14063 14064 // Convert the arguments. 14065 ExprResult InputInit 14066 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14067 Context, 14068 FnDecl->getParamDecl(0)), 14069 SourceLocation(), 14070 Args[1]); 14071 if (InputInit.isInvalid()) 14072 return ExprError(); 14073 14074 Args[1] = InputInit.getAs<Expr>(); 14075 14076 // Build the actual expression node. 14077 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14078 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14079 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14080 Best->FoundDecl, 14081 Base, 14082 HadMultipleCandidates, 14083 OpLocInfo.getLoc(), 14084 OpLocInfo.getInfo()); 14085 if (FnExpr.isInvalid()) 14086 return ExprError(); 14087 14088 // Determine the result type 14089 QualType ResultTy = FnDecl->getReturnType(); 14090 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14091 ResultTy = ResultTy.getNonLValueExprType(Context); 14092 14093 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14094 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 14095 CurFPFeatureOverrides()); 14096 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14097 return ExprError(); 14098 14099 if (CheckFunctionCall(Method, TheCall, 14100 Method->getType()->castAs<FunctionProtoType>())) 14101 return ExprError(); 14102 14103 return MaybeBindToTemporary(TheCall); 14104 } else { 14105 // We matched a built-in operator. Convert the arguments, then 14106 // break out so that we will build the appropriate built-in 14107 // operator node. 14108 ExprResult ArgsRes0 = PerformImplicitConversion( 14109 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14110 AA_Passing, CCK_ForBuiltinOverloadedOp); 14111 if (ArgsRes0.isInvalid()) 14112 return ExprError(); 14113 Args[0] = ArgsRes0.get(); 14114 14115 ExprResult ArgsRes1 = PerformImplicitConversion( 14116 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14117 AA_Passing, CCK_ForBuiltinOverloadedOp); 14118 if (ArgsRes1.isInvalid()) 14119 return ExprError(); 14120 Args[1] = ArgsRes1.get(); 14121 14122 break; 14123 } 14124 } 14125 14126 case OR_No_Viable_Function: { 14127 PartialDiagnostic PD = CandidateSet.empty() 14128 ? (PDiag(diag::err_ovl_no_oper) 14129 << Args[0]->getType() << /*subscript*/ 0 14130 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 14131 : (PDiag(diag::err_ovl_no_viable_subscript) 14132 << Args[0]->getType() << Args[0]->getSourceRange() 14133 << Args[1]->getSourceRange()); 14134 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14135 OCD_AllCandidates, Args, "[]", LLoc); 14136 return ExprError(); 14137 } 14138 14139 case OR_Ambiguous: 14140 CandidateSet.NoteCandidates( 14141 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14142 << "[]" << Args[0]->getType() 14143 << Args[1]->getType() 14144 << Args[0]->getSourceRange() 14145 << Args[1]->getSourceRange()), 14146 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14147 return ExprError(); 14148 14149 case OR_Deleted: 14150 CandidateSet.NoteCandidates( 14151 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14152 << "[]" << Args[0]->getSourceRange() 14153 << Args[1]->getSourceRange()), 14154 *this, OCD_AllCandidates, Args, "[]", LLoc); 14155 return ExprError(); 14156 } 14157 14158 // We matched a built-in operator; build it. 14159 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14160 } 14161 14162 /// BuildCallToMemberFunction - Build a call to a member 14163 /// function. MemExpr is the expression that refers to the member 14164 /// function (and includes the object parameter), Args/NumArgs are the 14165 /// arguments to the function call (not including the object 14166 /// parameter). The caller needs to validate that the member 14167 /// expression refers to a non-static member function or an overloaded 14168 /// member function. 14169 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14170 SourceLocation LParenLoc, 14171 MultiExprArg Args, 14172 SourceLocation RParenLoc, 14173 bool AllowRecovery) { 14174 assert(MemExprE->getType() == Context.BoundMemberTy || 14175 MemExprE->getType() == Context.OverloadTy); 14176 14177 // Dig out the member expression. This holds both the object 14178 // argument and the member function we're referring to. 14179 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14180 14181 // Determine whether this is a call to a pointer-to-member function. 14182 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14183 assert(op->getType() == Context.BoundMemberTy); 14184 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14185 14186 QualType fnType = 14187 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14188 14189 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14190 QualType resultType = proto->getCallResultType(Context); 14191 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14192 14193 // Check that the object type isn't more qualified than the 14194 // member function we're calling. 14195 Qualifiers funcQuals = proto->getMethodQuals(); 14196 14197 QualType objectType = op->getLHS()->getType(); 14198 if (op->getOpcode() == BO_PtrMemI) 14199 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14200 Qualifiers objectQuals = objectType.getQualifiers(); 14201 14202 Qualifiers difference = objectQuals - funcQuals; 14203 difference.removeObjCGCAttr(); 14204 difference.removeAddressSpace(); 14205 if (difference) { 14206 std::string qualsString = difference.getAsString(); 14207 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14208 << fnType.getUnqualifiedType() 14209 << qualsString 14210 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14211 } 14212 14213 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14214 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14215 CurFPFeatureOverrides(), proto->getNumParams()); 14216 14217 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14218 call, nullptr)) 14219 return ExprError(); 14220 14221 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14222 return ExprError(); 14223 14224 if (CheckOtherCall(call, proto)) 14225 return ExprError(); 14226 14227 return MaybeBindToTemporary(call); 14228 } 14229 14230 // We only try to build a recovery expr at this level if we can preserve 14231 // the return type, otherwise we return ExprError() and let the caller 14232 // recover. 14233 auto BuildRecoveryExpr = [&](QualType Type) { 14234 if (!AllowRecovery) 14235 return ExprError(); 14236 std::vector<Expr *> SubExprs = {MemExprE}; 14237 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); }); 14238 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14239 Type); 14240 }; 14241 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14242 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 14243 RParenLoc, CurFPFeatureOverrides()); 14244 14245 UnbridgedCastsSet UnbridgedCasts; 14246 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14247 return ExprError(); 14248 14249 MemberExpr *MemExpr; 14250 CXXMethodDecl *Method = nullptr; 14251 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14252 NestedNameSpecifier *Qualifier = nullptr; 14253 if (isa<MemberExpr>(NakedMemExpr)) { 14254 MemExpr = cast<MemberExpr>(NakedMemExpr); 14255 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14256 FoundDecl = MemExpr->getFoundDecl(); 14257 Qualifier = MemExpr->getQualifier(); 14258 UnbridgedCasts.restore(); 14259 } else { 14260 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14261 Qualifier = UnresExpr->getQualifier(); 14262 14263 QualType ObjectType = UnresExpr->getBaseType(); 14264 Expr::Classification ObjectClassification 14265 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14266 : UnresExpr->getBase()->Classify(Context); 14267 14268 // Add overload candidates 14269 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14270 OverloadCandidateSet::CSK_Normal); 14271 14272 // FIXME: avoid copy. 14273 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14274 if (UnresExpr->hasExplicitTemplateArgs()) { 14275 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14276 TemplateArgs = &TemplateArgsBuffer; 14277 } 14278 14279 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14280 E = UnresExpr->decls_end(); I != E; ++I) { 14281 14282 NamedDecl *Func = *I; 14283 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14284 if (isa<UsingShadowDecl>(Func)) 14285 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14286 14287 14288 // Microsoft supports direct constructor calls. 14289 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14290 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14291 CandidateSet, 14292 /*SuppressUserConversions*/ false); 14293 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14294 // If explicit template arguments were provided, we can't call a 14295 // non-template member function. 14296 if (TemplateArgs) 14297 continue; 14298 14299 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14300 ObjectClassification, Args, CandidateSet, 14301 /*SuppressUserConversions=*/false); 14302 } else { 14303 AddMethodTemplateCandidate( 14304 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14305 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14306 /*SuppressUserConversions=*/false); 14307 } 14308 } 14309 14310 DeclarationName DeclName = UnresExpr->getMemberName(); 14311 14312 UnbridgedCasts.restore(); 14313 14314 OverloadCandidateSet::iterator Best; 14315 bool Succeeded = false; 14316 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14317 Best)) { 14318 case OR_Success: 14319 Method = cast<CXXMethodDecl>(Best->Function); 14320 FoundDecl = Best->FoundDecl; 14321 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14322 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14323 break; 14324 // If FoundDecl is different from Method (such as if one is a template 14325 // and the other a specialization), make sure DiagnoseUseOfDecl is 14326 // called on both. 14327 // FIXME: This would be more comprehensively addressed by modifying 14328 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14329 // being used. 14330 if (Method != FoundDecl.getDecl() && 14331 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14332 break; 14333 Succeeded = true; 14334 break; 14335 14336 case OR_No_Viable_Function: 14337 CandidateSet.NoteCandidates( 14338 PartialDiagnosticAt( 14339 UnresExpr->getMemberLoc(), 14340 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14341 << DeclName << MemExprE->getSourceRange()), 14342 *this, OCD_AllCandidates, Args); 14343 break; 14344 case OR_Ambiguous: 14345 CandidateSet.NoteCandidates( 14346 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14347 PDiag(diag::err_ovl_ambiguous_member_call) 14348 << DeclName << MemExprE->getSourceRange()), 14349 *this, OCD_AmbiguousCandidates, Args); 14350 break; 14351 case OR_Deleted: 14352 CandidateSet.NoteCandidates( 14353 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14354 PDiag(diag::err_ovl_deleted_member_call) 14355 << DeclName << MemExprE->getSourceRange()), 14356 *this, OCD_AllCandidates, Args); 14357 break; 14358 } 14359 // Overload resolution fails, try to recover. 14360 if (!Succeeded) 14361 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14362 14363 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14364 14365 // If overload resolution picked a static member, build a 14366 // non-member call based on that function. 14367 if (Method->isStatic()) { 14368 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14369 RParenLoc); 14370 } 14371 14372 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14373 } 14374 14375 QualType ResultType = Method->getReturnType(); 14376 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14377 ResultType = ResultType.getNonLValueExprType(Context); 14378 14379 assert(Method && "Member call to something that isn't a method?"); 14380 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14381 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14382 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14383 CurFPFeatureOverrides(), Proto->getNumParams()); 14384 14385 // Check for a valid return type. 14386 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14387 TheCall, Method)) 14388 return BuildRecoveryExpr(ResultType); 14389 14390 // Convert the object argument (for a non-static member function call). 14391 // We only need to do this if there was actually an overload; otherwise 14392 // it was done at lookup. 14393 if (!Method->isStatic()) { 14394 ExprResult ObjectArg = 14395 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14396 FoundDecl, Method); 14397 if (ObjectArg.isInvalid()) 14398 return ExprError(); 14399 MemExpr->setBase(ObjectArg.get()); 14400 } 14401 14402 // Convert the rest of the arguments 14403 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14404 RParenLoc)) 14405 return BuildRecoveryExpr(ResultType); 14406 14407 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14408 14409 if (CheckFunctionCall(Method, TheCall, Proto)) 14410 return ExprError(); 14411 14412 // In the case the method to call was not selected by the overloading 14413 // resolution process, we still need to handle the enable_if attribute. Do 14414 // that here, so it will not hide previous -- and more relevant -- errors. 14415 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14416 if (const EnableIfAttr *Attr = 14417 CheckEnableIf(Method, LParenLoc, Args, true)) { 14418 Diag(MemE->getMemberLoc(), 14419 diag::err_ovl_no_viable_member_function_in_call) 14420 << Method << Method->getSourceRange(); 14421 Diag(Method->getLocation(), 14422 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14423 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14424 return ExprError(); 14425 } 14426 } 14427 14428 if ((isa<CXXConstructorDecl>(CurContext) || 14429 isa<CXXDestructorDecl>(CurContext)) && 14430 TheCall->getMethodDecl()->isPure()) { 14431 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14432 14433 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14434 MemExpr->performsVirtualDispatch(getLangOpts())) { 14435 Diag(MemExpr->getBeginLoc(), 14436 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14437 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14438 << MD->getParent(); 14439 14440 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14441 if (getLangOpts().AppleKext) 14442 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14443 << MD->getParent() << MD->getDeclName(); 14444 } 14445 } 14446 14447 if (CXXDestructorDecl *DD = 14448 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14449 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14450 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14451 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14452 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14453 MemExpr->getMemberLoc()); 14454 } 14455 14456 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14457 TheCall->getMethodDecl()); 14458 } 14459 14460 /// BuildCallToObjectOfClassType - Build a call to an object of class 14461 /// type (C++ [over.call.object]), which can end up invoking an 14462 /// overloaded function call operator (@c operator()) or performing a 14463 /// user-defined conversion on the object argument. 14464 ExprResult 14465 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14466 SourceLocation LParenLoc, 14467 MultiExprArg Args, 14468 SourceLocation RParenLoc) { 14469 if (checkPlaceholderForOverload(*this, Obj)) 14470 return ExprError(); 14471 ExprResult Object = Obj; 14472 14473 UnbridgedCastsSet UnbridgedCasts; 14474 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14475 return ExprError(); 14476 14477 assert(Object.get()->getType()->isRecordType() && 14478 "Requires object type argument"); 14479 14480 // C++ [over.call.object]p1: 14481 // If the primary-expression E in the function call syntax 14482 // evaluates to a class object of type "cv T", then the set of 14483 // candidate functions includes at least the function call 14484 // operators of T. The function call operators of T are obtained by 14485 // ordinary lookup of the name operator() in the context of 14486 // (E).operator(). 14487 OverloadCandidateSet CandidateSet(LParenLoc, 14488 OverloadCandidateSet::CSK_Operator); 14489 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14490 14491 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14492 diag::err_incomplete_object_call, Object.get())) 14493 return true; 14494 14495 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14496 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14497 LookupQualifiedName(R, Record->getDecl()); 14498 R.suppressDiagnostics(); 14499 14500 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14501 Oper != OperEnd; ++Oper) { 14502 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14503 Object.get()->Classify(Context), Args, CandidateSet, 14504 /*SuppressUserConversion=*/false); 14505 } 14506 14507 // C++ [over.call.object]p2: 14508 // In addition, for each (non-explicit in C++0x) conversion function 14509 // declared in T of the form 14510 // 14511 // operator conversion-type-id () cv-qualifier; 14512 // 14513 // where cv-qualifier is the same cv-qualification as, or a 14514 // greater cv-qualification than, cv, and where conversion-type-id 14515 // denotes the type "pointer to function of (P1,...,Pn) returning 14516 // R", or the type "reference to pointer to function of 14517 // (P1,...,Pn) returning R", or the type "reference to function 14518 // of (P1,...,Pn) returning R", a surrogate call function [...] 14519 // is also considered as a candidate function. Similarly, 14520 // surrogate call functions are added to the set of candidate 14521 // functions for each conversion function declared in an 14522 // accessible base class provided the function is not hidden 14523 // within T by another intervening declaration. 14524 const auto &Conversions = 14525 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14526 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14527 NamedDecl *D = *I; 14528 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14529 if (isa<UsingShadowDecl>(D)) 14530 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14531 14532 // Skip over templated conversion functions; they aren't 14533 // surrogates. 14534 if (isa<FunctionTemplateDecl>(D)) 14535 continue; 14536 14537 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14538 if (!Conv->isExplicit()) { 14539 // Strip the reference type (if any) and then the pointer type (if 14540 // any) to get down to what might be a function type. 14541 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14542 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14543 ConvType = ConvPtrType->getPointeeType(); 14544 14545 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14546 { 14547 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14548 Object.get(), Args, CandidateSet); 14549 } 14550 } 14551 } 14552 14553 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14554 14555 // Perform overload resolution. 14556 OverloadCandidateSet::iterator Best; 14557 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14558 Best)) { 14559 case OR_Success: 14560 // Overload resolution succeeded; we'll build the appropriate call 14561 // below. 14562 break; 14563 14564 case OR_No_Viable_Function: { 14565 PartialDiagnostic PD = 14566 CandidateSet.empty() 14567 ? (PDiag(diag::err_ovl_no_oper) 14568 << Object.get()->getType() << /*call*/ 1 14569 << Object.get()->getSourceRange()) 14570 : (PDiag(diag::err_ovl_no_viable_object_call) 14571 << Object.get()->getType() << Object.get()->getSourceRange()); 14572 CandidateSet.NoteCandidates( 14573 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14574 OCD_AllCandidates, Args); 14575 break; 14576 } 14577 case OR_Ambiguous: 14578 CandidateSet.NoteCandidates( 14579 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14580 PDiag(diag::err_ovl_ambiguous_object_call) 14581 << Object.get()->getType() 14582 << Object.get()->getSourceRange()), 14583 *this, OCD_AmbiguousCandidates, Args); 14584 break; 14585 14586 case OR_Deleted: 14587 CandidateSet.NoteCandidates( 14588 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14589 PDiag(diag::err_ovl_deleted_object_call) 14590 << Object.get()->getType() 14591 << Object.get()->getSourceRange()), 14592 *this, OCD_AllCandidates, Args); 14593 break; 14594 } 14595 14596 if (Best == CandidateSet.end()) 14597 return true; 14598 14599 UnbridgedCasts.restore(); 14600 14601 if (Best->Function == nullptr) { 14602 // Since there is no function declaration, this is one of the 14603 // surrogate candidates. Dig out the conversion function. 14604 CXXConversionDecl *Conv 14605 = cast<CXXConversionDecl>( 14606 Best->Conversions[0].UserDefined.ConversionFunction); 14607 14608 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14609 Best->FoundDecl); 14610 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14611 return ExprError(); 14612 assert(Conv == Best->FoundDecl.getDecl() && 14613 "Found Decl & conversion-to-functionptr should be same, right?!"); 14614 // We selected one of the surrogate functions that converts the 14615 // object parameter to a function pointer. Perform the conversion 14616 // on the object argument, then let BuildCallExpr finish the job. 14617 14618 // Create an implicit member expr to refer to the conversion operator. 14619 // and then call it. 14620 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14621 Conv, HadMultipleCandidates); 14622 if (Call.isInvalid()) 14623 return ExprError(); 14624 // Record usage of conversion in an implicit cast. 14625 Call = ImplicitCastExpr::Create( 14626 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14627 nullptr, VK_PRValue, CurFPFeatureOverrides()); 14628 14629 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14630 } 14631 14632 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14633 14634 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14635 // that calls this method, using Object for the implicit object 14636 // parameter and passing along the remaining arguments. 14637 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14638 14639 // An error diagnostic has already been printed when parsing the declaration. 14640 if (Method->isInvalidDecl()) 14641 return ExprError(); 14642 14643 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14644 unsigned NumParams = Proto->getNumParams(); 14645 14646 DeclarationNameInfo OpLocInfo( 14647 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14648 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14649 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14650 Obj, HadMultipleCandidates, 14651 OpLocInfo.getLoc(), 14652 OpLocInfo.getInfo()); 14653 if (NewFn.isInvalid()) 14654 return true; 14655 14656 // The number of argument slots to allocate in the call. If we have default 14657 // arguments we need to allocate space for them as well. We additionally 14658 // need one more slot for the object parameter. 14659 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14660 14661 // Build the full argument list for the method call (the implicit object 14662 // parameter is placed at the beginning of the list). 14663 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14664 14665 bool IsError = false; 14666 14667 // Initialize the implicit object parameter. 14668 ExprResult ObjRes = 14669 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14670 Best->FoundDecl, Method); 14671 if (ObjRes.isInvalid()) 14672 IsError = true; 14673 else 14674 Object = ObjRes; 14675 MethodArgs[0] = Object.get(); 14676 14677 // Check the argument types. 14678 for (unsigned i = 0; i != NumParams; i++) { 14679 Expr *Arg; 14680 if (i < Args.size()) { 14681 Arg = Args[i]; 14682 14683 // Pass the argument. 14684 14685 ExprResult InputInit 14686 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14687 Context, 14688 Method->getParamDecl(i)), 14689 SourceLocation(), Arg); 14690 14691 IsError |= InputInit.isInvalid(); 14692 Arg = InputInit.getAs<Expr>(); 14693 } else { 14694 ExprResult DefArg 14695 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14696 if (DefArg.isInvalid()) { 14697 IsError = true; 14698 break; 14699 } 14700 14701 Arg = DefArg.getAs<Expr>(); 14702 } 14703 14704 MethodArgs[i + 1] = Arg; 14705 } 14706 14707 // If this is a variadic call, handle args passed through "...". 14708 if (Proto->isVariadic()) { 14709 // Promote the arguments (C99 6.5.2.2p7). 14710 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14711 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14712 nullptr); 14713 IsError |= Arg.isInvalid(); 14714 MethodArgs[i + 1] = Arg.get(); 14715 } 14716 } 14717 14718 if (IsError) 14719 return true; 14720 14721 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14722 14723 // Once we've built TheCall, all of the expressions are properly owned. 14724 QualType ResultTy = Method->getReturnType(); 14725 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14726 ResultTy = ResultTy.getNonLValueExprType(Context); 14727 14728 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14729 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14730 CurFPFeatureOverrides()); 14731 14732 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14733 return true; 14734 14735 if (CheckFunctionCall(Method, TheCall, Proto)) 14736 return true; 14737 14738 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14739 } 14740 14741 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14742 /// (if one exists), where @c Base is an expression of class type and 14743 /// @c Member is the name of the member we're trying to find. 14744 ExprResult 14745 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14746 bool *NoArrowOperatorFound) { 14747 assert(Base->getType()->isRecordType() && 14748 "left-hand side must have class type"); 14749 14750 if (checkPlaceholderForOverload(*this, Base)) 14751 return ExprError(); 14752 14753 SourceLocation Loc = Base->getExprLoc(); 14754 14755 // C++ [over.ref]p1: 14756 // 14757 // [...] An expression x->m is interpreted as (x.operator->())->m 14758 // for a class object x of type T if T::operator->() exists and if 14759 // the operator is selected as the best match function by the 14760 // overload resolution mechanism (13.3). 14761 DeclarationName OpName = 14762 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14763 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14764 14765 if (RequireCompleteType(Loc, Base->getType(), 14766 diag::err_typecheck_incomplete_tag, Base)) 14767 return ExprError(); 14768 14769 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14770 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14771 R.suppressDiagnostics(); 14772 14773 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14774 Oper != OperEnd; ++Oper) { 14775 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14776 None, CandidateSet, /*SuppressUserConversion=*/false); 14777 } 14778 14779 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14780 14781 // Perform overload resolution. 14782 OverloadCandidateSet::iterator Best; 14783 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14784 case OR_Success: 14785 // Overload resolution succeeded; we'll build the call below. 14786 break; 14787 14788 case OR_No_Viable_Function: { 14789 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14790 if (CandidateSet.empty()) { 14791 QualType BaseType = Base->getType(); 14792 if (NoArrowOperatorFound) { 14793 // Report this specific error to the caller instead of emitting a 14794 // diagnostic, as requested. 14795 *NoArrowOperatorFound = true; 14796 return ExprError(); 14797 } 14798 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14799 << BaseType << Base->getSourceRange(); 14800 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14801 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14802 << FixItHint::CreateReplacement(OpLoc, "."); 14803 } 14804 } else 14805 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14806 << "operator->" << Base->getSourceRange(); 14807 CandidateSet.NoteCandidates(*this, Base, Cands); 14808 return ExprError(); 14809 } 14810 case OR_Ambiguous: 14811 CandidateSet.NoteCandidates( 14812 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14813 << "->" << Base->getType() 14814 << Base->getSourceRange()), 14815 *this, OCD_AmbiguousCandidates, Base); 14816 return ExprError(); 14817 14818 case OR_Deleted: 14819 CandidateSet.NoteCandidates( 14820 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14821 << "->" << Base->getSourceRange()), 14822 *this, OCD_AllCandidates, Base); 14823 return ExprError(); 14824 } 14825 14826 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14827 14828 // Convert the object parameter. 14829 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14830 ExprResult BaseResult = 14831 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14832 Best->FoundDecl, Method); 14833 if (BaseResult.isInvalid()) 14834 return ExprError(); 14835 Base = BaseResult.get(); 14836 14837 // Build the operator call. 14838 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14839 Base, HadMultipleCandidates, OpLoc); 14840 if (FnExpr.isInvalid()) 14841 return ExprError(); 14842 14843 QualType ResultTy = Method->getReturnType(); 14844 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14845 ResultTy = ResultTy.getNonLValueExprType(Context); 14846 CXXOperatorCallExpr *TheCall = 14847 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14848 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14849 14850 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14851 return ExprError(); 14852 14853 if (CheckFunctionCall(Method, TheCall, 14854 Method->getType()->castAs<FunctionProtoType>())) 14855 return ExprError(); 14856 14857 return MaybeBindToTemporary(TheCall); 14858 } 14859 14860 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14861 /// a literal operator described by the provided lookup results. 14862 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14863 DeclarationNameInfo &SuffixInfo, 14864 ArrayRef<Expr*> Args, 14865 SourceLocation LitEndLoc, 14866 TemplateArgumentListInfo *TemplateArgs) { 14867 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14868 14869 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14870 OverloadCandidateSet::CSK_Normal); 14871 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14872 TemplateArgs); 14873 14874 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14875 14876 // Perform overload resolution. This will usually be trivial, but might need 14877 // to perform substitutions for a literal operator template. 14878 OverloadCandidateSet::iterator Best; 14879 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14880 case OR_Success: 14881 case OR_Deleted: 14882 break; 14883 14884 case OR_No_Viable_Function: 14885 CandidateSet.NoteCandidates( 14886 PartialDiagnosticAt(UDSuffixLoc, 14887 PDiag(diag::err_ovl_no_viable_function_in_call) 14888 << R.getLookupName()), 14889 *this, OCD_AllCandidates, Args); 14890 return ExprError(); 14891 14892 case OR_Ambiguous: 14893 CandidateSet.NoteCandidates( 14894 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14895 << R.getLookupName()), 14896 *this, OCD_AmbiguousCandidates, Args); 14897 return ExprError(); 14898 } 14899 14900 FunctionDecl *FD = Best->Function; 14901 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14902 nullptr, HadMultipleCandidates, 14903 SuffixInfo.getLoc(), 14904 SuffixInfo.getInfo()); 14905 if (Fn.isInvalid()) 14906 return true; 14907 14908 // Check the argument types. This should almost always be a no-op, except 14909 // that array-to-pointer decay is applied to string literals. 14910 Expr *ConvArgs[2]; 14911 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14912 ExprResult InputInit = PerformCopyInitialization( 14913 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14914 SourceLocation(), Args[ArgIdx]); 14915 if (InputInit.isInvalid()) 14916 return true; 14917 ConvArgs[ArgIdx] = InputInit.get(); 14918 } 14919 14920 QualType ResultTy = FD->getReturnType(); 14921 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14922 ResultTy = ResultTy.getNonLValueExprType(Context); 14923 14924 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14925 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14926 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14927 14928 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14929 return ExprError(); 14930 14931 if (CheckFunctionCall(FD, UDL, nullptr)) 14932 return ExprError(); 14933 14934 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14935 } 14936 14937 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14938 /// given LookupResult is non-empty, it is assumed to describe a member which 14939 /// will be invoked. Otherwise, the function will be found via argument 14940 /// dependent lookup. 14941 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14942 /// otherwise CallExpr is set to ExprError() and some non-success value 14943 /// is returned. 14944 Sema::ForRangeStatus 14945 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14946 SourceLocation RangeLoc, 14947 const DeclarationNameInfo &NameInfo, 14948 LookupResult &MemberLookup, 14949 OverloadCandidateSet *CandidateSet, 14950 Expr *Range, ExprResult *CallExpr) { 14951 Scope *S = nullptr; 14952 14953 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14954 if (!MemberLookup.empty()) { 14955 ExprResult MemberRef = 14956 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14957 /*IsPtr=*/false, CXXScopeSpec(), 14958 /*TemplateKWLoc=*/SourceLocation(), 14959 /*FirstQualifierInScope=*/nullptr, 14960 MemberLookup, 14961 /*TemplateArgs=*/nullptr, S); 14962 if (MemberRef.isInvalid()) { 14963 *CallExpr = ExprError(); 14964 return FRS_DiagnosticIssued; 14965 } 14966 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14967 if (CallExpr->isInvalid()) { 14968 *CallExpr = ExprError(); 14969 return FRS_DiagnosticIssued; 14970 } 14971 } else { 14972 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14973 NestedNameSpecifierLoc(), 14974 NameInfo, UnresolvedSet<0>()); 14975 if (FnR.isInvalid()) 14976 return FRS_DiagnosticIssued; 14977 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14978 14979 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14980 CandidateSet, CallExpr); 14981 if (CandidateSet->empty() || CandidateSetError) { 14982 *CallExpr = ExprError(); 14983 return FRS_NoViableFunction; 14984 } 14985 OverloadCandidateSet::iterator Best; 14986 OverloadingResult OverloadResult = 14987 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14988 14989 if (OverloadResult == OR_No_Viable_Function) { 14990 *CallExpr = ExprError(); 14991 return FRS_NoViableFunction; 14992 } 14993 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14994 Loc, nullptr, CandidateSet, &Best, 14995 OverloadResult, 14996 /*AllowTypoCorrection=*/false); 14997 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14998 *CallExpr = ExprError(); 14999 return FRS_DiagnosticIssued; 15000 } 15001 } 15002 return FRS_Success; 15003 } 15004 15005 15006 /// FixOverloadedFunctionReference - E is an expression that refers to 15007 /// a C++ overloaded function (possibly with some parentheses and 15008 /// perhaps a '&' around it). We have resolved the overloaded function 15009 /// to the function declaration Fn, so patch up the expression E to 15010 /// refer (possibly indirectly) to Fn. Returns the new expr. 15011 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15012 FunctionDecl *Fn) { 15013 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15014 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15015 Found, Fn); 15016 if (SubExpr == PE->getSubExpr()) 15017 return PE; 15018 15019 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15020 } 15021 15022 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15023 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15024 Found, Fn); 15025 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15026 SubExpr->getType()) && 15027 "Implicit cast type cannot be determined from overload"); 15028 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15029 if (SubExpr == ICE->getSubExpr()) 15030 return ICE; 15031 15032 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15033 SubExpr, nullptr, ICE->getValueKind(), 15034 CurFPFeatureOverrides()); 15035 } 15036 15037 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15038 if (!GSE->isResultDependent()) { 15039 Expr *SubExpr = 15040 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15041 if (SubExpr == GSE->getResultExpr()) 15042 return GSE; 15043 15044 // Replace the resulting type information before rebuilding the generic 15045 // selection expression. 15046 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15047 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15048 unsigned ResultIdx = GSE->getResultIndex(); 15049 AssocExprs[ResultIdx] = SubExpr; 15050 15051 return GenericSelectionExpr::Create( 15052 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15053 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15054 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15055 ResultIdx); 15056 } 15057 // Rather than fall through to the unreachable, return the original generic 15058 // selection expression. 15059 return GSE; 15060 } 15061 15062 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15063 assert(UnOp->getOpcode() == UO_AddrOf && 15064 "Can only take the address of an overloaded function"); 15065 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15066 if (Method->isStatic()) { 15067 // Do nothing: static member functions aren't any different 15068 // from non-member functions. 15069 } else { 15070 // Fix the subexpression, which really has to be an 15071 // UnresolvedLookupExpr holding an overloaded member function 15072 // or template. 15073 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15074 Found, Fn); 15075 if (SubExpr == UnOp->getSubExpr()) 15076 return UnOp; 15077 15078 assert(isa<DeclRefExpr>(SubExpr) 15079 && "fixed to something other than a decl ref"); 15080 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15081 && "fixed to a member ref with no nested name qualifier"); 15082 15083 // We have taken the address of a pointer to member 15084 // function. Perform the computation here so that we get the 15085 // appropriate pointer to member type. 15086 QualType ClassType 15087 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15088 QualType MemPtrType 15089 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15090 // Under the MS ABI, lock down the inheritance model now. 15091 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15092 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15093 15094 return UnaryOperator::Create( 15095 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, 15096 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15097 } 15098 } 15099 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15100 Found, Fn); 15101 if (SubExpr == UnOp->getSubExpr()) 15102 return UnOp; 15103 15104 return UnaryOperator::Create( 15105 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()), 15106 VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false, 15107 CurFPFeatureOverrides()); 15108 } 15109 15110 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15111 // FIXME: avoid copy. 15112 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15113 if (ULE->hasExplicitTemplateArgs()) { 15114 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15115 TemplateArgs = &TemplateArgsBuffer; 15116 } 15117 15118 DeclRefExpr *DRE = 15119 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15120 ULE->getQualifierLoc(), Found.getDecl(), 15121 ULE->getTemplateKeywordLoc(), TemplateArgs); 15122 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15123 return DRE; 15124 } 15125 15126 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15127 // FIXME: avoid copy. 15128 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15129 if (MemExpr->hasExplicitTemplateArgs()) { 15130 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15131 TemplateArgs = &TemplateArgsBuffer; 15132 } 15133 15134 Expr *Base; 15135 15136 // If we're filling in a static method where we used to have an 15137 // implicit member access, rewrite to a simple decl ref. 15138 if (MemExpr->isImplicitAccess()) { 15139 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15140 DeclRefExpr *DRE = BuildDeclRefExpr( 15141 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15142 MemExpr->getQualifierLoc(), Found.getDecl(), 15143 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15144 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15145 return DRE; 15146 } else { 15147 SourceLocation Loc = MemExpr->getMemberLoc(); 15148 if (MemExpr->getQualifier()) 15149 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15150 Base = 15151 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15152 } 15153 } else 15154 Base = MemExpr->getBase(); 15155 15156 ExprValueKind valueKind; 15157 QualType type; 15158 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15159 valueKind = VK_LValue; 15160 type = Fn->getType(); 15161 } else { 15162 valueKind = VK_PRValue; 15163 type = Context.BoundMemberTy; 15164 } 15165 15166 return BuildMemberExpr( 15167 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15168 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15169 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15170 type, valueKind, OK_Ordinary, TemplateArgs); 15171 } 15172 15173 llvm_unreachable("Invalid reference to overloaded function"); 15174 } 15175 15176 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15177 DeclAccessPair Found, 15178 FunctionDecl *Fn) { 15179 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15180 } 15181