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 and __float128 if 1873 // 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 if (&S.Context.getFloatTypeSemantics(FromType) != 1880 &S.Context.getFloatTypeSemantics(ToType)) { 1881 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1882 ToType == S.Context.LongDoubleTy) || 1883 (FromType == S.Context.LongDoubleTy && 1884 ToType == S.Context.Float128Ty)); 1885 if (Float128AndLongDouble && 1886 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1887 &llvm::APFloat::PPCDoubleDouble())) 1888 return false; 1889 } 1890 // Floating point conversions (C++ 4.8). 1891 SCS.Second = ICK_Floating_Conversion; 1892 FromType = ToType.getUnqualifiedType(); 1893 } else if ((FromType->isRealFloatingType() && 1894 ToType->isIntegralType(S.Context)) || 1895 (FromType->isIntegralOrUnscopedEnumerationType() && 1896 ToType->isRealFloatingType())) { 1897 // Conversions between bfloat and int are not permitted. 1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1899 return false; 1900 1901 // Floating-integral conversions (C++ 4.9). 1902 SCS.Second = ICK_Floating_Integral; 1903 FromType = ToType.getUnqualifiedType(); 1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1905 SCS.Second = ICK_Block_Pointer_Conversion; 1906 } else if (AllowObjCWritebackConversion && 1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1908 SCS.Second = ICK_Writeback_Conversion; 1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1910 FromType, IncompatibleObjC)) { 1911 // Pointer conversions (C++ 4.10). 1912 SCS.Second = ICK_Pointer_Conversion; 1913 SCS.IncompatibleObjC = IncompatibleObjC; 1914 FromType = FromType.getUnqualifiedType(); 1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1916 InOverloadResolution, FromType)) { 1917 // Pointer to member conversions (4.11). 1918 SCS.Second = ICK_Pointer_Member; 1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1920 SCS.Second = SecondICK; 1921 FromType = ToType.getUnqualifiedType(); 1922 } else if (!S.getLangOpts().CPlusPlus && 1923 S.Context.typesAreCompatible(ToType, FromType)) { 1924 // Compatible conversions (Clang extension for C function overloading) 1925 SCS.Second = ICK_Compatible_Conversion; 1926 FromType = ToType.getUnqualifiedType(); 1927 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1928 InOverloadResolution, 1929 SCS, CStyle)) { 1930 SCS.Second = ICK_TransparentUnionConversion; 1931 FromType = ToType; 1932 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1933 CStyle)) { 1934 // tryAtomicConversion has updated the standard conversion sequence 1935 // appropriately. 1936 return true; 1937 } else if (ToType->isEventT() && 1938 From->isIntegerConstantExpr(S.getASTContext()) && 1939 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1940 SCS.Second = ICK_Zero_Event_Conversion; 1941 FromType = ToType; 1942 } else if (ToType->isQueueT() && 1943 From->isIntegerConstantExpr(S.getASTContext()) && 1944 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1945 SCS.Second = ICK_Zero_Queue_Conversion; 1946 FromType = ToType; 1947 } else if (ToType->isSamplerT() && 1948 From->isIntegerConstantExpr(S.getASTContext())) { 1949 SCS.Second = ICK_Compatible_Conversion; 1950 FromType = ToType; 1951 } else { 1952 // No second conversion required. 1953 SCS.Second = ICK_Identity; 1954 } 1955 SCS.setToType(1, FromType); 1956 1957 // The third conversion can be a function pointer conversion or a 1958 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1959 bool ObjCLifetimeConversion; 1960 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1961 // Function pointer conversions (removing 'noexcept') including removal of 1962 // 'noreturn' (Clang extension). 1963 SCS.Third = ICK_Function_Conversion; 1964 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1965 ObjCLifetimeConversion)) { 1966 SCS.Third = ICK_Qualification; 1967 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1968 FromType = ToType; 1969 } else { 1970 // No conversion required 1971 SCS.Third = ICK_Identity; 1972 } 1973 1974 // C++ [over.best.ics]p6: 1975 // [...] Any difference in top-level cv-qualification is 1976 // subsumed by the initialization itself and does not constitute 1977 // a conversion. [...] 1978 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1979 QualType CanonTo = S.Context.getCanonicalType(ToType); 1980 if (CanonFrom.getLocalUnqualifiedType() 1981 == CanonTo.getLocalUnqualifiedType() && 1982 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1983 FromType = ToType; 1984 CanonFrom = CanonTo; 1985 } 1986 1987 SCS.setToType(2, FromType); 1988 1989 if (CanonFrom == CanonTo) 1990 return true; 1991 1992 // If we have not converted the argument type to the parameter type, 1993 // this is a bad conversion sequence, unless we're resolving an overload in C. 1994 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1995 return false; 1996 1997 ExprResult ER = ExprResult{From}; 1998 Sema::AssignConvertType Conv = 1999 S.CheckSingleAssignmentConstraints(ToType, ER, 2000 /*Diagnose=*/false, 2001 /*DiagnoseCFAudited=*/false, 2002 /*ConvertRHS=*/false); 2003 ImplicitConversionKind SecondConv; 2004 switch (Conv) { 2005 case Sema::Compatible: 2006 SecondConv = ICK_C_Only_Conversion; 2007 break; 2008 // For our purposes, discarding qualifiers is just as bad as using an 2009 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2010 // qualifiers, as well. 2011 case Sema::CompatiblePointerDiscardsQualifiers: 2012 case Sema::IncompatiblePointer: 2013 case Sema::IncompatiblePointerSign: 2014 SecondConv = ICK_Incompatible_Pointer_Conversion; 2015 break; 2016 default: 2017 return false; 2018 } 2019 2020 // First can only be an lvalue conversion, so we pretend that this was the 2021 // second conversion. First should already be valid from earlier in the 2022 // function. 2023 SCS.Second = SecondConv; 2024 SCS.setToType(1, ToType); 2025 2026 // Third is Identity, because Second should rank us worse than any other 2027 // conversion. This could also be ICK_Qualification, but it's simpler to just 2028 // lump everything in with the second conversion, and we don't gain anything 2029 // from making this ICK_Qualification. 2030 SCS.Third = ICK_Identity; 2031 SCS.setToType(2, ToType); 2032 return true; 2033 } 2034 2035 static bool 2036 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2037 QualType &ToType, 2038 bool InOverloadResolution, 2039 StandardConversionSequence &SCS, 2040 bool CStyle) { 2041 2042 const RecordType *UT = ToType->getAsUnionType(); 2043 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2044 return false; 2045 // The field to initialize within the transparent union. 2046 RecordDecl *UD = UT->getDecl(); 2047 // It's compatible if the expression matches any of the fields. 2048 for (const auto *it : UD->fields()) { 2049 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2050 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2051 ToType = it->getType(); 2052 return true; 2053 } 2054 } 2055 return false; 2056 } 2057 2058 /// IsIntegralPromotion - Determines whether the conversion from the 2059 /// expression From (whose potentially-adjusted type is FromType) to 2060 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2061 /// sets PromotedType to the promoted type. 2062 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2063 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2064 // All integers are built-in. 2065 if (!To) { 2066 return false; 2067 } 2068 2069 // An rvalue of type char, signed char, unsigned char, short int, or 2070 // unsigned short int can be converted to an rvalue of type int if 2071 // int can represent all the values of the source type; otherwise, 2072 // the source rvalue can be converted to an rvalue of type unsigned 2073 // int (C++ 4.5p1). 2074 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2075 !FromType->isEnumeralType()) { 2076 if (// We can promote any signed, promotable integer type to an int 2077 (FromType->isSignedIntegerType() || 2078 // We can promote any unsigned integer type whose size is 2079 // less than int to an int. 2080 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2081 return To->getKind() == BuiltinType::Int; 2082 } 2083 2084 return To->getKind() == BuiltinType::UInt; 2085 } 2086 2087 // C++11 [conv.prom]p3: 2088 // A prvalue of an unscoped enumeration type whose underlying type is not 2089 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2090 // following types that can represent all the values of the enumeration 2091 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2092 // unsigned int, long int, unsigned long int, long long int, or unsigned 2093 // long long int. If none of the types in that list can represent all the 2094 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2095 // type can be converted to an rvalue a prvalue of the extended integer type 2096 // with lowest integer conversion rank (4.13) greater than the rank of long 2097 // long in which all the values of the enumeration can be represented. If 2098 // there are two such extended types, the signed one is chosen. 2099 // C++11 [conv.prom]p4: 2100 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2101 // can be converted to a prvalue of its underlying type. Moreover, if 2102 // integral promotion can be applied to its underlying type, a prvalue of an 2103 // unscoped enumeration type whose underlying type is fixed can also be 2104 // converted to a prvalue of the promoted underlying type. 2105 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2106 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2107 // provided for a scoped enumeration. 2108 if (FromEnumType->getDecl()->isScoped()) 2109 return false; 2110 2111 // We can perform an integral promotion to the underlying type of the enum, 2112 // even if that's not the promoted type. Note that the check for promoting 2113 // the underlying type is based on the type alone, and does not consider 2114 // the bitfield-ness of the actual source expression. 2115 if (FromEnumType->getDecl()->isFixed()) { 2116 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2117 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2118 IsIntegralPromotion(nullptr, Underlying, ToType); 2119 } 2120 2121 // We have already pre-calculated the promotion type, so this is trivial. 2122 if (ToType->isIntegerType() && 2123 isCompleteType(From->getBeginLoc(), FromType)) 2124 return Context.hasSameUnqualifiedType( 2125 ToType, FromEnumType->getDecl()->getPromotionType()); 2126 2127 // C++ [conv.prom]p5: 2128 // If the bit-field has an enumerated type, it is treated as any other 2129 // value of that type for promotion purposes. 2130 // 2131 // ... so do not fall through into the bit-field checks below in C++. 2132 if (getLangOpts().CPlusPlus) 2133 return false; 2134 } 2135 2136 // C++0x [conv.prom]p2: 2137 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2138 // to an rvalue a prvalue of the first of the following types that can 2139 // represent all the values of its underlying type: int, unsigned int, 2140 // long int, unsigned long int, long long int, or unsigned long long int. 2141 // If none of the types in that list can represent all the values of its 2142 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2143 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2144 // type. 2145 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2146 ToType->isIntegerType()) { 2147 // Determine whether the type we're converting from is signed or 2148 // unsigned. 2149 bool FromIsSigned = FromType->isSignedIntegerType(); 2150 uint64_t FromSize = Context.getTypeSize(FromType); 2151 2152 // The types we'll try to promote to, in the appropriate 2153 // order. Try each of these types. 2154 QualType PromoteTypes[6] = { 2155 Context.IntTy, Context.UnsignedIntTy, 2156 Context.LongTy, Context.UnsignedLongTy , 2157 Context.LongLongTy, Context.UnsignedLongLongTy 2158 }; 2159 for (int Idx = 0; Idx < 6; ++Idx) { 2160 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2161 if (FromSize < ToSize || 2162 (FromSize == ToSize && 2163 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2164 // We found the type that we can promote to. If this is the 2165 // type we wanted, we have a promotion. Otherwise, no 2166 // promotion. 2167 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2168 } 2169 } 2170 } 2171 2172 // An rvalue for an integral bit-field (9.6) can be converted to an 2173 // rvalue of type int if int can represent all the values of the 2174 // bit-field; otherwise, it can be converted to unsigned int if 2175 // unsigned int can represent all the values of the bit-field. If 2176 // the bit-field is larger yet, no integral promotion applies to 2177 // it. If the bit-field has an enumerated type, it is treated as any 2178 // other value of that type for promotion purposes (C++ 4.5p3). 2179 // FIXME: We should delay checking of bit-fields until we actually perform the 2180 // conversion. 2181 // 2182 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2183 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2184 // bit-fields and those whose underlying type is larger than int) for GCC 2185 // compatibility. 2186 if (From) { 2187 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2188 Optional<llvm::APSInt> BitWidth; 2189 if (FromType->isIntegralType(Context) && 2190 (BitWidth = 2191 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2192 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2193 ToSize = Context.getTypeSize(ToType); 2194 2195 // Are we promoting to an int from a bitfield that fits in an int? 2196 if (*BitWidth < ToSize || 2197 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2198 return To->getKind() == BuiltinType::Int; 2199 } 2200 2201 // Are we promoting to an unsigned int from an unsigned bitfield 2202 // that fits into an unsigned int? 2203 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2204 return To->getKind() == BuiltinType::UInt; 2205 } 2206 2207 return false; 2208 } 2209 } 2210 } 2211 2212 // An rvalue of type bool can be converted to an rvalue of type int, 2213 // with false becoming zero and true becoming one (C++ 4.5p4). 2214 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2215 return true; 2216 } 2217 2218 return false; 2219 } 2220 2221 /// IsFloatingPointPromotion - Determines whether the conversion from 2222 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2223 /// returns true and sets PromotedType to the promoted type. 2224 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2227 /// An rvalue of type float can be converted to an rvalue of type 2228 /// double. (C++ 4.6p1). 2229 if (FromBuiltin->getKind() == BuiltinType::Float && 2230 ToBuiltin->getKind() == BuiltinType::Double) 2231 return true; 2232 2233 // C99 6.3.1.5p1: 2234 // When a float is promoted to double or long double, or a 2235 // double is promoted to long double [...]. 2236 if (!getLangOpts().CPlusPlus && 2237 (FromBuiltin->getKind() == BuiltinType::Float || 2238 FromBuiltin->getKind() == BuiltinType::Double) && 2239 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2240 ToBuiltin->getKind() == BuiltinType::Float128)) 2241 return true; 2242 2243 // Half can be promoted to float. 2244 if (!getLangOpts().NativeHalfType && 2245 FromBuiltin->getKind() == BuiltinType::Half && 2246 ToBuiltin->getKind() == BuiltinType::Float) 2247 return true; 2248 } 2249 2250 return false; 2251 } 2252 2253 /// Determine if a conversion is a complex promotion. 2254 /// 2255 /// A complex promotion is defined as a complex -> complex conversion 2256 /// where the conversion between the underlying real types is a 2257 /// floating-point or integral promotion. 2258 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2259 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2260 if (!FromComplex) 2261 return false; 2262 2263 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2264 if (!ToComplex) 2265 return false; 2266 2267 return IsFloatingPointPromotion(FromComplex->getElementType(), 2268 ToComplex->getElementType()) || 2269 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2270 ToComplex->getElementType()); 2271 } 2272 2273 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2274 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2275 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2276 /// if non-empty, will be a pointer to ToType that may or may not have 2277 /// the right set of qualifiers on its pointee. 2278 /// 2279 static QualType 2280 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2281 QualType ToPointee, QualType ToType, 2282 ASTContext &Context, 2283 bool StripObjCLifetime = false) { 2284 assert((FromPtr->getTypeClass() == Type::Pointer || 2285 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2286 "Invalid similarly-qualified pointer type"); 2287 2288 /// Conversions to 'id' subsume cv-qualifier conversions. 2289 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2290 return ToType.getUnqualifiedType(); 2291 2292 QualType CanonFromPointee 2293 = Context.getCanonicalType(FromPtr->getPointeeType()); 2294 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2295 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2296 2297 if (StripObjCLifetime) 2298 Quals.removeObjCLifetime(); 2299 2300 // Exact qualifier match -> return the pointer type we're converting to. 2301 if (CanonToPointee.getLocalQualifiers() == Quals) { 2302 // ToType is exactly what we need. Return it. 2303 if (!ToType.isNull()) 2304 return ToType.getUnqualifiedType(); 2305 2306 // Build a pointer to ToPointee. It has the right qualifiers 2307 // already. 2308 if (isa<ObjCObjectPointerType>(ToType)) 2309 return Context.getObjCObjectPointerType(ToPointee); 2310 return Context.getPointerType(ToPointee); 2311 } 2312 2313 // Just build a canonical type that has the right qualifiers. 2314 QualType QualifiedCanonToPointee 2315 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2316 2317 if (isa<ObjCObjectPointerType>(ToType)) 2318 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2319 return Context.getPointerType(QualifiedCanonToPointee); 2320 } 2321 2322 static bool isNullPointerConstantForConversion(Expr *Expr, 2323 bool InOverloadResolution, 2324 ASTContext &Context) { 2325 // Handle value-dependent integral null pointer constants correctly. 2326 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2327 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2328 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2329 return !InOverloadResolution; 2330 2331 return Expr->isNullPointerConstant(Context, 2332 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2333 : Expr::NPC_ValueDependentIsNull); 2334 } 2335 2336 /// IsPointerConversion - Determines whether the conversion of the 2337 /// expression From, which has the (possibly adjusted) type FromType, 2338 /// can be converted to the type ToType via a pointer conversion (C++ 2339 /// 4.10). If so, returns true and places the converted type (that 2340 /// might differ from ToType in its cv-qualifiers at some level) into 2341 /// ConvertedType. 2342 /// 2343 /// This routine also supports conversions to and from block pointers 2344 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2345 /// pointers to interfaces. FIXME: Once we've determined the 2346 /// appropriate overloading rules for Objective-C, we may want to 2347 /// split the Objective-C checks into a different routine; however, 2348 /// GCC seems to consider all of these conversions to be pointer 2349 /// conversions, so for now they live here. IncompatibleObjC will be 2350 /// set if the conversion is an allowed Objective-C conversion that 2351 /// should result in a warning. 2352 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2353 bool InOverloadResolution, 2354 QualType& ConvertedType, 2355 bool &IncompatibleObjC) { 2356 IncompatibleObjC = false; 2357 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2358 IncompatibleObjC)) 2359 return true; 2360 2361 // Conversion from a null pointer constant to any Objective-C pointer type. 2362 if (ToType->isObjCObjectPointerType() && 2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2364 ConvertedType = ToType; 2365 return true; 2366 } 2367 2368 // Blocks: Block pointers can be converted to void*. 2369 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2370 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2371 ConvertedType = ToType; 2372 return true; 2373 } 2374 // Blocks: A null pointer constant can be converted to a block 2375 // pointer type. 2376 if (ToType->isBlockPointerType() && 2377 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2378 ConvertedType = ToType; 2379 return true; 2380 } 2381 2382 // If the left-hand-side is nullptr_t, the right side can be a null 2383 // pointer constant. 2384 if (ToType->isNullPtrType() && 2385 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2386 ConvertedType = ToType; 2387 return true; 2388 } 2389 2390 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2391 if (!ToTypePtr) 2392 return false; 2393 2394 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2395 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2396 ConvertedType = ToType; 2397 return true; 2398 } 2399 2400 // Beyond this point, both types need to be pointers 2401 // , including objective-c pointers. 2402 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2403 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2404 !getLangOpts().ObjCAutoRefCount) { 2405 ConvertedType = BuildSimilarlyQualifiedPointerType( 2406 FromType->getAs<ObjCObjectPointerType>(), 2407 ToPointeeType, 2408 ToType, Context); 2409 return true; 2410 } 2411 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2412 if (!FromTypePtr) 2413 return false; 2414 2415 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2416 2417 // If the unqualified pointee types are the same, this can't be a 2418 // pointer conversion, so don't do all of the work below. 2419 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2420 return false; 2421 2422 // An rvalue of type "pointer to cv T," where T is an object type, 2423 // can be converted to an rvalue of type "pointer to cv void" (C++ 2424 // 4.10p2). 2425 if (FromPointeeType->isIncompleteOrObjectType() && 2426 ToPointeeType->isVoidType()) { 2427 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2428 ToPointeeType, 2429 ToType, Context, 2430 /*StripObjCLifetime=*/true); 2431 return true; 2432 } 2433 2434 // MSVC allows implicit function to void* type conversion. 2435 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2436 ToPointeeType->isVoidType()) { 2437 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2438 ToPointeeType, 2439 ToType, Context); 2440 return true; 2441 } 2442 2443 // When we're overloading in C, we allow a special kind of pointer 2444 // conversion for compatible-but-not-identical pointee types. 2445 if (!getLangOpts().CPlusPlus && 2446 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2447 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2448 ToPointeeType, 2449 ToType, Context); 2450 return true; 2451 } 2452 2453 // C++ [conv.ptr]p3: 2454 // 2455 // An rvalue of type "pointer to cv D," where D is a class type, 2456 // can be converted to an rvalue of type "pointer to cv B," where 2457 // B is a base class (clause 10) of D. If B is an inaccessible 2458 // (clause 11) or ambiguous (10.2) base class of D, a program that 2459 // necessitates this conversion is ill-formed. The result of the 2460 // conversion is a pointer to the base class sub-object of the 2461 // derived class object. The null pointer value is converted to 2462 // the null pointer value of the destination type. 2463 // 2464 // Note that we do not check for ambiguity or inaccessibility 2465 // here. That is handled by CheckPointerConversion. 2466 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2467 ToPointeeType->isRecordType() && 2468 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2469 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2470 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2471 ToPointeeType, 2472 ToType, Context); 2473 return true; 2474 } 2475 2476 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2477 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2478 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2479 ToPointeeType, 2480 ToType, Context); 2481 return true; 2482 } 2483 2484 return false; 2485 } 2486 2487 /// Adopt the given qualifiers for the given type. 2488 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2489 Qualifiers TQs = T.getQualifiers(); 2490 2491 // Check whether qualifiers already match. 2492 if (TQs == Qs) 2493 return T; 2494 2495 if (Qs.compatiblyIncludes(TQs)) 2496 return Context.getQualifiedType(T, Qs); 2497 2498 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2499 } 2500 2501 /// isObjCPointerConversion - Determines whether this is an 2502 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2503 /// with the same arguments and return values. 2504 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2505 QualType& ConvertedType, 2506 bool &IncompatibleObjC) { 2507 if (!getLangOpts().ObjC) 2508 return false; 2509 2510 // The set of qualifiers on the type we're converting from. 2511 Qualifiers FromQualifiers = FromType.getQualifiers(); 2512 2513 // First, we handle all conversions on ObjC object pointer types. 2514 const ObjCObjectPointerType* ToObjCPtr = 2515 ToType->getAs<ObjCObjectPointerType>(); 2516 const ObjCObjectPointerType *FromObjCPtr = 2517 FromType->getAs<ObjCObjectPointerType>(); 2518 2519 if (ToObjCPtr && FromObjCPtr) { 2520 // If the pointee types are the same (ignoring qualifications), 2521 // then this is not a pointer conversion. 2522 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2523 FromObjCPtr->getPointeeType())) 2524 return false; 2525 2526 // Conversion between Objective-C pointers. 2527 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2528 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2529 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2530 if (getLangOpts().CPlusPlus && LHS && RHS && 2531 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2532 FromObjCPtr->getPointeeType())) 2533 return false; 2534 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2535 ToObjCPtr->getPointeeType(), 2536 ToType, Context); 2537 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2538 return true; 2539 } 2540 2541 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2542 // Okay: this is some kind of implicit downcast of Objective-C 2543 // interfaces, which is permitted. However, we're going to 2544 // complain about it. 2545 IncompatibleObjC = true; 2546 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2547 ToObjCPtr->getPointeeType(), 2548 ToType, Context); 2549 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2550 return true; 2551 } 2552 } 2553 // Beyond this point, both types need to be C pointers or block pointers. 2554 QualType ToPointeeType; 2555 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2556 ToPointeeType = ToCPtr->getPointeeType(); 2557 else if (const BlockPointerType *ToBlockPtr = 2558 ToType->getAs<BlockPointerType>()) { 2559 // Objective C++: We're able to convert from a pointer to any object 2560 // to a block pointer type. 2561 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2562 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2563 return true; 2564 } 2565 ToPointeeType = ToBlockPtr->getPointeeType(); 2566 } 2567 else if (FromType->getAs<BlockPointerType>() && 2568 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2569 // Objective C++: We're able to convert from a block pointer type to a 2570 // pointer to any object. 2571 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2572 return true; 2573 } 2574 else 2575 return false; 2576 2577 QualType FromPointeeType; 2578 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2579 FromPointeeType = FromCPtr->getPointeeType(); 2580 else if (const BlockPointerType *FromBlockPtr = 2581 FromType->getAs<BlockPointerType>()) 2582 FromPointeeType = FromBlockPtr->getPointeeType(); 2583 else 2584 return false; 2585 2586 // If we have pointers to pointers, recursively check whether this 2587 // is an Objective-C conversion. 2588 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2589 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2590 IncompatibleObjC)) { 2591 // We always complain about this conversion. 2592 IncompatibleObjC = true; 2593 ConvertedType = Context.getPointerType(ConvertedType); 2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2595 return true; 2596 } 2597 // Allow conversion of pointee being objective-c pointer to another one; 2598 // as in I* to id. 2599 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2600 ToPointeeType->getAs<ObjCObjectPointerType>() && 2601 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2602 IncompatibleObjC)) { 2603 2604 ConvertedType = Context.getPointerType(ConvertedType); 2605 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2606 return true; 2607 } 2608 2609 // If we have pointers to functions or blocks, check whether the only 2610 // differences in the argument and result types are in Objective-C 2611 // pointer conversions. If so, we permit the conversion (but 2612 // complain about it). 2613 const FunctionProtoType *FromFunctionType 2614 = FromPointeeType->getAs<FunctionProtoType>(); 2615 const FunctionProtoType *ToFunctionType 2616 = ToPointeeType->getAs<FunctionProtoType>(); 2617 if (FromFunctionType && ToFunctionType) { 2618 // If the function types are exactly the same, this isn't an 2619 // Objective-C pointer conversion. 2620 if (Context.getCanonicalType(FromPointeeType) 2621 == Context.getCanonicalType(ToPointeeType)) 2622 return false; 2623 2624 // Perform the quick checks that will tell us whether these 2625 // function types are obviously different. 2626 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2627 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2628 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2629 return false; 2630 2631 bool HasObjCConversion = false; 2632 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2633 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2634 // Okay, the types match exactly. Nothing to do. 2635 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2636 ToFunctionType->getReturnType(), 2637 ConvertedType, IncompatibleObjC)) { 2638 // Okay, we have an Objective-C pointer conversion. 2639 HasObjCConversion = true; 2640 } else { 2641 // Function types are too different. Abort. 2642 return false; 2643 } 2644 2645 // Check argument types. 2646 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2647 ArgIdx != NumArgs; ++ArgIdx) { 2648 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2649 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2650 if (Context.getCanonicalType(FromArgType) 2651 == Context.getCanonicalType(ToArgType)) { 2652 // Okay, the types match exactly. Nothing to do. 2653 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2654 ConvertedType, IncompatibleObjC)) { 2655 // Okay, we have an Objective-C pointer conversion. 2656 HasObjCConversion = true; 2657 } else { 2658 // Argument types are too different. Abort. 2659 return false; 2660 } 2661 } 2662 2663 if (HasObjCConversion) { 2664 // We had an Objective-C conversion. Allow this pointer 2665 // conversion, but complain about it. 2666 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2667 IncompatibleObjC = true; 2668 return true; 2669 } 2670 } 2671 2672 return false; 2673 } 2674 2675 /// Determine whether this is an Objective-C writeback conversion, 2676 /// used for parameter passing when performing automatic reference counting. 2677 /// 2678 /// \param FromType The type we're converting form. 2679 /// 2680 /// \param ToType The type we're converting to. 2681 /// 2682 /// \param ConvertedType The type that will be produced after applying 2683 /// this conversion. 2684 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2685 QualType &ConvertedType) { 2686 if (!getLangOpts().ObjCAutoRefCount || 2687 Context.hasSameUnqualifiedType(FromType, ToType)) 2688 return false; 2689 2690 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2691 QualType ToPointee; 2692 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2693 ToPointee = ToPointer->getPointeeType(); 2694 else 2695 return false; 2696 2697 Qualifiers ToQuals = ToPointee.getQualifiers(); 2698 if (!ToPointee->isObjCLifetimeType() || 2699 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2700 !ToQuals.withoutObjCLifetime().empty()) 2701 return false; 2702 2703 // Argument must be a pointer to __strong to __weak. 2704 QualType FromPointee; 2705 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2706 FromPointee = FromPointer->getPointeeType(); 2707 else 2708 return false; 2709 2710 Qualifiers FromQuals = FromPointee.getQualifiers(); 2711 if (!FromPointee->isObjCLifetimeType() || 2712 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2713 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2714 return false; 2715 2716 // Make sure that we have compatible qualifiers. 2717 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2718 if (!ToQuals.compatiblyIncludes(FromQuals)) 2719 return false; 2720 2721 // Remove qualifiers from the pointee type we're converting from; they 2722 // aren't used in the compatibility check belong, and we'll be adding back 2723 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2724 FromPointee = FromPointee.getUnqualifiedType(); 2725 2726 // The unqualified form of the pointee types must be compatible. 2727 ToPointee = ToPointee.getUnqualifiedType(); 2728 bool IncompatibleObjC; 2729 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2730 FromPointee = ToPointee; 2731 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2732 IncompatibleObjC)) 2733 return false; 2734 2735 /// Construct the type we're converting to, which is a pointer to 2736 /// __autoreleasing pointee. 2737 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2738 ConvertedType = Context.getPointerType(FromPointee); 2739 return true; 2740 } 2741 2742 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2743 QualType& ConvertedType) { 2744 QualType ToPointeeType; 2745 if (const BlockPointerType *ToBlockPtr = 2746 ToType->getAs<BlockPointerType>()) 2747 ToPointeeType = ToBlockPtr->getPointeeType(); 2748 else 2749 return false; 2750 2751 QualType FromPointeeType; 2752 if (const BlockPointerType *FromBlockPtr = 2753 FromType->getAs<BlockPointerType>()) 2754 FromPointeeType = FromBlockPtr->getPointeeType(); 2755 else 2756 return false; 2757 // We have pointer to blocks, check whether the only 2758 // differences in the argument and result types are in Objective-C 2759 // pointer conversions. If so, we permit the conversion. 2760 2761 const FunctionProtoType *FromFunctionType 2762 = FromPointeeType->getAs<FunctionProtoType>(); 2763 const FunctionProtoType *ToFunctionType 2764 = ToPointeeType->getAs<FunctionProtoType>(); 2765 2766 if (!FromFunctionType || !ToFunctionType) 2767 return false; 2768 2769 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2770 return true; 2771 2772 // Perform the quick checks that will tell us whether these 2773 // function types are obviously different. 2774 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2775 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2776 return false; 2777 2778 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2779 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2780 if (FromEInfo != ToEInfo) 2781 return false; 2782 2783 bool IncompatibleObjC = false; 2784 if (Context.hasSameType(FromFunctionType->getReturnType(), 2785 ToFunctionType->getReturnType())) { 2786 // Okay, the types match exactly. Nothing to do. 2787 } else { 2788 QualType RHS = FromFunctionType->getReturnType(); 2789 QualType LHS = ToFunctionType->getReturnType(); 2790 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2791 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2792 LHS = LHS.getUnqualifiedType(); 2793 2794 if (Context.hasSameType(RHS,LHS)) { 2795 // OK exact match. 2796 } else if (isObjCPointerConversion(RHS, LHS, 2797 ConvertedType, IncompatibleObjC)) { 2798 if (IncompatibleObjC) 2799 return false; 2800 // Okay, we have an Objective-C pointer conversion. 2801 } 2802 else 2803 return false; 2804 } 2805 2806 // Check argument types. 2807 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2808 ArgIdx != NumArgs; ++ArgIdx) { 2809 IncompatibleObjC = false; 2810 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2811 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2812 if (Context.hasSameType(FromArgType, ToArgType)) { 2813 // Okay, the types match exactly. Nothing to do. 2814 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2815 ConvertedType, IncompatibleObjC)) { 2816 if (IncompatibleObjC) 2817 return false; 2818 // Okay, we have an Objective-C pointer conversion. 2819 } else 2820 // Argument types are too different. Abort. 2821 return false; 2822 } 2823 2824 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2825 bool CanUseToFPT, CanUseFromFPT; 2826 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2827 CanUseToFPT, CanUseFromFPT, 2828 NewParamInfos)) 2829 return false; 2830 2831 ConvertedType = ToType; 2832 return true; 2833 } 2834 2835 enum { 2836 ft_default, 2837 ft_different_class, 2838 ft_parameter_arity, 2839 ft_parameter_mismatch, 2840 ft_return_type, 2841 ft_qualifer_mismatch, 2842 ft_noexcept 2843 }; 2844 2845 /// Attempts to get the FunctionProtoType from a Type. Handles 2846 /// MemberFunctionPointers properly. 2847 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2848 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2849 return FPT; 2850 2851 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2852 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2853 2854 return nullptr; 2855 } 2856 2857 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2858 /// function types. Catches different number of parameter, mismatch in 2859 /// parameter types, and different return types. 2860 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2861 QualType FromType, QualType ToType) { 2862 // If either type is not valid, include no extra info. 2863 if (FromType.isNull() || ToType.isNull()) { 2864 PDiag << ft_default; 2865 return; 2866 } 2867 2868 // Get the function type from the pointers. 2869 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2870 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2871 *ToMember = ToType->castAs<MemberPointerType>(); 2872 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2873 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2874 << QualType(FromMember->getClass(), 0); 2875 return; 2876 } 2877 FromType = FromMember->getPointeeType(); 2878 ToType = ToMember->getPointeeType(); 2879 } 2880 2881 if (FromType->isPointerType()) 2882 FromType = FromType->getPointeeType(); 2883 if (ToType->isPointerType()) 2884 ToType = ToType->getPointeeType(); 2885 2886 // Remove references. 2887 FromType = FromType.getNonReferenceType(); 2888 ToType = ToType.getNonReferenceType(); 2889 2890 // Don't print extra info for non-specialized template functions. 2891 if (FromType->isInstantiationDependentType() && 2892 !FromType->getAs<TemplateSpecializationType>()) { 2893 PDiag << ft_default; 2894 return; 2895 } 2896 2897 // No extra info for same types. 2898 if (Context.hasSameType(FromType, ToType)) { 2899 PDiag << ft_default; 2900 return; 2901 } 2902 2903 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2904 *ToFunction = tryGetFunctionProtoType(ToType); 2905 2906 // Both types need to be function types. 2907 if (!FromFunction || !ToFunction) { 2908 PDiag << ft_default; 2909 return; 2910 } 2911 2912 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2913 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2914 << FromFunction->getNumParams(); 2915 return; 2916 } 2917 2918 // Handle different parameter types. 2919 unsigned ArgPos; 2920 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2921 PDiag << ft_parameter_mismatch << ArgPos + 1 2922 << ToFunction->getParamType(ArgPos) 2923 << FromFunction->getParamType(ArgPos); 2924 return; 2925 } 2926 2927 // Handle different return type. 2928 if (!Context.hasSameType(FromFunction->getReturnType(), 2929 ToFunction->getReturnType())) { 2930 PDiag << ft_return_type << ToFunction->getReturnType() 2931 << FromFunction->getReturnType(); 2932 return; 2933 } 2934 2935 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2936 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2937 << FromFunction->getMethodQuals(); 2938 return; 2939 } 2940 2941 // Handle exception specification differences on canonical type (in C++17 2942 // onwards). 2943 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2944 ->isNothrow() != 2945 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2946 ->isNothrow()) { 2947 PDiag << ft_noexcept; 2948 return; 2949 } 2950 2951 // Unable to find a difference, so add no extra info. 2952 PDiag << ft_default; 2953 } 2954 2955 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2956 /// for equality of their argument types. Caller has already checked that 2957 /// they have same number of arguments. If the parameters are different, 2958 /// ArgPos will have the parameter index of the first different parameter. 2959 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2960 const FunctionProtoType *NewType, 2961 unsigned *ArgPos) { 2962 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2963 N = NewType->param_type_begin(), 2964 E = OldType->param_type_end(); 2965 O && (O != E); ++O, ++N) { 2966 // Ignore address spaces in pointee type. This is to disallow overloading 2967 // on __ptr32/__ptr64 address spaces. 2968 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2969 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2970 2971 if (!Context.hasSameType(Old, New)) { 2972 if (ArgPos) 2973 *ArgPos = O - OldType->param_type_begin(); 2974 return false; 2975 } 2976 } 2977 return true; 2978 } 2979 2980 /// CheckPointerConversion - Check the pointer conversion from the 2981 /// expression From to the type ToType. This routine checks for 2982 /// ambiguous or inaccessible derived-to-base pointer 2983 /// conversions for which IsPointerConversion has already returned 2984 /// true. It returns true and produces a diagnostic if there was an 2985 /// error, or returns false otherwise. 2986 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2987 CastKind &Kind, 2988 CXXCastPath& BasePath, 2989 bool IgnoreBaseAccess, 2990 bool Diagnose) { 2991 QualType FromType = From->getType(); 2992 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2993 2994 Kind = CK_BitCast; 2995 2996 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2997 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2998 Expr::NPCK_ZeroExpression) { 2999 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3000 DiagRuntimeBehavior(From->getExprLoc(), From, 3001 PDiag(diag::warn_impcast_bool_to_null_pointer) 3002 << ToType << From->getSourceRange()); 3003 else if (!isUnevaluatedContext()) 3004 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3005 << ToType << From->getSourceRange(); 3006 } 3007 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3008 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3009 QualType FromPointeeType = FromPtrType->getPointeeType(), 3010 ToPointeeType = ToPtrType->getPointeeType(); 3011 3012 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3013 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3014 // We must have a derived-to-base conversion. Check an 3015 // ambiguous or inaccessible conversion. 3016 unsigned InaccessibleID = 0; 3017 unsigned AmbiguousID = 0; 3018 if (Diagnose) { 3019 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3020 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3021 } 3022 if (CheckDerivedToBaseConversion( 3023 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3024 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3025 &BasePath, IgnoreBaseAccess)) 3026 return true; 3027 3028 // The conversion was successful. 3029 Kind = CK_DerivedToBase; 3030 } 3031 3032 if (Diagnose && !IsCStyleOrFunctionalCast && 3033 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3034 assert(getLangOpts().MSVCCompat && 3035 "this should only be possible with MSVCCompat!"); 3036 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3037 << From->getSourceRange(); 3038 } 3039 } 3040 } else if (const ObjCObjectPointerType *ToPtrType = 3041 ToType->getAs<ObjCObjectPointerType>()) { 3042 if (const ObjCObjectPointerType *FromPtrType = 3043 FromType->getAs<ObjCObjectPointerType>()) { 3044 // Objective-C++ conversions are always okay. 3045 // FIXME: We should have a different class of conversions for the 3046 // Objective-C++ implicit conversions. 3047 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3048 return false; 3049 } else if (FromType->isBlockPointerType()) { 3050 Kind = CK_BlockPointerToObjCPointerCast; 3051 } else { 3052 Kind = CK_CPointerToObjCPointerCast; 3053 } 3054 } else if (ToType->isBlockPointerType()) { 3055 if (!FromType->isBlockPointerType()) 3056 Kind = CK_AnyPointerToBlockPointerCast; 3057 } 3058 3059 // We shouldn't fall into this case unless it's valid for other 3060 // reasons. 3061 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3062 Kind = CK_NullToPointer; 3063 3064 return false; 3065 } 3066 3067 /// IsMemberPointerConversion - Determines whether the conversion of the 3068 /// expression From, which has the (possibly adjusted) type FromType, can be 3069 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3070 /// If so, returns true and places the converted type (that might differ from 3071 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3072 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3073 QualType ToType, 3074 bool InOverloadResolution, 3075 QualType &ConvertedType) { 3076 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3077 if (!ToTypePtr) 3078 return false; 3079 3080 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3081 if (From->isNullPointerConstant(Context, 3082 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3083 : Expr::NPC_ValueDependentIsNull)) { 3084 ConvertedType = ToType; 3085 return true; 3086 } 3087 3088 // Otherwise, both types have to be member pointers. 3089 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3090 if (!FromTypePtr) 3091 return false; 3092 3093 // A pointer to member of B can be converted to a pointer to member of D, 3094 // where D is derived from B (C++ 4.11p2). 3095 QualType FromClass(FromTypePtr->getClass(), 0); 3096 QualType ToClass(ToTypePtr->getClass(), 0); 3097 3098 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3099 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3100 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3101 ToClass.getTypePtr()); 3102 return true; 3103 } 3104 3105 return false; 3106 } 3107 3108 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3109 /// expression From to the type ToType. This routine checks for ambiguous or 3110 /// virtual or inaccessible base-to-derived member pointer conversions 3111 /// for which IsMemberPointerConversion has already returned true. It returns 3112 /// true and produces a diagnostic if there was an error, or returns false 3113 /// otherwise. 3114 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3115 CastKind &Kind, 3116 CXXCastPath &BasePath, 3117 bool IgnoreBaseAccess) { 3118 QualType FromType = From->getType(); 3119 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3120 if (!FromPtrType) { 3121 // This must be a null pointer to member pointer conversion 3122 assert(From->isNullPointerConstant(Context, 3123 Expr::NPC_ValueDependentIsNull) && 3124 "Expr must be null pointer constant!"); 3125 Kind = CK_NullToMemberPointer; 3126 return false; 3127 } 3128 3129 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3130 assert(ToPtrType && "No member pointer cast has a target type " 3131 "that is not a member pointer."); 3132 3133 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3134 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3135 3136 // FIXME: What about dependent types? 3137 assert(FromClass->isRecordType() && "Pointer into non-class."); 3138 assert(ToClass->isRecordType() && "Pointer into non-class."); 3139 3140 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3141 /*DetectVirtual=*/true); 3142 bool DerivationOkay = 3143 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3144 assert(DerivationOkay && 3145 "Should not have been called if derivation isn't OK."); 3146 (void)DerivationOkay; 3147 3148 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3149 getUnqualifiedType())) { 3150 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3151 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3152 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3153 return true; 3154 } 3155 3156 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3157 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3158 << FromClass << ToClass << QualType(VBase, 0) 3159 << From->getSourceRange(); 3160 return true; 3161 } 3162 3163 if (!IgnoreBaseAccess) 3164 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3165 Paths.front(), 3166 diag::err_downcast_from_inaccessible_base); 3167 3168 // Must be a base to derived member conversion. 3169 BuildBasePathArray(Paths, BasePath); 3170 Kind = CK_BaseToDerivedMemberPointer; 3171 return false; 3172 } 3173 3174 /// Determine whether the lifetime conversion between the two given 3175 /// qualifiers sets is nontrivial. 3176 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3177 Qualifiers ToQuals) { 3178 // Converting anything to const __unsafe_unretained is trivial. 3179 if (ToQuals.hasConst() && 3180 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3181 return false; 3182 3183 return true; 3184 } 3185 3186 /// Perform a single iteration of the loop for checking if a qualification 3187 /// conversion is valid. 3188 /// 3189 /// Specifically, check whether any change between the qualifiers of \p 3190 /// FromType and \p ToType is permissible, given knowledge about whether every 3191 /// outer layer is const-qualified. 3192 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3193 bool CStyle, bool IsTopLevel, 3194 bool &PreviousToQualsIncludeConst, 3195 bool &ObjCLifetimeConversion) { 3196 Qualifiers FromQuals = FromType.getQualifiers(); 3197 Qualifiers ToQuals = ToType.getQualifiers(); 3198 3199 // Ignore __unaligned qualifier if this type is void. 3200 if (ToType.getUnqualifiedType()->isVoidType()) 3201 FromQuals.removeUnaligned(); 3202 3203 // Objective-C ARC: 3204 // Check Objective-C lifetime conversions. 3205 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3206 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3207 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3208 ObjCLifetimeConversion = true; 3209 FromQuals.removeObjCLifetime(); 3210 ToQuals.removeObjCLifetime(); 3211 } else { 3212 // Qualification conversions cannot cast between different 3213 // Objective-C lifetime qualifiers. 3214 return false; 3215 } 3216 } 3217 3218 // Allow addition/removal of GC attributes but not changing GC attributes. 3219 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3220 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3221 FromQuals.removeObjCGCAttr(); 3222 ToQuals.removeObjCGCAttr(); 3223 } 3224 3225 // -- for every j > 0, if const is in cv 1,j then const is in cv 3226 // 2,j, and similarly for volatile. 3227 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3228 return false; 3229 3230 // If address spaces mismatch: 3231 // - in top level it is only valid to convert to addr space that is a 3232 // superset in all cases apart from C-style casts where we allow 3233 // conversions between overlapping address spaces. 3234 // - in non-top levels it is not a valid conversion. 3235 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3236 (!IsTopLevel || 3237 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3238 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3239 return false; 3240 3241 // -- if the cv 1,j and cv 2,j are different, then const is in 3242 // every cv for 0 < k < j. 3243 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3244 !PreviousToQualsIncludeConst) 3245 return false; 3246 3247 // Keep track of whether all prior cv-qualifiers in the "to" type 3248 // include const. 3249 PreviousToQualsIncludeConst = 3250 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3251 return true; 3252 } 3253 3254 /// IsQualificationConversion - Determines whether the conversion from 3255 /// an rvalue of type FromType to ToType is a qualification conversion 3256 /// (C++ 4.4). 3257 /// 3258 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3259 /// when the qualification conversion involves a change in the Objective-C 3260 /// object lifetime. 3261 bool 3262 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3263 bool CStyle, bool &ObjCLifetimeConversion) { 3264 FromType = Context.getCanonicalType(FromType); 3265 ToType = Context.getCanonicalType(ToType); 3266 ObjCLifetimeConversion = false; 3267 3268 // If FromType and ToType are the same type, this is not a 3269 // qualification conversion. 3270 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3271 return false; 3272 3273 // (C++ 4.4p4): 3274 // A conversion can add cv-qualifiers at levels other than the first 3275 // in multi-level pointers, subject to the following rules: [...] 3276 bool PreviousToQualsIncludeConst = true; 3277 bool UnwrappedAnyPointer = false; 3278 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3279 if (!isQualificationConversionStep( 3280 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3281 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3282 return false; 3283 UnwrappedAnyPointer = true; 3284 } 3285 3286 // We are left with FromType and ToType being the pointee types 3287 // after unwrapping the original FromType and ToType the same number 3288 // of times. If we unwrapped any pointers, and if FromType and 3289 // ToType have the same unqualified type (since we checked 3290 // qualifiers above), then this is a qualification conversion. 3291 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3292 } 3293 3294 /// - Determine whether this is a conversion from a scalar type to an 3295 /// atomic type. 3296 /// 3297 /// If successful, updates \c SCS's second and third steps in the conversion 3298 /// sequence to finish the conversion. 3299 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3300 bool InOverloadResolution, 3301 StandardConversionSequence &SCS, 3302 bool CStyle) { 3303 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3304 if (!ToAtomic) 3305 return false; 3306 3307 StandardConversionSequence InnerSCS; 3308 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3309 InOverloadResolution, InnerSCS, 3310 CStyle, /*AllowObjCWritebackConversion=*/false)) 3311 return false; 3312 3313 SCS.Second = InnerSCS.Second; 3314 SCS.setToType(1, InnerSCS.getToType(1)); 3315 SCS.Third = InnerSCS.Third; 3316 SCS.QualificationIncludesObjCLifetime 3317 = InnerSCS.QualificationIncludesObjCLifetime; 3318 SCS.setToType(2, InnerSCS.getToType(2)); 3319 return true; 3320 } 3321 3322 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3323 CXXConstructorDecl *Constructor, 3324 QualType Type) { 3325 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3326 if (CtorType->getNumParams() > 0) { 3327 QualType FirstArg = CtorType->getParamType(0); 3328 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3329 return true; 3330 } 3331 return false; 3332 } 3333 3334 static OverloadingResult 3335 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3336 CXXRecordDecl *To, 3337 UserDefinedConversionSequence &User, 3338 OverloadCandidateSet &CandidateSet, 3339 bool AllowExplicit) { 3340 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3341 for (auto *D : S.LookupConstructors(To)) { 3342 auto Info = getConstructorInfo(D); 3343 if (!Info) 3344 continue; 3345 3346 bool Usable = !Info.Constructor->isInvalidDecl() && 3347 S.isInitListConstructor(Info.Constructor); 3348 if (Usable) { 3349 // If the first argument is (a reference to) the target type, 3350 // suppress conversions. 3351 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3352 S.Context, Info.Constructor, ToType); 3353 if (Info.ConstructorTmpl) 3354 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3355 /*ExplicitArgs*/ nullptr, From, 3356 CandidateSet, SuppressUserConversions, 3357 /*PartialOverloading*/ false, 3358 AllowExplicit); 3359 else 3360 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3361 CandidateSet, SuppressUserConversions, 3362 /*PartialOverloading*/ false, AllowExplicit); 3363 } 3364 } 3365 3366 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3367 3368 OverloadCandidateSet::iterator Best; 3369 switch (auto Result = 3370 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3371 case OR_Deleted: 3372 case OR_Success: { 3373 // Record the standard conversion we used and the conversion function. 3374 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3375 QualType ThisType = Constructor->getThisType(); 3376 // Initializer lists don't have conversions as such. 3377 User.Before.setAsIdentityConversion(); 3378 User.HadMultipleCandidates = HadMultipleCandidates; 3379 User.ConversionFunction = Constructor; 3380 User.FoundConversionFunction = Best->FoundDecl; 3381 User.After.setAsIdentityConversion(); 3382 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3383 User.After.setAllToTypes(ToType); 3384 return Result; 3385 } 3386 3387 case OR_No_Viable_Function: 3388 return OR_No_Viable_Function; 3389 case OR_Ambiguous: 3390 return OR_Ambiguous; 3391 } 3392 3393 llvm_unreachable("Invalid OverloadResult!"); 3394 } 3395 3396 /// Determines whether there is a user-defined conversion sequence 3397 /// (C++ [over.ics.user]) that converts expression From to the type 3398 /// ToType. If such a conversion exists, User will contain the 3399 /// user-defined conversion sequence that performs such a conversion 3400 /// and this routine will return true. Otherwise, this routine returns 3401 /// false and User is unspecified. 3402 /// 3403 /// \param AllowExplicit true if the conversion should consider C++0x 3404 /// "explicit" conversion functions as well as non-explicit conversion 3405 /// functions (C++0x [class.conv.fct]p2). 3406 /// 3407 /// \param AllowObjCConversionOnExplicit true if the conversion should 3408 /// allow an extra Objective-C pointer conversion on uses of explicit 3409 /// constructors. Requires \c AllowExplicit to also be set. 3410 static OverloadingResult 3411 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3412 UserDefinedConversionSequence &User, 3413 OverloadCandidateSet &CandidateSet, 3414 AllowedExplicit AllowExplicit, 3415 bool AllowObjCConversionOnExplicit) { 3416 assert(AllowExplicit != AllowedExplicit::None || 3417 !AllowObjCConversionOnExplicit); 3418 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3419 3420 // Whether we will only visit constructors. 3421 bool ConstructorsOnly = false; 3422 3423 // If the type we are conversion to is a class type, enumerate its 3424 // constructors. 3425 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3426 // C++ [over.match.ctor]p1: 3427 // When objects of class type are direct-initialized (8.5), or 3428 // copy-initialized from an expression of the same or a 3429 // derived class type (8.5), overload resolution selects the 3430 // constructor. [...] For copy-initialization, the candidate 3431 // functions are all the converting constructors (12.3.1) of 3432 // that class. The argument list is the expression-list within 3433 // the parentheses of the initializer. 3434 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3435 (From->getType()->getAs<RecordType>() && 3436 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3437 ConstructorsOnly = true; 3438 3439 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3440 // We're not going to find any constructors. 3441 } else if (CXXRecordDecl *ToRecordDecl 3442 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3443 3444 Expr **Args = &From; 3445 unsigned NumArgs = 1; 3446 bool ListInitializing = false; 3447 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3448 // But first, see if there is an init-list-constructor that will work. 3449 OverloadingResult Result = IsInitializerListConstructorConversion( 3450 S, From, ToType, ToRecordDecl, User, CandidateSet, 3451 AllowExplicit == AllowedExplicit::All); 3452 if (Result != OR_No_Viable_Function) 3453 return Result; 3454 // Never mind. 3455 CandidateSet.clear( 3456 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3457 3458 // If we're list-initializing, we pass the individual elements as 3459 // arguments, not the entire list. 3460 Args = InitList->getInits(); 3461 NumArgs = InitList->getNumInits(); 3462 ListInitializing = true; 3463 } 3464 3465 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3466 auto Info = getConstructorInfo(D); 3467 if (!Info) 3468 continue; 3469 3470 bool Usable = !Info.Constructor->isInvalidDecl(); 3471 if (!ListInitializing) 3472 Usable = Usable && Info.Constructor->isConvertingConstructor( 3473 /*AllowExplicit*/ true); 3474 if (Usable) { 3475 bool SuppressUserConversions = !ConstructorsOnly; 3476 if (SuppressUserConversions && ListInitializing) { 3477 SuppressUserConversions = false; 3478 if (NumArgs == 1) { 3479 // If the first argument is (a reference to) the target type, 3480 // suppress conversions. 3481 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3482 S.Context, Info.Constructor, ToType); 3483 } 3484 } 3485 if (Info.ConstructorTmpl) 3486 S.AddTemplateOverloadCandidate( 3487 Info.ConstructorTmpl, Info.FoundDecl, 3488 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3489 CandidateSet, SuppressUserConversions, 3490 /*PartialOverloading*/ false, 3491 AllowExplicit == AllowedExplicit::All); 3492 else 3493 // Allow one user-defined conversion when user specifies a 3494 // From->ToType conversion via an static cast (c-style, etc). 3495 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3496 llvm::makeArrayRef(Args, NumArgs), 3497 CandidateSet, SuppressUserConversions, 3498 /*PartialOverloading*/ false, 3499 AllowExplicit == AllowedExplicit::All); 3500 } 3501 } 3502 } 3503 } 3504 3505 // Enumerate conversion functions, if we're allowed to. 3506 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3507 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3508 // No conversion functions from incomplete types. 3509 } else if (const RecordType *FromRecordType = 3510 From->getType()->getAs<RecordType>()) { 3511 if (CXXRecordDecl *FromRecordDecl 3512 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3513 // Add all of the conversion functions as candidates. 3514 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3515 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3516 DeclAccessPair FoundDecl = I.getPair(); 3517 NamedDecl *D = FoundDecl.getDecl(); 3518 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3519 if (isa<UsingShadowDecl>(D)) 3520 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3521 3522 CXXConversionDecl *Conv; 3523 FunctionTemplateDecl *ConvTemplate; 3524 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3525 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3526 else 3527 Conv = cast<CXXConversionDecl>(D); 3528 3529 if (ConvTemplate) 3530 S.AddTemplateConversionCandidate( 3531 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3532 CandidateSet, AllowObjCConversionOnExplicit, 3533 AllowExplicit != AllowedExplicit::None); 3534 else 3535 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3536 CandidateSet, AllowObjCConversionOnExplicit, 3537 AllowExplicit != AllowedExplicit::None); 3538 } 3539 } 3540 } 3541 3542 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3543 3544 OverloadCandidateSet::iterator Best; 3545 switch (auto Result = 3546 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3547 case OR_Success: 3548 case OR_Deleted: 3549 // Record the standard conversion we used and the conversion function. 3550 if (CXXConstructorDecl *Constructor 3551 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3552 // C++ [over.ics.user]p1: 3553 // If the user-defined conversion is specified by a 3554 // constructor (12.3.1), the initial standard conversion 3555 // sequence converts the source type to the type required by 3556 // the argument of the constructor. 3557 // 3558 QualType ThisType = Constructor->getThisType(); 3559 if (isa<InitListExpr>(From)) { 3560 // Initializer lists don't have conversions as such. 3561 User.Before.setAsIdentityConversion(); 3562 } else { 3563 if (Best->Conversions[0].isEllipsis()) 3564 User.EllipsisConversion = true; 3565 else { 3566 User.Before = Best->Conversions[0].Standard; 3567 User.EllipsisConversion = false; 3568 } 3569 } 3570 User.HadMultipleCandidates = HadMultipleCandidates; 3571 User.ConversionFunction = Constructor; 3572 User.FoundConversionFunction = Best->FoundDecl; 3573 User.After.setAsIdentityConversion(); 3574 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3575 User.After.setAllToTypes(ToType); 3576 return Result; 3577 } 3578 if (CXXConversionDecl *Conversion 3579 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3580 // C++ [over.ics.user]p1: 3581 // 3582 // [...] If the user-defined conversion is specified by a 3583 // conversion function (12.3.2), the initial standard 3584 // conversion sequence converts the source type to the 3585 // implicit object parameter of the conversion function. 3586 User.Before = Best->Conversions[0].Standard; 3587 User.HadMultipleCandidates = HadMultipleCandidates; 3588 User.ConversionFunction = Conversion; 3589 User.FoundConversionFunction = Best->FoundDecl; 3590 User.EllipsisConversion = false; 3591 3592 // C++ [over.ics.user]p2: 3593 // The second standard conversion sequence converts the 3594 // result of the user-defined conversion to the target type 3595 // for the sequence. Since an implicit conversion sequence 3596 // is an initialization, the special rules for 3597 // initialization by user-defined conversion apply when 3598 // selecting the best user-defined conversion for a 3599 // user-defined conversion sequence (see 13.3.3 and 3600 // 13.3.3.1). 3601 User.After = Best->FinalConversion; 3602 return Result; 3603 } 3604 llvm_unreachable("Not a constructor or conversion function?"); 3605 3606 case OR_No_Viable_Function: 3607 return OR_No_Viable_Function; 3608 3609 case OR_Ambiguous: 3610 return OR_Ambiguous; 3611 } 3612 3613 llvm_unreachable("Invalid OverloadResult!"); 3614 } 3615 3616 bool 3617 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3618 ImplicitConversionSequence ICS; 3619 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3620 OverloadCandidateSet::CSK_Normal); 3621 OverloadingResult OvResult = 3622 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3623 CandidateSet, AllowedExplicit::None, false); 3624 3625 if (!(OvResult == OR_Ambiguous || 3626 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3627 return false; 3628 3629 auto Cands = CandidateSet.CompleteCandidates( 3630 *this, 3631 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3632 From); 3633 if (OvResult == OR_Ambiguous) 3634 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3635 << From->getType() << ToType << From->getSourceRange(); 3636 else { // OR_No_Viable_Function && !CandidateSet.empty() 3637 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3638 diag::err_typecheck_nonviable_condition_incomplete, 3639 From->getType(), From->getSourceRange())) 3640 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3641 << false << From->getType() << From->getSourceRange() << ToType; 3642 } 3643 3644 CandidateSet.NoteCandidates( 3645 *this, From, Cands); 3646 return true; 3647 } 3648 3649 // Helper for compareConversionFunctions that gets the FunctionType that the 3650 // conversion-operator return value 'points' to, or nullptr. 3651 static const FunctionType * 3652 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3653 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3654 const PointerType *RetPtrTy = 3655 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3656 3657 if (!RetPtrTy) 3658 return nullptr; 3659 3660 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3661 } 3662 3663 /// Compare the user-defined conversion functions or constructors 3664 /// of two user-defined conversion sequences to determine whether any ordering 3665 /// is possible. 3666 static ImplicitConversionSequence::CompareKind 3667 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3668 FunctionDecl *Function2) { 3669 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3670 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3671 if (!Conv1 || !Conv2) 3672 return ImplicitConversionSequence::Indistinguishable; 3673 3674 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3675 return ImplicitConversionSequence::Indistinguishable; 3676 3677 // Objective-C++: 3678 // If both conversion functions are implicitly-declared conversions from 3679 // a lambda closure type to a function pointer and a block pointer, 3680 // respectively, always prefer the conversion to a function pointer, 3681 // because the function pointer is more lightweight and is more likely 3682 // to keep code working. 3683 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3684 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3685 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3686 if (Block1 != Block2) 3687 return Block1 ? ImplicitConversionSequence::Worse 3688 : ImplicitConversionSequence::Better; 3689 } 3690 3691 // In order to support multiple calling conventions for the lambda conversion 3692 // operator (such as when the free and member function calling convention is 3693 // different), prefer the 'free' mechanism, followed by the calling-convention 3694 // of operator(). The latter is in place to support the MSVC-like solution of 3695 // defining ALL of the possible conversions in regards to calling-convention. 3696 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3697 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3698 3699 if (Conv1FuncRet && Conv2FuncRet && 3700 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3701 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3702 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3703 3704 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3705 const FunctionProtoType *CallOpProto = 3706 CallOp->getType()->getAs<FunctionProtoType>(); 3707 3708 CallingConv CallOpCC = 3709 CallOp->getType()->getAs<FunctionType>()->getCallConv(); 3710 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3711 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3712 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3713 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3714 3715 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3716 for (CallingConv CC : PrefOrder) { 3717 if (Conv1CC == CC) 3718 return ImplicitConversionSequence::Better; 3719 if (Conv2CC == CC) 3720 return ImplicitConversionSequence::Worse; 3721 } 3722 } 3723 3724 return ImplicitConversionSequence::Indistinguishable; 3725 } 3726 3727 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3728 const ImplicitConversionSequence &ICS) { 3729 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3730 (ICS.isUserDefined() && 3731 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3732 } 3733 3734 /// CompareImplicitConversionSequences - Compare two implicit 3735 /// conversion sequences to determine whether one is better than the 3736 /// other or if they are indistinguishable (C++ 13.3.3.2). 3737 static ImplicitConversionSequence::CompareKind 3738 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3739 const ImplicitConversionSequence& ICS1, 3740 const ImplicitConversionSequence& ICS2) 3741 { 3742 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3743 // conversion sequences (as defined in 13.3.3.1) 3744 // -- a standard conversion sequence (13.3.3.1.1) is a better 3745 // conversion sequence than a user-defined conversion sequence or 3746 // an ellipsis conversion sequence, and 3747 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3748 // conversion sequence than an ellipsis conversion sequence 3749 // (13.3.3.1.3). 3750 // 3751 // C++0x [over.best.ics]p10: 3752 // For the purpose of ranking implicit conversion sequences as 3753 // described in 13.3.3.2, the ambiguous conversion sequence is 3754 // treated as a user-defined sequence that is indistinguishable 3755 // from any other user-defined conversion sequence. 3756 3757 // String literal to 'char *' conversion has been deprecated in C++03. It has 3758 // been removed from C++11. We still accept this conversion, if it happens at 3759 // the best viable function. Otherwise, this conversion is considered worse 3760 // than ellipsis conversion. Consider this as an extension; this is not in the 3761 // standard. For example: 3762 // 3763 // int &f(...); // #1 3764 // void f(char*); // #2 3765 // void g() { int &r = f("foo"); } 3766 // 3767 // In C++03, we pick #2 as the best viable function. 3768 // In C++11, we pick #1 as the best viable function, because ellipsis 3769 // conversion is better than string-literal to char* conversion (since there 3770 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3771 // convert arguments, #2 would be the best viable function in C++11. 3772 // If the best viable function has this conversion, a warning will be issued 3773 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3774 3775 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3776 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3777 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3778 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3779 ? ImplicitConversionSequence::Worse 3780 : ImplicitConversionSequence::Better; 3781 3782 if (ICS1.getKindRank() < ICS2.getKindRank()) 3783 return ImplicitConversionSequence::Better; 3784 if (ICS2.getKindRank() < ICS1.getKindRank()) 3785 return ImplicitConversionSequence::Worse; 3786 3787 // The following checks require both conversion sequences to be of 3788 // the same kind. 3789 if (ICS1.getKind() != ICS2.getKind()) 3790 return ImplicitConversionSequence::Indistinguishable; 3791 3792 ImplicitConversionSequence::CompareKind Result = 3793 ImplicitConversionSequence::Indistinguishable; 3794 3795 // Two implicit conversion sequences of the same form are 3796 // indistinguishable conversion sequences unless one of the 3797 // following rules apply: (C++ 13.3.3.2p3): 3798 3799 // List-initialization sequence L1 is a better conversion sequence than 3800 // list-initialization sequence L2 if: 3801 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3802 // if not that, 3803 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3804 // and N1 is smaller than N2., 3805 // even if one of the other rules in this paragraph would otherwise apply. 3806 if (!ICS1.isBad()) { 3807 if (ICS1.isStdInitializerListElement() && 3808 !ICS2.isStdInitializerListElement()) 3809 return ImplicitConversionSequence::Better; 3810 if (!ICS1.isStdInitializerListElement() && 3811 ICS2.isStdInitializerListElement()) 3812 return ImplicitConversionSequence::Worse; 3813 } 3814 3815 if (ICS1.isStandard()) 3816 // Standard conversion sequence S1 is a better conversion sequence than 3817 // standard conversion sequence S2 if [...] 3818 Result = CompareStandardConversionSequences(S, Loc, 3819 ICS1.Standard, ICS2.Standard); 3820 else if (ICS1.isUserDefined()) { 3821 // User-defined conversion sequence U1 is a better conversion 3822 // sequence than another user-defined conversion sequence U2 if 3823 // they contain the same user-defined conversion function or 3824 // constructor and if the second standard conversion sequence of 3825 // U1 is better than the second standard conversion sequence of 3826 // U2 (C++ 13.3.3.2p3). 3827 if (ICS1.UserDefined.ConversionFunction == 3828 ICS2.UserDefined.ConversionFunction) 3829 Result = CompareStandardConversionSequences(S, Loc, 3830 ICS1.UserDefined.After, 3831 ICS2.UserDefined.After); 3832 else 3833 Result = compareConversionFunctions(S, 3834 ICS1.UserDefined.ConversionFunction, 3835 ICS2.UserDefined.ConversionFunction); 3836 } 3837 3838 return Result; 3839 } 3840 3841 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3842 // determine if one is a proper subset of the other. 3843 static ImplicitConversionSequence::CompareKind 3844 compareStandardConversionSubsets(ASTContext &Context, 3845 const StandardConversionSequence& SCS1, 3846 const StandardConversionSequence& SCS2) { 3847 ImplicitConversionSequence::CompareKind Result 3848 = ImplicitConversionSequence::Indistinguishable; 3849 3850 // the identity conversion sequence is considered to be a subsequence of 3851 // any non-identity conversion sequence 3852 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3853 return ImplicitConversionSequence::Better; 3854 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3855 return ImplicitConversionSequence::Worse; 3856 3857 if (SCS1.Second != SCS2.Second) { 3858 if (SCS1.Second == ICK_Identity) 3859 Result = ImplicitConversionSequence::Better; 3860 else if (SCS2.Second == ICK_Identity) 3861 Result = ImplicitConversionSequence::Worse; 3862 else 3863 return ImplicitConversionSequence::Indistinguishable; 3864 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3865 return ImplicitConversionSequence::Indistinguishable; 3866 3867 if (SCS1.Third == SCS2.Third) { 3868 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3869 : ImplicitConversionSequence::Indistinguishable; 3870 } 3871 3872 if (SCS1.Third == ICK_Identity) 3873 return Result == ImplicitConversionSequence::Worse 3874 ? ImplicitConversionSequence::Indistinguishable 3875 : ImplicitConversionSequence::Better; 3876 3877 if (SCS2.Third == ICK_Identity) 3878 return Result == ImplicitConversionSequence::Better 3879 ? ImplicitConversionSequence::Indistinguishable 3880 : ImplicitConversionSequence::Worse; 3881 3882 return ImplicitConversionSequence::Indistinguishable; 3883 } 3884 3885 /// Determine whether one of the given reference bindings is better 3886 /// than the other based on what kind of bindings they are. 3887 static bool 3888 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3889 const StandardConversionSequence &SCS2) { 3890 // C++0x [over.ics.rank]p3b4: 3891 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3892 // implicit object parameter of a non-static member function declared 3893 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3894 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3895 // lvalue reference to a function lvalue and S2 binds an rvalue 3896 // reference*. 3897 // 3898 // FIXME: Rvalue references. We're going rogue with the above edits, 3899 // because the semantics in the current C++0x working paper (N3225 at the 3900 // time of this writing) break the standard definition of std::forward 3901 // and std::reference_wrapper when dealing with references to functions. 3902 // Proposed wording changes submitted to CWG for consideration. 3903 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3904 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3905 return false; 3906 3907 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3908 SCS2.IsLvalueReference) || 3909 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3910 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3911 } 3912 3913 enum class FixedEnumPromotion { 3914 None, 3915 ToUnderlyingType, 3916 ToPromotedUnderlyingType 3917 }; 3918 3919 /// Returns kind of fixed enum promotion the \a SCS uses. 3920 static FixedEnumPromotion 3921 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3922 3923 if (SCS.Second != ICK_Integral_Promotion) 3924 return FixedEnumPromotion::None; 3925 3926 QualType FromType = SCS.getFromType(); 3927 if (!FromType->isEnumeralType()) 3928 return FixedEnumPromotion::None; 3929 3930 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3931 if (!Enum->isFixed()) 3932 return FixedEnumPromotion::None; 3933 3934 QualType UnderlyingType = Enum->getIntegerType(); 3935 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3936 return FixedEnumPromotion::ToUnderlyingType; 3937 3938 return FixedEnumPromotion::ToPromotedUnderlyingType; 3939 } 3940 3941 /// CompareStandardConversionSequences - Compare two standard 3942 /// conversion sequences to determine whether one is better than the 3943 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3944 static ImplicitConversionSequence::CompareKind 3945 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3946 const StandardConversionSequence& SCS1, 3947 const StandardConversionSequence& SCS2) 3948 { 3949 // Standard conversion sequence S1 is a better conversion sequence 3950 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3951 3952 // -- S1 is a proper subsequence of S2 (comparing the conversion 3953 // sequences in the canonical form defined by 13.3.3.1.1, 3954 // excluding any Lvalue Transformation; the identity conversion 3955 // sequence is considered to be a subsequence of any 3956 // non-identity conversion sequence) or, if not that, 3957 if (ImplicitConversionSequence::CompareKind CK 3958 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3959 return CK; 3960 3961 // -- the rank of S1 is better than the rank of S2 (by the rules 3962 // defined below), or, if not that, 3963 ImplicitConversionRank Rank1 = SCS1.getRank(); 3964 ImplicitConversionRank Rank2 = SCS2.getRank(); 3965 if (Rank1 < Rank2) 3966 return ImplicitConversionSequence::Better; 3967 else if (Rank2 < Rank1) 3968 return ImplicitConversionSequence::Worse; 3969 3970 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3971 // are indistinguishable unless one of the following rules 3972 // applies: 3973 3974 // A conversion that is not a conversion of a pointer, or 3975 // pointer to member, to bool is better than another conversion 3976 // that is such a conversion. 3977 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3978 return SCS2.isPointerConversionToBool() 3979 ? ImplicitConversionSequence::Better 3980 : ImplicitConversionSequence::Worse; 3981 3982 // C++14 [over.ics.rank]p4b2: 3983 // This is retroactively applied to C++11 by CWG 1601. 3984 // 3985 // A conversion that promotes an enumeration whose underlying type is fixed 3986 // to its underlying type is better than one that promotes to the promoted 3987 // underlying type, if the two are different. 3988 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3989 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3990 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3991 FEP1 != FEP2) 3992 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3993 ? ImplicitConversionSequence::Better 3994 : ImplicitConversionSequence::Worse; 3995 3996 // C++ [over.ics.rank]p4b2: 3997 // 3998 // If class B is derived directly or indirectly from class A, 3999 // conversion of B* to A* is better than conversion of B* to 4000 // void*, and conversion of A* to void* is better than conversion 4001 // of B* to void*. 4002 bool SCS1ConvertsToVoid 4003 = SCS1.isPointerConversionToVoidPointer(S.Context); 4004 bool SCS2ConvertsToVoid 4005 = SCS2.isPointerConversionToVoidPointer(S.Context); 4006 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4007 // Exactly one of the conversion sequences is a conversion to 4008 // a void pointer; it's the worse conversion. 4009 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4010 : ImplicitConversionSequence::Worse; 4011 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4012 // Neither conversion sequence converts to a void pointer; compare 4013 // their derived-to-base conversions. 4014 if (ImplicitConversionSequence::CompareKind DerivedCK 4015 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4016 return DerivedCK; 4017 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4018 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4019 // Both conversion sequences are conversions to void 4020 // pointers. Compare the source types to determine if there's an 4021 // inheritance relationship in their sources. 4022 QualType FromType1 = SCS1.getFromType(); 4023 QualType FromType2 = SCS2.getFromType(); 4024 4025 // Adjust the types we're converting from via the array-to-pointer 4026 // conversion, if we need to. 4027 if (SCS1.First == ICK_Array_To_Pointer) 4028 FromType1 = S.Context.getArrayDecayedType(FromType1); 4029 if (SCS2.First == ICK_Array_To_Pointer) 4030 FromType2 = S.Context.getArrayDecayedType(FromType2); 4031 4032 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4033 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4034 4035 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4036 return ImplicitConversionSequence::Better; 4037 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4038 return ImplicitConversionSequence::Worse; 4039 4040 // Objective-C++: If one interface is more specific than the 4041 // other, it is the better one. 4042 const ObjCObjectPointerType* FromObjCPtr1 4043 = FromType1->getAs<ObjCObjectPointerType>(); 4044 const ObjCObjectPointerType* FromObjCPtr2 4045 = FromType2->getAs<ObjCObjectPointerType>(); 4046 if (FromObjCPtr1 && FromObjCPtr2) { 4047 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4048 FromObjCPtr2); 4049 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4050 FromObjCPtr1); 4051 if (AssignLeft != AssignRight) { 4052 return AssignLeft? ImplicitConversionSequence::Better 4053 : ImplicitConversionSequence::Worse; 4054 } 4055 } 4056 } 4057 4058 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4059 // Check for a better reference binding based on the kind of bindings. 4060 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4061 return ImplicitConversionSequence::Better; 4062 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4063 return ImplicitConversionSequence::Worse; 4064 } 4065 4066 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4067 // bullet 3). 4068 if (ImplicitConversionSequence::CompareKind QualCK 4069 = CompareQualificationConversions(S, SCS1, SCS2)) 4070 return QualCK; 4071 4072 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4073 // C++ [over.ics.rank]p3b4: 4074 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4075 // which the references refer are the same type except for 4076 // top-level cv-qualifiers, and the type to which the reference 4077 // initialized by S2 refers is more cv-qualified than the type 4078 // to which the reference initialized by S1 refers. 4079 QualType T1 = SCS1.getToType(2); 4080 QualType T2 = SCS2.getToType(2); 4081 T1 = S.Context.getCanonicalType(T1); 4082 T2 = S.Context.getCanonicalType(T2); 4083 Qualifiers T1Quals, T2Quals; 4084 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4085 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4086 if (UnqualT1 == UnqualT2) { 4087 // Objective-C++ ARC: If the references refer to objects with different 4088 // lifetimes, prefer bindings that don't change lifetime. 4089 if (SCS1.ObjCLifetimeConversionBinding != 4090 SCS2.ObjCLifetimeConversionBinding) { 4091 return SCS1.ObjCLifetimeConversionBinding 4092 ? ImplicitConversionSequence::Worse 4093 : ImplicitConversionSequence::Better; 4094 } 4095 4096 // If the type is an array type, promote the element qualifiers to the 4097 // type for comparison. 4098 if (isa<ArrayType>(T1) && T1Quals) 4099 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4100 if (isa<ArrayType>(T2) && T2Quals) 4101 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4102 if (T2.isMoreQualifiedThan(T1)) 4103 return ImplicitConversionSequence::Better; 4104 if (T1.isMoreQualifiedThan(T2)) 4105 return ImplicitConversionSequence::Worse; 4106 } 4107 } 4108 4109 // In Microsoft mode, prefer an integral conversion to a 4110 // floating-to-integral conversion if the integral conversion 4111 // is between types of the same size. 4112 // For example: 4113 // void f(float); 4114 // void f(int); 4115 // int main { 4116 // long a; 4117 // f(a); 4118 // } 4119 // Here, MSVC will call f(int) instead of generating a compile error 4120 // as clang will do in standard mode. 4121 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4122 SCS2.Second == ICK_Floating_Integral && 4123 S.Context.getTypeSize(SCS1.getFromType()) == 4124 S.Context.getTypeSize(SCS1.getToType(2))) 4125 return ImplicitConversionSequence::Better; 4126 4127 // Prefer a compatible vector conversion over a lax vector conversion 4128 // For example: 4129 // 4130 // typedef float __v4sf __attribute__((__vector_size__(16))); 4131 // void f(vector float); 4132 // void f(vector signed int); 4133 // int main() { 4134 // __v4sf a; 4135 // f(a); 4136 // } 4137 // Here, we'd like to choose f(vector float) and not 4138 // report an ambiguous call error 4139 if (SCS1.Second == ICK_Vector_Conversion && 4140 SCS2.Second == ICK_Vector_Conversion) { 4141 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4142 SCS1.getFromType(), SCS1.getToType(2)); 4143 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4144 SCS2.getFromType(), SCS2.getToType(2)); 4145 4146 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4147 return SCS1IsCompatibleVectorConversion 4148 ? ImplicitConversionSequence::Better 4149 : ImplicitConversionSequence::Worse; 4150 } 4151 4152 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4153 SCS2.Second == ICK_SVE_Vector_Conversion) { 4154 bool SCS1IsCompatibleSVEVectorConversion = 4155 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4156 bool SCS2IsCompatibleSVEVectorConversion = 4157 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4158 4159 if (SCS1IsCompatibleSVEVectorConversion != 4160 SCS2IsCompatibleSVEVectorConversion) 4161 return SCS1IsCompatibleSVEVectorConversion 4162 ? ImplicitConversionSequence::Better 4163 : ImplicitConversionSequence::Worse; 4164 } 4165 4166 return ImplicitConversionSequence::Indistinguishable; 4167 } 4168 4169 /// CompareQualificationConversions - Compares two standard conversion 4170 /// sequences to determine whether they can be ranked based on their 4171 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4172 static ImplicitConversionSequence::CompareKind 4173 CompareQualificationConversions(Sema &S, 4174 const StandardConversionSequence& SCS1, 4175 const StandardConversionSequence& SCS2) { 4176 // C++ 13.3.3.2p3: 4177 // -- S1 and S2 differ only in their qualification conversion and 4178 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4179 // cv-qualification signature of type T1 is a proper subset of 4180 // the cv-qualification signature of type T2, and S1 is not the 4181 // deprecated string literal array-to-pointer conversion (4.2). 4182 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4183 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4184 return ImplicitConversionSequence::Indistinguishable; 4185 4186 // FIXME: the example in the standard doesn't use a qualification 4187 // conversion (!) 4188 QualType T1 = SCS1.getToType(2); 4189 QualType T2 = SCS2.getToType(2); 4190 T1 = S.Context.getCanonicalType(T1); 4191 T2 = S.Context.getCanonicalType(T2); 4192 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4193 Qualifiers T1Quals, T2Quals; 4194 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4195 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4196 4197 // If the types are the same, we won't learn anything by unwrapping 4198 // them. 4199 if (UnqualT1 == UnqualT2) 4200 return ImplicitConversionSequence::Indistinguishable; 4201 4202 ImplicitConversionSequence::CompareKind Result 4203 = ImplicitConversionSequence::Indistinguishable; 4204 4205 // Objective-C++ ARC: 4206 // Prefer qualification conversions not involving a change in lifetime 4207 // to qualification conversions that do not change lifetime. 4208 if (SCS1.QualificationIncludesObjCLifetime != 4209 SCS2.QualificationIncludesObjCLifetime) { 4210 Result = SCS1.QualificationIncludesObjCLifetime 4211 ? ImplicitConversionSequence::Worse 4212 : ImplicitConversionSequence::Better; 4213 } 4214 4215 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4216 // Within each iteration of the loop, we check the qualifiers to 4217 // determine if this still looks like a qualification 4218 // conversion. Then, if all is well, we unwrap one more level of 4219 // pointers or pointers-to-members and do it all again 4220 // until there are no more pointers or pointers-to-members left 4221 // to unwrap. This essentially mimics what 4222 // IsQualificationConversion does, but here we're checking for a 4223 // strict subset of qualifiers. 4224 if (T1.getQualifiers().withoutObjCLifetime() == 4225 T2.getQualifiers().withoutObjCLifetime()) 4226 // The qualifiers are the same, so this doesn't tell us anything 4227 // about how the sequences rank. 4228 // ObjC ownership quals are omitted above as they interfere with 4229 // the ARC overload rule. 4230 ; 4231 else if (T2.isMoreQualifiedThan(T1)) { 4232 // T1 has fewer qualifiers, so it could be the better sequence. 4233 if (Result == ImplicitConversionSequence::Worse) 4234 // Neither has qualifiers that are a subset of the other's 4235 // qualifiers. 4236 return ImplicitConversionSequence::Indistinguishable; 4237 4238 Result = ImplicitConversionSequence::Better; 4239 } else if (T1.isMoreQualifiedThan(T2)) { 4240 // T2 has fewer qualifiers, so it could be the better sequence. 4241 if (Result == ImplicitConversionSequence::Better) 4242 // Neither has qualifiers that are a subset of the other's 4243 // qualifiers. 4244 return ImplicitConversionSequence::Indistinguishable; 4245 4246 Result = ImplicitConversionSequence::Worse; 4247 } else { 4248 // Qualifiers are disjoint. 4249 return ImplicitConversionSequence::Indistinguishable; 4250 } 4251 4252 // If the types after this point are equivalent, we're done. 4253 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4254 break; 4255 } 4256 4257 // Check that the winning standard conversion sequence isn't using 4258 // the deprecated string literal array to pointer conversion. 4259 switch (Result) { 4260 case ImplicitConversionSequence::Better: 4261 if (SCS1.DeprecatedStringLiteralToCharPtr) 4262 Result = ImplicitConversionSequence::Indistinguishable; 4263 break; 4264 4265 case ImplicitConversionSequence::Indistinguishable: 4266 break; 4267 4268 case ImplicitConversionSequence::Worse: 4269 if (SCS2.DeprecatedStringLiteralToCharPtr) 4270 Result = ImplicitConversionSequence::Indistinguishable; 4271 break; 4272 } 4273 4274 return Result; 4275 } 4276 4277 /// CompareDerivedToBaseConversions - Compares two standard conversion 4278 /// sequences to determine whether they can be ranked based on their 4279 /// various kinds of derived-to-base conversions (C++ 4280 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4281 /// conversions between Objective-C interface types. 4282 static ImplicitConversionSequence::CompareKind 4283 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4284 const StandardConversionSequence& SCS1, 4285 const StandardConversionSequence& SCS2) { 4286 QualType FromType1 = SCS1.getFromType(); 4287 QualType ToType1 = SCS1.getToType(1); 4288 QualType FromType2 = SCS2.getFromType(); 4289 QualType ToType2 = SCS2.getToType(1); 4290 4291 // Adjust the types we're converting from via the array-to-pointer 4292 // conversion, if we need to. 4293 if (SCS1.First == ICK_Array_To_Pointer) 4294 FromType1 = S.Context.getArrayDecayedType(FromType1); 4295 if (SCS2.First == ICK_Array_To_Pointer) 4296 FromType2 = S.Context.getArrayDecayedType(FromType2); 4297 4298 // Canonicalize all of the types. 4299 FromType1 = S.Context.getCanonicalType(FromType1); 4300 ToType1 = S.Context.getCanonicalType(ToType1); 4301 FromType2 = S.Context.getCanonicalType(FromType2); 4302 ToType2 = S.Context.getCanonicalType(ToType2); 4303 4304 // C++ [over.ics.rank]p4b3: 4305 // 4306 // If class B is derived directly or indirectly from class A and 4307 // class C is derived directly or indirectly from B, 4308 // 4309 // Compare based on pointer conversions. 4310 if (SCS1.Second == ICK_Pointer_Conversion && 4311 SCS2.Second == ICK_Pointer_Conversion && 4312 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4313 FromType1->isPointerType() && FromType2->isPointerType() && 4314 ToType1->isPointerType() && ToType2->isPointerType()) { 4315 QualType FromPointee1 = 4316 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4317 QualType ToPointee1 = 4318 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4319 QualType FromPointee2 = 4320 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4321 QualType ToPointee2 = 4322 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4323 4324 // -- conversion of C* to B* is better than conversion of C* to A*, 4325 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4326 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4327 return ImplicitConversionSequence::Better; 4328 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4329 return ImplicitConversionSequence::Worse; 4330 } 4331 4332 // -- conversion of B* to A* is better than conversion of C* to A*, 4333 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4334 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4335 return ImplicitConversionSequence::Better; 4336 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4337 return ImplicitConversionSequence::Worse; 4338 } 4339 } else if (SCS1.Second == ICK_Pointer_Conversion && 4340 SCS2.Second == ICK_Pointer_Conversion) { 4341 const ObjCObjectPointerType *FromPtr1 4342 = FromType1->getAs<ObjCObjectPointerType>(); 4343 const ObjCObjectPointerType *FromPtr2 4344 = FromType2->getAs<ObjCObjectPointerType>(); 4345 const ObjCObjectPointerType *ToPtr1 4346 = ToType1->getAs<ObjCObjectPointerType>(); 4347 const ObjCObjectPointerType *ToPtr2 4348 = ToType2->getAs<ObjCObjectPointerType>(); 4349 4350 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4351 // Apply the same conversion ranking rules for Objective-C pointer types 4352 // that we do for C++ pointers to class types. However, we employ the 4353 // Objective-C pseudo-subtyping relationship used for assignment of 4354 // Objective-C pointer types. 4355 bool FromAssignLeft 4356 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4357 bool FromAssignRight 4358 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4359 bool ToAssignLeft 4360 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4361 bool ToAssignRight 4362 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4363 4364 // A conversion to an a non-id object pointer type or qualified 'id' 4365 // type is better than a conversion to 'id'. 4366 if (ToPtr1->isObjCIdType() && 4367 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4368 return ImplicitConversionSequence::Worse; 4369 if (ToPtr2->isObjCIdType() && 4370 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4371 return ImplicitConversionSequence::Better; 4372 4373 // A conversion to a non-id object pointer type is better than a 4374 // conversion to a qualified 'id' type 4375 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4376 return ImplicitConversionSequence::Worse; 4377 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4378 return ImplicitConversionSequence::Better; 4379 4380 // A conversion to an a non-Class object pointer type or qualified 'Class' 4381 // type is better than a conversion to 'Class'. 4382 if (ToPtr1->isObjCClassType() && 4383 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4384 return ImplicitConversionSequence::Worse; 4385 if (ToPtr2->isObjCClassType() && 4386 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4387 return ImplicitConversionSequence::Better; 4388 4389 // A conversion to a non-Class object pointer type is better than a 4390 // conversion to a qualified 'Class' type. 4391 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4392 return ImplicitConversionSequence::Worse; 4393 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4394 return ImplicitConversionSequence::Better; 4395 4396 // -- "conversion of C* to B* is better than conversion of C* to A*," 4397 if (S.Context.hasSameType(FromType1, FromType2) && 4398 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4399 (ToAssignLeft != ToAssignRight)) { 4400 if (FromPtr1->isSpecialized()) { 4401 // "conversion of B<A> * to B * is better than conversion of B * to 4402 // C *. 4403 bool IsFirstSame = 4404 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4405 bool IsSecondSame = 4406 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4407 if (IsFirstSame) { 4408 if (!IsSecondSame) 4409 return ImplicitConversionSequence::Better; 4410 } else if (IsSecondSame) 4411 return ImplicitConversionSequence::Worse; 4412 } 4413 return ToAssignLeft? ImplicitConversionSequence::Worse 4414 : ImplicitConversionSequence::Better; 4415 } 4416 4417 // -- "conversion of B* to A* is better than conversion of C* to A*," 4418 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4419 (FromAssignLeft != FromAssignRight)) 4420 return FromAssignLeft? ImplicitConversionSequence::Better 4421 : ImplicitConversionSequence::Worse; 4422 } 4423 } 4424 4425 // Ranking of member-pointer types. 4426 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4427 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4428 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4429 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4430 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4431 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4432 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4433 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4434 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4435 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4436 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4437 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4438 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4439 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4440 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4441 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4442 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4443 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4444 return ImplicitConversionSequence::Worse; 4445 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4446 return ImplicitConversionSequence::Better; 4447 } 4448 // conversion of B::* to C::* is better than conversion of A::* to C::* 4449 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4450 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4451 return ImplicitConversionSequence::Better; 4452 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4453 return ImplicitConversionSequence::Worse; 4454 } 4455 } 4456 4457 if (SCS1.Second == ICK_Derived_To_Base) { 4458 // -- conversion of C to B is better than conversion of C to A, 4459 // -- binding of an expression of type C to a reference of type 4460 // B& is better than binding an expression of type C to a 4461 // reference of type A&, 4462 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4463 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4464 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4465 return ImplicitConversionSequence::Better; 4466 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4467 return ImplicitConversionSequence::Worse; 4468 } 4469 4470 // -- conversion of B to A is better than conversion of C to A. 4471 // -- binding of an expression of type B to a reference of type 4472 // A& is better than binding an expression of type C to a 4473 // reference of type A&, 4474 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4475 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4476 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4477 return ImplicitConversionSequence::Better; 4478 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4479 return ImplicitConversionSequence::Worse; 4480 } 4481 } 4482 4483 return ImplicitConversionSequence::Indistinguishable; 4484 } 4485 4486 /// Determine whether the given type is valid, e.g., it is not an invalid 4487 /// C++ class. 4488 static bool isTypeValid(QualType T) { 4489 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4490 return !Record->isInvalidDecl(); 4491 4492 return true; 4493 } 4494 4495 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4496 if (!T.getQualifiers().hasUnaligned()) 4497 return T; 4498 4499 Qualifiers Q; 4500 T = Ctx.getUnqualifiedArrayType(T, Q); 4501 Q.removeUnaligned(); 4502 return Ctx.getQualifiedType(T, Q); 4503 } 4504 4505 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4506 /// determine whether they are reference-compatible, 4507 /// reference-related, or incompatible, for use in C++ initialization by 4508 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4509 /// type, and the first type (T1) is the pointee type of the reference 4510 /// type being initialized. 4511 Sema::ReferenceCompareResult 4512 Sema::CompareReferenceRelationship(SourceLocation Loc, 4513 QualType OrigT1, QualType OrigT2, 4514 ReferenceConversions *ConvOut) { 4515 assert(!OrigT1->isReferenceType() && 4516 "T1 must be the pointee type of the reference type"); 4517 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4518 4519 QualType T1 = Context.getCanonicalType(OrigT1); 4520 QualType T2 = Context.getCanonicalType(OrigT2); 4521 Qualifiers T1Quals, T2Quals; 4522 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4523 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4524 4525 ReferenceConversions ConvTmp; 4526 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4527 Conv = ReferenceConversions(); 4528 4529 // C++2a [dcl.init.ref]p4: 4530 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4531 // reference-related to "cv2 T2" if T1 is similar to T2, or 4532 // T1 is a base class of T2. 4533 // "cv1 T1" is reference-compatible with "cv2 T2" if 4534 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4535 // "pointer to cv1 T1" via a standard conversion sequence. 4536 4537 // Check for standard conversions we can apply to pointers: derived-to-base 4538 // conversions, ObjC pointer conversions, and function pointer conversions. 4539 // (Qualification conversions are checked last.) 4540 QualType ConvertedT2; 4541 if (UnqualT1 == UnqualT2) { 4542 // Nothing to do. 4543 } else if (isCompleteType(Loc, OrigT2) && 4544 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4545 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4546 Conv |= ReferenceConversions::DerivedToBase; 4547 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4548 UnqualT2->isObjCObjectOrInterfaceType() && 4549 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4550 Conv |= ReferenceConversions::ObjC; 4551 else if (UnqualT2->isFunctionType() && 4552 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4553 Conv |= ReferenceConversions::Function; 4554 // No need to check qualifiers; function types don't have them. 4555 return Ref_Compatible; 4556 } 4557 bool ConvertedReferent = Conv != 0; 4558 4559 // We can have a qualification conversion. Compute whether the types are 4560 // similar at the same time. 4561 bool PreviousToQualsIncludeConst = true; 4562 bool TopLevel = true; 4563 do { 4564 if (T1 == T2) 4565 break; 4566 4567 // We will need a qualification conversion. 4568 Conv |= ReferenceConversions::Qualification; 4569 4570 // Track whether we performed a qualification conversion anywhere other 4571 // than the top level. This matters for ranking reference bindings in 4572 // overload resolution. 4573 if (!TopLevel) 4574 Conv |= ReferenceConversions::NestedQualification; 4575 4576 // MS compiler ignores __unaligned qualifier for references; do the same. 4577 T1 = withoutUnaligned(Context, T1); 4578 T2 = withoutUnaligned(Context, T2); 4579 4580 // If we find a qualifier mismatch, the types are not reference-compatible, 4581 // but are still be reference-related if they're similar. 4582 bool ObjCLifetimeConversion = false; 4583 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4584 PreviousToQualsIncludeConst, 4585 ObjCLifetimeConversion)) 4586 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4587 ? Ref_Related 4588 : Ref_Incompatible; 4589 4590 // FIXME: Should we track this for any level other than the first? 4591 if (ObjCLifetimeConversion) 4592 Conv |= ReferenceConversions::ObjCLifetime; 4593 4594 TopLevel = false; 4595 } while (Context.UnwrapSimilarTypes(T1, T2)); 4596 4597 // At this point, if the types are reference-related, we must either have the 4598 // same inner type (ignoring qualifiers), or must have already worked out how 4599 // to convert the referent. 4600 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4601 ? Ref_Compatible 4602 : Ref_Incompatible; 4603 } 4604 4605 /// Look for a user-defined conversion to a value reference-compatible 4606 /// with DeclType. Return true if something definite is found. 4607 static bool 4608 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4609 QualType DeclType, SourceLocation DeclLoc, 4610 Expr *Init, QualType T2, bool AllowRvalues, 4611 bool AllowExplicit) { 4612 assert(T2->isRecordType() && "Can only find conversions of record types."); 4613 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4614 4615 OverloadCandidateSet CandidateSet( 4616 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4617 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4618 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4619 NamedDecl *D = *I; 4620 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4621 if (isa<UsingShadowDecl>(D)) 4622 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4623 4624 FunctionTemplateDecl *ConvTemplate 4625 = dyn_cast<FunctionTemplateDecl>(D); 4626 CXXConversionDecl *Conv; 4627 if (ConvTemplate) 4628 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4629 else 4630 Conv = cast<CXXConversionDecl>(D); 4631 4632 if (AllowRvalues) { 4633 // If we are initializing an rvalue reference, don't permit conversion 4634 // functions that return lvalues. 4635 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4636 const ReferenceType *RefType 4637 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4638 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4639 continue; 4640 } 4641 4642 if (!ConvTemplate && 4643 S.CompareReferenceRelationship( 4644 DeclLoc, 4645 Conv->getConversionType() 4646 .getNonReferenceType() 4647 .getUnqualifiedType(), 4648 DeclType.getNonReferenceType().getUnqualifiedType()) == 4649 Sema::Ref_Incompatible) 4650 continue; 4651 } else { 4652 // If the conversion function doesn't return a reference type, 4653 // it can't be considered for this conversion. An rvalue reference 4654 // is only acceptable if its referencee is a function type. 4655 4656 const ReferenceType *RefType = 4657 Conv->getConversionType()->getAs<ReferenceType>(); 4658 if (!RefType || 4659 (!RefType->isLValueReferenceType() && 4660 !RefType->getPointeeType()->isFunctionType())) 4661 continue; 4662 } 4663 4664 if (ConvTemplate) 4665 S.AddTemplateConversionCandidate( 4666 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4667 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4668 else 4669 S.AddConversionCandidate( 4670 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4671 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4672 } 4673 4674 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4675 4676 OverloadCandidateSet::iterator Best; 4677 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4678 case OR_Success: 4679 // C++ [over.ics.ref]p1: 4680 // 4681 // [...] If the parameter binds directly to the result of 4682 // applying a conversion function to the argument 4683 // expression, the implicit conversion sequence is a 4684 // user-defined conversion sequence (13.3.3.1.2), with the 4685 // second standard conversion sequence either an identity 4686 // conversion or, if the conversion function returns an 4687 // entity of a type that is a derived class of the parameter 4688 // type, a derived-to-base Conversion. 4689 if (!Best->FinalConversion.DirectBinding) 4690 return false; 4691 4692 ICS.setUserDefined(); 4693 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4694 ICS.UserDefined.After = Best->FinalConversion; 4695 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4696 ICS.UserDefined.ConversionFunction = Best->Function; 4697 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4698 ICS.UserDefined.EllipsisConversion = false; 4699 assert(ICS.UserDefined.After.ReferenceBinding && 4700 ICS.UserDefined.After.DirectBinding && 4701 "Expected a direct reference binding!"); 4702 return true; 4703 4704 case OR_Ambiguous: 4705 ICS.setAmbiguous(); 4706 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4707 Cand != CandidateSet.end(); ++Cand) 4708 if (Cand->Best) 4709 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4710 return true; 4711 4712 case OR_No_Viable_Function: 4713 case OR_Deleted: 4714 // There was no suitable conversion, or we found a deleted 4715 // conversion; continue with other checks. 4716 return false; 4717 } 4718 4719 llvm_unreachable("Invalid OverloadResult!"); 4720 } 4721 4722 /// Compute an implicit conversion sequence for reference 4723 /// initialization. 4724 static ImplicitConversionSequence 4725 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4726 SourceLocation DeclLoc, 4727 bool SuppressUserConversions, 4728 bool AllowExplicit) { 4729 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4730 4731 // Most paths end in a failed conversion. 4732 ImplicitConversionSequence ICS; 4733 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4734 4735 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4736 QualType T2 = Init->getType(); 4737 4738 // If the initializer is the address of an overloaded function, try 4739 // to resolve the overloaded function. If all goes well, T2 is the 4740 // type of the resulting function. 4741 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4742 DeclAccessPair Found; 4743 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4744 false, Found)) 4745 T2 = Fn->getType(); 4746 } 4747 4748 // Compute some basic properties of the types and the initializer. 4749 bool isRValRef = DeclType->isRValueReferenceType(); 4750 Expr::Classification InitCategory = Init->Classify(S.Context); 4751 4752 Sema::ReferenceConversions RefConv; 4753 Sema::ReferenceCompareResult RefRelationship = 4754 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4755 4756 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4757 ICS.setStandard(); 4758 ICS.Standard.First = ICK_Identity; 4759 // FIXME: A reference binding can be a function conversion too. We should 4760 // consider that when ordering reference-to-function bindings. 4761 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4762 ? ICK_Derived_To_Base 4763 : (RefConv & Sema::ReferenceConversions::ObjC) 4764 ? ICK_Compatible_Conversion 4765 : ICK_Identity; 4766 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4767 // a reference binding that performs a non-top-level qualification 4768 // conversion as a qualification conversion, not as an identity conversion. 4769 ICS.Standard.Third = (RefConv & 4770 Sema::ReferenceConversions::NestedQualification) 4771 ? ICK_Qualification 4772 : ICK_Identity; 4773 ICS.Standard.setFromType(T2); 4774 ICS.Standard.setToType(0, T2); 4775 ICS.Standard.setToType(1, T1); 4776 ICS.Standard.setToType(2, T1); 4777 ICS.Standard.ReferenceBinding = true; 4778 ICS.Standard.DirectBinding = BindsDirectly; 4779 ICS.Standard.IsLvalueReference = !isRValRef; 4780 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4781 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4782 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4783 ICS.Standard.ObjCLifetimeConversionBinding = 4784 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4785 ICS.Standard.CopyConstructor = nullptr; 4786 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4787 }; 4788 4789 // C++0x [dcl.init.ref]p5: 4790 // A reference to type "cv1 T1" is initialized by an expression 4791 // of type "cv2 T2" as follows: 4792 4793 // -- If reference is an lvalue reference and the initializer expression 4794 if (!isRValRef) { 4795 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4796 // reference-compatible with "cv2 T2," or 4797 // 4798 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4799 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4800 // C++ [over.ics.ref]p1: 4801 // When a parameter of reference type binds directly (8.5.3) 4802 // to an argument expression, the implicit conversion sequence 4803 // is the identity conversion, unless the argument expression 4804 // has a type that is a derived class of the parameter type, 4805 // in which case the implicit conversion sequence is a 4806 // derived-to-base Conversion (13.3.3.1). 4807 SetAsReferenceBinding(/*BindsDirectly=*/true); 4808 4809 // Nothing more to do: the inaccessibility/ambiguity check for 4810 // derived-to-base conversions is suppressed when we're 4811 // computing the implicit conversion sequence (C++ 4812 // [over.best.ics]p2). 4813 return ICS; 4814 } 4815 4816 // -- has a class type (i.e., T2 is a class type), where T1 is 4817 // not reference-related to T2, and can be implicitly 4818 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4819 // is reference-compatible with "cv3 T3" 92) (this 4820 // conversion is selected by enumerating the applicable 4821 // conversion functions (13.3.1.6) and choosing the best 4822 // one through overload resolution (13.3)), 4823 if (!SuppressUserConversions && T2->isRecordType() && 4824 S.isCompleteType(DeclLoc, T2) && 4825 RefRelationship == Sema::Ref_Incompatible) { 4826 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4827 Init, T2, /*AllowRvalues=*/false, 4828 AllowExplicit)) 4829 return ICS; 4830 } 4831 } 4832 4833 // -- Otherwise, the reference shall be an lvalue reference to a 4834 // non-volatile const type (i.e., cv1 shall be const), or the reference 4835 // shall be an rvalue reference. 4836 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4837 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4838 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4839 return ICS; 4840 } 4841 4842 // -- If the initializer expression 4843 // 4844 // -- is an xvalue, class prvalue, array prvalue or function 4845 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4846 if (RefRelationship == Sema::Ref_Compatible && 4847 (InitCategory.isXValue() || 4848 (InitCategory.isPRValue() && 4849 (T2->isRecordType() || T2->isArrayType())) || 4850 (InitCategory.isLValue() && T2->isFunctionType()))) { 4851 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4852 // binding unless we're binding to a class prvalue. 4853 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4854 // allow the use of rvalue references in C++98/03 for the benefit of 4855 // standard library implementors; therefore, we need the xvalue check here. 4856 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4857 !(InitCategory.isPRValue() || T2->isRecordType())); 4858 return ICS; 4859 } 4860 4861 // -- has a class type (i.e., T2 is a class type), where T1 is not 4862 // reference-related to T2, and can be implicitly converted to 4863 // an xvalue, class prvalue, or function lvalue of type 4864 // "cv3 T3", where "cv1 T1" is reference-compatible with 4865 // "cv3 T3", 4866 // 4867 // then the reference is bound to the value of the initializer 4868 // expression in the first case and to the result of the conversion 4869 // in the second case (or, in either case, to an appropriate base 4870 // class subobject). 4871 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4872 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4873 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4874 Init, T2, /*AllowRvalues=*/true, 4875 AllowExplicit)) { 4876 // In the second case, if the reference is an rvalue reference 4877 // and the second standard conversion sequence of the 4878 // user-defined conversion sequence includes an lvalue-to-rvalue 4879 // conversion, the program is ill-formed. 4880 if (ICS.isUserDefined() && isRValRef && 4881 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4882 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4883 4884 return ICS; 4885 } 4886 4887 // A temporary of function type cannot be created; don't even try. 4888 if (T1->isFunctionType()) 4889 return ICS; 4890 4891 // -- Otherwise, a temporary of type "cv1 T1" is created and 4892 // initialized from the initializer expression using the 4893 // rules for a non-reference copy initialization (8.5). The 4894 // reference is then bound to the temporary. If T1 is 4895 // reference-related to T2, cv1 must be the same 4896 // cv-qualification as, or greater cv-qualification than, 4897 // cv2; otherwise, the program is ill-formed. 4898 if (RefRelationship == Sema::Ref_Related) { 4899 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4900 // we would be reference-compatible or reference-compatible with 4901 // added qualification. But that wasn't the case, so the reference 4902 // initialization fails. 4903 // 4904 // Note that we only want to check address spaces and cvr-qualifiers here. 4905 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4906 Qualifiers T1Quals = T1.getQualifiers(); 4907 Qualifiers T2Quals = T2.getQualifiers(); 4908 T1Quals.removeObjCGCAttr(); 4909 T1Quals.removeObjCLifetime(); 4910 T2Quals.removeObjCGCAttr(); 4911 T2Quals.removeObjCLifetime(); 4912 // MS compiler ignores __unaligned qualifier for references; do the same. 4913 T1Quals.removeUnaligned(); 4914 T2Quals.removeUnaligned(); 4915 if (!T1Quals.compatiblyIncludes(T2Quals)) 4916 return ICS; 4917 } 4918 4919 // If at least one of the types is a class type, the types are not 4920 // related, and we aren't allowed any user conversions, the 4921 // reference binding fails. This case is important for breaking 4922 // recursion, since TryImplicitConversion below will attempt to 4923 // create a temporary through the use of a copy constructor. 4924 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4925 (T1->isRecordType() || T2->isRecordType())) 4926 return ICS; 4927 4928 // If T1 is reference-related to T2 and the reference is an rvalue 4929 // reference, the initializer expression shall not be an lvalue. 4930 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4931 Init->Classify(S.Context).isLValue()) { 4932 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4933 return ICS; 4934 } 4935 4936 // C++ [over.ics.ref]p2: 4937 // When a parameter of reference type is not bound directly to 4938 // an argument expression, the conversion sequence is the one 4939 // required to convert the argument expression to the 4940 // underlying type of the reference according to 4941 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4942 // to copy-initializing a temporary of the underlying type with 4943 // the argument expression. Any difference in top-level 4944 // cv-qualification is subsumed by the initialization itself 4945 // and does not constitute a conversion. 4946 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4947 AllowedExplicit::None, 4948 /*InOverloadResolution=*/false, 4949 /*CStyle=*/false, 4950 /*AllowObjCWritebackConversion=*/false, 4951 /*AllowObjCConversionOnExplicit=*/false); 4952 4953 // Of course, that's still a reference binding. 4954 if (ICS.isStandard()) { 4955 ICS.Standard.ReferenceBinding = true; 4956 ICS.Standard.IsLvalueReference = !isRValRef; 4957 ICS.Standard.BindsToFunctionLvalue = false; 4958 ICS.Standard.BindsToRvalue = true; 4959 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4960 ICS.Standard.ObjCLifetimeConversionBinding = false; 4961 } else if (ICS.isUserDefined()) { 4962 const ReferenceType *LValRefType = 4963 ICS.UserDefined.ConversionFunction->getReturnType() 4964 ->getAs<LValueReferenceType>(); 4965 4966 // C++ [over.ics.ref]p3: 4967 // Except for an implicit object parameter, for which see 13.3.1, a 4968 // standard conversion sequence cannot be formed if it requires [...] 4969 // binding an rvalue reference to an lvalue other than a function 4970 // lvalue. 4971 // Note that the function case is not possible here. 4972 if (isRValRef && LValRefType) { 4973 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4974 return ICS; 4975 } 4976 4977 ICS.UserDefined.After.ReferenceBinding = true; 4978 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4979 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4980 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4981 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4982 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4983 } 4984 4985 return ICS; 4986 } 4987 4988 static ImplicitConversionSequence 4989 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4990 bool SuppressUserConversions, 4991 bool InOverloadResolution, 4992 bool AllowObjCWritebackConversion, 4993 bool AllowExplicit = false); 4994 4995 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4996 /// initializer list From. 4997 static ImplicitConversionSequence 4998 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4999 bool SuppressUserConversions, 5000 bool InOverloadResolution, 5001 bool AllowObjCWritebackConversion) { 5002 // C++11 [over.ics.list]p1: 5003 // When an argument is an initializer list, it is not an expression and 5004 // special rules apply for converting it to a parameter type. 5005 5006 ImplicitConversionSequence Result; 5007 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5008 5009 // We need a complete type for what follows. Incomplete types can never be 5010 // initialized from init lists. 5011 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 5012 return Result; 5013 5014 // Per DR1467: 5015 // If the parameter type is a class X and the initializer list has a single 5016 // element of type cv U, where U is X or a class derived from X, the 5017 // implicit conversion sequence is the one required to convert the element 5018 // to the parameter type. 5019 // 5020 // Otherwise, if the parameter type is a character array [... ] 5021 // and the initializer list has a single element that is an 5022 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5023 // implicit conversion sequence is the identity conversion. 5024 if (From->getNumInits() == 1) { 5025 if (ToType->isRecordType()) { 5026 QualType InitType = From->getInit(0)->getType(); 5027 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5028 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5029 return TryCopyInitialization(S, From->getInit(0), ToType, 5030 SuppressUserConversions, 5031 InOverloadResolution, 5032 AllowObjCWritebackConversion); 5033 } 5034 5035 if (const auto *AT = S.Context.getAsArrayType(ToType)) { 5036 if (S.IsStringInit(From->getInit(0), AT)) { 5037 InitializedEntity Entity = 5038 InitializedEntity::InitializeParameter(S.Context, ToType, 5039 /*Consumed=*/false); 5040 if (S.CanPerformCopyInitialization(Entity, From)) { 5041 Result.setStandard(); 5042 Result.Standard.setAsIdentityConversion(); 5043 Result.Standard.setFromType(ToType); 5044 Result.Standard.setAllToTypes(ToType); 5045 return Result; 5046 } 5047 } 5048 } 5049 } 5050 5051 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5052 // C++11 [over.ics.list]p2: 5053 // If the parameter type is std::initializer_list<X> or "array of X" and 5054 // all the elements can be implicitly converted to X, the implicit 5055 // conversion sequence is the worst conversion necessary to convert an 5056 // element of the list to X. 5057 // 5058 // C++14 [over.ics.list]p3: 5059 // Otherwise, if the parameter type is "array of N X", if the initializer 5060 // list has exactly N elements or if it has fewer than N elements and X is 5061 // default-constructible, and if all the elements of the initializer list 5062 // can be implicitly converted to X, the implicit conversion sequence is 5063 // the worst conversion necessary to convert an element of the list to X. 5064 // 5065 // FIXME: We're missing a lot of these checks. 5066 bool toStdInitializerList = false; 5067 QualType X; 5068 if (ToType->isArrayType()) 5069 X = S.Context.getAsArrayType(ToType)->getElementType(); 5070 else 5071 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5072 if (!X.isNull()) { 5073 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5074 Expr *Init = From->getInit(i); 5075 ImplicitConversionSequence ICS = 5076 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5077 InOverloadResolution, 5078 AllowObjCWritebackConversion); 5079 // If a single element isn't convertible, fail. 5080 if (ICS.isBad()) { 5081 Result = ICS; 5082 break; 5083 } 5084 // Otherwise, look for the worst conversion. 5085 if (Result.isBad() || CompareImplicitConversionSequences( 5086 S, From->getBeginLoc(), ICS, Result) == 5087 ImplicitConversionSequence::Worse) 5088 Result = ICS; 5089 } 5090 5091 // For an empty list, we won't have computed any conversion sequence. 5092 // Introduce the identity conversion sequence. 5093 if (From->getNumInits() == 0) { 5094 Result.setStandard(); 5095 Result.Standard.setAsIdentityConversion(); 5096 Result.Standard.setFromType(ToType); 5097 Result.Standard.setAllToTypes(ToType); 5098 } 5099 5100 Result.setStdInitializerListElement(toStdInitializerList); 5101 return Result; 5102 } 5103 5104 // C++14 [over.ics.list]p4: 5105 // C++11 [over.ics.list]p3: 5106 // Otherwise, if the parameter is a non-aggregate class X and overload 5107 // resolution chooses a single best constructor [...] the implicit 5108 // conversion sequence is a user-defined conversion sequence. If multiple 5109 // constructors are viable but none is better than the others, the 5110 // implicit conversion sequence is a user-defined conversion sequence. 5111 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5112 // This function can deal with initializer lists. 5113 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5114 AllowedExplicit::None, 5115 InOverloadResolution, /*CStyle=*/false, 5116 AllowObjCWritebackConversion, 5117 /*AllowObjCConversionOnExplicit=*/false); 5118 } 5119 5120 // C++14 [over.ics.list]p5: 5121 // C++11 [over.ics.list]p4: 5122 // Otherwise, if the parameter has an aggregate type which can be 5123 // initialized from the initializer list [...] the implicit conversion 5124 // sequence is a user-defined conversion sequence. 5125 if (ToType->isAggregateType()) { 5126 // Type is an aggregate, argument is an init list. At this point it comes 5127 // down to checking whether the initialization works. 5128 // FIXME: Find out whether this parameter is consumed or not. 5129 InitializedEntity Entity = 5130 InitializedEntity::InitializeParameter(S.Context, ToType, 5131 /*Consumed=*/false); 5132 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5133 From)) { 5134 Result.setUserDefined(); 5135 Result.UserDefined.Before.setAsIdentityConversion(); 5136 // Initializer lists don't have a type. 5137 Result.UserDefined.Before.setFromType(QualType()); 5138 Result.UserDefined.Before.setAllToTypes(QualType()); 5139 5140 Result.UserDefined.After.setAsIdentityConversion(); 5141 Result.UserDefined.After.setFromType(ToType); 5142 Result.UserDefined.After.setAllToTypes(ToType); 5143 Result.UserDefined.ConversionFunction = nullptr; 5144 } 5145 return Result; 5146 } 5147 5148 // C++14 [over.ics.list]p6: 5149 // C++11 [over.ics.list]p5: 5150 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5151 if (ToType->isReferenceType()) { 5152 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5153 // mention initializer lists in any way. So we go by what list- 5154 // initialization would do and try to extrapolate from that. 5155 5156 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5157 5158 // If the initializer list has a single element that is reference-related 5159 // to the parameter type, we initialize the reference from that. 5160 if (From->getNumInits() == 1) { 5161 Expr *Init = From->getInit(0); 5162 5163 QualType T2 = Init->getType(); 5164 5165 // If the initializer is the address of an overloaded function, try 5166 // to resolve the overloaded function. If all goes well, T2 is the 5167 // type of the resulting function. 5168 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5169 DeclAccessPair Found; 5170 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5171 Init, ToType, false, Found)) 5172 T2 = Fn->getType(); 5173 } 5174 5175 // Compute some basic properties of the types and the initializer. 5176 Sema::ReferenceCompareResult RefRelationship = 5177 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5178 5179 if (RefRelationship >= Sema::Ref_Related) { 5180 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5181 SuppressUserConversions, 5182 /*AllowExplicit=*/false); 5183 } 5184 } 5185 5186 // Otherwise, we bind the reference to a temporary created from the 5187 // initializer list. 5188 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5189 InOverloadResolution, 5190 AllowObjCWritebackConversion); 5191 if (Result.isFailure()) 5192 return Result; 5193 assert(!Result.isEllipsis() && 5194 "Sub-initialization cannot result in ellipsis conversion."); 5195 5196 // Can we even bind to a temporary? 5197 if (ToType->isRValueReferenceType() || 5198 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5199 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5200 Result.UserDefined.After; 5201 SCS.ReferenceBinding = true; 5202 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5203 SCS.BindsToRvalue = true; 5204 SCS.BindsToFunctionLvalue = false; 5205 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5206 SCS.ObjCLifetimeConversionBinding = false; 5207 } else 5208 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5209 From, ToType); 5210 return Result; 5211 } 5212 5213 // C++14 [over.ics.list]p7: 5214 // C++11 [over.ics.list]p6: 5215 // Otherwise, if the parameter type is not a class: 5216 if (!ToType->isRecordType()) { 5217 // - if the initializer list has one element that is not itself an 5218 // initializer list, the implicit conversion sequence is the one 5219 // required to convert the element to the parameter type. 5220 unsigned NumInits = From->getNumInits(); 5221 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5222 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5223 SuppressUserConversions, 5224 InOverloadResolution, 5225 AllowObjCWritebackConversion); 5226 // - if the initializer list has no elements, the implicit conversion 5227 // sequence is the identity conversion. 5228 else if (NumInits == 0) { 5229 Result.setStandard(); 5230 Result.Standard.setAsIdentityConversion(); 5231 Result.Standard.setFromType(ToType); 5232 Result.Standard.setAllToTypes(ToType); 5233 } 5234 return Result; 5235 } 5236 5237 // C++14 [over.ics.list]p8: 5238 // C++11 [over.ics.list]p7: 5239 // In all cases other than those enumerated above, no conversion is possible 5240 return Result; 5241 } 5242 5243 /// TryCopyInitialization - Try to copy-initialize a value of type 5244 /// ToType from the expression From. Return the implicit conversion 5245 /// sequence required to pass this argument, which may be a bad 5246 /// conversion sequence (meaning that the argument cannot be passed to 5247 /// a parameter of this type). If @p SuppressUserConversions, then we 5248 /// do not permit any user-defined conversion sequences. 5249 static ImplicitConversionSequence 5250 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5251 bool SuppressUserConversions, 5252 bool InOverloadResolution, 5253 bool AllowObjCWritebackConversion, 5254 bool AllowExplicit) { 5255 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5256 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5257 InOverloadResolution,AllowObjCWritebackConversion); 5258 5259 if (ToType->isReferenceType()) 5260 return TryReferenceInit(S, From, ToType, 5261 /*FIXME:*/ From->getBeginLoc(), 5262 SuppressUserConversions, AllowExplicit); 5263 5264 return TryImplicitConversion(S, From, ToType, 5265 SuppressUserConversions, 5266 AllowedExplicit::None, 5267 InOverloadResolution, 5268 /*CStyle=*/false, 5269 AllowObjCWritebackConversion, 5270 /*AllowObjCConversionOnExplicit=*/false); 5271 } 5272 5273 static bool TryCopyInitialization(const CanQualType FromQTy, 5274 const CanQualType ToQTy, 5275 Sema &S, 5276 SourceLocation Loc, 5277 ExprValueKind FromVK) { 5278 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5279 ImplicitConversionSequence ICS = 5280 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5281 5282 return !ICS.isBad(); 5283 } 5284 5285 /// TryObjectArgumentInitialization - Try to initialize the object 5286 /// parameter of the given member function (@c Method) from the 5287 /// expression @p From. 5288 static ImplicitConversionSequence 5289 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5290 Expr::Classification FromClassification, 5291 CXXMethodDecl *Method, 5292 CXXRecordDecl *ActingContext) { 5293 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5294 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5295 // const volatile object. 5296 Qualifiers Quals = Method->getMethodQualifiers(); 5297 if (isa<CXXDestructorDecl>(Method)) { 5298 Quals.addConst(); 5299 Quals.addVolatile(); 5300 } 5301 5302 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5303 5304 // Set up the conversion sequence as a "bad" conversion, to allow us 5305 // to exit early. 5306 ImplicitConversionSequence ICS; 5307 5308 // We need to have an object of class type. 5309 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5310 FromType = PT->getPointeeType(); 5311 5312 // When we had a pointer, it's implicitly dereferenced, so we 5313 // better have an lvalue. 5314 assert(FromClassification.isLValue()); 5315 } 5316 5317 assert(FromType->isRecordType()); 5318 5319 // C++0x [over.match.funcs]p4: 5320 // For non-static member functions, the type of the implicit object 5321 // parameter is 5322 // 5323 // - "lvalue reference to cv X" for functions declared without a 5324 // ref-qualifier or with the & ref-qualifier 5325 // - "rvalue reference to cv X" for functions declared with the && 5326 // ref-qualifier 5327 // 5328 // where X is the class of which the function is a member and cv is the 5329 // cv-qualification on the member function declaration. 5330 // 5331 // However, when finding an implicit conversion sequence for the argument, we 5332 // are not allowed to perform user-defined conversions 5333 // (C++ [over.match.funcs]p5). We perform a simplified version of 5334 // reference binding here, that allows class rvalues to bind to 5335 // non-constant references. 5336 5337 // First check the qualifiers. 5338 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5339 if (ImplicitParamType.getCVRQualifiers() 5340 != FromTypeCanon.getLocalCVRQualifiers() && 5341 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5342 ICS.setBad(BadConversionSequence::bad_qualifiers, 5343 FromType, ImplicitParamType); 5344 return ICS; 5345 } 5346 5347 if (FromTypeCanon.hasAddressSpace()) { 5348 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5349 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5350 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5351 ICS.setBad(BadConversionSequence::bad_qualifiers, 5352 FromType, ImplicitParamType); 5353 return ICS; 5354 } 5355 } 5356 5357 // Check that we have either the same type or a derived type. It 5358 // affects the conversion rank. 5359 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5360 ImplicitConversionKind SecondKind; 5361 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5362 SecondKind = ICK_Identity; 5363 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5364 SecondKind = ICK_Derived_To_Base; 5365 else { 5366 ICS.setBad(BadConversionSequence::unrelated_class, 5367 FromType, ImplicitParamType); 5368 return ICS; 5369 } 5370 5371 // Check the ref-qualifier. 5372 switch (Method->getRefQualifier()) { 5373 case RQ_None: 5374 // Do nothing; we don't care about lvalueness or rvalueness. 5375 break; 5376 5377 case RQ_LValue: 5378 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5379 // non-const lvalue reference cannot bind to an rvalue 5380 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5381 ImplicitParamType); 5382 return ICS; 5383 } 5384 break; 5385 5386 case RQ_RValue: 5387 if (!FromClassification.isRValue()) { 5388 // rvalue reference cannot bind to an lvalue 5389 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5390 ImplicitParamType); 5391 return ICS; 5392 } 5393 break; 5394 } 5395 5396 // Success. Mark this as a reference binding. 5397 ICS.setStandard(); 5398 ICS.Standard.setAsIdentityConversion(); 5399 ICS.Standard.Second = SecondKind; 5400 ICS.Standard.setFromType(FromType); 5401 ICS.Standard.setAllToTypes(ImplicitParamType); 5402 ICS.Standard.ReferenceBinding = true; 5403 ICS.Standard.DirectBinding = true; 5404 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5405 ICS.Standard.BindsToFunctionLvalue = false; 5406 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5407 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5408 = (Method->getRefQualifier() == RQ_None); 5409 return ICS; 5410 } 5411 5412 /// PerformObjectArgumentInitialization - Perform initialization of 5413 /// the implicit object parameter for the given Method with the given 5414 /// expression. 5415 ExprResult 5416 Sema::PerformObjectArgumentInitialization(Expr *From, 5417 NestedNameSpecifier *Qualifier, 5418 NamedDecl *FoundDecl, 5419 CXXMethodDecl *Method) { 5420 QualType FromRecordType, DestType; 5421 QualType ImplicitParamRecordType = 5422 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5423 5424 Expr::Classification FromClassification; 5425 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5426 FromRecordType = PT->getPointeeType(); 5427 DestType = Method->getThisType(); 5428 FromClassification = Expr::Classification::makeSimpleLValue(); 5429 } else { 5430 FromRecordType = From->getType(); 5431 DestType = ImplicitParamRecordType; 5432 FromClassification = From->Classify(Context); 5433 5434 // When performing member access on an rvalue, materialize a temporary. 5435 if (From->isRValue()) { 5436 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5437 Method->getRefQualifier() != 5438 RefQualifierKind::RQ_RValue); 5439 } 5440 } 5441 5442 // Note that we always use the true parent context when performing 5443 // the actual argument initialization. 5444 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5445 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5446 Method->getParent()); 5447 if (ICS.isBad()) { 5448 switch (ICS.Bad.Kind) { 5449 case BadConversionSequence::bad_qualifiers: { 5450 Qualifiers FromQs = FromRecordType.getQualifiers(); 5451 Qualifiers ToQs = DestType.getQualifiers(); 5452 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5453 if (CVR) { 5454 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5455 << Method->getDeclName() << FromRecordType << (CVR - 1) 5456 << From->getSourceRange(); 5457 Diag(Method->getLocation(), diag::note_previous_decl) 5458 << Method->getDeclName(); 5459 return ExprError(); 5460 } 5461 break; 5462 } 5463 5464 case BadConversionSequence::lvalue_ref_to_rvalue: 5465 case BadConversionSequence::rvalue_ref_to_lvalue: { 5466 bool IsRValueQualified = 5467 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5468 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5469 << Method->getDeclName() << FromClassification.isRValue() 5470 << IsRValueQualified; 5471 Diag(Method->getLocation(), diag::note_previous_decl) 5472 << Method->getDeclName(); 5473 return ExprError(); 5474 } 5475 5476 case BadConversionSequence::no_conversion: 5477 case BadConversionSequence::unrelated_class: 5478 break; 5479 } 5480 5481 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5482 << ImplicitParamRecordType << FromRecordType 5483 << From->getSourceRange(); 5484 } 5485 5486 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5487 ExprResult FromRes = 5488 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5489 if (FromRes.isInvalid()) 5490 return ExprError(); 5491 From = FromRes.get(); 5492 } 5493 5494 if (!Context.hasSameType(From->getType(), DestType)) { 5495 CastKind CK; 5496 QualType PteeTy = DestType->getPointeeType(); 5497 LangAS DestAS = 5498 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5499 if (FromRecordType.getAddressSpace() != DestAS) 5500 CK = CK_AddressSpaceConversion; 5501 else 5502 CK = CK_NoOp; 5503 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5504 } 5505 return From; 5506 } 5507 5508 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5509 /// expression From to bool (C++0x [conv]p3). 5510 static ImplicitConversionSequence 5511 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5512 // C++ [dcl.init]/17.8: 5513 // - Otherwise, if the initialization is direct-initialization, the source 5514 // type is std::nullptr_t, and the destination type is bool, the initial 5515 // value of the object being initialized is false. 5516 if (From->getType()->isNullPtrType()) 5517 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5518 S.Context.BoolTy, 5519 From->isGLValue()); 5520 5521 // All other direct-initialization of bool is equivalent to an implicit 5522 // conversion to bool in which explicit conversions are permitted. 5523 return TryImplicitConversion(S, From, S.Context.BoolTy, 5524 /*SuppressUserConversions=*/false, 5525 AllowedExplicit::Conversions, 5526 /*InOverloadResolution=*/false, 5527 /*CStyle=*/false, 5528 /*AllowObjCWritebackConversion=*/false, 5529 /*AllowObjCConversionOnExplicit=*/false); 5530 } 5531 5532 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5533 /// of the expression From to bool (C++0x [conv]p3). 5534 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5535 if (checkPlaceholderForOverload(*this, From)) 5536 return ExprError(); 5537 5538 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5539 if (!ICS.isBad()) 5540 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5541 5542 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5543 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5544 << From->getType() << From->getSourceRange(); 5545 return ExprError(); 5546 } 5547 5548 /// Check that the specified conversion is permitted in a converted constant 5549 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5550 /// is acceptable. 5551 static bool CheckConvertedConstantConversions(Sema &S, 5552 StandardConversionSequence &SCS) { 5553 // Since we know that the target type is an integral or unscoped enumeration 5554 // type, most conversion kinds are impossible. All possible First and Third 5555 // conversions are fine. 5556 switch (SCS.Second) { 5557 case ICK_Identity: 5558 case ICK_Integral_Promotion: 5559 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5560 case ICK_Zero_Queue_Conversion: 5561 return true; 5562 5563 case ICK_Boolean_Conversion: 5564 // Conversion from an integral or unscoped enumeration type to bool is 5565 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5566 // conversion, so we allow it in a converted constant expression. 5567 // 5568 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5569 // a lot of popular code. We should at least add a warning for this 5570 // (non-conforming) extension. 5571 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5572 SCS.getToType(2)->isBooleanType(); 5573 5574 case ICK_Pointer_Conversion: 5575 case ICK_Pointer_Member: 5576 // C++1z: null pointer conversions and null member pointer conversions are 5577 // only permitted if the source type is std::nullptr_t. 5578 return SCS.getFromType()->isNullPtrType(); 5579 5580 case ICK_Floating_Promotion: 5581 case ICK_Complex_Promotion: 5582 case ICK_Floating_Conversion: 5583 case ICK_Complex_Conversion: 5584 case ICK_Floating_Integral: 5585 case ICK_Compatible_Conversion: 5586 case ICK_Derived_To_Base: 5587 case ICK_Vector_Conversion: 5588 case ICK_SVE_Vector_Conversion: 5589 case ICK_Vector_Splat: 5590 case ICK_Complex_Real: 5591 case ICK_Block_Pointer_Conversion: 5592 case ICK_TransparentUnionConversion: 5593 case ICK_Writeback_Conversion: 5594 case ICK_Zero_Event_Conversion: 5595 case ICK_C_Only_Conversion: 5596 case ICK_Incompatible_Pointer_Conversion: 5597 return false; 5598 5599 case ICK_Lvalue_To_Rvalue: 5600 case ICK_Array_To_Pointer: 5601 case ICK_Function_To_Pointer: 5602 llvm_unreachable("found a first conversion kind in Second"); 5603 5604 case ICK_Function_Conversion: 5605 case ICK_Qualification: 5606 llvm_unreachable("found a third conversion kind in Second"); 5607 5608 case ICK_Num_Conversion_Kinds: 5609 break; 5610 } 5611 5612 llvm_unreachable("unknown conversion kind"); 5613 } 5614 5615 /// CheckConvertedConstantExpression - Check that the expression From is a 5616 /// converted constant expression of type T, perform the conversion and produce 5617 /// the converted expression, per C++11 [expr.const]p3. 5618 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5619 QualType T, APValue &Value, 5620 Sema::CCEKind CCE, 5621 bool RequireInt, 5622 NamedDecl *Dest) { 5623 assert(S.getLangOpts().CPlusPlus11 && 5624 "converted constant expression outside C++11"); 5625 5626 if (checkPlaceholderForOverload(S, From)) 5627 return ExprError(); 5628 5629 // C++1z [expr.const]p3: 5630 // A converted constant expression of type T is an expression, 5631 // implicitly converted to type T, where the converted 5632 // expression is a constant expression and the implicit conversion 5633 // sequence contains only [... list of conversions ...]. 5634 // C++1z [stmt.if]p2: 5635 // If the if statement is of the form if constexpr, the value of the 5636 // condition shall be a contextually converted constant expression of type 5637 // bool. 5638 ImplicitConversionSequence ICS = 5639 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5640 ? TryContextuallyConvertToBool(S, From) 5641 : TryCopyInitialization(S, From, T, 5642 /*SuppressUserConversions=*/false, 5643 /*InOverloadResolution=*/false, 5644 /*AllowObjCWritebackConversion=*/false, 5645 /*AllowExplicit=*/false); 5646 StandardConversionSequence *SCS = nullptr; 5647 switch (ICS.getKind()) { 5648 case ImplicitConversionSequence::StandardConversion: 5649 SCS = &ICS.Standard; 5650 break; 5651 case ImplicitConversionSequence::UserDefinedConversion: 5652 if (T->isRecordType()) 5653 SCS = &ICS.UserDefined.Before; 5654 else 5655 SCS = &ICS.UserDefined.After; 5656 break; 5657 case ImplicitConversionSequence::AmbiguousConversion: 5658 case ImplicitConversionSequence::BadConversion: 5659 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5660 return S.Diag(From->getBeginLoc(), 5661 diag::err_typecheck_converted_constant_expression) 5662 << From->getType() << From->getSourceRange() << T; 5663 return ExprError(); 5664 5665 case ImplicitConversionSequence::EllipsisConversion: 5666 llvm_unreachable("ellipsis conversion in converted constant expression"); 5667 } 5668 5669 // Check that we would only use permitted conversions. 5670 if (!CheckConvertedConstantConversions(S, *SCS)) { 5671 return S.Diag(From->getBeginLoc(), 5672 diag::err_typecheck_converted_constant_expression_disallowed) 5673 << From->getType() << From->getSourceRange() << T; 5674 } 5675 // [...] and where the reference binding (if any) binds directly. 5676 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5677 return S.Diag(From->getBeginLoc(), 5678 diag::err_typecheck_converted_constant_expression_indirect) 5679 << From->getType() << From->getSourceRange() << T; 5680 } 5681 5682 // Usually we can simply apply the ImplicitConversionSequence we formed 5683 // earlier, but that's not guaranteed to work when initializing an object of 5684 // class type. 5685 ExprResult Result; 5686 if (T->isRecordType()) { 5687 assert(CCE == Sema::CCEK_TemplateArg && 5688 "unexpected class type converted constant expr"); 5689 Result = S.PerformCopyInitialization( 5690 InitializedEntity::InitializeTemplateParameter( 5691 T, cast<NonTypeTemplateParmDecl>(Dest)), 5692 SourceLocation(), From); 5693 } else { 5694 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5695 } 5696 if (Result.isInvalid()) 5697 return Result; 5698 5699 // C++2a [intro.execution]p5: 5700 // A full-expression is [...] a constant-expression [...] 5701 Result = 5702 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5703 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5704 if (Result.isInvalid()) 5705 return Result; 5706 5707 // Check for a narrowing implicit conversion. 5708 bool ReturnPreNarrowingValue = false; 5709 APValue PreNarrowingValue; 5710 QualType PreNarrowingType; 5711 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5712 PreNarrowingType)) { 5713 case NK_Dependent_Narrowing: 5714 // Implicit conversion to a narrower type, but the expression is 5715 // value-dependent so we can't tell whether it's actually narrowing. 5716 case NK_Variable_Narrowing: 5717 // Implicit conversion to a narrower type, and the value is not a constant 5718 // expression. We'll diagnose this in a moment. 5719 case NK_Not_Narrowing: 5720 break; 5721 5722 case NK_Constant_Narrowing: 5723 if (CCE == Sema::CCEK_ArrayBound && 5724 PreNarrowingType->isIntegralOrEnumerationType() && 5725 PreNarrowingValue.isInt()) { 5726 // Don't diagnose array bound narrowing here; we produce more precise 5727 // errors by allowing the un-narrowed value through. 5728 ReturnPreNarrowingValue = true; 5729 break; 5730 } 5731 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5732 << CCE << /*Constant*/ 1 5733 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5734 break; 5735 5736 case NK_Type_Narrowing: 5737 // FIXME: It would be better to diagnose that the expression is not a 5738 // constant expression. 5739 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5740 << CCE << /*Constant*/ 0 << From->getType() << T; 5741 break; 5742 } 5743 5744 if (Result.get()->isValueDependent()) { 5745 Value = APValue(); 5746 return Result; 5747 } 5748 5749 // Check the expression is a constant expression. 5750 SmallVector<PartialDiagnosticAt, 8> Notes; 5751 Expr::EvalResult Eval; 5752 Eval.Diag = &Notes; 5753 5754 ConstantExprKind Kind; 5755 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5756 Kind = ConstantExprKind::ClassTemplateArgument; 5757 else if (CCE == Sema::CCEK_TemplateArg) 5758 Kind = ConstantExprKind::NonClassTemplateArgument; 5759 else 5760 Kind = ConstantExprKind::Normal; 5761 5762 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5763 (RequireInt && !Eval.Val.isInt())) { 5764 // The expression can't be folded, so we can't keep it at this position in 5765 // the AST. 5766 Result = ExprError(); 5767 } else { 5768 Value = Eval.Val; 5769 5770 if (Notes.empty()) { 5771 // It's a constant expression. 5772 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5773 if (ReturnPreNarrowingValue) 5774 Value = std::move(PreNarrowingValue); 5775 return E; 5776 } 5777 } 5778 5779 // It's not a constant expression. Produce an appropriate diagnostic. 5780 if (Notes.size() == 1 && 5781 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5782 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5783 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5784 diag::note_constexpr_invalid_template_arg) { 5785 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5786 for (unsigned I = 0; I < Notes.size(); ++I) 5787 S.Diag(Notes[I].first, Notes[I].second); 5788 } else { 5789 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5790 << CCE << From->getSourceRange(); 5791 for (unsigned I = 0; I < Notes.size(); ++I) 5792 S.Diag(Notes[I].first, Notes[I].second); 5793 } 5794 return ExprError(); 5795 } 5796 5797 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5798 APValue &Value, CCEKind CCE, 5799 NamedDecl *Dest) { 5800 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5801 Dest); 5802 } 5803 5804 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5805 llvm::APSInt &Value, 5806 CCEKind CCE) { 5807 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5808 5809 APValue V; 5810 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5811 /*Dest=*/nullptr); 5812 if (!R.isInvalid() && !R.get()->isValueDependent()) 5813 Value = V.getInt(); 5814 return R; 5815 } 5816 5817 5818 /// dropPointerConversions - If the given standard conversion sequence 5819 /// involves any pointer conversions, remove them. This may change 5820 /// the result type of the conversion sequence. 5821 static void dropPointerConversion(StandardConversionSequence &SCS) { 5822 if (SCS.Second == ICK_Pointer_Conversion) { 5823 SCS.Second = ICK_Identity; 5824 SCS.Third = ICK_Identity; 5825 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5826 } 5827 } 5828 5829 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5830 /// convert the expression From to an Objective-C pointer type. 5831 static ImplicitConversionSequence 5832 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5833 // Do an implicit conversion to 'id'. 5834 QualType Ty = S.Context.getObjCIdType(); 5835 ImplicitConversionSequence ICS 5836 = TryImplicitConversion(S, From, Ty, 5837 // FIXME: Are these flags correct? 5838 /*SuppressUserConversions=*/false, 5839 AllowedExplicit::Conversions, 5840 /*InOverloadResolution=*/false, 5841 /*CStyle=*/false, 5842 /*AllowObjCWritebackConversion=*/false, 5843 /*AllowObjCConversionOnExplicit=*/true); 5844 5845 // Strip off any final conversions to 'id'. 5846 switch (ICS.getKind()) { 5847 case ImplicitConversionSequence::BadConversion: 5848 case ImplicitConversionSequence::AmbiguousConversion: 5849 case ImplicitConversionSequence::EllipsisConversion: 5850 break; 5851 5852 case ImplicitConversionSequence::UserDefinedConversion: 5853 dropPointerConversion(ICS.UserDefined.After); 5854 break; 5855 5856 case ImplicitConversionSequence::StandardConversion: 5857 dropPointerConversion(ICS.Standard); 5858 break; 5859 } 5860 5861 return ICS; 5862 } 5863 5864 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5865 /// conversion of the expression From to an Objective-C pointer type. 5866 /// Returns a valid but null ExprResult if no conversion sequence exists. 5867 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5868 if (checkPlaceholderForOverload(*this, From)) 5869 return ExprError(); 5870 5871 QualType Ty = Context.getObjCIdType(); 5872 ImplicitConversionSequence ICS = 5873 TryContextuallyConvertToObjCPointer(*this, From); 5874 if (!ICS.isBad()) 5875 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5876 return ExprResult(); 5877 } 5878 5879 /// Determine whether the provided type is an integral type, or an enumeration 5880 /// type of a permitted flavor. 5881 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5882 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5883 : T->isIntegralOrUnscopedEnumerationType(); 5884 } 5885 5886 static ExprResult 5887 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5888 Sema::ContextualImplicitConverter &Converter, 5889 QualType T, UnresolvedSetImpl &ViableConversions) { 5890 5891 if (Converter.Suppress) 5892 return ExprError(); 5893 5894 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5895 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5896 CXXConversionDecl *Conv = 5897 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5898 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5899 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5900 } 5901 return From; 5902 } 5903 5904 static bool 5905 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5906 Sema::ContextualImplicitConverter &Converter, 5907 QualType T, bool HadMultipleCandidates, 5908 UnresolvedSetImpl &ExplicitConversions) { 5909 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5910 DeclAccessPair Found = ExplicitConversions[0]; 5911 CXXConversionDecl *Conversion = 5912 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5913 5914 // The user probably meant to invoke the given explicit 5915 // conversion; use it. 5916 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5917 std::string TypeStr; 5918 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5919 5920 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5921 << FixItHint::CreateInsertion(From->getBeginLoc(), 5922 "static_cast<" + TypeStr + ">(") 5923 << FixItHint::CreateInsertion( 5924 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5925 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5926 5927 // If we aren't in a SFINAE context, build a call to the 5928 // explicit conversion function. 5929 if (SemaRef.isSFINAEContext()) 5930 return true; 5931 5932 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5933 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5934 HadMultipleCandidates); 5935 if (Result.isInvalid()) 5936 return true; 5937 // Record usage of conversion in an implicit cast. 5938 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5939 CK_UserDefinedConversion, Result.get(), 5940 nullptr, Result.get()->getValueKind(), 5941 SemaRef.CurFPFeatureOverrides()); 5942 } 5943 return false; 5944 } 5945 5946 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5947 Sema::ContextualImplicitConverter &Converter, 5948 QualType T, bool HadMultipleCandidates, 5949 DeclAccessPair &Found) { 5950 CXXConversionDecl *Conversion = 5951 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5952 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5953 5954 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5955 if (!Converter.SuppressConversion) { 5956 if (SemaRef.isSFINAEContext()) 5957 return true; 5958 5959 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5960 << From->getSourceRange(); 5961 } 5962 5963 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5964 HadMultipleCandidates); 5965 if (Result.isInvalid()) 5966 return true; 5967 // Record usage of conversion in an implicit cast. 5968 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5969 CK_UserDefinedConversion, Result.get(), 5970 nullptr, Result.get()->getValueKind(), 5971 SemaRef.CurFPFeatureOverrides()); 5972 return false; 5973 } 5974 5975 static ExprResult finishContextualImplicitConversion( 5976 Sema &SemaRef, SourceLocation Loc, Expr *From, 5977 Sema::ContextualImplicitConverter &Converter) { 5978 if (!Converter.match(From->getType()) && !Converter.Suppress) 5979 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5980 << From->getSourceRange(); 5981 5982 return SemaRef.DefaultLvalueConversion(From); 5983 } 5984 5985 static void 5986 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5987 UnresolvedSetImpl &ViableConversions, 5988 OverloadCandidateSet &CandidateSet) { 5989 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5990 DeclAccessPair FoundDecl = ViableConversions[I]; 5991 NamedDecl *D = FoundDecl.getDecl(); 5992 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5993 if (isa<UsingShadowDecl>(D)) 5994 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5995 5996 CXXConversionDecl *Conv; 5997 FunctionTemplateDecl *ConvTemplate; 5998 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5999 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6000 else 6001 Conv = cast<CXXConversionDecl>(D); 6002 6003 if (ConvTemplate) 6004 SemaRef.AddTemplateConversionCandidate( 6005 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6006 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6007 else 6008 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6009 ToType, CandidateSet, 6010 /*AllowObjCConversionOnExplicit=*/false, 6011 /*AllowExplicit*/ true); 6012 } 6013 } 6014 6015 /// Attempt to convert the given expression to a type which is accepted 6016 /// by the given converter. 6017 /// 6018 /// This routine will attempt to convert an expression of class type to a 6019 /// type accepted by the specified converter. In C++11 and before, the class 6020 /// must have a single non-explicit conversion function converting to a matching 6021 /// type. In C++1y, there can be multiple such conversion functions, but only 6022 /// one target type. 6023 /// 6024 /// \param Loc The source location of the construct that requires the 6025 /// conversion. 6026 /// 6027 /// \param From The expression we're converting from. 6028 /// 6029 /// \param Converter Used to control and diagnose the conversion process. 6030 /// 6031 /// \returns The expression, converted to an integral or enumeration type if 6032 /// successful. 6033 ExprResult Sema::PerformContextualImplicitConversion( 6034 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6035 // We can't perform any more checking for type-dependent expressions. 6036 if (From->isTypeDependent()) 6037 return From; 6038 6039 // Process placeholders immediately. 6040 if (From->hasPlaceholderType()) { 6041 ExprResult result = CheckPlaceholderExpr(From); 6042 if (result.isInvalid()) 6043 return result; 6044 From = result.get(); 6045 } 6046 6047 // If the expression already has a matching type, we're golden. 6048 QualType T = From->getType(); 6049 if (Converter.match(T)) 6050 return DefaultLvalueConversion(From); 6051 6052 // FIXME: Check for missing '()' if T is a function type? 6053 6054 // We can only perform contextual implicit conversions on objects of class 6055 // type. 6056 const RecordType *RecordTy = T->getAs<RecordType>(); 6057 if (!RecordTy || !getLangOpts().CPlusPlus) { 6058 if (!Converter.Suppress) 6059 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6060 return From; 6061 } 6062 6063 // We must have a complete class type. 6064 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6065 ContextualImplicitConverter &Converter; 6066 Expr *From; 6067 6068 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6069 : Converter(Converter), From(From) {} 6070 6071 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6072 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6073 } 6074 } IncompleteDiagnoser(Converter, From); 6075 6076 if (Converter.Suppress ? !isCompleteType(Loc, T) 6077 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6078 return From; 6079 6080 // Look for a conversion to an integral or enumeration type. 6081 UnresolvedSet<4> 6082 ViableConversions; // These are *potentially* viable in C++1y. 6083 UnresolvedSet<4> ExplicitConversions; 6084 const auto &Conversions = 6085 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6086 6087 bool HadMultipleCandidates = 6088 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6089 6090 // To check that there is only one target type, in C++1y: 6091 QualType ToType; 6092 bool HasUniqueTargetType = true; 6093 6094 // Collect explicit or viable (potentially in C++1y) conversions. 6095 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6096 NamedDecl *D = (*I)->getUnderlyingDecl(); 6097 CXXConversionDecl *Conversion; 6098 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6099 if (ConvTemplate) { 6100 if (getLangOpts().CPlusPlus14) 6101 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6102 else 6103 continue; // C++11 does not consider conversion operator templates(?). 6104 } else 6105 Conversion = cast<CXXConversionDecl>(D); 6106 6107 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6108 "Conversion operator templates are considered potentially " 6109 "viable in C++1y"); 6110 6111 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6112 if (Converter.match(CurToType) || ConvTemplate) { 6113 6114 if (Conversion->isExplicit()) { 6115 // FIXME: For C++1y, do we need this restriction? 6116 // cf. diagnoseNoViableConversion() 6117 if (!ConvTemplate) 6118 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6119 } else { 6120 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6121 if (ToType.isNull()) 6122 ToType = CurToType.getUnqualifiedType(); 6123 else if (HasUniqueTargetType && 6124 (CurToType.getUnqualifiedType() != ToType)) 6125 HasUniqueTargetType = false; 6126 } 6127 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6128 } 6129 } 6130 } 6131 6132 if (getLangOpts().CPlusPlus14) { 6133 // C++1y [conv]p6: 6134 // ... An expression e of class type E appearing in such a context 6135 // is said to be contextually implicitly converted to a specified 6136 // type T and is well-formed if and only if e can be implicitly 6137 // converted to a type T that is determined as follows: E is searched 6138 // for conversion functions whose return type is cv T or reference to 6139 // cv T such that T is allowed by the context. There shall be 6140 // exactly one such T. 6141 6142 // If no unique T is found: 6143 if (ToType.isNull()) { 6144 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6145 HadMultipleCandidates, 6146 ExplicitConversions)) 6147 return ExprError(); 6148 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6149 } 6150 6151 // If more than one unique Ts are found: 6152 if (!HasUniqueTargetType) 6153 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6154 ViableConversions); 6155 6156 // If one unique T is found: 6157 // First, build a candidate set from the previously recorded 6158 // potentially viable conversions. 6159 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6160 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6161 CandidateSet); 6162 6163 // Then, perform overload resolution over the candidate set. 6164 OverloadCandidateSet::iterator Best; 6165 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6166 case OR_Success: { 6167 // Apply this conversion. 6168 DeclAccessPair Found = 6169 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6170 if (recordConversion(*this, Loc, From, Converter, T, 6171 HadMultipleCandidates, Found)) 6172 return ExprError(); 6173 break; 6174 } 6175 case OR_Ambiguous: 6176 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6177 ViableConversions); 6178 case OR_No_Viable_Function: 6179 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6180 HadMultipleCandidates, 6181 ExplicitConversions)) 6182 return ExprError(); 6183 LLVM_FALLTHROUGH; 6184 case OR_Deleted: 6185 // We'll complain below about a non-integral condition type. 6186 break; 6187 } 6188 } else { 6189 switch (ViableConversions.size()) { 6190 case 0: { 6191 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6192 HadMultipleCandidates, 6193 ExplicitConversions)) 6194 return ExprError(); 6195 6196 // We'll complain below about a non-integral condition type. 6197 break; 6198 } 6199 case 1: { 6200 // Apply this conversion. 6201 DeclAccessPair Found = ViableConversions[0]; 6202 if (recordConversion(*this, Loc, From, Converter, T, 6203 HadMultipleCandidates, Found)) 6204 return ExprError(); 6205 break; 6206 } 6207 default: 6208 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6209 ViableConversions); 6210 } 6211 } 6212 6213 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6214 } 6215 6216 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6217 /// an acceptable non-member overloaded operator for a call whose 6218 /// arguments have types T1 (and, if non-empty, T2). This routine 6219 /// implements the check in C++ [over.match.oper]p3b2 concerning 6220 /// enumeration types. 6221 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6222 FunctionDecl *Fn, 6223 ArrayRef<Expr *> Args) { 6224 QualType T1 = Args[0]->getType(); 6225 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6226 6227 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6228 return true; 6229 6230 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6231 return true; 6232 6233 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6234 if (Proto->getNumParams() < 1) 6235 return false; 6236 6237 if (T1->isEnumeralType()) { 6238 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6239 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6240 return true; 6241 } 6242 6243 if (Proto->getNumParams() < 2) 6244 return false; 6245 6246 if (!T2.isNull() && T2->isEnumeralType()) { 6247 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6248 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6249 return true; 6250 } 6251 6252 return false; 6253 } 6254 6255 /// AddOverloadCandidate - Adds the given function to the set of 6256 /// candidate functions, using the given function call arguments. If 6257 /// @p SuppressUserConversions, then don't allow user-defined 6258 /// conversions via constructors or conversion operators. 6259 /// 6260 /// \param PartialOverloading true if we are performing "partial" overloading 6261 /// based on an incomplete set of function arguments. This feature is used by 6262 /// code completion. 6263 void Sema::AddOverloadCandidate( 6264 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6265 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6266 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6267 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6268 OverloadCandidateParamOrder PO) { 6269 const FunctionProtoType *Proto 6270 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6271 assert(Proto && "Functions without a prototype cannot be overloaded"); 6272 assert(!Function->getDescribedFunctionTemplate() && 6273 "Use AddTemplateOverloadCandidate for function templates"); 6274 6275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6276 if (!isa<CXXConstructorDecl>(Method)) { 6277 // If we get here, it's because we're calling a member function 6278 // that is named without a member access expression (e.g., 6279 // "this->f") that was either written explicitly or created 6280 // implicitly. This can happen with a qualified call to a member 6281 // function, e.g., X::f(). We use an empty type for the implied 6282 // object argument (C++ [over.call.func]p3), and the acting context 6283 // is irrelevant. 6284 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6285 Expr::Classification::makeSimpleLValue(), Args, 6286 CandidateSet, SuppressUserConversions, 6287 PartialOverloading, EarlyConversions, PO); 6288 return; 6289 } 6290 // We treat a constructor like a non-member function, since its object 6291 // argument doesn't participate in overload resolution. 6292 } 6293 6294 if (!CandidateSet.isNewCandidate(Function, PO)) 6295 return; 6296 6297 // C++11 [class.copy]p11: [DR1402] 6298 // A defaulted move constructor that is defined as deleted is ignored by 6299 // overload resolution. 6300 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6301 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6302 Constructor->isMoveConstructor()) 6303 return; 6304 6305 // Overload resolution is always an unevaluated context. 6306 EnterExpressionEvaluationContext Unevaluated( 6307 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6308 6309 // C++ [over.match.oper]p3: 6310 // if no operand has a class type, only those non-member functions in the 6311 // lookup set that have a first parameter of type T1 or "reference to 6312 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6313 // is a right operand) a second parameter of type T2 or "reference to 6314 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6315 // candidate functions. 6316 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6317 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6318 return; 6319 6320 // Add this candidate 6321 OverloadCandidate &Candidate = 6322 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6323 Candidate.FoundDecl = FoundDecl; 6324 Candidate.Function = Function; 6325 Candidate.Viable = true; 6326 Candidate.RewriteKind = 6327 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6328 Candidate.IsSurrogate = false; 6329 Candidate.IsADLCandidate = IsADLCandidate; 6330 Candidate.IgnoreObjectArgument = false; 6331 Candidate.ExplicitCallArguments = Args.size(); 6332 6333 // Explicit functions are not actually candidates at all if we're not 6334 // allowing them in this context, but keep them around so we can point 6335 // to them in diagnostics. 6336 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6337 Candidate.Viable = false; 6338 Candidate.FailureKind = ovl_fail_explicit; 6339 return; 6340 } 6341 6342 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6343 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6344 Candidate.Viable = false; 6345 Candidate.FailureKind = ovl_non_default_multiversion_function; 6346 return; 6347 } 6348 6349 if (Constructor) { 6350 // C++ [class.copy]p3: 6351 // A member function template is never instantiated to perform the copy 6352 // of a class object to an object of its class type. 6353 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6354 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6355 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6356 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6357 ClassType))) { 6358 Candidate.Viable = false; 6359 Candidate.FailureKind = ovl_fail_illegal_constructor; 6360 return; 6361 } 6362 6363 // C++ [over.match.funcs]p8: (proposed DR resolution) 6364 // A constructor inherited from class type C that has a first parameter 6365 // of type "reference to P" (including such a constructor instantiated 6366 // from a template) is excluded from the set of candidate functions when 6367 // constructing an object of type cv D if the argument list has exactly 6368 // one argument and D is reference-related to P and P is reference-related 6369 // to C. 6370 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6371 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6372 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6373 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6374 QualType C = Context.getRecordType(Constructor->getParent()); 6375 QualType D = Context.getRecordType(Shadow->getParent()); 6376 SourceLocation Loc = Args.front()->getExprLoc(); 6377 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6378 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6379 Candidate.Viable = false; 6380 Candidate.FailureKind = ovl_fail_inhctor_slice; 6381 return; 6382 } 6383 } 6384 6385 // Check that the constructor is capable of constructing an object in the 6386 // destination address space. 6387 if (!Qualifiers::isAddressSpaceSupersetOf( 6388 Constructor->getMethodQualifiers().getAddressSpace(), 6389 CandidateSet.getDestAS())) { 6390 Candidate.Viable = false; 6391 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6392 } 6393 } 6394 6395 unsigned NumParams = Proto->getNumParams(); 6396 6397 // (C++ 13.3.2p2): A candidate function having fewer than m 6398 // parameters is viable only if it has an ellipsis in its parameter 6399 // list (8.3.5). 6400 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6401 !Proto->isVariadic()) { 6402 Candidate.Viable = false; 6403 Candidate.FailureKind = ovl_fail_too_many_arguments; 6404 return; 6405 } 6406 6407 // (C++ 13.3.2p2): A candidate function having more than m parameters 6408 // is viable only if the (m+1)st parameter has a default argument 6409 // (8.3.6). For the purposes of overload resolution, the 6410 // parameter list is truncated on the right, so that there are 6411 // exactly m parameters. 6412 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6413 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6414 // Not enough arguments. 6415 Candidate.Viable = false; 6416 Candidate.FailureKind = ovl_fail_too_few_arguments; 6417 return; 6418 } 6419 6420 // (CUDA B.1): Check for invalid calls between targets. 6421 if (getLangOpts().CUDA) 6422 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6423 // Skip the check for callers that are implicit members, because in this 6424 // case we may not yet know what the member's target is; the target is 6425 // inferred for the member automatically, based on the bases and fields of 6426 // the class. 6427 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6428 Candidate.Viable = false; 6429 Candidate.FailureKind = ovl_fail_bad_target; 6430 return; 6431 } 6432 6433 if (Function->getTrailingRequiresClause()) { 6434 ConstraintSatisfaction Satisfaction; 6435 if (CheckFunctionConstraints(Function, Satisfaction) || 6436 !Satisfaction.IsSatisfied) { 6437 Candidate.Viable = false; 6438 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6439 return; 6440 } 6441 } 6442 6443 // Determine the implicit conversion sequences for each of the 6444 // arguments. 6445 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6446 unsigned ConvIdx = 6447 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6448 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6449 // We already formed a conversion sequence for this parameter during 6450 // template argument deduction. 6451 } else if (ArgIdx < NumParams) { 6452 // (C++ 13.3.2p3): for F to be a viable function, there shall 6453 // exist for each argument an implicit conversion sequence 6454 // (13.3.3.1) that converts that argument to the corresponding 6455 // parameter of F. 6456 QualType ParamType = Proto->getParamType(ArgIdx); 6457 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6458 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6459 /*InOverloadResolution=*/true, 6460 /*AllowObjCWritebackConversion=*/ 6461 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6462 if (Candidate.Conversions[ConvIdx].isBad()) { 6463 Candidate.Viable = false; 6464 Candidate.FailureKind = ovl_fail_bad_conversion; 6465 return; 6466 } 6467 } else { 6468 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6469 // argument for which there is no corresponding parameter is 6470 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6471 Candidate.Conversions[ConvIdx].setEllipsis(); 6472 } 6473 } 6474 6475 if (EnableIfAttr *FailedAttr = 6476 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6477 Candidate.Viable = false; 6478 Candidate.FailureKind = ovl_fail_enable_if; 6479 Candidate.DeductionFailure.Data = FailedAttr; 6480 return; 6481 } 6482 6483 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6484 Candidate.Viable = false; 6485 Candidate.FailureKind = ovl_fail_ext_disabled; 6486 return; 6487 } 6488 } 6489 6490 ObjCMethodDecl * 6491 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6492 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6493 if (Methods.size() <= 1) 6494 return nullptr; 6495 6496 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6497 bool Match = true; 6498 ObjCMethodDecl *Method = Methods[b]; 6499 unsigned NumNamedArgs = Sel.getNumArgs(); 6500 // Method might have more arguments than selector indicates. This is due 6501 // to addition of c-style arguments in method. 6502 if (Method->param_size() > NumNamedArgs) 6503 NumNamedArgs = Method->param_size(); 6504 if (Args.size() < NumNamedArgs) 6505 continue; 6506 6507 for (unsigned i = 0; i < NumNamedArgs; i++) { 6508 // We can't do any type-checking on a type-dependent argument. 6509 if (Args[i]->isTypeDependent()) { 6510 Match = false; 6511 break; 6512 } 6513 6514 ParmVarDecl *param = Method->parameters()[i]; 6515 Expr *argExpr = Args[i]; 6516 assert(argExpr && "SelectBestMethod(): missing expression"); 6517 6518 // Strip the unbridged-cast placeholder expression off unless it's 6519 // a consumed argument. 6520 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6521 !param->hasAttr<CFConsumedAttr>()) 6522 argExpr = stripARCUnbridgedCast(argExpr); 6523 6524 // If the parameter is __unknown_anytype, move on to the next method. 6525 if (param->getType() == Context.UnknownAnyTy) { 6526 Match = false; 6527 break; 6528 } 6529 6530 ImplicitConversionSequence ConversionState 6531 = TryCopyInitialization(*this, argExpr, param->getType(), 6532 /*SuppressUserConversions*/false, 6533 /*InOverloadResolution=*/true, 6534 /*AllowObjCWritebackConversion=*/ 6535 getLangOpts().ObjCAutoRefCount, 6536 /*AllowExplicit*/false); 6537 // This function looks for a reasonably-exact match, so we consider 6538 // incompatible pointer conversions to be a failure here. 6539 if (ConversionState.isBad() || 6540 (ConversionState.isStandard() && 6541 ConversionState.Standard.Second == 6542 ICK_Incompatible_Pointer_Conversion)) { 6543 Match = false; 6544 break; 6545 } 6546 } 6547 // Promote additional arguments to variadic methods. 6548 if (Match && Method->isVariadic()) { 6549 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6550 if (Args[i]->isTypeDependent()) { 6551 Match = false; 6552 break; 6553 } 6554 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6555 nullptr); 6556 if (Arg.isInvalid()) { 6557 Match = false; 6558 break; 6559 } 6560 } 6561 } else { 6562 // Check for extra arguments to non-variadic methods. 6563 if (Args.size() != NumNamedArgs) 6564 Match = false; 6565 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6566 // Special case when selectors have no argument. In this case, select 6567 // one with the most general result type of 'id'. 6568 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6569 QualType ReturnT = Methods[b]->getReturnType(); 6570 if (ReturnT->isObjCIdType()) 6571 return Methods[b]; 6572 } 6573 } 6574 } 6575 6576 if (Match) 6577 return Method; 6578 } 6579 return nullptr; 6580 } 6581 6582 static bool convertArgsForAvailabilityChecks( 6583 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6584 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6585 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6586 if (ThisArg) { 6587 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6588 assert(!isa<CXXConstructorDecl>(Method) && 6589 "Shouldn't have `this` for ctors!"); 6590 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6591 ExprResult R = S.PerformObjectArgumentInitialization( 6592 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6593 if (R.isInvalid()) 6594 return false; 6595 ConvertedThis = R.get(); 6596 } else { 6597 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6598 (void)MD; 6599 assert((MissingImplicitThis || MD->isStatic() || 6600 isa<CXXConstructorDecl>(MD)) && 6601 "Expected `this` for non-ctor instance methods"); 6602 } 6603 ConvertedThis = nullptr; 6604 } 6605 6606 // Ignore any variadic arguments. Converting them is pointless, since the 6607 // user can't refer to them in the function condition. 6608 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6609 6610 // Convert the arguments. 6611 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6612 ExprResult R; 6613 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6614 S.Context, Function->getParamDecl(I)), 6615 SourceLocation(), Args[I]); 6616 6617 if (R.isInvalid()) 6618 return false; 6619 6620 ConvertedArgs.push_back(R.get()); 6621 } 6622 6623 if (Trap.hasErrorOccurred()) 6624 return false; 6625 6626 // Push default arguments if needed. 6627 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6628 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6629 ParmVarDecl *P = Function->getParamDecl(i); 6630 if (!P->hasDefaultArg()) 6631 return false; 6632 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6633 if (R.isInvalid()) 6634 return false; 6635 ConvertedArgs.push_back(R.get()); 6636 } 6637 6638 if (Trap.hasErrorOccurred()) 6639 return false; 6640 } 6641 return true; 6642 } 6643 6644 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6645 SourceLocation CallLoc, 6646 ArrayRef<Expr *> Args, 6647 bool MissingImplicitThis) { 6648 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6649 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6650 return nullptr; 6651 6652 SFINAETrap Trap(*this); 6653 SmallVector<Expr *, 16> ConvertedArgs; 6654 // FIXME: We should look into making enable_if late-parsed. 6655 Expr *DiscardedThis; 6656 if (!convertArgsForAvailabilityChecks( 6657 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6658 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6659 return *EnableIfAttrs.begin(); 6660 6661 for (auto *EIA : EnableIfAttrs) { 6662 APValue Result; 6663 // FIXME: This doesn't consider value-dependent cases, because doing so is 6664 // very difficult. Ideally, we should handle them more gracefully. 6665 if (EIA->getCond()->isValueDependent() || 6666 !EIA->getCond()->EvaluateWithSubstitution( 6667 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6668 return EIA; 6669 6670 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6671 return EIA; 6672 } 6673 return nullptr; 6674 } 6675 6676 template <typename CheckFn> 6677 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6678 bool ArgDependent, SourceLocation Loc, 6679 CheckFn &&IsSuccessful) { 6680 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6681 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6682 if (ArgDependent == DIA->getArgDependent()) 6683 Attrs.push_back(DIA); 6684 } 6685 6686 // Common case: No diagnose_if attributes, so we can quit early. 6687 if (Attrs.empty()) 6688 return false; 6689 6690 auto WarningBegin = std::stable_partition( 6691 Attrs.begin(), Attrs.end(), 6692 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6693 6694 // Note that diagnose_if attributes are late-parsed, so they appear in the 6695 // correct order (unlike enable_if attributes). 6696 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6697 IsSuccessful); 6698 if (ErrAttr != WarningBegin) { 6699 const DiagnoseIfAttr *DIA = *ErrAttr; 6700 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6701 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6702 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6703 return true; 6704 } 6705 6706 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6707 if (IsSuccessful(DIA)) { 6708 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6709 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6710 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6711 } 6712 6713 return false; 6714 } 6715 6716 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6717 const Expr *ThisArg, 6718 ArrayRef<const Expr *> Args, 6719 SourceLocation Loc) { 6720 return diagnoseDiagnoseIfAttrsWith( 6721 *this, Function, /*ArgDependent=*/true, Loc, 6722 [&](const DiagnoseIfAttr *DIA) { 6723 APValue Result; 6724 // It's sane to use the same Args for any redecl of this function, since 6725 // EvaluateWithSubstitution only cares about the position of each 6726 // argument in the arg list, not the ParmVarDecl* it maps to. 6727 if (!DIA->getCond()->EvaluateWithSubstitution( 6728 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6729 return false; 6730 return Result.isInt() && Result.getInt().getBoolValue(); 6731 }); 6732 } 6733 6734 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6735 SourceLocation Loc) { 6736 return diagnoseDiagnoseIfAttrsWith( 6737 *this, ND, /*ArgDependent=*/false, Loc, 6738 [&](const DiagnoseIfAttr *DIA) { 6739 bool Result; 6740 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6741 Result; 6742 }); 6743 } 6744 6745 /// Add all of the function declarations in the given function set to 6746 /// the overload candidate set. 6747 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6748 ArrayRef<Expr *> Args, 6749 OverloadCandidateSet &CandidateSet, 6750 TemplateArgumentListInfo *ExplicitTemplateArgs, 6751 bool SuppressUserConversions, 6752 bool PartialOverloading, 6753 bool FirstArgumentIsBase) { 6754 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6755 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6756 ArrayRef<Expr *> FunctionArgs = Args; 6757 6758 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6759 FunctionDecl *FD = 6760 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6761 6762 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6763 QualType ObjectType; 6764 Expr::Classification ObjectClassification; 6765 if (Args.size() > 0) { 6766 if (Expr *E = Args[0]) { 6767 // Use the explicit base to restrict the lookup: 6768 ObjectType = E->getType(); 6769 // Pointers in the object arguments are implicitly dereferenced, so we 6770 // always classify them as l-values. 6771 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6772 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6773 else 6774 ObjectClassification = E->Classify(Context); 6775 } // .. else there is an implicit base. 6776 FunctionArgs = Args.slice(1); 6777 } 6778 if (FunTmpl) { 6779 AddMethodTemplateCandidate( 6780 FunTmpl, F.getPair(), 6781 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6782 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6783 FunctionArgs, CandidateSet, SuppressUserConversions, 6784 PartialOverloading); 6785 } else { 6786 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6787 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6788 ObjectClassification, FunctionArgs, CandidateSet, 6789 SuppressUserConversions, PartialOverloading); 6790 } 6791 } else { 6792 // This branch handles both standalone functions and static methods. 6793 6794 // Slice the first argument (which is the base) when we access 6795 // static method as non-static. 6796 if (Args.size() > 0 && 6797 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6798 !isa<CXXConstructorDecl>(FD)))) { 6799 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6800 FunctionArgs = Args.slice(1); 6801 } 6802 if (FunTmpl) { 6803 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6804 ExplicitTemplateArgs, FunctionArgs, 6805 CandidateSet, SuppressUserConversions, 6806 PartialOverloading); 6807 } else { 6808 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6809 SuppressUserConversions, PartialOverloading); 6810 } 6811 } 6812 } 6813 } 6814 6815 /// AddMethodCandidate - Adds a named decl (which is some kind of 6816 /// method) as a method candidate to the given overload set. 6817 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6818 Expr::Classification ObjectClassification, 6819 ArrayRef<Expr *> Args, 6820 OverloadCandidateSet &CandidateSet, 6821 bool SuppressUserConversions, 6822 OverloadCandidateParamOrder PO) { 6823 NamedDecl *Decl = FoundDecl.getDecl(); 6824 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6825 6826 if (isa<UsingShadowDecl>(Decl)) 6827 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6828 6829 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6830 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6831 "Expected a member function template"); 6832 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6833 /*ExplicitArgs*/ nullptr, ObjectType, 6834 ObjectClassification, Args, CandidateSet, 6835 SuppressUserConversions, false, PO); 6836 } else { 6837 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6838 ObjectType, ObjectClassification, Args, CandidateSet, 6839 SuppressUserConversions, false, None, PO); 6840 } 6841 } 6842 6843 /// AddMethodCandidate - Adds the given C++ member function to the set 6844 /// of candidate functions, using the given function call arguments 6845 /// and the object argument (@c Object). For example, in a call 6846 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6847 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6848 /// allow user-defined conversions via constructors or conversion 6849 /// operators. 6850 void 6851 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6852 CXXRecordDecl *ActingContext, QualType ObjectType, 6853 Expr::Classification ObjectClassification, 6854 ArrayRef<Expr *> Args, 6855 OverloadCandidateSet &CandidateSet, 6856 bool SuppressUserConversions, 6857 bool PartialOverloading, 6858 ConversionSequenceList EarlyConversions, 6859 OverloadCandidateParamOrder PO) { 6860 const FunctionProtoType *Proto 6861 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6862 assert(Proto && "Methods without a prototype cannot be overloaded"); 6863 assert(!isa<CXXConstructorDecl>(Method) && 6864 "Use AddOverloadCandidate for constructors"); 6865 6866 if (!CandidateSet.isNewCandidate(Method, PO)) 6867 return; 6868 6869 // C++11 [class.copy]p23: [DR1402] 6870 // A defaulted move assignment operator that is defined as deleted is 6871 // ignored by overload resolution. 6872 if (Method->isDefaulted() && Method->isDeleted() && 6873 Method->isMoveAssignmentOperator()) 6874 return; 6875 6876 // Overload resolution is always an unevaluated context. 6877 EnterExpressionEvaluationContext Unevaluated( 6878 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6879 6880 // Add this candidate 6881 OverloadCandidate &Candidate = 6882 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6883 Candidate.FoundDecl = FoundDecl; 6884 Candidate.Function = Method; 6885 Candidate.RewriteKind = 6886 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6887 Candidate.IsSurrogate = false; 6888 Candidate.IgnoreObjectArgument = false; 6889 Candidate.ExplicitCallArguments = Args.size(); 6890 6891 unsigned NumParams = Proto->getNumParams(); 6892 6893 // (C++ 13.3.2p2): A candidate function having fewer than m 6894 // parameters is viable only if it has an ellipsis in its parameter 6895 // list (8.3.5). 6896 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6897 !Proto->isVariadic()) { 6898 Candidate.Viable = false; 6899 Candidate.FailureKind = ovl_fail_too_many_arguments; 6900 return; 6901 } 6902 6903 // (C++ 13.3.2p2): A candidate function having more than m parameters 6904 // is viable only if the (m+1)st parameter has a default argument 6905 // (8.3.6). For the purposes of overload resolution, the 6906 // parameter list is truncated on the right, so that there are 6907 // exactly m parameters. 6908 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6909 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6910 // Not enough arguments. 6911 Candidate.Viable = false; 6912 Candidate.FailureKind = ovl_fail_too_few_arguments; 6913 return; 6914 } 6915 6916 Candidate.Viable = true; 6917 6918 if (Method->isStatic() || ObjectType.isNull()) 6919 // The implicit object argument is ignored. 6920 Candidate.IgnoreObjectArgument = true; 6921 else { 6922 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6923 // Determine the implicit conversion sequence for the object 6924 // parameter. 6925 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6926 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6927 Method, ActingContext); 6928 if (Candidate.Conversions[ConvIdx].isBad()) { 6929 Candidate.Viable = false; 6930 Candidate.FailureKind = ovl_fail_bad_conversion; 6931 return; 6932 } 6933 } 6934 6935 // (CUDA B.1): Check for invalid calls between targets. 6936 if (getLangOpts().CUDA) 6937 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6938 if (!IsAllowedCUDACall(Caller, Method)) { 6939 Candidate.Viable = false; 6940 Candidate.FailureKind = ovl_fail_bad_target; 6941 return; 6942 } 6943 6944 if (Method->getTrailingRequiresClause()) { 6945 ConstraintSatisfaction Satisfaction; 6946 if (CheckFunctionConstraints(Method, Satisfaction) || 6947 !Satisfaction.IsSatisfied) { 6948 Candidate.Viable = false; 6949 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6950 return; 6951 } 6952 } 6953 6954 // Determine the implicit conversion sequences for each of the 6955 // arguments. 6956 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6957 unsigned ConvIdx = 6958 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6959 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6960 // We already formed a conversion sequence for this parameter during 6961 // template argument deduction. 6962 } else if (ArgIdx < NumParams) { 6963 // (C++ 13.3.2p3): for F to be a viable function, there shall 6964 // exist for each argument an implicit conversion sequence 6965 // (13.3.3.1) that converts that argument to the corresponding 6966 // parameter of F. 6967 QualType ParamType = Proto->getParamType(ArgIdx); 6968 Candidate.Conversions[ConvIdx] 6969 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6970 SuppressUserConversions, 6971 /*InOverloadResolution=*/true, 6972 /*AllowObjCWritebackConversion=*/ 6973 getLangOpts().ObjCAutoRefCount); 6974 if (Candidate.Conversions[ConvIdx].isBad()) { 6975 Candidate.Viable = false; 6976 Candidate.FailureKind = ovl_fail_bad_conversion; 6977 return; 6978 } 6979 } else { 6980 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6981 // argument for which there is no corresponding parameter is 6982 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6983 Candidate.Conversions[ConvIdx].setEllipsis(); 6984 } 6985 } 6986 6987 if (EnableIfAttr *FailedAttr = 6988 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6989 Candidate.Viable = false; 6990 Candidate.FailureKind = ovl_fail_enable_if; 6991 Candidate.DeductionFailure.Data = FailedAttr; 6992 return; 6993 } 6994 6995 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6996 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6997 Candidate.Viable = false; 6998 Candidate.FailureKind = ovl_non_default_multiversion_function; 6999 } 7000 } 7001 7002 /// Add a C++ member function template as a candidate to the candidate 7003 /// set, using template argument deduction to produce an appropriate member 7004 /// function template specialization. 7005 void Sema::AddMethodTemplateCandidate( 7006 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7007 CXXRecordDecl *ActingContext, 7008 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7009 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7010 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7011 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7012 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7013 return; 7014 7015 // C++ [over.match.funcs]p7: 7016 // In each case where a candidate is a function template, candidate 7017 // function template specializations are generated using template argument 7018 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7019 // candidate functions in the usual way.113) A given name can refer to one 7020 // or more function templates and also to a set of overloaded non-template 7021 // functions. In such a case, the candidate functions generated from each 7022 // function template are combined with the set of non-template candidate 7023 // functions. 7024 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7025 FunctionDecl *Specialization = nullptr; 7026 ConversionSequenceList Conversions; 7027 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7028 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7029 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7030 return CheckNonDependentConversions( 7031 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7032 SuppressUserConversions, ActingContext, ObjectType, 7033 ObjectClassification, PO); 7034 })) { 7035 OverloadCandidate &Candidate = 7036 CandidateSet.addCandidate(Conversions.size(), Conversions); 7037 Candidate.FoundDecl = FoundDecl; 7038 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7039 Candidate.Viable = false; 7040 Candidate.RewriteKind = 7041 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7042 Candidate.IsSurrogate = false; 7043 Candidate.IgnoreObjectArgument = 7044 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7045 ObjectType.isNull(); 7046 Candidate.ExplicitCallArguments = Args.size(); 7047 if (Result == TDK_NonDependentConversionFailure) 7048 Candidate.FailureKind = ovl_fail_bad_conversion; 7049 else { 7050 Candidate.FailureKind = ovl_fail_bad_deduction; 7051 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7052 Info); 7053 } 7054 return; 7055 } 7056 7057 // Add the function template specialization produced by template argument 7058 // deduction as a candidate. 7059 assert(Specialization && "Missing member function template specialization?"); 7060 assert(isa<CXXMethodDecl>(Specialization) && 7061 "Specialization is not a member function?"); 7062 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7063 ActingContext, ObjectType, ObjectClassification, Args, 7064 CandidateSet, SuppressUserConversions, PartialOverloading, 7065 Conversions, PO); 7066 } 7067 7068 /// Determine whether a given function template has a simple explicit specifier 7069 /// or a non-value-dependent explicit-specification that evaluates to true. 7070 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7071 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7072 } 7073 7074 /// Add a C++ function template specialization as a candidate 7075 /// in the candidate set, using template argument deduction to produce 7076 /// an appropriate function template specialization. 7077 void Sema::AddTemplateOverloadCandidate( 7078 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7079 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7080 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7081 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7082 OverloadCandidateParamOrder PO) { 7083 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7084 return; 7085 7086 // If the function template has a non-dependent explicit specification, 7087 // exclude it now if appropriate; we are not permitted to perform deduction 7088 // and substitution in this case. 7089 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7090 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7091 Candidate.FoundDecl = FoundDecl; 7092 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7093 Candidate.Viable = false; 7094 Candidate.FailureKind = ovl_fail_explicit; 7095 return; 7096 } 7097 7098 // C++ [over.match.funcs]p7: 7099 // In each case where a candidate is a function template, candidate 7100 // function template specializations are generated using template argument 7101 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7102 // candidate functions in the usual way.113) A given name can refer to one 7103 // or more function templates and also to a set of overloaded non-template 7104 // functions. In such a case, the candidate functions generated from each 7105 // function template are combined with the set of non-template candidate 7106 // functions. 7107 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7108 FunctionDecl *Specialization = nullptr; 7109 ConversionSequenceList Conversions; 7110 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7111 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7112 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7113 return CheckNonDependentConversions( 7114 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7115 SuppressUserConversions, nullptr, QualType(), {}, PO); 7116 })) { 7117 OverloadCandidate &Candidate = 7118 CandidateSet.addCandidate(Conversions.size(), Conversions); 7119 Candidate.FoundDecl = FoundDecl; 7120 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7121 Candidate.Viable = false; 7122 Candidate.RewriteKind = 7123 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7124 Candidate.IsSurrogate = false; 7125 Candidate.IsADLCandidate = IsADLCandidate; 7126 // Ignore the object argument if there is one, since we don't have an object 7127 // type. 7128 Candidate.IgnoreObjectArgument = 7129 isa<CXXMethodDecl>(Candidate.Function) && 7130 !isa<CXXConstructorDecl>(Candidate.Function); 7131 Candidate.ExplicitCallArguments = Args.size(); 7132 if (Result == TDK_NonDependentConversionFailure) 7133 Candidate.FailureKind = ovl_fail_bad_conversion; 7134 else { 7135 Candidate.FailureKind = ovl_fail_bad_deduction; 7136 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7137 Info); 7138 } 7139 return; 7140 } 7141 7142 // Add the function template specialization produced by template argument 7143 // deduction as a candidate. 7144 assert(Specialization && "Missing function template specialization?"); 7145 AddOverloadCandidate( 7146 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7147 PartialOverloading, AllowExplicit, 7148 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7149 } 7150 7151 /// Check that implicit conversion sequences can be formed for each argument 7152 /// whose corresponding parameter has a non-dependent type, per DR1391's 7153 /// [temp.deduct.call]p10. 7154 bool Sema::CheckNonDependentConversions( 7155 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7156 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7157 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7158 CXXRecordDecl *ActingContext, QualType ObjectType, 7159 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7160 // FIXME: The cases in which we allow explicit conversions for constructor 7161 // arguments never consider calling a constructor template. It's not clear 7162 // that is correct. 7163 const bool AllowExplicit = false; 7164 7165 auto *FD = FunctionTemplate->getTemplatedDecl(); 7166 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7167 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7168 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7169 7170 Conversions = 7171 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7172 7173 // Overload resolution is always an unevaluated context. 7174 EnterExpressionEvaluationContext Unevaluated( 7175 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7176 7177 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7178 // require that, but this check should never result in a hard error, and 7179 // overload resolution is permitted to sidestep instantiations. 7180 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7181 !ObjectType.isNull()) { 7182 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7183 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7184 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7185 Method, ActingContext); 7186 if (Conversions[ConvIdx].isBad()) 7187 return true; 7188 } 7189 7190 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7191 ++I) { 7192 QualType ParamType = ParamTypes[I]; 7193 if (!ParamType->isDependentType()) { 7194 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7195 ? 0 7196 : (ThisConversions + I); 7197 Conversions[ConvIdx] 7198 = TryCopyInitialization(*this, Args[I], ParamType, 7199 SuppressUserConversions, 7200 /*InOverloadResolution=*/true, 7201 /*AllowObjCWritebackConversion=*/ 7202 getLangOpts().ObjCAutoRefCount, 7203 AllowExplicit); 7204 if (Conversions[ConvIdx].isBad()) 7205 return true; 7206 } 7207 } 7208 7209 return false; 7210 } 7211 7212 /// Determine whether this is an allowable conversion from the result 7213 /// of an explicit conversion operator to the expected type, per C++ 7214 /// [over.match.conv]p1 and [over.match.ref]p1. 7215 /// 7216 /// \param ConvType The return type of the conversion function. 7217 /// 7218 /// \param ToType The type we are converting to. 7219 /// 7220 /// \param AllowObjCPointerConversion Allow a conversion from one 7221 /// Objective-C pointer to another. 7222 /// 7223 /// \returns true if the conversion is allowable, false otherwise. 7224 static bool isAllowableExplicitConversion(Sema &S, 7225 QualType ConvType, QualType ToType, 7226 bool AllowObjCPointerConversion) { 7227 QualType ToNonRefType = ToType.getNonReferenceType(); 7228 7229 // Easy case: the types are the same. 7230 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7231 return true; 7232 7233 // Allow qualification conversions. 7234 bool ObjCLifetimeConversion; 7235 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7236 ObjCLifetimeConversion)) 7237 return true; 7238 7239 // If we're not allowed to consider Objective-C pointer conversions, 7240 // we're done. 7241 if (!AllowObjCPointerConversion) 7242 return false; 7243 7244 // Is this an Objective-C pointer conversion? 7245 bool IncompatibleObjC = false; 7246 QualType ConvertedType; 7247 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7248 IncompatibleObjC); 7249 } 7250 7251 /// AddConversionCandidate - Add a C++ conversion function as a 7252 /// candidate in the candidate set (C++ [over.match.conv], 7253 /// C++ [over.match.copy]). From is the expression we're converting from, 7254 /// and ToType is the type that we're eventually trying to convert to 7255 /// (which may or may not be the same type as the type that the 7256 /// conversion function produces). 7257 void Sema::AddConversionCandidate( 7258 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7259 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7260 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7261 bool AllowExplicit, bool AllowResultConversion) { 7262 assert(!Conversion->getDescribedFunctionTemplate() && 7263 "Conversion function templates use AddTemplateConversionCandidate"); 7264 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7265 if (!CandidateSet.isNewCandidate(Conversion)) 7266 return; 7267 7268 // If the conversion function has an undeduced return type, trigger its 7269 // deduction now. 7270 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7271 if (DeduceReturnType(Conversion, From->getExprLoc())) 7272 return; 7273 ConvType = Conversion->getConversionType().getNonReferenceType(); 7274 } 7275 7276 // If we don't allow any conversion of the result type, ignore conversion 7277 // functions that don't convert to exactly (possibly cv-qualified) T. 7278 if (!AllowResultConversion && 7279 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7280 return; 7281 7282 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7283 // operator is only a candidate if its return type is the target type or 7284 // can be converted to the target type with a qualification conversion. 7285 // 7286 // FIXME: Include such functions in the candidate list and explain why we 7287 // can't select them. 7288 if (Conversion->isExplicit() && 7289 !isAllowableExplicitConversion(*this, ConvType, ToType, 7290 AllowObjCConversionOnExplicit)) 7291 return; 7292 7293 // Overload resolution is always an unevaluated context. 7294 EnterExpressionEvaluationContext Unevaluated( 7295 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7296 7297 // Add this candidate 7298 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7299 Candidate.FoundDecl = FoundDecl; 7300 Candidate.Function = Conversion; 7301 Candidate.IsSurrogate = false; 7302 Candidate.IgnoreObjectArgument = false; 7303 Candidate.FinalConversion.setAsIdentityConversion(); 7304 Candidate.FinalConversion.setFromType(ConvType); 7305 Candidate.FinalConversion.setAllToTypes(ToType); 7306 Candidate.Viable = true; 7307 Candidate.ExplicitCallArguments = 1; 7308 7309 // Explicit functions are not actually candidates at all if we're not 7310 // allowing them in this context, but keep them around so we can point 7311 // to them in diagnostics. 7312 if (!AllowExplicit && Conversion->isExplicit()) { 7313 Candidate.Viable = false; 7314 Candidate.FailureKind = ovl_fail_explicit; 7315 return; 7316 } 7317 7318 // C++ [over.match.funcs]p4: 7319 // For conversion functions, the function is considered to be a member of 7320 // the class of the implicit implied object argument for the purpose of 7321 // defining the type of the implicit object parameter. 7322 // 7323 // Determine the implicit conversion sequence for the implicit 7324 // object parameter. 7325 QualType ImplicitParamType = From->getType(); 7326 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7327 ImplicitParamType = FromPtrType->getPointeeType(); 7328 CXXRecordDecl *ConversionContext 7329 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7330 7331 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7332 *this, CandidateSet.getLocation(), From->getType(), 7333 From->Classify(Context), Conversion, ConversionContext); 7334 7335 if (Candidate.Conversions[0].isBad()) { 7336 Candidate.Viable = false; 7337 Candidate.FailureKind = ovl_fail_bad_conversion; 7338 return; 7339 } 7340 7341 if (Conversion->getTrailingRequiresClause()) { 7342 ConstraintSatisfaction Satisfaction; 7343 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7344 !Satisfaction.IsSatisfied) { 7345 Candidate.Viable = false; 7346 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7347 return; 7348 } 7349 } 7350 7351 // We won't go through a user-defined type conversion function to convert a 7352 // derived to base as such conversions are given Conversion Rank. They only 7353 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7354 QualType FromCanon 7355 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7356 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7357 if (FromCanon == ToCanon || 7358 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7359 Candidate.Viable = false; 7360 Candidate.FailureKind = ovl_fail_trivial_conversion; 7361 return; 7362 } 7363 7364 // To determine what the conversion from the result of calling the 7365 // conversion function to the type we're eventually trying to 7366 // convert to (ToType), we need to synthesize a call to the 7367 // conversion function and attempt copy initialization from it. This 7368 // makes sure that we get the right semantics with respect to 7369 // lvalues/rvalues and the type. Fortunately, we can allocate this 7370 // call on the stack and we don't need its arguments to be 7371 // well-formed. 7372 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7373 VK_LValue, From->getBeginLoc()); 7374 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7375 Context.getPointerType(Conversion->getType()), 7376 CK_FunctionToPointerDecay, &ConversionRef, 7377 VK_RValue, FPOptionsOverride()); 7378 7379 QualType ConversionType = Conversion->getConversionType(); 7380 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7381 Candidate.Viable = false; 7382 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7383 return; 7384 } 7385 7386 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7387 7388 // Note that it is safe to allocate CallExpr on the stack here because 7389 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7390 // allocator). 7391 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7392 7393 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7394 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7395 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7396 7397 ImplicitConversionSequence ICS = 7398 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7399 /*SuppressUserConversions=*/true, 7400 /*InOverloadResolution=*/false, 7401 /*AllowObjCWritebackConversion=*/false); 7402 7403 switch (ICS.getKind()) { 7404 case ImplicitConversionSequence::StandardConversion: 7405 Candidate.FinalConversion = ICS.Standard; 7406 7407 // C++ [over.ics.user]p3: 7408 // If the user-defined conversion is specified by a specialization of a 7409 // conversion function template, the second standard conversion sequence 7410 // shall have exact match rank. 7411 if (Conversion->getPrimaryTemplate() && 7412 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7413 Candidate.Viable = false; 7414 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7415 return; 7416 } 7417 7418 // C++0x [dcl.init.ref]p5: 7419 // In the second case, if the reference is an rvalue reference and 7420 // the second standard conversion sequence of the user-defined 7421 // conversion sequence includes an lvalue-to-rvalue conversion, the 7422 // program is ill-formed. 7423 if (ToType->isRValueReferenceType() && 7424 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7425 Candidate.Viable = false; 7426 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7427 return; 7428 } 7429 break; 7430 7431 case ImplicitConversionSequence::BadConversion: 7432 Candidate.Viable = false; 7433 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7434 return; 7435 7436 default: 7437 llvm_unreachable( 7438 "Can only end up with a standard conversion sequence or failure"); 7439 } 7440 7441 if (EnableIfAttr *FailedAttr = 7442 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7443 Candidate.Viable = false; 7444 Candidate.FailureKind = ovl_fail_enable_if; 7445 Candidate.DeductionFailure.Data = FailedAttr; 7446 return; 7447 } 7448 7449 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7450 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7451 Candidate.Viable = false; 7452 Candidate.FailureKind = ovl_non_default_multiversion_function; 7453 } 7454 } 7455 7456 /// Adds a conversion function template specialization 7457 /// candidate to the overload set, using template argument deduction 7458 /// to deduce the template arguments of the conversion function 7459 /// template from the type that we are converting to (C++ 7460 /// [temp.deduct.conv]). 7461 void Sema::AddTemplateConversionCandidate( 7462 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7463 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7464 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7465 bool AllowExplicit, bool AllowResultConversion) { 7466 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7467 "Only conversion function templates permitted here"); 7468 7469 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7470 return; 7471 7472 // If the function template has a non-dependent explicit specification, 7473 // exclude it now if appropriate; we are not permitted to perform deduction 7474 // and substitution in this case. 7475 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7476 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7477 Candidate.FoundDecl = FoundDecl; 7478 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7479 Candidate.Viable = false; 7480 Candidate.FailureKind = ovl_fail_explicit; 7481 return; 7482 } 7483 7484 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7485 CXXConversionDecl *Specialization = nullptr; 7486 if (TemplateDeductionResult Result 7487 = DeduceTemplateArguments(FunctionTemplate, ToType, 7488 Specialization, Info)) { 7489 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7490 Candidate.FoundDecl = FoundDecl; 7491 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7492 Candidate.Viable = false; 7493 Candidate.FailureKind = ovl_fail_bad_deduction; 7494 Candidate.IsSurrogate = false; 7495 Candidate.IgnoreObjectArgument = false; 7496 Candidate.ExplicitCallArguments = 1; 7497 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7498 Info); 7499 return; 7500 } 7501 7502 // Add the conversion function template specialization produced by 7503 // template argument deduction as a candidate. 7504 assert(Specialization && "Missing function template specialization?"); 7505 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7506 CandidateSet, AllowObjCConversionOnExplicit, 7507 AllowExplicit, AllowResultConversion); 7508 } 7509 7510 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7511 /// converts the given @c Object to a function pointer via the 7512 /// conversion function @c Conversion, and then attempts to call it 7513 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7514 /// the type of function that we'll eventually be calling. 7515 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7516 DeclAccessPair FoundDecl, 7517 CXXRecordDecl *ActingContext, 7518 const FunctionProtoType *Proto, 7519 Expr *Object, 7520 ArrayRef<Expr *> Args, 7521 OverloadCandidateSet& CandidateSet) { 7522 if (!CandidateSet.isNewCandidate(Conversion)) 7523 return; 7524 7525 // Overload resolution is always an unevaluated context. 7526 EnterExpressionEvaluationContext Unevaluated( 7527 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7528 7529 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7530 Candidate.FoundDecl = FoundDecl; 7531 Candidate.Function = nullptr; 7532 Candidate.Surrogate = Conversion; 7533 Candidate.Viable = true; 7534 Candidate.IsSurrogate = true; 7535 Candidate.IgnoreObjectArgument = false; 7536 Candidate.ExplicitCallArguments = Args.size(); 7537 7538 // Determine the implicit conversion sequence for the implicit 7539 // object parameter. 7540 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7541 *this, CandidateSet.getLocation(), Object->getType(), 7542 Object->Classify(Context), Conversion, ActingContext); 7543 if (ObjectInit.isBad()) { 7544 Candidate.Viable = false; 7545 Candidate.FailureKind = ovl_fail_bad_conversion; 7546 Candidate.Conversions[0] = ObjectInit; 7547 return; 7548 } 7549 7550 // The first conversion is actually a user-defined conversion whose 7551 // first conversion is ObjectInit's standard conversion (which is 7552 // effectively a reference binding). Record it as such. 7553 Candidate.Conversions[0].setUserDefined(); 7554 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7555 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7556 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7557 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7558 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7559 Candidate.Conversions[0].UserDefined.After 7560 = Candidate.Conversions[0].UserDefined.Before; 7561 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7562 7563 // Find the 7564 unsigned NumParams = Proto->getNumParams(); 7565 7566 // (C++ 13.3.2p2): A candidate function having fewer than m 7567 // parameters is viable only if it has an ellipsis in its parameter 7568 // list (8.3.5). 7569 if (Args.size() > NumParams && !Proto->isVariadic()) { 7570 Candidate.Viable = false; 7571 Candidate.FailureKind = ovl_fail_too_many_arguments; 7572 return; 7573 } 7574 7575 // Function types don't have any default arguments, so just check if 7576 // we have enough arguments. 7577 if (Args.size() < NumParams) { 7578 // Not enough arguments. 7579 Candidate.Viable = false; 7580 Candidate.FailureKind = ovl_fail_too_few_arguments; 7581 return; 7582 } 7583 7584 // Determine the implicit conversion sequences for each of the 7585 // arguments. 7586 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7587 if (ArgIdx < NumParams) { 7588 // (C++ 13.3.2p3): for F to be a viable function, there shall 7589 // exist for each argument an implicit conversion sequence 7590 // (13.3.3.1) that converts that argument to the corresponding 7591 // parameter of F. 7592 QualType ParamType = Proto->getParamType(ArgIdx); 7593 Candidate.Conversions[ArgIdx + 1] 7594 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7595 /*SuppressUserConversions=*/false, 7596 /*InOverloadResolution=*/false, 7597 /*AllowObjCWritebackConversion=*/ 7598 getLangOpts().ObjCAutoRefCount); 7599 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7600 Candidate.Viable = false; 7601 Candidate.FailureKind = ovl_fail_bad_conversion; 7602 return; 7603 } 7604 } else { 7605 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7606 // argument for which there is no corresponding parameter is 7607 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7608 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7609 } 7610 } 7611 7612 if (EnableIfAttr *FailedAttr = 7613 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7614 Candidate.Viable = false; 7615 Candidate.FailureKind = ovl_fail_enable_if; 7616 Candidate.DeductionFailure.Data = FailedAttr; 7617 return; 7618 } 7619 } 7620 7621 /// Add all of the non-member operator function declarations in the given 7622 /// function set to the overload candidate set. 7623 void Sema::AddNonMemberOperatorCandidates( 7624 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7625 OverloadCandidateSet &CandidateSet, 7626 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7627 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7628 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7629 ArrayRef<Expr *> FunctionArgs = Args; 7630 7631 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7632 FunctionDecl *FD = 7633 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7634 7635 // Don't consider rewritten functions if we're not rewriting. 7636 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7637 continue; 7638 7639 assert(!isa<CXXMethodDecl>(FD) && 7640 "unqualified operator lookup found a member function"); 7641 7642 if (FunTmpl) { 7643 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7644 FunctionArgs, CandidateSet); 7645 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7646 AddTemplateOverloadCandidate( 7647 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7648 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7649 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7650 } else { 7651 if (ExplicitTemplateArgs) 7652 continue; 7653 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7654 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7655 AddOverloadCandidate(FD, F.getPair(), 7656 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7657 false, false, true, false, ADLCallKind::NotADL, 7658 None, OverloadCandidateParamOrder::Reversed); 7659 } 7660 } 7661 } 7662 7663 /// Add overload candidates for overloaded operators that are 7664 /// member functions. 7665 /// 7666 /// Add the overloaded operator candidates that are member functions 7667 /// for the operator Op that was used in an operator expression such 7668 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7669 /// CandidateSet will store the added overload candidates. (C++ 7670 /// [over.match.oper]). 7671 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7672 SourceLocation OpLoc, 7673 ArrayRef<Expr *> Args, 7674 OverloadCandidateSet &CandidateSet, 7675 OverloadCandidateParamOrder PO) { 7676 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7677 7678 // C++ [over.match.oper]p3: 7679 // For a unary operator @ with an operand of a type whose 7680 // cv-unqualified version is T1, and for a binary operator @ with 7681 // a left operand of a type whose cv-unqualified version is T1 and 7682 // a right operand of a type whose cv-unqualified version is T2, 7683 // three sets of candidate functions, designated member 7684 // candidates, non-member candidates and built-in candidates, are 7685 // constructed as follows: 7686 QualType T1 = Args[0]->getType(); 7687 7688 // -- If T1 is a complete class type or a class currently being 7689 // defined, the set of member candidates is the result of the 7690 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7691 // the set of member candidates is empty. 7692 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7693 // Complete the type if it can be completed. 7694 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7695 return; 7696 // If the type is neither complete nor being defined, bail out now. 7697 if (!T1Rec->getDecl()->getDefinition()) 7698 return; 7699 7700 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7701 LookupQualifiedName(Operators, T1Rec->getDecl()); 7702 Operators.suppressDiagnostics(); 7703 7704 for (LookupResult::iterator Oper = Operators.begin(), 7705 OperEnd = Operators.end(); 7706 Oper != OperEnd; 7707 ++Oper) 7708 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7709 Args[0]->Classify(Context), Args.slice(1), 7710 CandidateSet, /*SuppressUserConversion=*/false, PO); 7711 } 7712 } 7713 7714 /// AddBuiltinCandidate - Add a candidate for a built-in 7715 /// operator. ResultTy and ParamTys are the result and parameter types 7716 /// of the built-in candidate, respectively. Args and NumArgs are the 7717 /// arguments being passed to the candidate. IsAssignmentOperator 7718 /// should be true when this built-in candidate is an assignment 7719 /// operator. NumContextualBoolArguments is the number of arguments 7720 /// (at the beginning of the argument list) that will be contextually 7721 /// converted to bool. 7722 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7723 OverloadCandidateSet& CandidateSet, 7724 bool IsAssignmentOperator, 7725 unsigned NumContextualBoolArguments) { 7726 // Overload resolution is always an unevaluated context. 7727 EnterExpressionEvaluationContext Unevaluated( 7728 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7729 7730 // Add this candidate 7731 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7732 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7733 Candidate.Function = nullptr; 7734 Candidate.IsSurrogate = false; 7735 Candidate.IgnoreObjectArgument = false; 7736 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7737 7738 // Determine the implicit conversion sequences for each of the 7739 // arguments. 7740 Candidate.Viable = true; 7741 Candidate.ExplicitCallArguments = Args.size(); 7742 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7743 // C++ [over.match.oper]p4: 7744 // For the built-in assignment operators, conversions of the 7745 // left operand are restricted as follows: 7746 // -- no temporaries are introduced to hold the left operand, and 7747 // -- no user-defined conversions are applied to the left 7748 // operand to achieve a type match with the left-most 7749 // parameter of a built-in candidate. 7750 // 7751 // We block these conversions by turning off user-defined 7752 // conversions, since that is the only way that initialization of 7753 // a reference to a non-class type can occur from something that 7754 // is not of the same type. 7755 if (ArgIdx < NumContextualBoolArguments) { 7756 assert(ParamTys[ArgIdx] == Context.BoolTy && 7757 "Contextual conversion to bool requires bool type"); 7758 Candidate.Conversions[ArgIdx] 7759 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7760 } else { 7761 Candidate.Conversions[ArgIdx] 7762 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7763 ArgIdx == 0 && IsAssignmentOperator, 7764 /*InOverloadResolution=*/false, 7765 /*AllowObjCWritebackConversion=*/ 7766 getLangOpts().ObjCAutoRefCount); 7767 } 7768 if (Candidate.Conversions[ArgIdx].isBad()) { 7769 Candidate.Viable = false; 7770 Candidate.FailureKind = ovl_fail_bad_conversion; 7771 break; 7772 } 7773 } 7774 } 7775 7776 namespace { 7777 7778 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7779 /// candidate operator functions for built-in operators (C++ 7780 /// [over.built]). The types are separated into pointer types and 7781 /// enumeration types. 7782 class BuiltinCandidateTypeSet { 7783 /// TypeSet - A set of types. 7784 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7785 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7786 7787 /// PointerTypes - The set of pointer types that will be used in the 7788 /// built-in candidates. 7789 TypeSet PointerTypes; 7790 7791 /// MemberPointerTypes - The set of member pointer types that will be 7792 /// used in the built-in candidates. 7793 TypeSet MemberPointerTypes; 7794 7795 /// EnumerationTypes - The set of enumeration types that will be 7796 /// used in the built-in candidates. 7797 TypeSet EnumerationTypes; 7798 7799 /// The set of vector types that will be used in the built-in 7800 /// candidates. 7801 TypeSet VectorTypes; 7802 7803 /// The set of matrix types that will be used in the built-in 7804 /// candidates. 7805 TypeSet MatrixTypes; 7806 7807 /// A flag indicating non-record types are viable candidates 7808 bool HasNonRecordTypes; 7809 7810 /// A flag indicating whether either arithmetic or enumeration types 7811 /// were present in the candidate set. 7812 bool HasArithmeticOrEnumeralTypes; 7813 7814 /// A flag indicating whether the nullptr type was present in the 7815 /// candidate set. 7816 bool HasNullPtrType; 7817 7818 /// Sema - The semantic analysis instance where we are building the 7819 /// candidate type set. 7820 Sema &SemaRef; 7821 7822 /// Context - The AST context in which we will build the type sets. 7823 ASTContext &Context; 7824 7825 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7826 const Qualifiers &VisibleQuals); 7827 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7828 7829 public: 7830 /// iterator - Iterates through the types that are part of the set. 7831 typedef TypeSet::iterator iterator; 7832 7833 BuiltinCandidateTypeSet(Sema &SemaRef) 7834 : HasNonRecordTypes(false), 7835 HasArithmeticOrEnumeralTypes(false), 7836 HasNullPtrType(false), 7837 SemaRef(SemaRef), 7838 Context(SemaRef.Context) { } 7839 7840 void AddTypesConvertedFrom(QualType Ty, 7841 SourceLocation Loc, 7842 bool AllowUserConversions, 7843 bool AllowExplicitConversions, 7844 const Qualifiers &VisibleTypeConversionsQuals); 7845 7846 /// pointer_begin - First pointer type found; 7847 iterator pointer_begin() { return PointerTypes.begin(); } 7848 7849 /// pointer_end - Past the last pointer type found; 7850 iterator pointer_end() { return PointerTypes.end(); } 7851 7852 /// member_pointer_begin - First member pointer type found; 7853 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7854 7855 /// member_pointer_end - Past the last member pointer type found; 7856 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7857 7858 /// enumeration_begin - First enumeration type found; 7859 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7860 7861 /// enumeration_end - Past the last enumeration type found; 7862 iterator enumeration_end() { return EnumerationTypes.end(); } 7863 7864 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7865 7866 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7867 7868 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7869 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7870 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7871 bool hasNullPtrType() const { return HasNullPtrType; } 7872 }; 7873 7874 } // end anonymous namespace 7875 7876 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7877 /// the set of pointer types along with any more-qualified variants of 7878 /// that type. For example, if @p Ty is "int const *", this routine 7879 /// will add "int const *", "int const volatile *", "int const 7880 /// restrict *", and "int const volatile restrict *" to the set of 7881 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7882 /// false otherwise. 7883 /// 7884 /// FIXME: what to do about extended qualifiers? 7885 bool 7886 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7887 const Qualifiers &VisibleQuals) { 7888 7889 // Insert this type. 7890 if (!PointerTypes.insert(Ty)) 7891 return false; 7892 7893 QualType PointeeTy; 7894 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7895 bool buildObjCPtr = false; 7896 if (!PointerTy) { 7897 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7898 PointeeTy = PTy->getPointeeType(); 7899 buildObjCPtr = true; 7900 } else { 7901 PointeeTy = PointerTy->getPointeeType(); 7902 } 7903 7904 // Don't add qualified variants of arrays. For one, they're not allowed 7905 // (the qualifier would sink to the element type), and for another, the 7906 // only overload situation where it matters is subscript or pointer +- int, 7907 // and those shouldn't have qualifier variants anyway. 7908 if (PointeeTy->isArrayType()) 7909 return true; 7910 7911 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7912 bool hasVolatile = VisibleQuals.hasVolatile(); 7913 bool hasRestrict = VisibleQuals.hasRestrict(); 7914 7915 // Iterate through all strict supersets of BaseCVR. 7916 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7917 if ((CVR | BaseCVR) != CVR) continue; 7918 // Skip over volatile if no volatile found anywhere in the types. 7919 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7920 7921 // Skip over restrict if no restrict found anywhere in the types, or if 7922 // the type cannot be restrict-qualified. 7923 if ((CVR & Qualifiers::Restrict) && 7924 (!hasRestrict || 7925 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7926 continue; 7927 7928 // Build qualified pointee type. 7929 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7930 7931 // Build qualified pointer type. 7932 QualType QPointerTy; 7933 if (!buildObjCPtr) 7934 QPointerTy = Context.getPointerType(QPointeeTy); 7935 else 7936 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7937 7938 // Insert qualified pointer type. 7939 PointerTypes.insert(QPointerTy); 7940 } 7941 7942 return true; 7943 } 7944 7945 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7946 /// to the set of pointer types along with any more-qualified variants of 7947 /// that type. For example, if @p Ty is "int const *", this routine 7948 /// will add "int const *", "int const volatile *", "int const 7949 /// restrict *", and "int const volatile restrict *" to the set of 7950 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7951 /// false otherwise. 7952 /// 7953 /// FIXME: what to do about extended qualifiers? 7954 bool 7955 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7956 QualType Ty) { 7957 // Insert this type. 7958 if (!MemberPointerTypes.insert(Ty)) 7959 return false; 7960 7961 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7962 assert(PointerTy && "type was not a member pointer type!"); 7963 7964 QualType PointeeTy = PointerTy->getPointeeType(); 7965 // Don't add qualified variants of arrays. For one, they're not allowed 7966 // (the qualifier would sink to the element type), and for another, the 7967 // only overload situation where it matters is subscript or pointer +- int, 7968 // and those shouldn't have qualifier variants anyway. 7969 if (PointeeTy->isArrayType()) 7970 return true; 7971 const Type *ClassTy = PointerTy->getClass(); 7972 7973 // Iterate through all strict supersets of the pointee type's CVR 7974 // qualifiers. 7975 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7976 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7977 if ((CVR | BaseCVR) != CVR) continue; 7978 7979 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7980 MemberPointerTypes.insert( 7981 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7982 } 7983 7984 return true; 7985 } 7986 7987 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7988 /// Ty can be implicit converted to the given set of @p Types. We're 7989 /// primarily interested in pointer types and enumeration types. We also 7990 /// take member pointer types, for the conditional operator. 7991 /// AllowUserConversions is true if we should look at the conversion 7992 /// functions of a class type, and AllowExplicitConversions if we 7993 /// should also include the explicit conversion functions of a class 7994 /// type. 7995 void 7996 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7997 SourceLocation Loc, 7998 bool AllowUserConversions, 7999 bool AllowExplicitConversions, 8000 const Qualifiers &VisibleQuals) { 8001 // Only deal with canonical types. 8002 Ty = Context.getCanonicalType(Ty); 8003 8004 // Look through reference types; they aren't part of the type of an 8005 // expression for the purposes of conversions. 8006 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8007 Ty = RefTy->getPointeeType(); 8008 8009 // If we're dealing with an array type, decay to the pointer. 8010 if (Ty->isArrayType()) 8011 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8012 8013 // Otherwise, we don't care about qualifiers on the type. 8014 Ty = Ty.getLocalUnqualifiedType(); 8015 8016 // Flag if we ever add a non-record type. 8017 const RecordType *TyRec = Ty->getAs<RecordType>(); 8018 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8019 8020 // Flag if we encounter an arithmetic type. 8021 HasArithmeticOrEnumeralTypes = 8022 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8023 8024 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8025 PointerTypes.insert(Ty); 8026 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8027 // Insert our type, and its more-qualified variants, into the set 8028 // of types. 8029 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8030 return; 8031 } else if (Ty->isMemberPointerType()) { 8032 // Member pointers are far easier, since the pointee can't be converted. 8033 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8034 return; 8035 } else if (Ty->isEnumeralType()) { 8036 HasArithmeticOrEnumeralTypes = true; 8037 EnumerationTypes.insert(Ty); 8038 } else if (Ty->isVectorType()) { 8039 // We treat vector types as arithmetic types in many contexts as an 8040 // extension. 8041 HasArithmeticOrEnumeralTypes = true; 8042 VectorTypes.insert(Ty); 8043 } else if (Ty->isMatrixType()) { 8044 // Similar to vector types, we treat vector types as arithmetic types in 8045 // many contexts as an extension. 8046 HasArithmeticOrEnumeralTypes = true; 8047 MatrixTypes.insert(Ty); 8048 } else if (Ty->isNullPtrType()) { 8049 HasNullPtrType = true; 8050 } else if (AllowUserConversions && TyRec) { 8051 // No conversion functions in incomplete types. 8052 if (!SemaRef.isCompleteType(Loc, Ty)) 8053 return; 8054 8055 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8056 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8057 if (isa<UsingShadowDecl>(D)) 8058 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8059 8060 // Skip conversion function templates; they don't tell us anything 8061 // about which builtin types we can convert to. 8062 if (isa<FunctionTemplateDecl>(D)) 8063 continue; 8064 8065 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8066 if (AllowExplicitConversions || !Conv->isExplicit()) { 8067 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8068 VisibleQuals); 8069 } 8070 } 8071 } 8072 } 8073 /// Helper function for adjusting address spaces for the pointer or reference 8074 /// operands of builtin operators depending on the argument. 8075 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8076 Expr *Arg) { 8077 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8078 } 8079 8080 /// Helper function for AddBuiltinOperatorCandidates() that adds 8081 /// the volatile- and non-volatile-qualified assignment operators for the 8082 /// given type to the candidate set. 8083 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8084 QualType T, 8085 ArrayRef<Expr *> Args, 8086 OverloadCandidateSet &CandidateSet) { 8087 QualType ParamTypes[2]; 8088 8089 // T& operator=(T&, T) 8090 ParamTypes[0] = S.Context.getLValueReferenceType( 8091 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8092 ParamTypes[1] = T; 8093 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8094 /*IsAssignmentOperator=*/true); 8095 8096 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8097 // volatile T& operator=(volatile T&, T) 8098 ParamTypes[0] = S.Context.getLValueReferenceType( 8099 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8100 Args[0])); 8101 ParamTypes[1] = T; 8102 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8103 /*IsAssignmentOperator=*/true); 8104 } 8105 } 8106 8107 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8108 /// if any, found in visible type conversion functions found in ArgExpr's type. 8109 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8110 Qualifiers VRQuals; 8111 const RecordType *TyRec; 8112 if (const MemberPointerType *RHSMPType = 8113 ArgExpr->getType()->getAs<MemberPointerType>()) 8114 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8115 else 8116 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8117 if (!TyRec) { 8118 // Just to be safe, assume the worst case. 8119 VRQuals.addVolatile(); 8120 VRQuals.addRestrict(); 8121 return VRQuals; 8122 } 8123 8124 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8125 if (!ClassDecl->hasDefinition()) 8126 return VRQuals; 8127 8128 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8129 if (isa<UsingShadowDecl>(D)) 8130 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8131 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8132 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8133 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8134 CanTy = ResTypeRef->getPointeeType(); 8135 // Need to go down the pointer/mempointer chain and add qualifiers 8136 // as see them. 8137 bool done = false; 8138 while (!done) { 8139 if (CanTy.isRestrictQualified()) 8140 VRQuals.addRestrict(); 8141 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8142 CanTy = ResTypePtr->getPointeeType(); 8143 else if (const MemberPointerType *ResTypeMPtr = 8144 CanTy->getAs<MemberPointerType>()) 8145 CanTy = ResTypeMPtr->getPointeeType(); 8146 else 8147 done = true; 8148 if (CanTy.isVolatileQualified()) 8149 VRQuals.addVolatile(); 8150 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8151 return VRQuals; 8152 } 8153 } 8154 } 8155 return VRQuals; 8156 } 8157 8158 namespace { 8159 8160 /// Helper class to manage the addition of builtin operator overload 8161 /// candidates. It provides shared state and utility methods used throughout 8162 /// the process, as well as a helper method to add each group of builtin 8163 /// operator overloads from the standard to a candidate set. 8164 class BuiltinOperatorOverloadBuilder { 8165 // Common instance state available to all overload candidate addition methods. 8166 Sema &S; 8167 ArrayRef<Expr *> Args; 8168 Qualifiers VisibleTypeConversionsQuals; 8169 bool HasArithmeticOrEnumeralCandidateType; 8170 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8171 OverloadCandidateSet &CandidateSet; 8172 8173 static constexpr int ArithmeticTypesCap = 24; 8174 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8175 8176 // Define some indices used to iterate over the arithmetic types in 8177 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8178 // types are that preserved by promotion (C++ [over.built]p2). 8179 unsigned FirstIntegralType, 8180 LastIntegralType; 8181 unsigned FirstPromotedIntegralType, 8182 LastPromotedIntegralType; 8183 unsigned FirstPromotedArithmeticType, 8184 LastPromotedArithmeticType; 8185 unsigned NumArithmeticTypes; 8186 8187 void InitArithmeticTypes() { 8188 // Start of promoted types. 8189 FirstPromotedArithmeticType = 0; 8190 ArithmeticTypes.push_back(S.Context.FloatTy); 8191 ArithmeticTypes.push_back(S.Context.DoubleTy); 8192 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8193 if (S.Context.getTargetInfo().hasFloat128Type()) 8194 ArithmeticTypes.push_back(S.Context.Float128Ty); 8195 8196 // Start of integral types. 8197 FirstIntegralType = ArithmeticTypes.size(); 8198 FirstPromotedIntegralType = ArithmeticTypes.size(); 8199 ArithmeticTypes.push_back(S.Context.IntTy); 8200 ArithmeticTypes.push_back(S.Context.LongTy); 8201 ArithmeticTypes.push_back(S.Context.LongLongTy); 8202 if (S.Context.getTargetInfo().hasInt128Type()) 8203 ArithmeticTypes.push_back(S.Context.Int128Ty); 8204 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8205 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8206 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8207 if (S.Context.getTargetInfo().hasInt128Type()) 8208 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8209 LastPromotedIntegralType = ArithmeticTypes.size(); 8210 LastPromotedArithmeticType = ArithmeticTypes.size(); 8211 // End of promoted types. 8212 8213 ArithmeticTypes.push_back(S.Context.BoolTy); 8214 ArithmeticTypes.push_back(S.Context.CharTy); 8215 ArithmeticTypes.push_back(S.Context.WCharTy); 8216 if (S.Context.getLangOpts().Char8) 8217 ArithmeticTypes.push_back(S.Context.Char8Ty); 8218 ArithmeticTypes.push_back(S.Context.Char16Ty); 8219 ArithmeticTypes.push_back(S.Context.Char32Ty); 8220 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8221 ArithmeticTypes.push_back(S.Context.ShortTy); 8222 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8223 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8224 LastIntegralType = ArithmeticTypes.size(); 8225 NumArithmeticTypes = ArithmeticTypes.size(); 8226 // End of integral types. 8227 // FIXME: What about complex? What about half? 8228 8229 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8230 "Enough inline storage for all arithmetic types."); 8231 } 8232 8233 /// Helper method to factor out the common pattern of adding overloads 8234 /// for '++' and '--' builtin operators. 8235 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8236 bool HasVolatile, 8237 bool HasRestrict) { 8238 QualType ParamTypes[2] = { 8239 S.Context.getLValueReferenceType(CandidateTy), 8240 S.Context.IntTy 8241 }; 8242 8243 // Non-volatile version. 8244 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8245 8246 // Use a heuristic to reduce number of builtin candidates in the set: 8247 // add volatile version only if there are conversions to a volatile type. 8248 if (HasVolatile) { 8249 ParamTypes[0] = 8250 S.Context.getLValueReferenceType( 8251 S.Context.getVolatileType(CandidateTy)); 8252 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8253 } 8254 8255 // Add restrict version only if there are conversions to a restrict type 8256 // and our candidate type is a non-restrict-qualified pointer. 8257 if (HasRestrict && CandidateTy->isAnyPointerType() && 8258 !CandidateTy.isRestrictQualified()) { 8259 ParamTypes[0] 8260 = S.Context.getLValueReferenceType( 8261 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8262 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8263 8264 if (HasVolatile) { 8265 ParamTypes[0] 8266 = S.Context.getLValueReferenceType( 8267 S.Context.getCVRQualifiedType(CandidateTy, 8268 (Qualifiers::Volatile | 8269 Qualifiers::Restrict))); 8270 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8271 } 8272 } 8273 8274 } 8275 8276 /// Helper to add an overload candidate for a binary builtin with types \p L 8277 /// and \p R. 8278 void AddCandidate(QualType L, QualType R) { 8279 QualType LandR[2] = {L, R}; 8280 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8281 } 8282 8283 public: 8284 BuiltinOperatorOverloadBuilder( 8285 Sema &S, ArrayRef<Expr *> Args, 8286 Qualifiers VisibleTypeConversionsQuals, 8287 bool HasArithmeticOrEnumeralCandidateType, 8288 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8289 OverloadCandidateSet &CandidateSet) 8290 : S(S), Args(Args), 8291 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8292 HasArithmeticOrEnumeralCandidateType( 8293 HasArithmeticOrEnumeralCandidateType), 8294 CandidateTypes(CandidateTypes), 8295 CandidateSet(CandidateSet) { 8296 8297 InitArithmeticTypes(); 8298 } 8299 8300 // Increment is deprecated for bool since C++17. 8301 // 8302 // C++ [over.built]p3: 8303 // 8304 // For every pair (T, VQ), where T is an arithmetic type other 8305 // than bool, and VQ is either volatile or empty, there exist 8306 // candidate operator functions of the form 8307 // 8308 // VQ T& operator++(VQ T&); 8309 // T operator++(VQ T&, int); 8310 // 8311 // C++ [over.built]p4: 8312 // 8313 // For every pair (T, VQ), where T is an arithmetic type other 8314 // than bool, and VQ is either volatile or empty, there exist 8315 // candidate operator functions of the form 8316 // 8317 // VQ T& operator--(VQ T&); 8318 // T operator--(VQ T&, int); 8319 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8320 if (!HasArithmeticOrEnumeralCandidateType) 8321 return; 8322 8323 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8324 const auto TypeOfT = ArithmeticTypes[Arith]; 8325 if (TypeOfT == S.Context.BoolTy) { 8326 if (Op == OO_MinusMinus) 8327 continue; 8328 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8329 continue; 8330 } 8331 addPlusPlusMinusMinusStyleOverloads( 8332 TypeOfT, 8333 VisibleTypeConversionsQuals.hasVolatile(), 8334 VisibleTypeConversionsQuals.hasRestrict()); 8335 } 8336 } 8337 8338 // C++ [over.built]p5: 8339 // 8340 // For every pair (T, VQ), where T is a cv-qualified or 8341 // cv-unqualified object type, and VQ is either volatile or 8342 // empty, there exist candidate operator functions of the form 8343 // 8344 // T*VQ& operator++(T*VQ&); 8345 // T*VQ& operator--(T*VQ&); 8346 // T* operator++(T*VQ&, int); 8347 // T* operator--(T*VQ&, int); 8348 void addPlusPlusMinusMinusPointerOverloads() { 8349 for (BuiltinCandidateTypeSet::iterator 8350 Ptr = CandidateTypes[0].pointer_begin(), 8351 PtrEnd = CandidateTypes[0].pointer_end(); 8352 Ptr != PtrEnd; ++Ptr) { 8353 // Skip pointer types that aren't pointers to object types. 8354 if (!(*Ptr)->getPointeeType()->isObjectType()) 8355 continue; 8356 8357 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8358 (!(*Ptr).isVolatileQualified() && 8359 VisibleTypeConversionsQuals.hasVolatile()), 8360 (!(*Ptr).isRestrictQualified() && 8361 VisibleTypeConversionsQuals.hasRestrict())); 8362 } 8363 } 8364 8365 // C++ [over.built]p6: 8366 // For every cv-qualified or cv-unqualified object type T, there 8367 // exist candidate operator functions of the form 8368 // 8369 // T& operator*(T*); 8370 // 8371 // C++ [over.built]p7: 8372 // For every function type T that does not have cv-qualifiers or a 8373 // ref-qualifier, there exist candidate operator functions of the form 8374 // T& operator*(T*); 8375 void addUnaryStarPointerOverloads() { 8376 for (BuiltinCandidateTypeSet::iterator 8377 Ptr = CandidateTypes[0].pointer_begin(), 8378 PtrEnd = CandidateTypes[0].pointer_end(); 8379 Ptr != PtrEnd; ++Ptr) { 8380 QualType ParamTy = *Ptr; 8381 QualType PointeeTy = ParamTy->getPointeeType(); 8382 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8383 continue; 8384 8385 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8386 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8387 continue; 8388 8389 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8390 } 8391 } 8392 8393 // C++ [over.built]p9: 8394 // For every promoted arithmetic type T, there exist candidate 8395 // operator functions of the form 8396 // 8397 // T operator+(T); 8398 // T operator-(T); 8399 void addUnaryPlusOrMinusArithmeticOverloads() { 8400 if (!HasArithmeticOrEnumeralCandidateType) 8401 return; 8402 8403 for (unsigned Arith = FirstPromotedArithmeticType; 8404 Arith < LastPromotedArithmeticType; ++Arith) { 8405 QualType ArithTy = ArithmeticTypes[Arith]; 8406 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8407 } 8408 8409 // Extension: We also add these operators for vector types. 8410 for (QualType VecTy : CandidateTypes[0].vector_types()) 8411 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8412 } 8413 8414 // C++ [over.built]p8: 8415 // For every type T, there exist candidate operator functions of 8416 // the form 8417 // 8418 // T* operator+(T*); 8419 void addUnaryPlusPointerOverloads() { 8420 for (BuiltinCandidateTypeSet::iterator 8421 Ptr = CandidateTypes[0].pointer_begin(), 8422 PtrEnd = CandidateTypes[0].pointer_end(); 8423 Ptr != PtrEnd; ++Ptr) { 8424 QualType ParamTy = *Ptr; 8425 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8426 } 8427 } 8428 8429 // C++ [over.built]p10: 8430 // For every promoted integral type T, there exist candidate 8431 // operator functions of the form 8432 // 8433 // T operator~(T); 8434 void addUnaryTildePromotedIntegralOverloads() { 8435 if (!HasArithmeticOrEnumeralCandidateType) 8436 return; 8437 8438 for (unsigned Int = FirstPromotedIntegralType; 8439 Int < LastPromotedIntegralType; ++Int) { 8440 QualType IntTy = ArithmeticTypes[Int]; 8441 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8442 } 8443 8444 // Extension: We also add this operator for vector types. 8445 for (QualType VecTy : CandidateTypes[0].vector_types()) 8446 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8447 } 8448 8449 // C++ [over.match.oper]p16: 8450 // For every pointer to member type T or type std::nullptr_t, there 8451 // exist candidate operator functions of the form 8452 // 8453 // bool operator==(T,T); 8454 // bool operator!=(T,T); 8455 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8456 /// Set of (canonical) types that we've already handled. 8457 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8458 8459 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8460 for (BuiltinCandidateTypeSet::iterator 8461 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8462 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8463 MemPtr != MemPtrEnd; 8464 ++MemPtr) { 8465 // Don't add the same builtin candidate twice. 8466 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8467 continue; 8468 8469 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8470 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8471 } 8472 8473 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8474 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8475 if (AddedTypes.insert(NullPtrTy).second) { 8476 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8477 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8478 } 8479 } 8480 } 8481 } 8482 8483 // C++ [over.built]p15: 8484 // 8485 // For every T, where T is an enumeration type or a pointer type, 8486 // there exist candidate operator functions of the form 8487 // 8488 // bool operator<(T, T); 8489 // bool operator>(T, T); 8490 // bool operator<=(T, T); 8491 // bool operator>=(T, T); 8492 // bool operator==(T, T); 8493 // bool operator!=(T, T); 8494 // R operator<=>(T, T) 8495 void addGenericBinaryPointerOrEnumeralOverloads() { 8496 // C++ [over.match.oper]p3: 8497 // [...]the built-in candidates include all of the candidate operator 8498 // functions defined in 13.6 that, compared to the given operator, [...] 8499 // do not have the same parameter-type-list as any non-template non-member 8500 // candidate. 8501 // 8502 // Note that in practice, this only affects enumeration types because there 8503 // aren't any built-in candidates of record type, and a user-defined operator 8504 // must have an operand of record or enumeration type. Also, the only other 8505 // overloaded operator with enumeration arguments, operator=, 8506 // cannot be overloaded for enumeration types, so this is the only place 8507 // where we must suppress candidates like this. 8508 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8509 UserDefinedBinaryOperators; 8510 8511 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8512 if (CandidateTypes[ArgIdx].enumeration_begin() != 8513 CandidateTypes[ArgIdx].enumeration_end()) { 8514 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8515 CEnd = CandidateSet.end(); 8516 C != CEnd; ++C) { 8517 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8518 continue; 8519 8520 if (C->Function->isFunctionTemplateSpecialization()) 8521 continue; 8522 8523 // We interpret "same parameter-type-list" as applying to the 8524 // "synthesized candidate, with the order of the two parameters 8525 // reversed", not to the original function. 8526 bool Reversed = C->isReversed(); 8527 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8528 ->getType() 8529 .getUnqualifiedType(); 8530 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8531 ->getType() 8532 .getUnqualifiedType(); 8533 8534 // Skip if either parameter isn't of enumeral type. 8535 if (!FirstParamType->isEnumeralType() || 8536 !SecondParamType->isEnumeralType()) 8537 continue; 8538 8539 // Add this operator to the set of known user-defined operators. 8540 UserDefinedBinaryOperators.insert( 8541 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8542 S.Context.getCanonicalType(SecondParamType))); 8543 } 8544 } 8545 } 8546 8547 /// Set of (canonical) types that we've already handled. 8548 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8549 8550 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8551 for (BuiltinCandidateTypeSet::iterator 8552 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8553 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8554 Ptr != PtrEnd; ++Ptr) { 8555 // Don't add the same builtin candidate twice. 8556 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8557 continue; 8558 8559 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8560 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8561 } 8562 for (BuiltinCandidateTypeSet::iterator 8563 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8564 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8565 Enum != EnumEnd; ++Enum) { 8566 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8567 8568 // Don't add the same builtin candidate twice, or if a user defined 8569 // candidate exists. 8570 if (!AddedTypes.insert(CanonType).second || 8571 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8572 CanonType))) 8573 continue; 8574 QualType ParamTypes[2] = { *Enum, *Enum }; 8575 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8576 } 8577 } 8578 } 8579 8580 // C++ [over.built]p13: 8581 // 8582 // For every cv-qualified or cv-unqualified object type T 8583 // there exist candidate operator functions of the form 8584 // 8585 // T* operator+(T*, ptrdiff_t); 8586 // T& operator[](T*, ptrdiff_t); [BELOW] 8587 // T* operator-(T*, ptrdiff_t); 8588 // T* operator+(ptrdiff_t, T*); 8589 // T& operator[](ptrdiff_t, T*); [BELOW] 8590 // 8591 // C++ [over.built]p14: 8592 // 8593 // For every T, where T is a pointer to object type, there 8594 // exist candidate operator functions of the form 8595 // 8596 // ptrdiff_t operator-(T, T); 8597 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8598 /// Set of (canonical) types that we've already handled. 8599 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8600 8601 for (int Arg = 0; Arg < 2; ++Arg) { 8602 QualType AsymmetricParamTypes[2] = { 8603 S.Context.getPointerDiffType(), 8604 S.Context.getPointerDiffType(), 8605 }; 8606 for (BuiltinCandidateTypeSet::iterator 8607 Ptr = CandidateTypes[Arg].pointer_begin(), 8608 PtrEnd = CandidateTypes[Arg].pointer_end(); 8609 Ptr != PtrEnd; ++Ptr) { 8610 QualType PointeeTy = (*Ptr)->getPointeeType(); 8611 if (!PointeeTy->isObjectType()) 8612 continue; 8613 8614 AsymmetricParamTypes[Arg] = *Ptr; 8615 if (Arg == 0 || Op == OO_Plus) { 8616 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8617 // T* operator+(ptrdiff_t, T*); 8618 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8619 } 8620 if (Op == OO_Minus) { 8621 // ptrdiff_t operator-(T, T); 8622 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8623 continue; 8624 8625 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8626 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8627 } 8628 } 8629 } 8630 } 8631 8632 // C++ [over.built]p12: 8633 // 8634 // For every pair of promoted arithmetic types L and R, there 8635 // exist candidate operator functions of the form 8636 // 8637 // LR operator*(L, R); 8638 // LR operator/(L, R); 8639 // LR operator+(L, R); 8640 // LR operator-(L, R); 8641 // bool operator<(L, R); 8642 // bool operator>(L, R); 8643 // bool operator<=(L, R); 8644 // bool operator>=(L, R); 8645 // bool operator==(L, R); 8646 // bool operator!=(L, R); 8647 // 8648 // where LR is the result of the usual arithmetic conversions 8649 // between types L and R. 8650 // 8651 // C++ [over.built]p24: 8652 // 8653 // For every pair of promoted arithmetic types L and R, there exist 8654 // candidate operator functions of the form 8655 // 8656 // LR operator?(bool, L, R); 8657 // 8658 // where LR is the result of the usual arithmetic conversions 8659 // between types L and R. 8660 // Our candidates ignore the first parameter. 8661 void addGenericBinaryArithmeticOverloads() { 8662 if (!HasArithmeticOrEnumeralCandidateType) 8663 return; 8664 8665 for (unsigned Left = FirstPromotedArithmeticType; 8666 Left < LastPromotedArithmeticType; ++Left) { 8667 for (unsigned Right = FirstPromotedArithmeticType; 8668 Right < LastPromotedArithmeticType; ++Right) { 8669 QualType LandR[2] = { ArithmeticTypes[Left], 8670 ArithmeticTypes[Right] }; 8671 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8672 } 8673 } 8674 8675 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8676 // conditional operator for vector types. 8677 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8678 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8679 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8680 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8681 } 8682 } 8683 8684 /// Add binary operator overloads for each candidate matrix type M1, M2: 8685 /// * (M1, M1) -> M1 8686 /// * (M1, M1.getElementType()) -> M1 8687 /// * (M2.getElementType(), M2) -> M2 8688 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8689 void addMatrixBinaryArithmeticOverloads() { 8690 if (!HasArithmeticOrEnumeralCandidateType) 8691 return; 8692 8693 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8694 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8695 AddCandidate(M1, M1); 8696 } 8697 8698 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8699 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8700 if (!CandidateTypes[0].containsMatrixType(M2)) 8701 AddCandidate(M2, M2); 8702 } 8703 } 8704 8705 // C++2a [over.built]p14: 8706 // 8707 // For every integral type T there exists a candidate operator function 8708 // of the form 8709 // 8710 // std::strong_ordering operator<=>(T, T) 8711 // 8712 // C++2a [over.built]p15: 8713 // 8714 // For every pair of floating-point types L and R, there exists a candidate 8715 // operator function of the form 8716 // 8717 // std::partial_ordering operator<=>(L, R); 8718 // 8719 // FIXME: The current specification for integral types doesn't play nice with 8720 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8721 // comparisons. Under the current spec this can lead to ambiguity during 8722 // overload resolution. For example: 8723 // 8724 // enum A : int {a}; 8725 // auto x = (a <=> (long)42); 8726 // 8727 // error: call is ambiguous for arguments 'A' and 'long'. 8728 // note: candidate operator<=>(int, int) 8729 // note: candidate operator<=>(long, long) 8730 // 8731 // To avoid this error, this function deviates from the specification and adds 8732 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8733 // arithmetic types (the same as the generic relational overloads). 8734 // 8735 // For now this function acts as a placeholder. 8736 void addThreeWayArithmeticOverloads() { 8737 addGenericBinaryArithmeticOverloads(); 8738 } 8739 8740 // C++ [over.built]p17: 8741 // 8742 // For every pair of promoted integral types L and R, there 8743 // exist candidate operator functions of the form 8744 // 8745 // LR operator%(L, R); 8746 // LR operator&(L, R); 8747 // LR operator^(L, R); 8748 // LR operator|(L, R); 8749 // L operator<<(L, R); 8750 // L operator>>(L, R); 8751 // 8752 // where LR is the result of the usual arithmetic conversions 8753 // between types L and R. 8754 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8755 if (!HasArithmeticOrEnumeralCandidateType) 8756 return; 8757 8758 for (unsigned Left = FirstPromotedIntegralType; 8759 Left < LastPromotedIntegralType; ++Left) { 8760 for (unsigned Right = FirstPromotedIntegralType; 8761 Right < LastPromotedIntegralType; ++Right) { 8762 QualType LandR[2] = { ArithmeticTypes[Left], 8763 ArithmeticTypes[Right] }; 8764 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8765 } 8766 } 8767 } 8768 8769 // C++ [over.built]p20: 8770 // 8771 // For every pair (T, VQ), where T is an enumeration or 8772 // pointer to member type and VQ is either volatile or 8773 // empty, there exist candidate operator functions of the form 8774 // 8775 // VQ T& operator=(VQ T&, T); 8776 void addAssignmentMemberPointerOrEnumeralOverloads() { 8777 /// Set of (canonical) types that we've already handled. 8778 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8779 8780 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8781 for (BuiltinCandidateTypeSet::iterator 8782 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8783 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8784 Enum != EnumEnd; ++Enum) { 8785 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8786 continue; 8787 8788 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8789 } 8790 8791 for (BuiltinCandidateTypeSet::iterator 8792 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8793 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8794 MemPtr != MemPtrEnd; ++MemPtr) { 8795 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8796 continue; 8797 8798 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8799 } 8800 } 8801 } 8802 8803 // C++ [over.built]p19: 8804 // 8805 // For every pair (T, VQ), where T is any type and VQ is either 8806 // volatile or empty, there exist candidate operator functions 8807 // of the form 8808 // 8809 // T*VQ& operator=(T*VQ&, T*); 8810 // 8811 // C++ [over.built]p21: 8812 // 8813 // For every pair (T, VQ), where T is a cv-qualified or 8814 // cv-unqualified object type and VQ is either volatile or 8815 // empty, there exist candidate operator functions of the form 8816 // 8817 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8818 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8819 void addAssignmentPointerOverloads(bool isEqualOp) { 8820 /// Set of (canonical) types that we've already handled. 8821 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8822 8823 for (BuiltinCandidateTypeSet::iterator 8824 Ptr = CandidateTypes[0].pointer_begin(), 8825 PtrEnd = CandidateTypes[0].pointer_end(); 8826 Ptr != PtrEnd; ++Ptr) { 8827 // If this is operator=, keep track of the builtin candidates we added. 8828 if (isEqualOp) 8829 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8830 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8831 continue; 8832 8833 // non-volatile version 8834 QualType ParamTypes[2] = { 8835 S.Context.getLValueReferenceType(*Ptr), 8836 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8837 }; 8838 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8839 /*IsAssignmentOperator=*/ isEqualOp); 8840 8841 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8842 VisibleTypeConversionsQuals.hasVolatile(); 8843 if (NeedVolatile) { 8844 // volatile version 8845 ParamTypes[0] = 8846 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8847 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8848 /*IsAssignmentOperator=*/isEqualOp); 8849 } 8850 8851 if (!(*Ptr).isRestrictQualified() && 8852 VisibleTypeConversionsQuals.hasRestrict()) { 8853 // restrict version 8854 ParamTypes[0] 8855 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8856 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8857 /*IsAssignmentOperator=*/isEqualOp); 8858 8859 if (NeedVolatile) { 8860 // volatile restrict version 8861 ParamTypes[0] 8862 = S.Context.getLValueReferenceType( 8863 S.Context.getCVRQualifiedType(*Ptr, 8864 (Qualifiers::Volatile | 8865 Qualifiers::Restrict))); 8866 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8867 /*IsAssignmentOperator=*/isEqualOp); 8868 } 8869 } 8870 } 8871 8872 if (isEqualOp) { 8873 for (BuiltinCandidateTypeSet::iterator 8874 Ptr = CandidateTypes[1].pointer_begin(), 8875 PtrEnd = CandidateTypes[1].pointer_end(); 8876 Ptr != PtrEnd; ++Ptr) { 8877 // Make sure we don't add the same candidate twice. 8878 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8879 continue; 8880 8881 QualType ParamTypes[2] = { 8882 S.Context.getLValueReferenceType(*Ptr), 8883 *Ptr, 8884 }; 8885 8886 // non-volatile version 8887 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8888 /*IsAssignmentOperator=*/true); 8889 8890 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8891 VisibleTypeConversionsQuals.hasVolatile(); 8892 if (NeedVolatile) { 8893 // volatile version 8894 ParamTypes[0] = 8895 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8896 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8897 /*IsAssignmentOperator=*/true); 8898 } 8899 8900 if (!(*Ptr).isRestrictQualified() && 8901 VisibleTypeConversionsQuals.hasRestrict()) { 8902 // restrict version 8903 ParamTypes[0] 8904 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8905 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8906 /*IsAssignmentOperator=*/true); 8907 8908 if (NeedVolatile) { 8909 // volatile restrict version 8910 ParamTypes[0] 8911 = S.Context.getLValueReferenceType( 8912 S.Context.getCVRQualifiedType(*Ptr, 8913 (Qualifiers::Volatile | 8914 Qualifiers::Restrict))); 8915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8916 /*IsAssignmentOperator=*/true); 8917 } 8918 } 8919 } 8920 } 8921 } 8922 8923 // C++ [over.built]p18: 8924 // 8925 // For every triple (L, VQ, R), where L is an arithmetic type, 8926 // VQ is either volatile or empty, and R is a promoted 8927 // arithmetic type, there exist candidate operator functions of 8928 // the form 8929 // 8930 // VQ L& operator=(VQ L&, R); 8931 // VQ L& operator*=(VQ L&, R); 8932 // VQ L& operator/=(VQ L&, R); 8933 // VQ L& operator+=(VQ L&, R); 8934 // VQ L& operator-=(VQ L&, R); 8935 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8936 if (!HasArithmeticOrEnumeralCandidateType) 8937 return; 8938 8939 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8940 for (unsigned Right = FirstPromotedArithmeticType; 8941 Right < LastPromotedArithmeticType; ++Right) { 8942 QualType ParamTypes[2]; 8943 ParamTypes[1] = ArithmeticTypes[Right]; 8944 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8945 S, ArithmeticTypes[Left], Args[0]); 8946 // Add this built-in operator as a candidate (VQ is empty). 8947 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8948 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8949 /*IsAssignmentOperator=*/isEqualOp); 8950 8951 // Add this built-in operator as a candidate (VQ is 'volatile'). 8952 if (VisibleTypeConversionsQuals.hasVolatile()) { 8953 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8954 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8955 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8956 /*IsAssignmentOperator=*/isEqualOp); 8957 } 8958 } 8959 } 8960 8961 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8962 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8963 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8964 QualType ParamTypes[2]; 8965 ParamTypes[1] = Vec2Ty; 8966 // Add this built-in operator as a candidate (VQ is empty). 8967 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8968 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8969 /*IsAssignmentOperator=*/isEqualOp); 8970 8971 // Add this built-in operator as a candidate (VQ is 'volatile'). 8972 if (VisibleTypeConversionsQuals.hasVolatile()) { 8973 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8974 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8975 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8976 /*IsAssignmentOperator=*/isEqualOp); 8977 } 8978 } 8979 } 8980 8981 // C++ [over.built]p22: 8982 // 8983 // For every triple (L, VQ, R), where L is an integral type, VQ 8984 // is either volatile or empty, and R is a promoted integral 8985 // type, there exist candidate operator functions of the form 8986 // 8987 // VQ L& operator%=(VQ L&, R); 8988 // VQ L& operator<<=(VQ L&, R); 8989 // VQ L& operator>>=(VQ L&, R); 8990 // VQ L& operator&=(VQ L&, R); 8991 // VQ L& operator^=(VQ L&, R); 8992 // VQ L& operator|=(VQ L&, R); 8993 void addAssignmentIntegralOverloads() { 8994 if (!HasArithmeticOrEnumeralCandidateType) 8995 return; 8996 8997 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8998 for (unsigned Right = FirstPromotedIntegralType; 8999 Right < LastPromotedIntegralType; ++Right) { 9000 QualType ParamTypes[2]; 9001 ParamTypes[1] = ArithmeticTypes[Right]; 9002 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9003 S, ArithmeticTypes[Left], Args[0]); 9004 // Add this built-in operator as a candidate (VQ is empty). 9005 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 9006 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9007 if (VisibleTypeConversionsQuals.hasVolatile()) { 9008 // Add this built-in operator as a candidate (VQ is 'volatile'). 9009 ParamTypes[0] = LeftBaseTy; 9010 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 9011 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9012 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9013 } 9014 } 9015 } 9016 } 9017 9018 // C++ [over.operator]p23: 9019 // 9020 // There also exist candidate operator functions of the form 9021 // 9022 // bool operator!(bool); 9023 // bool operator&&(bool, bool); 9024 // bool operator||(bool, bool); 9025 void addExclaimOverload() { 9026 QualType ParamTy = S.Context.BoolTy; 9027 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9028 /*IsAssignmentOperator=*/false, 9029 /*NumContextualBoolArguments=*/1); 9030 } 9031 void addAmpAmpOrPipePipeOverload() { 9032 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9033 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9034 /*IsAssignmentOperator=*/false, 9035 /*NumContextualBoolArguments=*/2); 9036 } 9037 9038 // C++ [over.built]p13: 9039 // 9040 // For every cv-qualified or cv-unqualified object type T there 9041 // exist candidate operator functions of the form 9042 // 9043 // T* operator+(T*, ptrdiff_t); [ABOVE] 9044 // T& operator[](T*, ptrdiff_t); 9045 // T* operator-(T*, ptrdiff_t); [ABOVE] 9046 // T* operator+(ptrdiff_t, T*); [ABOVE] 9047 // T& operator[](ptrdiff_t, T*); 9048 void addSubscriptOverloads() { 9049 for (BuiltinCandidateTypeSet::iterator 9050 Ptr = CandidateTypes[0].pointer_begin(), 9051 PtrEnd = CandidateTypes[0].pointer_end(); 9052 Ptr != PtrEnd; ++Ptr) { 9053 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 9054 QualType PointeeType = (*Ptr)->getPointeeType(); 9055 if (!PointeeType->isObjectType()) 9056 continue; 9057 9058 // T& operator[](T*, ptrdiff_t) 9059 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9060 } 9061 9062 for (BuiltinCandidateTypeSet::iterator 9063 Ptr = CandidateTypes[1].pointer_begin(), 9064 PtrEnd = CandidateTypes[1].pointer_end(); 9065 Ptr != PtrEnd; ++Ptr) { 9066 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 9067 QualType PointeeType = (*Ptr)->getPointeeType(); 9068 if (!PointeeType->isObjectType()) 9069 continue; 9070 9071 // T& operator[](ptrdiff_t, T*) 9072 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9073 } 9074 } 9075 9076 // C++ [over.built]p11: 9077 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9078 // C1 is the same type as C2 or is a derived class of C2, T is an object 9079 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9080 // there exist candidate operator functions of the form 9081 // 9082 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9083 // 9084 // where CV12 is the union of CV1 and CV2. 9085 void addArrowStarOverloads() { 9086 for (BuiltinCandidateTypeSet::iterator 9087 Ptr = CandidateTypes[0].pointer_begin(), 9088 PtrEnd = CandidateTypes[0].pointer_end(); 9089 Ptr != PtrEnd; ++Ptr) { 9090 QualType C1Ty = (*Ptr); 9091 QualType C1; 9092 QualifierCollector Q1; 9093 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9094 if (!isa<RecordType>(C1)) 9095 continue; 9096 // heuristic to reduce number of builtin candidates in the set. 9097 // Add volatile/restrict version only if there are conversions to a 9098 // volatile/restrict type. 9099 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9100 continue; 9101 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9102 continue; 9103 for (BuiltinCandidateTypeSet::iterator 9104 MemPtr = CandidateTypes[1].member_pointer_begin(), 9105 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 9106 MemPtr != MemPtrEnd; ++MemPtr) { 9107 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 9108 QualType C2 = QualType(mptr->getClass(), 0); 9109 C2 = C2.getUnqualifiedType(); 9110 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9111 break; 9112 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 9113 // build CV12 T& 9114 QualType T = mptr->getPointeeType(); 9115 if (!VisibleTypeConversionsQuals.hasVolatile() && 9116 T.isVolatileQualified()) 9117 continue; 9118 if (!VisibleTypeConversionsQuals.hasRestrict() && 9119 T.isRestrictQualified()) 9120 continue; 9121 T = Q1.apply(S.Context, T); 9122 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9123 } 9124 } 9125 } 9126 9127 // Note that we don't consider the first argument, since it has been 9128 // contextually converted to bool long ago. The candidates below are 9129 // therefore added as binary. 9130 // 9131 // C++ [over.built]p25: 9132 // For every type T, where T is a pointer, pointer-to-member, or scoped 9133 // enumeration type, there exist candidate operator functions of the form 9134 // 9135 // T operator?(bool, T, T); 9136 // 9137 void addConditionalOperatorOverloads() { 9138 /// Set of (canonical) types that we've already handled. 9139 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9140 9141 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9142 for (BuiltinCandidateTypeSet::iterator 9143 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9144 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9145 Ptr != PtrEnd; ++Ptr) { 9146 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9147 continue; 9148 9149 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9150 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9151 } 9152 9153 for (BuiltinCandidateTypeSet::iterator 9154 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9155 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9156 MemPtr != MemPtrEnd; ++MemPtr) { 9157 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9158 continue; 9159 9160 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9161 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9162 } 9163 9164 if (S.getLangOpts().CPlusPlus11) { 9165 for (BuiltinCandidateTypeSet::iterator 9166 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9167 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9168 Enum != EnumEnd; ++Enum) { 9169 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9170 continue; 9171 9172 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9173 continue; 9174 9175 QualType ParamTypes[2] = { *Enum, *Enum }; 9176 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9177 } 9178 } 9179 } 9180 } 9181 }; 9182 9183 } // end anonymous namespace 9184 9185 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9186 /// operator overloads to the candidate set (C++ [over.built]), based 9187 /// on the operator @p Op and the arguments given. For example, if the 9188 /// operator is a binary '+', this routine might add "int 9189 /// operator+(int, int)" to cover integer addition. 9190 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9191 SourceLocation OpLoc, 9192 ArrayRef<Expr *> Args, 9193 OverloadCandidateSet &CandidateSet) { 9194 // Find all of the types that the arguments can convert to, but only 9195 // if the operator we're looking at has built-in operator candidates 9196 // that make use of these types. Also record whether we encounter non-record 9197 // candidate types or either arithmetic or enumeral candidate types. 9198 Qualifiers VisibleTypeConversionsQuals; 9199 VisibleTypeConversionsQuals.addConst(); 9200 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9201 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9202 9203 bool HasNonRecordCandidateType = false; 9204 bool HasArithmeticOrEnumeralCandidateType = false; 9205 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9206 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9207 CandidateTypes.emplace_back(*this); 9208 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9209 OpLoc, 9210 true, 9211 (Op == OO_Exclaim || 9212 Op == OO_AmpAmp || 9213 Op == OO_PipePipe), 9214 VisibleTypeConversionsQuals); 9215 HasNonRecordCandidateType = HasNonRecordCandidateType || 9216 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9217 HasArithmeticOrEnumeralCandidateType = 9218 HasArithmeticOrEnumeralCandidateType || 9219 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9220 } 9221 9222 // Exit early when no non-record types have been added to the candidate set 9223 // for any of the arguments to the operator. 9224 // 9225 // We can't exit early for !, ||, or &&, since there we have always have 9226 // 'bool' overloads. 9227 if (!HasNonRecordCandidateType && 9228 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9229 return; 9230 9231 // Setup an object to manage the common state for building overloads. 9232 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9233 VisibleTypeConversionsQuals, 9234 HasArithmeticOrEnumeralCandidateType, 9235 CandidateTypes, CandidateSet); 9236 9237 // Dispatch over the operation to add in only those overloads which apply. 9238 switch (Op) { 9239 case OO_None: 9240 case NUM_OVERLOADED_OPERATORS: 9241 llvm_unreachable("Expected an overloaded operator"); 9242 9243 case OO_New: 9244 case OO_Delete: 9245 case OO_Array_New: 9246 case OO_Array_Delete: 9247 case OO_Call: 9248 llvm_unreachable( 9249 "Special operators don't use AddBuiltinOperatorCandidates"); 9250 9251 case OO_Comma: 9252 case OO_Arrow: 9253 case OO_Coawait: 9254 // C++ [over.match.oper]p3: 9255 // -- For the operator ',', the unary operator '&', the 9256 // operator '->', or the operator 'co_await', the 9257 // built-in candidates set is empty. 9258 break; 9259 9260 case OO_Plus: // '+' is either unary or binary 9261 if (Args.size() == 1) 9262 OpBuilder.addUnaryPlusPointerOverloads(); 9263 LLVM_FALLTHROUGH; 9264 9265 case OO_Minus: // '-' is either unary or binary 9266 if (Args.size() == 1) { 9267 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9268 } else { 9269 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9270 OpBuilder.addGenericBinaryArithmeticOverloads(); 9271 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9272 } 9273 break; 9274 9275 case OO_Star: // '*' is either unary or binary 9276 if (Args.size() == 1) 9277 OpBuilder.addUnaryStarPointerOverloads(); 9278 else { 9279 OpBuilder.addGenericBinaryArithmeticOverloads(); 9280 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9281 } 9282 break; 9283 9284 case OO_Slash: 9285 OpBuilder.addGenericBinaryArithmeticOverloads(); 9286 break; 9287 9288 case OO_PlusPlus: 9289 case OO_MinusMinus: 9290 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9291 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9292 break; 9293 9294 case OO_EqualEqual: 9295 case OO_ExclaimEqual: 9296 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9297 LLVM_FALLTHROUGH; 9298 9299 case OO_Less: 9300 case OO_Greater: 9301 case OO_LessEqual: 9302 case OO_GreaterEqual: 9303 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9304 OpBuilder.addGenericBinaryArithmeticOverloads(); 9305 break; 9306 9307 case OO_Spaceship: 9308 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9309 OpBuilder.addThreeWayArithmeticOverloads(); 9310 break; 9311 9312 case OO_Percent: 9313 case OO_Caret: 9314 case OO_Pipe: 9315 case OO_LessLess: 9316 case OO_GreaterGreater: 9317 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9318 break; 9319 9320 case OO_Amp: // '&' is either unary or binary 9321 if (Args.size() == 1) 9322 // C++ [over.match.oper]p3: 9323 // -- For the operator ',', the unary operator '&', or the 9324 // operator '->', the built-in candidates set is empty. 9325 break; 9326 9327 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9328 break; 9329 9330 case OO_Tilde: 9331 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9332 break; 9333 9334 case OO_Equal: 9335 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9336 LLVM_FALLTHROUGH; 9337 9338 case OO_PlusEqual: 9339 case OO_MinusEqual: 9340 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9341 LLVM_FALLTHROUGH; 9342 9343 case OO_StarEqual: 9344 case OO_SlashEqual: 9345 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9346 break; 9347 9348 case OO_PercentEqual: 9349 case OO_LessLessEqual: 9350 case OO_GreaterGreaterEqual: 9351 case OO_AmpEqual: 9352 case OO_CaretEqual: 9353 case OO_PipeEqual: 9354 OpBuilder.addAssignmentIntegralOverloads(); 9355 break; 9356 9357 case OO_Exclaim: 9358 OpBuilder.addExclaimOverload(); 9359 break; 9360 9361 case OO_AmpAmp: 9362 case OO_PipePipe: 9363 OpBuilder.addAmpAmpOrPipePipeOverload(); 9364 break; 9365 9366 case OO_Subscript: 9367 OpBuilder.addSubscriptOverloads(); 9368 break; 9369 9370 case OO_ArrowStar: 9371 OpBuilder.addArrowStarOverloads(); 9372 break; 9373 9374 case OO_Conditional: 9375 OpBuilder.addConditionalOperatorOverloads(); 9376 OpBuilder.addGenericBinaryArithmeticOverloads(); 9377 break; 9378 } 9379 } 9380 9381 /// Add function candidates found via argument-dependent lookup 9382 /// to the set of overloading candidates. 9383 /// 9384 /// This routine performs argument-dependent name lookup based on the 9385 /// given function name (which may also be an operator name) and adds 9386 /// all of the overload candidates found by ADL to the overload 9387 /// candidate set (C++ [basic.lookup.argdep]). 9388 void 9389 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9390 SourceLocation Loc, 9391 ArrayRef<Expr *> Args, 9392 TemplateArgumentListInfo *ExplicitTemplateArgs, 9393 OverloadCandidateSet& CandidateSet, 9394 bool PartialOverloading) { 9395 ADLResult Fns; 9396 9397 // FIXME: This approach for uniquing ADL results (and removing 9398 // redundant candidates from the set) relies on pointer-equality, 9399 // which means we need to key off the canonical decl. However, 9400 // always going back to the canonical decl might not get us the 9401 // right set of default arguments. What default arguments are 9402 // we supposed to consider on ADL candidates, anyway? 9403 9404 // FIXME: Pass in the explicit template arguments? 9405 ArgumentDependentLookup(Name, Loc, Args, Fns); 9406 9407 // Erase all of the candidates we already knew about. 9408 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9409 CandEnd = CandidateSet.end(); 9410 Cand != CandEnd; ++Cand) 9411 if (Cand->Function) { 9412 Fns.erase(Cand->Function); 9413 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9414 Fns.erase(FunTmpl); 9415 } 9416 9417 // For each of the ADL candidates we found, add it to the overload 9418 // set. 9419 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9420 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9421 9422 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9423 if (ExplicitTemplateArgs) 9424 continue; 9425 9426 AddOverloadCandidate( 9427 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9428 PartialOverloading, /*AllowExplicit=*/true, 9429 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9430 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9431 AddOverloadCandidate( 9432 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9433 /*SuppressUserConversions=*/false, PartialOverloading, 9434 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9435 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9436 } 9437 } else { 9438 auto *FTD = cast<FunctionTemplateDecl>(*I); 9439 AddTemplateOverloadCandidate( 9440 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9441 /*SuppressUserConversions=*/false, PartialOverloading, 9442 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9443 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9444 Context, FTD->getTemplatedDecl())) { 9445 AddTemplateOverloadCandidate( 9446 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9447 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9448 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9449 OverloadCandidateParamOrder::Reversed); 9450 } 9451 } 9452 } 9453 } 9454 9455 namespace { 9456 enum class Comparison { Equal, Better, Worse }; 9457 } 9458 9459 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9460 /// overload resolution. 9461 /// 9462 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9463 /// Cand1's first N enable_if attributes have precisely the same conditions as 9464 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9465 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9466 /// 9467 /// Note that you can have a pair of candidates such that Cand1's enable_if 9468 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9469 /// worse than Cand1's. 9470 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9471 const FunctionDecl *Cand2) { 9472 // Common case: One (or both) decls don't have enable_if attrs. 9473 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9474 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9475 if (!Cand1Attr || !Cand2Attr) { 9476 if (Cand1Attr == Cand2Attr) 9477 return Comparison::Equal; 9478 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9479 } 9480 9481 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9482 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9483 9484 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9485 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9486 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9487 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9488 9489 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9490 // has fewer enable_if attributes than Cand2, and vice versa. 9491 if (!Cand1A) 9492 return Comparison::Worse; 9493 if (!Cand2A) 9494 return Comparison::Better; 9495 9496 Cand1ID.clear(); 9497 Cand2ID.clear(); 9498 9499 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9500 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9501 if (Cand1ID != Cand2ID) 9502 return Comparison::Worse; 9503 } 9504 9505 return Comparison::Equal; 9506 } 9507 9508 static Comparison 9509 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9510 const OverloadCandidate &Cand2) { 9511 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9512 !Cand2.Function->isMultiVersion()) 9513 return Comparison::Equal; 9514 9515 // If both are invalid, they are equal. If one of them is invalid, the other 9516 // is better. 9517 if (Cand1.Function->isInvalidDecl()) { 9518 if (Cand2.Function->isInvalidDecl()) 9519 return Comparison::Equal; 9520 return Comparison::Worse; 9521 } 9522 if (Cand2.Function->isInvalidDecl()) 9523 return Comparison::Better; 9524 9525 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9526 // cpu_dispatch, else arbitrarily based on the identifiers. 9527 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9528 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9529 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9530 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9531 9532 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9533 return Comparison::Equal; 9534 9535 if (Cand1CPUDisp && !Cand2CPUDisp) 9536 return Comparison::Better; 9537 if (Cand2CPUDisp && !Cand1CPUDisp) 9538 return Comparison::Worse; 9539 9540 if (Cand1CPUSpec && Cand2CPUSpec) { 9541 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9542 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9543 ? Comparison::Better 9544 : Comparison::Worse; 9545 9546 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9547 FirstDiff = std::mismatch( 9548 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9549 Cand2CPUSpec->cpus_begin(), 9550 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9551 return LHS->getName() == RHS->getName(); 9552 }); 9553 9554 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9555 "Two different cpu-specific versions should not have the same " 9556 "identifier list, otherwise they'd be the same decl!"); 9557 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9558 ? Comparison::Better 9559 : Comparison::Worse; 9560 } 9561 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9562 } 9563 9564 /// Compute the type of the implicit object parameter for the given function, 9565 /// if any. Returns None if there is no implicit object parameter, and a null 9566 /// QualType if there is a 'matches anything' implicit object parameter. 9567 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9568 const FunctionDecl *F) { 9569 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9570 return llvm::None; 9571 9572 auto *M = cast<CXXMethodDecl>(F); 9573 // Static member functions' object parameters match all types. 9574 if (M->isStatic()) 9575 return QualType(); 9576 9577 QualType T = M->getThisObjectType(); 9578 if (M->getRefQualifier() == RQ_RValue) 9579 return Context.getRValueReferenceType(T); 9580 return Context.getLValueReferenceType(T); 9581 } 9582 9583 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9584 const FunctionDecl *F2, unsigned NumParams) { 9585 if (declaresSameEntity(F1, F2)) 9586 return true; 9587 9588 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9589 if (First) { 9590 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9591 return *T; 9592 } 9593 assert(I < F->getNumParams()); 9594 return F->getParamDecl(I++)->getType(); 9595 }; 9596 9597 unsigned I1 = 0, I2 = 0; 9598 for (unsigned I = 0; I != NumParams; ++I) { 9599 QualType T1 = NextParam(F1, I1, I == 0); 9600 QualType T2 = NextParam(F2, I2, I == 0); 9601 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9602 return false; 9603 } 9604 return true; 9605 } 9606 9607 /// isBetterOverloadCandidate - Determines whether the first overload 9608 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9609 bool clang::isBetterOverloadCandidate( 9610 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9611 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9612 // Define viable functions to be better candidates than non-viable 9613 // functions. 9614 if (!Cand2.Viable) 9615 return Cand1.Viable; 9616 else if (!Cand1.Viable) 9617 return false; 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 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9854 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9855 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9856 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9857 } 9858 9859 bool HasPS1 = Cand1.Function != nullptr && 9860 functionHasPassObjectSizeParams(Cand1.Function); 9861 bool HasPS2 = Cand2.Function != nullptr && 9862 functionHasPassObjectSizeParams(Cand2.Function); 9863 if (HasPS1 != HasPS2 && HasPS1) 9864 return true; 9865 9866 Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2); 9867 return MV == Comparison::Better; 9868 } 9869 9870 /// Determine whether two declarations are "equivalent" for the purposes of 9871 /// name lookup and overload resolution. This applies when the same internal/no 9872 /// linkage entity is defined by two modules (probably by textually including 9873 /// the same header). In such a case, we don't consider the declarations to 9874 /// declare the same entity, but we also don't want lookups with both 9875 /// declarations visible to be ambiguous in some cases (this happens when using 9876 /// a modularized libstdc++). 9877 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9878 const NamedDecl *B) { 9879 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9880 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9881 if (!VA || !VB) 9882 return false; 9883 9884 // The declarations must be declaring the same name as an internal linkage 9885 // entity in different modules. 9886 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9887 VB->getDeclContext()->getRedeclContext()) || 9888 getOwningModule(VA) == getOwningModule(VB) || 9889 VA->isExternallyVisible() || VB->isExternallyVisible()) 9890 return false; 9891 9892 // Check that the declarations appear to be equivalent. 9893 // 9894 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9895 // For constants and functions, we should check the initializer or body is 9896 // the same. For non-constant variables, we shouldn't allow it at all. 9897 if (Context.hasSameType(VA->getType(), VB->getType())) 9898 return true; 9899 9900 // Enum constants within unnamed enumerations will have different types, but 9901 // may still be similar enough to be interchangeable for our purposes. 9902 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9903 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9904 // Only handle anonymous enums. If the enumerations were named and 9905 // equivalent, they would have been merged to the same type. 9906 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9907 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9908 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9909 !Context.hasSameType(EnumA->getIntegerType(), 9910 EnumB->getIntegerType())) 9911 return false; 9912 // Allow this only if the value is the same for both enumerators. 9913 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9914 } 9915 } 9916 9917 // Nothing else is sufficiently similar. 9918 return false; 9919 } 9920 9921 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9922 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9923 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9924 9925 Module *M = getOwningModule(D); 9926 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9927 << !M << (M ? M->getFullModuleName() : ""); 9928 9929 for (auto *E : Equiv) { 9930 Module *M = getOwningModule(E); 9931 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9932 << !M << (M ? M->getFullModuleName() : ""); 9933 } 9934 } 9935 9936 /// Computes the best viable function (C++ 13.3.3) 9937 /// within an overload candidate set. 9938 /// 9939 /// \param Loc The location of the function name (or operator symbol) for 9940 /// which overload resolution occurs. 9941 /// 9942 /// \param Best If overload resolution was successful or found a deleted 9943 /// function, \p Best points to the candidate function found. 9944 /// 9945 /// \returns The result of overload resolution. 9946 OverloadingResult 9947 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9948 iterator &Best) { 9949 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9950 std::transform(begin(), end(), std::back_inserter(Candidates), 9951 [](OverloadCandidate &Cand) { return &Cand; }); 9952 9953 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9954 // are accepted by both clang and NVCC. However, during a particular 9955 // compilation mode only one call variant is viable. We need to 9956 // exclude non-viable overload candidates from consideration based 9957 // only on their host/device attributes. Specifically, if one 9958 // candidate call is WrongSide and the other is SameSide, we ignore 9959 // the WrongSide candidate. 9960 if (S.getLangOpts().CUDA) { 9961 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9962 bool ContainsSameSideCandidate = 9963 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9964 // Check viable function only. 9965 return Cand->Viable && Cand->Function && 9966 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9967 Sema::CFP_SameSide; 9968 }); 9969 if (ContainsSameSideCandidate) { 9970 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9971 // Check viable function only to avoid unnecessary data copying/moving. 9972 return Cand->Viable && Cand->Function && 9973 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9974 Sema::CFP_WrongSide; 9975 }; 9976 llvm::erase_if(Candidates, IsWrongSideCandidate); 9977 } 9978 } 9979 9980 // Find the best viable function. 9981 Best = end(); 9982 for (auto *Cand : Candidates) { 9983 Cand->Best = false; 9984 if (Cand->Viable) 9985 if (Best == end() || 9986 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9987 Best = Cand; 9988 } 9989 9990 // If we didn't find any viable functions, abort. 9991 if (Best == end()) 9992 return OR_No_Viable_Function; 9993 9994 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9995 9996 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9997 PendingBest.push_back(&*Best); 9998 Best->Best = true; 9999 10000 // Make sure that this function is better than every other viable 10001 // function. If not, we have an ambiguity. 10002 while (!PendingBest.empty()) { 10003 auto *Curr = PendingBest.pop_back_val(); 10004 for (auto *Cand : Candidates) { 10005 if (Cand->Viable && !Cand->Best && 10006 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10007 PendingBest.push_back(Cand); 10008 Cand->Best = true; 10009 10010 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10011 Curr->Function)) 10012 EquivalentCands.push_back(Cand->Function); 10013 else 10014 Best = end(); 10015 } 10016 } 10017 } 10018 10019 // If we found more than one best candidate, this is ambiguous. 10020 if (Best == end()) 10021 return OR_Ambiguous; 10022 10023 // Best is the best viable function. 10024 if (Best->Function && Best->Function->isDeleted()) 10025 return OR_Deleted; 10026 10027 if (!EquivalentCands.empty()) 10028 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10029 EquivalentCands); 10030 10031 return OR_Success; 10032 } 10033 10034 namespace { 10035 10036 enum OverloadCandidateKind { 10037 oc_function, 10038 oc_method, 10039 oc_reversed_binary_operator, 10040 oc_constructor, 10041 oc_implicit_default_constructor, 10042 oc_implicit_copy_constructor, 10043 oc_implicit_move_constructor, 10044 oc_implicit_copy_assignment, 10045 oc_implicit_move_assignment, 10046 oc_implicit_equality_comparison, 10047 oc_inherited_constructor 10048 }; 10049 10050 enum OverloadCandidateSelect { 10051 ocs_non_template, 10052 ocs_template, 10053 ocs_described_template, 10054 }; 10055 10056 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10057 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10058 OverloadCandidateRewriteKind CRK, 10059 std::string &Description) { 10060 10061 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10062 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10063 isTemplate = true; 10064 Description = S.getTemplateArgumentBindingsText( 10065 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10066 } 10067 10068 OverloadCandidateSelect Select = [&]() { 10069 if (!Description.empty()) 10070 return ocs_described_template; 10071 return isTemplate ? ocs_template : ocs_non_template; 10072 }(); 10073 10074 OverloadCandidateKind Kind = [&]() { 10075 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10076 return oc_implicit_equality_comparison; 10077 10078 if (CRK & CRK_Reversed) 10079 return oc_reversed_binary_operator; 10080 10081 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10082 if (!Ctor->isImplicit()) { 10083 if (isa<ConstructorUsingShadowDecl>(Found)) 10084 return oc_inherited_constructor; 10085 else 10086 return oc_constructor; 10087 } 10088 10089 if (Ctor->isDefaultConstructor()) 10090 return oc_implicit_default_constructor; 10091 10092 if (Ctor->isMoveConstructor()) 10093 return oc_implicit_move_constructor; 10094 10095 assert(Ctor->isCopyConstructor() && 10096 "unexpected sort of implicit constructor"); 10097 return oc_implicit_copy_constructor; 10098 } 10099 10100 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10101 // This actually gets spelled 'candidate function' for now, but 10102 // it doesn't hurt to split it out. 10103 if (!Meth->isImplicit()) 10104 return oc_method; 10105 10106 if (Meth->isMoveAssignmentOperator()) 10107 return oc_implicit_move_assignment; 10108 10109 if (Meth->isCopyAssignmentOperator()) 10110 return oc_implicit_copy_assignment; 10111 10112 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10113 return oc_method; 10114 } 10115 10116 return oc_function; 10117 }(); 10118 10119 return std::make_pair(Kind, Select); 10120 } 10121 10122 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10123 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10124 // set. 10125 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10126 S.Diag(FoundDecl->getLocation(), 10127 diag::note_ovl_candidate_inherited_constructor) 10128 << Shadow->getNominatedBaseClass(); 10129 } 10130 10131 } // end anonymous namespace 10132 10133 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10134 const FunctionDecl *FD) { 10135 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10136 bool AlwaysTrue; 10137 if (EnableIf->getCond()->isValueDependent() || 10138 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10139 return false; 10140 if (!AlwaysTrue) 10141 return false; 10142 } 10143 return true; 10144 } 10145 10146 /// Returns true if we can take the address of the function. 10147 /// 10148 /// \param Complain - If true, we'll emit a diagnostic 10149 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10150 /// we in overload resolution? 10151 /// \param Loc - The location of the statement we're complaining about. Ignored 10152 /// if we're not complaining, or if we're in overload resolution. 10153 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10154 bool Complain, 10155 bool InOverloadResolution, 10156 SourceLocation Loc) { 10157 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10158 if (Complain) { 10159 if (InOverloadResolution) 10160 S.Diag(FD->getBeginLoc(), 10161 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10162 else 10163 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10164 } 10165 return false; 10166 } 10167 10168 if (FD->getTrailingRequiresClause()) { 10169 ConstraintSatisfaction Satisfaction; 10170 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10171 return false; 10172 if (!Satisfaction.IsSatisfied) { 10173 if (Complain) { 10174 if (InOverloadResolution) 10175 S.Diag(FD->getBeginLoc(), 10176 diag::note_ovl_candidate_unsatisfied_constraints); 10177 else 10178 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10179 << FD; 10180 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10181 } 10182 return false; 10183 } 10184 } 10185 10186 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10187 return P->hasAttr<PassObjectSizeAttr>(); 10188 }); 10189 if (I == FD->param_end()) 10190 return true; 10191 10192 if (Complain) { 10193 // Add one to ParamNo because it's user-facing 10194 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10195 if (InOverloadResolution) 10196 S.Diag(FD->getLocation(), 10197 diag::note_ovl_candidate_has_pass_object_size_params) 10198 << ParamNo; 10199 else 10200 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10201 << FD << ParamNo; 10202 } 10203 return false; 10204 } 10205 10206 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10207 const FunctionDecl *FD) { 10208 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10209 /*InOverloadResolution=*/true, 10210 /*Loc=*/SourceLocation()); 10211 } 10212 10213 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10214 bool Complain, 10215 SourceLocation Loc) { 10216 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10217 /*InOverloadResolution=*/false, 10218 Loc); 10219 } 10220 10221 // Don't print candidates other than the one that matches the calling 10222 // convention of the call operator, since that is guaranteed to exist. 10223 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10224 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10225 10226 if (!ConvD) 10227 return false; 10228 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10229 if (!RD->isLambda()) 10230 return false; 10231 10232 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10233 CallingConv CallOpCC = 10234 CallOp->getType()->getAs<FunctionType>()->getCallConv(); 10235 QualType ConvRTy = ConvD->getType()->getAs<FunctionType>()->getReturnType(); 10236 CallingConv ConvToCC = 10237 ConvRTy->getPointeeType()->getAs<FunctionType>()->getCallConv(); 10238 10239 return ConvToCC != CallOpCC; 10240 } 10241 10242 // Notes the location of an overload candidate. 10243 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10244 OverloadCandidateRewriteKind RewriteKind, 10245 QualType DestType, bool TakingAddress) { 10246 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10247 return; 10248 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10249 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10250 return; 10251 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10252 return; 10253 10254 std::string FnDesc; 10255 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10256 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10257 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10258 << (unsigned)KSPair.first << (unsigned)KSPair.second 10259 << Fn << FnDesc; 10260 10261 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10262 Diag(Fn->getLocation(), PD); 10263 MaybeEmitInheritedConstructorNote(*this, Found); 10264 } 10265 10266 static void 10267 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10268 // Perhaps the ambiguity was caused by two atomic constraints that are 10269 // 'identical' but not equivalent: 10270 // 10271 // void foo() requires (sizeof(T) > 4) { } // #1 10272 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10273 // 10274 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10275 // #2 to subsume #1, but these constraint are not considered equivalent 10276 // according to the subsumption rules because they are not the same 10277 // source-level construct. This behavior is quite confusing and we should try 10278 // to help the user figure out what happened. 10279 10280 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10281 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10282 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10283 if (!I->Function) 10284 continue; 10285 SmallVector<const Expr *, 3> AC; 10286 if (auto *Template = I->Function->getPrimaryTemplate()) 10287 Template->getAssociatedConstraints(AC); 10288 else 10289 I->Function->getAssociatedConstraints(AC); 10290 if (AC.empty()) 10291 continue; 10292 if (FirstCand == nullptr) { 10293 FirstCand = I->Function; 10294 FirstAC = AC; 10295 } else if (SecondCand == nullptr) { 10296 SecondCand = I->Function; 10297 SecondAC = AC; 10298 } else { 10299 // We have more than one pair of constrained functions - this check is 10300 // expensive and we'd rather not try to diagnose it. 10301 return; 10302 } 10303 } 10304 if (!SecondCand) 10305 return; 10306 // The diagnostic can only happen if there are associated constraints on 10307 // both sides (there needs to be some identical atomic constraint). 10308 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10309 SecondCand, SecondAC)) 10310 // Just show the user one diagnostic, they'll probably figure it out 10311 // from here. 10312 return; 10313 } 10314 10315 // Notes the location of all overload candidates designated through 10316 // OverloadedExpr 10317 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10318 bool TakingAddress) { 10319 assert(OverloadedExpr->getType() == Context.OverloadTy); 10320 10321 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10322 OverloadExpr *OvlExpr = Ovl.Expression; 10323 10324 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10325 IEnd = OvlExpr->decls_end(); 10326 I != IEnd; ++I) { 10327 if (FunctionTemplateDecl *FunTmpl = 10328 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10329 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10330 TakingAddress); 10331 } else if (FunctionDecl *Fun 10332 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10333 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10334 } 10335 } 10336 } 10337 10338 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10339 /// "lead" diagnostic; it will be given two arguments, the source and 10340 /// target types of the conversion. 10341 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10342 Sema &S, 10343 SourceLocation CaretLoc, 10344 const PartialDiagnostic &PDiag) const { 10345 S.Diag(CaretLoc, PDiag) 10346 << Ambiguous.getFromType() << Ambiguous.getToType(); 10347 // FIXME: The note limiting machinery is borrowed from 10348 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10349 // refactoring here. 10350 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10351 unsigned CandsShown = 0; 10352 AmbiguousConversionSequence::const_iterator I, E; 10353 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10354 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10355 break; 10356 ++CandsShown; 10357 S.NoteOverloadCandidate(I->first, I->second); 10358 } 10359 if (I != E) 10360 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10361 } 10362 10363 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10364 unsigned I, bool TakingCandidateAddress) { 10365 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10366 assert(Conv.isBad()); 10367 assert(Cand->Function && "for now, candidate must be a function"); 10368 FunctionDecl *Fn = Cand->Function; 10369 10370 // There's a conversion slot for the object argument if this is a 10371 // non-constructor method. Note that 'I' corresponds the 10372 // conversion-slot index. 10373 bool isObjectArgument = false; 10374 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10375 if (I == 0) 10376 isObjectArgument = true; 10377 else 10378 I--; 10379 } 10380 10381 std::string FnDesc; 10382 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10383 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10384 FnDesc); 10385 10386 Expr *FromExpr = Conv.Bad.FromExpr; 10387 QualType FromTy = Conv.Bad.getFromType(); 10388 QualType ToTy = Conv.Bad.getToType(); 10389 10390 if (FromTy == S.Context.OverloadTy) { 10391 assert(FromExpr && "overload set argument came from implicit argument?"); 10392 Expr *E = FromExpr->IgnoreParens(); 10393 if (isa<UnaryOperator>(E)) 10394 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10395 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10396 10397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10398 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10399 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10400 << Name << I + 1; 10401 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10402 return; 10403 } 10404 10405 // Do some hand-waving analysis to see if the non-viability is due 10406 // to a qualifier mismatch. 10407 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10408 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10409 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10410 CToTy = RT->getPointeeType(); 10411 else { 10412 // TODO: detect and diagnose the full richness of const mismatches. 10413 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10414 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10415 CFromTy = FromPT->getPointeeType(); 10416 CToTy = ToPT->getPointeeType(); 10417 } 10418 } 10419 10420 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10421 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10422 Qualifiers FromQs = CFromTy.getQualifiers(); 10423 Qualifiers ToQs = CToTy.getQualifiers(); 10424 10425 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10426 if (isObjectArgument) 10427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10428 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10429 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10430 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10431 else 10432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10433 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10434 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10435 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10436 << ToTy->isReferenceType() << I + 1; 10437 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10438 return; 10439 } 10440 10441 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10442 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10443 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10444 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10445 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10446 << (unsigned)isObjectArgument << I + 1; 10447 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10448 return; 10449 } 10450 10451 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10452 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10453 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10454 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10455 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10456 << (unsigned)isObjectArgument << I + 1; 10457 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10458 return; 10459 } 10460 10461 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10462 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10463 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10464 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10465 << FromQs.hasUnaligned() << I + 1; 10466 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10467 return; 10468 } 10469 10470 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10471 assert(CVR && "expected qualifiers mismatch"); 10472 10473 if (isObjectArgument) { 10474 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10475 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10476 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10477 << (CVR - 1); 10478 } else { 10479 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10480 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10481 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10482 << (CVR - 1) << I + 1; 10483 } 10484 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10485 return; 10486 } 10487 10488 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10489 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10490 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10491 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10492 << (unsigned)isObjectArgument << I + 1 10493 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10494 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10495 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10496 return; 10497 } 10498 10499 // Special diagnostic for failure to convert an initializer list, since 10500 // telling the user that it has type void is not useful. 10501 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10502 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10503 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10504 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10505 << ToTy << (unsigned)isObjectArgument << I + 1; 10506 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10507 return; 10508 } 10509 10510 // Diagnose references or pointers to incomplete types differently, 10511 // since it's far from impossible that the incompleteness triggered 10512 // the failure. 10513 QualType TempFromTy = FromTy.getNonReferenceType(); 10514 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10515 TempFromTy = PTy->getPointeeType(); 10516 if (TempFromTy->isIncompleteType()) { 10517 // Emit the generic diagnostic and, optionally, add the hints to it. 10518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10519 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10521 << ToTy << (unsigned)isObjectArgument << I + 1 10522 << (unsigned)(Cand->Fix.Kind); 10523 10524 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10525 return; 10526 } 10527 10528 // Diagnose base -> derived pointer conversions. 10529 unsigned BaseToDerivedConversion = 0; 10530 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10531 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10532 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10533 FromPtrTy->getPointeeType()) && 10534 !FromPtrTy->getPointeeType()->isIncompleteType() && 10535 !ToPtrTy->getPointeeType()->isIncompleteType() && 10536 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10537 FromPtrTy->getPointeeType())) 10538 BaseToDerivedConversion = 1; 10539 } 10540 } else if (const ObjCObjectPointerType *FromPtrTy 10541 = FromTy->getAs<ObjCObjectPointerType>()) { 10542 if (const ObjCObjectPointerType *ToPtrTy 10543 = ToTy->getAs<ObjCObjectPointerType>()) 10544 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10545 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10546 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10547 FromPtrTy->getPointeeType()) && 10548 FromIface->isSuperClassOf(ToIface)) 10549 BaseToDerivedConversion = 2; 10550 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10551 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10552 !FromTy->isIncompleteType() && 10553 !ToRefTy->getPointeeType()->isIncompleteType() && 10554 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10555 BaseToDerivedConversion = 3; 10556 } 10557 } 10558 10559 if (BaseToDerivedConversion) { 10560 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10561 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10562 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10563 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10564 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10565 return; 10566 } 10567 10568 if (isa<ObjCObjectPointerType>(CFromTy) && 10569 isa<PointerType>(CToTy)) { 10570 Qualifiers FromQs = CFromTy.getQualifiers(); 10571 Qualifiers ToQs = CToTy.getQualifiers(); 10572 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10574 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10575 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10576 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10577 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10578 return; 10579 } 10580 } 10581 10582 if (TakingCandidateAddress && 10583 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10584 return; 10585 10586 // Emit the generic diagnostic and, optionally, add the hints to it. 10587 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10588 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10589 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10590 << ToTy << (unsigned)isObjectArgument << I + 1 10591 << (unsigned)(Cand->Fix.Kind); 10592 10593 // If we can fix the conversion, suggest the FixIts. 10594 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10595 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10596 FDiag << *HI; 10597 S.Diag(Fn->getLocation(), FDiag); 10598 10599 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10600 } 10601 10602 /// Additional arity mismatch diagnosis specific to a function overload 10603 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10604 /// over a candidate in any candidate set. 10605 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10606 unsigned NumArgs) { 10607 FunctionDecl *Fn = Cand->Function; 10608 unsigned MinParams = Fn->getMinRequiredArguments(); 10609 10610 // With invalid overloaded operators, it's possible that we think we 10611 // have an arity mismatch when in fact it looks like we have the 10612 // right number of arguments, because only overloaded operators have 10613 // the weird behavior of overloading member and non-member functions. 10614 // Just don't report anything. 10615 if (Fn->isInvalidDecl() && 10616 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10617 return true; 10618 10619 if (NumArgs < MinParams) { 10620 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10621 (Cand->FailureKind == ovl_fail_bad_deduction && 10622 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10623 } else { 10624 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10625 (Cand->FailureKind == ovl_fail_bad_deduction && 10626 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10627 } 10628 10629 return false; 10630 } 10631 10632 /// General arity mismatch diagnosis over a candidate in a candidate set. 10633 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10634 unsigned NumFormalArgs) { 10635 assert(isa<FunctionDecl>(D) && 10636 "The templated declaration should at least be a function" 10637 " when diagnosing bad template argument deduction due to too many" 10638 " or too few arguments"); 10639 10640 FunctionDecl *Fn = cast<FunctionDecl>(D); 10641 10642 // TODO: treat calls to a missing default constructor as a special case 10643 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10644 unsigned MinParams = Fn->getMinRequiredArguments(); 10645 10646 // at least / at most / exactly 10647 unsigned mode, modeCount; 10648 if (NumFormalArgs < MinParams) { 10649 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10650 FnTy->isTemplateVariadic()) 10651 mode = 0; // "at least" 10652 else 10653 mode = 2; // "exactly" 10654 modeCount = MinParams; 10655 } else { 10656 if (MinParams != FnTy->getNumParams()) 10657 mode = 1; // "at most" 10658 else 10659 mode = 2; // "exactly" 10660 modeCount = FnTy->getNumParams(); 10661 } 10662 10663 std::string Description; 10664 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10665 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10666 10667 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10668 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10669 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10670 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10671 else 10672 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10673 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10674 << Description << mode << modeCount << NumFormalArgs; 10675 10676 MaybeEmitInheritedConstructorNote(S, Found); 10677 } 10678 10679 /// Arity mismatch diagnosis specific to a function overload candidate. 10680 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10681 unsigned NumFormalArgs) { 10682 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10683 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10684 } 10685 10686 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10687 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10688 return TD; 10689 llvm_unreachable("Unsupported: Getting the described template declaration" 10690 " for bad deduction diagnosis"); 10691 } 10692 10693 /// Diagnose a failed template-argument deduction. 10694 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10695 DeductionFailureInfo &DeductionFailure, 10696 unsigned NumArgs, 10697 bool TakingCandidateAddress) { 10698 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10699 NamedDecl *ParamD; 10700 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10701 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10702 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10703 switch (DeductionFailure.Result) { 10704 case Sema::TDK_Success: 10705 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10706 10707 case Sema::TDK_Incomplete: { 10708 assert(ParamD && "no parameter found for incomplete deduction result"); 10709 S.Diag(Templated->getLocation(), 10710 diag::note_ovl_candidate_incomplete_deduction) 10711 << ParamD->getDeclName(); 10712 MaybeEmitInheritedConstructorNote(S, Found); 10713 return; 10714 } 10715 10716 case Sema::TDK_IncompletePack: { 10717 assert(ParamD && "no parameter found for incomplete deduction result"); 10718 S.Diag(Templated->getLocation(), 10719 diag::note_ovl_candidate_incomplete_deduction_pack) 10720 << ParamD->getDeclName() 10721 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10722 << *DeductionFailure.getFirstArg(); 10723 MaybeEmitInheritedConstructorNote(S, Found); 10724 return; 10725 } 10726 10727 case Sema::TDK_Underqualified: { 10728 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10729 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10730 10731 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10732 10733 // Param will have been canonicalized, but it should just be a 10734 // qualified version of ParamD, so move the qualifiers to that. 10735 QualifierCollector Qs; 10736 Qs.strip(Param); 10737 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10738 assert(S.Context.hasSameType(Param, NonCanonParam)); 10739 10740 // Arg has also been canonicalized, but there's nothing we can do 10741 // about that. It also doesn't matter as much, because it won't 10742 // have any template parameters in it (because deduction isn't 10743 // done on dependent types). 10744 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10745 10746 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10747 << ParamD->getDeclName() << Arg << NonCanonParam; 10748 MaybeEmitInheritedConstructorNote(S, Found); 10749 return; 10750 } 10751 10752 case Sema::TDK_Inconsistent: { 10753 assert(ParamD && "no parameter found for inconsistent deduction result"); 10754 int which = 0; 10755 if (isa<TemplateTypeParmDecl>(ParamD)) 10756 which = 0; 10757 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10758 // Deduction might have failed because we deduced arguments of two 10759 // different types for a non-type template parameter. 10760 // FIXME: Use a different TDK value for this. 10761 QualType T1 = 10762 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10763 QualType T2 = 10764 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10765 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10766 S.Diag(Templated->getLocation(), 10767 diag::note_ovl_candidate_inconsistent_deduction_types) 10768 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10769 << *DeductionFailure.getSecondArg() << T2; 10770 MaybeEmitInheritedConstructorNote(S, Found); 10771 return; 10772 } 10773 10774 which = 1; 10775 } else { 10776 which = 2; 10777 } 10778 10779 // Tweak the diagnostic if the problem is that we deduced packs of 10780 // different arities. We'll print the actual packs anyway in case that 10781 // includes additional useful information. 10782 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10783 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10784 DeductionFailure.getFirstArg()->pack_size() != 10785 DeductionFailure.getSecondArg()->pack_size()) { 10786 which = 3; 10787 } 10788 10789 S.Diag(Templated->getLocation(), 10790 diag::note_ovl_candidate_inconsistent_deduction) 10791 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10792 << *DeductionFailure.getSecondArg(); 10793 MaybeEmitInheritedConstructorNote(S, Found); 10794 return; 10795 } 10796 10797 case Sema::TDK_InvalidExplicitArguments: 10798 assert(ParamD && "no parameter found for invalid explicit arguments"); 10799 if (ParamD->getDeclName()) 10800 S.Diag(Templated->getLocation(), 10801 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10802 << ParamD->getDeclName(); 10803 else { 10804 int index = 0; 10805 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10806 index = TTP->getIndex(); 10807 else if (NonTypeTemplateParmDecl *NTTP 10808 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10809 index = NTTP->getIndex(); 10810 else 10811 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10812 S.Diag(Templated->getLocation(), 10813 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10814 << (index + 1); 10815 } 10816 MaybeEmitInheritedConstructorNote(S, Found); 10817 return; 10818 10819 case Sema::TDK_ConstraintsNotSatisfied: { 10820 // Format the template argument list into the argument string. 10821 SmallString<128> TemplateArgString; 10822 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10823 TemplateArgString = " "; 10824 TemplateArgString += S.getTemplateArgumentBindingsText( 10825 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10826 if (TemplateArgString.size() == 1) 10827 TemplateArgString.clear(); 10828 S.Diag(Templated->getLocation(), 10829 diag::note_ovl_candidate_unsatisfied_constraints) 10830 << TemplateArgString; 10831 10832 S.DiagnoseUnsatisfiedConstraint( 10833 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10834 return; 10835 } 10836 case Sema::TDK_TooManyArguments: 10837 case Sema::TDK_TooFewArguments: 10838 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10839 return; 10840 10841 case Sema::TDK_InstantiationDepth: 10842 S.Diag(Templated->getLocation(), 10843 diag::note_ovl_candidate_instantiation_depth); 10844 MaybeEmitInheritedConstructorNote(S, Found); 10845 return; 10846 10847 case Sema::TDK_SubstitutionFailure: { 10848 // Format the template argument list into the argument string. 10849 SmallString<128> TemplateArgString; 10850 if (TemplateArgumentList *Args = 10851 DeductionFailure.getTemplateArgumentList()) { 10852 TemplateArgString = " "; 10853 TemplateArgString += S.getTemplateArgumentBindingsText( 10854 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10855 if (TemplateArgString.size() == 1) 10856 TemplateArgString.clear(); 10857 } 10858 10859 // If this candidate was disabled by enable_if, say so. 10860 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10861 if (PDiag && PDiag->second.getDiagID() == 10862 diag::err_typename_nested_not_found_enable_if) { 10863 // FIXME: Use the source range of the condition, and the fully-qualified 10864 // name of the enable_if template. These are both present in PDiag. 10865 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10866 << "'enable_if'" << TemplateArgString; 10867 return; 10868 } 10869 10870 // We found a specific requirement that disabled the enable_if. 10871 if (PDiag && PDiag->second.getDiagID() == 10872 diag::err_typename_nested_not_found_requirement) { 10873 S.Diag(Templated->getLocation(), 10874 diag::note_ovl_candidate_disabled_by_requirement) 10875 << PDiag->second.getStringArg(0) << TemplateArgString; 10876 return; 10877 } 10878 10879 // Format the SFINAE diagnostic into the argument string. 10880 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10881 // formatted message in another diagnostic. 10882 SmallString<128> SFINAEArgString; 10883 SourceRange R; 10884 if (PDiag) { 10885 SFINAEArgString = ": "; 10886 R = SourceRange(PDiag->first, PDiag->first); 10887 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10888 } 10889 10890 S.Diag(Templated->getLocation(), 10891 diag::note_ovl_candidate_substitution_failure) 10892 << TemplateArgString << SFINAEArgString << R; 10893 MaybeEmitInheritedConstructorNote(S, Found); 10894 return; 10895 } 10896 10897 case Sema::TDK_DeducedMismatch: 10898 case Sema::TDK_DeducedMismatchNested: { 10899 // Format the template argument list into the argument string. 10900 SmallString<128> TemplateArgString; 10901 if (TemplateArgumentList *Args = 10902 DeductionFailure.getTemplateArgumentList()) { 10903 TemplateArgString = " "; 10904 TemplateArgString += S.getTemplateArgumentBindingsText( 10905 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10906 if (TemplateArgString.size() == 1) 10907 TemplateArgString.clear(); 10908 } 10909 10910 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10911 << (*DeductionFailure.getCallArgIndex() + 1) 10912 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10913 << TemplateArgString 10914 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10915 break; 10916 } 10917 10918 case Sema::TDK_NonDeducedMismatch: { 10919 // FIXME: Provide a source location to indicate what we couldn't match. 10920 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10921 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10922 if (FirstTA.getKind() == TemplateArgument::Template && 10923 SecondTA.getKind() == TemplateArgument::Template) { 10924 TemplateName FirstTN = FirstTA.getAsTemplate(); 10925 TemplateName SecondTN = SecondTA.getAsTemplate(); 10926 if (FirstTN.getKind() == TemplateName::Template && 10927 SecondTN.getKind() == TemplateName::Template) { 10928 if (FirstTN.getAsTemplateDecl()->getName() == 10929 SecondTN.getAsTemplateDecl()->getName()) { 10930 // FIXME: This fixes a bad diagnostic where both templates are named 10931 // the same. This particular case is a bit difficult since: 10932 // 1) It is passed as a string to the diagnostic printer. 10933 // 2) The diagnostic printer only attempts to find a better 10934 // name for types, not decls. 10935 // Ideally, this should folded into the diagnostic printer. 10936 S.Diag(Templated->getLocation(), 10937 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10938 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10939 return; 10940 } 10941 } 10942 } 10943 10944 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10945 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10946 return; 10947 10948 // FIXME: For generic lambda parameters, check if the function is a lambda 10949 // call operator, and if so, emit a prettier and more informative 10950 // diagnostic that mentions 'auto' and lambda in addition to 10951 // (or instead of?) the canonical template type parameters. 10952 S.Diag(Templated->getLocation(), 10953 diag::note_ovl_candidate_non_deduced_mismatch) 10954 << FirstTA << SecondTA; 10955 return; 10956 } 10957 // TODO: diagnose these individually, then kill off 10958 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10959 case Sema::TDK_MiscellaneousDeductionFailure: 10960 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10961 MaybeEmitInheritedConstructorNote(S, Found); 10962 return; 10963 case Sema::TDK_CUDATargetMismatch: 10964 S.Diag(Templated->getLocation(), 10965 diag::note_cuda_ovl_candidate_target_mismatch); 10966 return; 10967 } 10968 } 10969 10970 /// Diagnose a failed template-argument deduction, for function calls. 10971 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10972 unsigned NumArgs, 10973 bool TakingCandidateAddress) { 10974 unsigned TDK = Cand->DeductionFailure.Result; 10975 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10976 if (CheckArityMismatch(S, Cand, NumArgs)) 10977 return; 10978 } 10979 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10980 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10981 } 10982 10983 /// CUDA: diagnose an invalid call across targets. 10984 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10985 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10986 FunctionDecl *Callee = Cand->Function; 10987 10988 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10989 CalleeTarget = S.IdentifyCUDATarget(Callee); 10990 10991 std::string FnDesc; 10992 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10993 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10994 Cand->getRewriteKind(), FnDesc); 10995 10996 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10997 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10998 << FnDesc /* Ignored */ 10999 << CalleeTarget << CallerTarget; 11000 11001 // This could be an implicit constructor for which we could not infer the 11002 // target due to a collsion. Diagnose that case. 11003 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11004 if (Meth != nullptr && Meth->isImplicit()) { 11005 CXXRecordDecl *ParentClass = Meth->getParent(); 11006 Sema::CXXSpecialMember CSM; 11007 11008 switch (FnKindPair.first) { 11009 default: 11010 return; 11011 case oc_implicit_default_constructor: 11012 CSM = Sema::CXXDefaultConstructor; 11013 break; 11014 case oc_implicit_copy_constructor: 11015 CSM = Sema::CXXCopyConstructor; 11016 break; 11017 case oc_implicit_move_constructor: 11018 CSM = Sema::CXXMoveConstructor; 11019 break; 11020 case oc_implicit_copy_assignment: 11021 CSM = Sema::CXXCopyAssignment; 11022 break; 11023 case oc_implicit_move_assignment: 11024 CSM = Sema::CXXMoveAssignment; 11025 break; 11026 }; 11027 11028 bool ConstRHS = false; 11029 if (Meth->getNumParams()) { 11030 if (const ReferenceType *RT = 11031 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11032 ConstRHS = RT->getPointeeType().isConstQualified(); 11033 } 11034 } 11035 11036 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11037 /* ConstRHS */ ConstRHS, 11038 /* Diagnose */ true); 11039 } 11040 } 11041 11042 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11043 FunctionDecl *Callee = Cand->Function; 11044 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11045 11046 S.Diag(Callee->getLocation(), 11047 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11048 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11049 } 11050 11051 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11052 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11053 assert(ES.isExplicit() && "not an explicit candidate"); 11054 11055 unsigned Kind; 11056 switch (Cand->Function->getDeclKind()) { 11057 case Decl::Kind::CXXConstructor: 11058 Kind = 0; 11059 break; 11060 case Decl::Kind::CXXConversion: 11061 Kind = 1; 11062 break; 11063 case Decl::Kind::CXXDeductionGuide: 11064 Kind = Cand->Function->isImplicit() ? 0 : 2; 11065 break; 11066 default: 11067 llvm_unreachable("invalid Decl"); 11068 } 11069 11070 // Note the location of the first (in-class) declaration; a redeclaration 11071 // (particularly an out-of-class definition) will typically lack the 11072 // 'explicit' specifier. 11073 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11074 FunctionDecl *First = Cand->Function->getFirstDecl(); 11075 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11076 First = Pattern->getFirstDecl(); 11077 11078 S.Diag(First->getLocation(), 11079 diag::note_ovl_candidate_explicit) 11080 << Kind << (ES.getExpr() ? 1 : 0) 11081 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11082 } 11083 11084 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 11085 FunctionDecl *Callee = Cand->Function; 11086 11087 S.Diag(Callee->getLocation(), 11088 diag::note_ovl_candidate_disabled_by_extension) 11089 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 11090 } 11091 11092 /// Generates a 'note' diagnostic for an overload candidate. We've 11093 /// already generated a primary error at the call site. 11094 /// 11095 /// It really does need to be a single diagnostic with its caret 11096 /// pointed at the candidate declaration. Yes, this creates some 11097 /// major challenges of technical writing. Yes, this makes pointing 11098 /// out problems with specific arguments quite awkward. It's still 11099 /// better than generating twenty screens of text for every failed 11100 /// overload. 11101 /// 11102 /// It would be great to be able to express per-candidate problems 11103 /// more richly for those diagnostic clients that cared, but we'd 11104 /// still have to be just as careful with the default diagnostics. 11105 /// \param CtorDestAS Addr space of object being constructed (for ctor 11106 /// candidates only). 11107 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11108 unsigned NumArgs, 11109 bool TakingCandidateAddress, 11110 LangAS CtorDestAS = LangAS::Default) { 11111 FunctionDecl *Fn = Cand->Function; 11112 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11113 return; 11114 11115 // Note deleted candidates, but only if they're viable. 11116 if (Cand->Viable) { 11117 if (Fn->isDeleted()) { 11118 std::string FnDesc; 11119 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11120 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11121 Cand->getRewriteKind(), FnDesc); 11122 11123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11124 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11125 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11126 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11127 return; 11128 } 11129 11130 // We don't really have anything else to say about viable candidates. 11131 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11132 return; 11133 } 11134 11135 switch (Cand->FailureKind) { 11136 case ovl_fail_too_many_arguments: 11137 case ovl_fail_too_few_arguments: 11138 return DiagnoseArityMismatch(S, Cand, NumArgs); 11139 11140 case ovl_fail_bad_deduction: 11141 return DiagnoseBadDeduction(S, Cand, NumArgs, 11142 TakingCandidateAddress); 11143 11144 case ovl_fail_illegal_constructor: { 11145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11146 << (Fn->getPrimaryTemplate() ? 1 : 0); 11147 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11148 return; 11149 } 11150 11151 case ovl_fail_object_addrspace_mismatch: { 11152 Qualifiers QualsForPrinting; 11153 QualsForPrinting.setAddressSpace(CtorDestAS); 11154 S.Diag(Fn->getLocation(), 11155 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11156 << QualsForPrinting; 11157 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11158 return; 11159 } 11160 11161 case ovl_fail_trivial_conversion: 11162 case ovl_fail_bad_final_conversion: 11163 case ovl_fail_final_conversion_not_exact: 11164 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11165 11166 case ovl_fail_bad_conversion: { 11167 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11168 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11169 if (Cand->Conversions[I].isBad()) 11170 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11171 11172 // FIXME: this currently happens when we're called from SemaInit 11173 // when user-conversion overload fails. Figure out how to handle 11174 // those conditions and diagnose them well. 11175 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11176 } 11177 11178 case ovl_fail_bad_target: 11179 return DiagnoseBadTarget(S, Cand); 11180 11181 case ovl_fail_enable_if: 11182 return DiagnoseFailedEnableIfAttr(S, Cand); 11183 11184 case ovl_fail_explicit: 11185 return DiagnoseFailedExplicitSpec(S, Cand); 11186 11187 case ovl_fail_ext_disabled: 11188 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11189 11190 case ovl_fail_inhctor_slice: 11191 // It's generally not interesting to note copy/move constructors here. 11192 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11193 return; 11194 S.Diag(Fn->getLocation(), 11195 diag::note_ovl_candidate_inherited_constructor_slice) 11196 << (Fn->getPrimaryTemplate() ? 1 : 0) 11197 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11198 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11199 return; 11200 11201 case ovl_fail_addr_not_available: { 11202 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11203 (void)Available; 11204 assert(!Available); 11205 break; 11206 } 11207 case ovl_non_default_multiversion_function: 11208 // Do nothing, these should simply be ignored. 11209 break; 11210 11211 case ovl_fail_constraints_not_satisfied: { 11212 std::string FnDesc; 11213 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11214 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11215 Cand->getRewriteKind(), FnDesc); 11216 11217 S.Diag(Fn->getLocation(), 11218 diag::note_ovl_candidate_constraints_not_satisfied) 11219 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11220 << FnDesc /* Ignored */; 11221 ConstraintSatisfaction Satisfaction; 11222 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11223 break; 11224 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11225 } 11226 } 11227 } 11228 11229 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11230 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11231 return; 11232 11233 // Desugar the type of the surrogate down to a function type, 11234 // retaining as many typedefs as possible while still showing 11235 // the function type (and, therefore, its parameter types). 11236 QualType FnType = Cand->Surrogate->getConversionType(); 11237 bool isLValueReference = false; 11238 bool isRValueReference = false; 11239 bool isPointer = false; 11240 if (const LValueReferenceType *FnTypeRef = 11241 FnType->getAs<LValueReferenceType>()) { 11242 FnType = FnTypeRef->getPointeeType(); 11243 isLValueReference = true; 11244 } else if (const RValueReferenceType *FnTypeRef = 11245 FnType->getAs<RValueReferenceType>()) { 11246 FnType = FnTypeRef->getPointeeType(); 11247 isRValueReference = true; 11248 } 11249 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11250 FnType = FnTypePtr->getPointeeType(); 11251 isPointer = true; 11252 } 11253 // Desugar down to a function type. 11254 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11255 // Reconstruct the pointer/reference as appropriate. 11256 if (isPointer) FnType = S.Context.getPointerType(FnType); 11257 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11258 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11259 11260 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11261 << FnType; 11262 } 11263 11264 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11265 SourceLocation OpLoc, 11266 OverloadCandidate *Cand) { 11267 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11268 std::string TypeStr("operator"); 11269 TypeStr += Opc; 11270 TypeStr += "("; 11271 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11272 if (Cand->Conversions.size() == 1) { 11273 TypeStr += ")"; 11274 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11275 } else { 11276 TypeStr += ", "; 11277 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11278 TypeStr += ")"; 11279 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11280 } 11281 } 11282 11283 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11284 OverloadCandidate *Cand) { 11285 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11286 if (ICS.isBad()) break; // all meaningless after first invalid 11287 if (!ICS.isAmbiguous()) continue; 11288 11289 ICS.DiagnoseAmbiguousConversion( 11290 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11291 } 11292 } 11293 11294 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11295 if (Cand->Function) 11296 return Cand->Function->getLocation(); 11297 if (Cand->IsSurrogate) 11298 return Cand->Surrogate->getLocation(); 11299 return SourceLocation(); 11300 } 11301 11302 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11303 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11304 case Sema::TDK_Success: 11305 case Sema::TDK_NonDependentConversionFailure: 11306 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11307 11308 case Sema::TDK_Invalid: 11309 case Sema::TDK_Incomplete: 11310 case Sema::TDK_IncompletePack: 11311 return 1; 11312 11313 case Sema::TDK_Underqualified: 11314 case Sema::TDK_Inconsistent: 11315 return 2; 11316 11317 case Sema::TDK_SubstitutionFailure: 11318 case Sema::TDK_DeducedMismatch: 11319 case Sema::TDK_ConstraintsNotSatisfied: 11320 case Sema::TDK_DeducedMismatchNested: 11321 case Sema::TDK_NonDeducedMismatch: 11322 case Sema::TDK_MiscellaneousDeductionFailure: 11323 case Sema::TDK_CUDATargetMismatch: 11324 return 3; 11325 11326 case Sema::TDK_InstantiationDepth: 11327 return 4; 11328 11329 case Sema::TDK_InvalidExplicitArguments: 11330 return 5; 11331 11332 case Sema::TDK_TooManyArguments: 11333 case Sema::TDK_TooFewArguments: 11334 return 6; 11335 } 11336 llvm_unreachable("Unhandled deduction result"); 11337 } 11338 11339 namespace { 11340 struct CompareOverloadCandidatesForDisplay { 11341 Sema &S; 11342 SourceLocation Loc; 11343 size_t NumArgs; 11344 OverloadCandidateSet::CandidateSetKind CSK; 11345 11346 CompareOverloadCandidatesForDisplay( 11347 Sema &S, SourceLocation Loc, size_t NArgs, 11348 OverloadCandidateSet::CandidateSetKind CSK) 11349 : S(S), NumArgs(NArgs), CSK(CSK) {} 11350 11351 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11352 // If there are too many or too few arguments, that's the high-order bit we 11353 // want to sort by, even if the immediate failure kind was something else. 11354 if (C->FailureKind == ovl_fail_too_many_arguments || 11355 C->FailureKind == ovl_fail_too_few_arguments) 11356 return static_cast<OverloadFailureKind>(C->FailureKind); 11357 11358 if (C->Function) { 11359 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11360 return ovl_fail_too_many_arguments; 11361 if (NumArgs < C->Function->getMinRequiredArguments()) 11362 return ovl_fail_too_few_arguments; 11363 } 11364 11365 return static_cast<OverloadFailureKind>(C->FailureKind); 11366 } 11367 11368 bool operator()(const OverloadCandidate *L, 11369 const OverloadCandidate *R) { 11370 // Fast-path this check. 11371 if (L == R) return false; 11372 11373 // Order first by viability. 11374 if (L->Viable) { 11375 if (!R->Viable) return true; 11376 11377 // TODO: introduce a tri-valued comparison for overload 11378 // candidates. Would be more worthwhile if we had a sort 11379 // that could exploit it. 11380 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11381 return true; 11382 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11383 return false; 11384 } else if (R->Viable) 11385 return false; 11386 11387 assert(L->Viable == R->Viable); 11388 11389 // Criteria by which we can sort non-viable candidates: 11390 if (!L->Viable) { 11391 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11392 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11393 11394 // 1. Arity mismatches come after other candidates. 11395 if (LFailureKind == ovl_fail_too_many_arguments || 11396 LFailureKind == ovl_fail_too_few_arguments) { 11397 if (RFailureKind == ovl_fail_too_many_arguments || 11398 RFailureKind == ovl_fail_too_few_arguments) { 11399 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11400 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11401 if (LDist == RDist) { 11402 if (LFailureKind == RFailureKind) 11403 // Sort non-surrogates before surrogates. 11404 return !L->IsSurrogate && R->IsSurrogate; 11405 // Sort candidates requiring fewer parameters than there were 11406 // arguments given after candidates requiring more parameters 11407 // than there were arguments given. 11408 return LFailureKind == ovl_fail_too_many_arguments; 11409 } 11410 return LDist < RDist; 11411 } 11412 return false; 11413 } 11414 if (RFailureKind == ovl_fail_too_many_arguments || 11415 RFailureKind == ovl_fail_too_few_arguments) 11416 return true; 11417 11418 // 2. Bad conversions come first and are ordered by the number 11419 // of bad conversions and quality of good conversions. 11420 if (LFailureKind == ovl_fail_bad_conversion) { 11421 if (RFailureKind != ovl_fail_bad_conversion) 11422 return true; 11423 11424 // The conversion that can be fixed with a smaller number of changes, 11425 // comes first. 11426 unsigned numLFixes = L->Fix.NumConversionsFixed; 11427 unsigned numRFixes = R->Fix.NumConversionsFixed; 11428 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11429 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11430 if (numLFixes != numRFixes) { 11431 return numLFixes < numRFixes; 11432 } 11433 11434 // If there's any ordering between the defined conversions... 11435 // FIXME: this might not be transitive. 11436 assert(L->Conversions.size() == R->Conversions.size()); 11437 11438 int leftBetter = 0; 11439 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11440 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11441 switch (CompareImplicitConversionSequences(S, Loc, 11442 L->Conversions[I], 11443 R->Conversions[I])) { 11444 case ImplicitConversionSequence::Better: 11445 leftBetter++; 11446 break; 11447 11448 case ImplicitConversionSequence::Worse: 11449 leftBetter--; 11450 break; 11451 11452 case ImplicitConversionSequence::Indistinguishable: 11453 break; 11454 } 11455 } 11456 if (leftBetter > 0) return true; 11457 if (leftBetter < 0) return false; 11458 11459 } else if (RFailureKind == ovl_fail_bad_conversion) 11460 return false; 11461 11462 if (LFailureKind == ovl_fail_bad_deduction) { 11463 if (RFailureKind != ovl_fail_bad_deduction) 11464 return true; 11465 11466 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11467 return RankDeductionFailure(L->DeductionFailure) 11468 < RankDeductionFailure(R->DeductionFailure); 11469 } else if (RFailureKind == ovl_fail_bad_deduction) 11470 return false; 11471 11472 // TODO: others? 11473 } 11474 11475 // Sort everything else by location. 11476 SourceLocation LLoc = GetLocationForCandidate(L); 11477 SourceLocation RLoc = GetLocationForCandidate(R); 11478 11479 // Put candidates without locations (e.g. builtins) at the end. 11480 if (LLoc.isInvalid()) return false; 11481 if (RLoc.isInvalid()) return true; 11482 11483 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11484 } 11485 }; 11486 } 11487 11488 /// CompleteNonViableCandidate - Normally, overload resolution only 11489 /// computes up to the first bad conversion. Produces the FixIt set if 11490 /// possible. 11491 static void 11492 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11493 ArrayRef<Expr *> Args, 11494 OverloadCandidateSet::CandidateSetKind CSK) { 11495 assert(!Cand->Viable); 11496 11497 // Don't do anything on failures other than bad conversion. 11498 if (Cand->FailureKind != ovl_fail_bad_conversion) 11499 return; 11500 11501 // We only want the FixIts if all the arguments can be corrected. 11502 bool Unfixable = false; 11503 // Use a implicit copy initialization to check conversion fixes. 11504 Cand->Fix.setConversionChecker(TryCopyInitialization); 11505 11506 // Attempt to fix the bad conversion. 11507 unsigned ConvCount = Cand->Conversions.size(); 11508 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11509 ++ConvIdx) { 11510 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11511 if (Cand->Conversions[ConvIdx].isInitialized() && 11512 Cand->Conversions[ConvIdx].isBad()) { 11513 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11514 break; 11515 } 11516 } 11517 11518 // FIXME: this should probably be preserved from the overload 11519 // operation somehow. 11520 bool SuppressUserConversions = false; 11521 11522 unsigned ConvIdx = 0; 11523 unsigned ArgIdx = 0; 11524 ArrayRef<QualType> ParamTypes; 11525 bool Reversed = Cand->isReversed(); 11526 11527 if (Cand->IsSurrogate) { 11528 QualType ConvType 11529 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11530 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11531 ConvType = ConvPtrType->getPointeeType(); 11532 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11533 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11534 ConvIdx = 1; 11535 } else if (Cand->Function) { 11536 ParamTypes = 11537 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11538 if (isa<CXXMethodDecl>(Cand->Function) && 11539 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11540 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11541 ConvIdx = 1; 11542 if (CSK == OverloadCandidateSet::CSK_Operator && 11543 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11544 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11545 ArgIdx = 1; 11546 } 11547 } else { 11548 // Builtin operator. 11549 assert(ConvCount <= 3); 11550 ParamTypes = Cand->BuiltinParamTypes; 11551 } 11552 11553 // Fill in the rest of the conversions. 11554 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11555 ConvIdx != ConvCount; 11556 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11557 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11558 if (Cand->Conversions[ConvIdx].isInitialized()) { 11559 // We've already checked this conversion. 11560 } else if (ParamIdx < ParamTypes.size()) { 11561 if (ParamTypes[ParamIdx]->isDependentType()) 11562 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11563 Args[ArgIdx]->getType()); 11564 else { 11565 Cand->Conversions[ConvIdx] = 11566 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11567 SuppressUserConversions, 11568 /*InOverloadResolution=*/true, 11569 /*AllowObjCWritebackConversion=*/ 11570 S.getLangOpts().ObjCAutoRefCount); 11571 // Store the FixIt in the candidate if it exists. 11572 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11573 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11574 } 11575 } else 11576 Cand->Conversions[ConvIdx].setEllipsis(); 11577 } 11578 } 11579 11580 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11581 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11582 SourceLocation OpLoc, 11583 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11584 // Sort the candidates by viability and position. Sorting directly would 11585 // be prohibitive, so we make a set of pointers and sort those. 11586 SmallVector<OverloadCandidate*, 32> Cands; 11587 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11588 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11589 if (!Filter(*Cand)) 11590 continue; 11591 switch (OCD) { 11592 case OCD_AllCandidates: 11593 if (!Cand->Viable) { 11594 if (!Cand->Function && !Cand->IsSurrogate) { 11595 // This a non-viable builtin candidate. We do not, in general, 11596 // want to list every possible builtin candidate. 11597 continue; 11598 } 11599 CompleteNonViableCandidate(S, Cand, Args, Kind); 11600 } 11601 break; 11602 11603 case OCD_ViableCandidates: 11604 if (!Cand->Viable) 11605 continue; 11606 break; 11607 11608 case OCD_AmbiguousCandidates: 11609 if (!Cand->Best) 11610 continue; 11611 break; 11612 } 11613 11614 Cands.push_back(Cand); 11615 } 11616 11617 llvm::stable_sort( 11618 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11619 11620 return Cands; 11621 } 11622 11623 /// When overload resolution fails, prints diagnostic messages containing the 11624 /// candidates in the candidate set. 11625 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11626 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11627 StringRef Opc, SourceLocation OpLoc, 11628 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11629 11630 bool DeferHint = false; 11631 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11632 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates. 11633 auto WrongSidedCands = 11634 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11635 return Cand.Viable == false && 11636 Cand.FailureKind == ovl_fail_bad_target; 11637 }); 11638 DeferHint = WrongSidedCands.size(); 11639 } 11640 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11641 11642 S.Diag(PD.first, PD.second, DeferHint); 11643 11644 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11645 11646 if (OCD == OCD_AmbiguousCandidates) 11647 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11648 } 11649 11650 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11651 ArrayRef<OverloadCandidate *> Cands, 11652 StringRef Opc, SourceLocation OpLoc) { 11653 bool ReportedAmbiguousConversions = false; 11654 11655 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11656 unsigned CandsShown = 0; 11657 auto I = Cands.begin(), E = Cands.end(); 11658 for (; I != E; ++I) { 11659 OverloadCandidate *Cand = *I; 11660 11661 // Set an arbitrary limit on the number of candidate functions we'll spam 11662 // the user with. FIXME: This limit should depend on details of the 11663 // candidate list. 11664 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11665 break; 11666 } 11667 ++CandsShown; 11668 11669 if (Cand->Function) 11670 NoteFunctionCandidate(S, Cand, Args.size(), 11671 /*TakingCandidateAddress=*/false, DestAS); 11672 else if (Cand->IsSurrogate) 11673 NoteSurrogateCandidate(S, Cand); 11674 else { 11675 assert(Cand->Viable && 11676 "Non-viable built-in candidates are not added to Cands."); 11677 // Generally we only see ambiguities including viable builtin 11678 // operators if overload resolution got screwed up by an 11679 // ambiguous user-defined conversion. 11680 // 11681 // FIXME: It's quite possible for different conversions to see 11682 // different ambiguities, though. 11683 if (!ReportedAmbiguousConversions) { 11684 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11685 ReportedAmbiguousConversions = true; 11686 } 11687 11688 // If this is a viable builtin, print it. 11689 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11690 } 11691 } 11692 11693 if (I != E) 11694 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11695 } 11696 11697 static SourceLocation 11698 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11699 return Cand->Specialization ? Cand->Specialization->getLocation() 11700 : SourceLocation(); 11701 } 11702 11703 namespace { 11704 struct CompareTemplateSpecCandidatesForDisplay { 11705 Sema &S; 11706 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11707 11708 bool operator()(const TemplateSpecCandidate *L, 11709 const TemplateSpecCandidate *R) { 11710 // Fast-path this check. 11711 if (L == R) 11712 return false; 11713 11714 // Assuming that both candidates are not matches... 11715 11716 // Sort by the ranking of deduction failures. 11717 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11718 return RankDeductionFailure(L->DeductionFailure) < 11719 RankDeductionFailure(R->DeductionFailure); 11720 11721 // Sort everything else by location. 11722 SourceLocation LLoc = GetLocationForCandidate(L); 11723 SourceLocation RLoc = GetLocationForCandidate(R); 11724 11725 // Put candidates without locations (e.g. builtins) at the end. 11726 if (LLoc.isInvalid()) 11727 return false; 11728 if (RLoc.isInvalid()) 11729 return true; 11730 11731 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11732 } 11733 }; 11734 } 11735 11736 /// Diagnose a template argument deduction failure. 11737 /// We are treating these failures as overload failures due to bad 11738 /// deductions. 11739 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11740 bool ForTakingAddress) { 11741 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11742 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11743 } 11744 11745 void TemplateSpecCandidateSet::destroyCandidates() { 11746 for (iterator i = begin(), e = end(); i != e; ++i) { 11747 i->DeductionFailure.Destroy(); 11748 } 11749 } 11750 11751 void TemplateSpecCandidateSet::clear() { 11752 destroyCandidates(); 11753 Candidates.clear(); 11754 } 11755 11756 /// NoteCandidates - When no template specialization match is found, prints 11757 /// diagnostic messages containing the non-matching specializations that form 11758 /// the candidate set. 11759 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11760 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11761 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11762 // Sort the candidates by position (assuming no candidate is a match). 11763 // Sorting directly would be prohibitive, so we make a set of pointers 11764 // and sort those. 11765 SmallVector<TemplateSpecCandidate *, 32> Cands; 11766 Cands.reserve(size()); 11767 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11768 if (Cand->Specialization) 11769 Cands.push_back(Cand); 11770 // Otherwise, this is a non-matching builtin candidate. We do not, 11771 // in general, want to list every possible builtin candidate. 11772 } 11773 11774 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11775 11776 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11777 // for generalization purposes (?). 11778 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11779 11780 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11781 unsigned CandsShown = 0; 11782 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11783 TemplateSpecCandidate *Cand = *I; 11784 11785 // Set an arbitrary limit on the number of candidates we'll spam 11786 // the user with. FIXME: This limit should depend on details of the 11787 // candidate list. 11788 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11789 break; 11790 ++CandsShown; 11791 11792 assert(Cand->Specialization && 11793 "Non-matching built-in candidates are not added to Cands."); 11794 Cand->NoteDeductionFailure(S, ForTakingAddress); 11795 } 11796 11797 if (I != E) 11798 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11799 } 11800 11801 // [PossiblyAFunctionType] --> [Return] 11802 // NonFunctionType --> NonFunctionType 11803 // R (A) --> R(A) 11804 // R (*)(A) --> R (A) 11805 // R (&)(A) --> R (A) 11806 // R (S::*)(A) --> R (A) 11807 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11808 QualType Ret = PossiblyAFunctionType; 11809 if (const PointerType *ToTypePtr = 11810 PossiblyAFunctionType->getAs<PointerType>()) 11811 Ret = ToTypePtr->getPointeeType(); 11812 else if (const ReferenceType *ToTypeRef = 11813 PossiblyAFunctionType->getAs<ReferenceType>()) 11814 Ret = ToTypeRef->getPointeeType(); 11815 else if (const MemberPointerType *MemTypePtr = 11816 PossiblyAFunctionType->getAs<MemberPointerType>()) 11817 Ret = MemTypePtr->getPointeeType(); 11818 Ret = 11819 Context.getCanonicalType(Ret).getUnqualifiedType(); 11820 return Ret; 11821 } 11822 11823 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11824 bool Complain = true) { 11825 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11826 S.DeduceReturnType(FD, Loc, Complain)) 11827 return true; 11828 11829 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11830 if (S.getLangOpts().CPlusPlus17 && 11831 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11832 !S.ResolveExceptionSpec(Loc, FPT)) 11833 return true; 11834 11835 return false; 11836 } 11837 11838 namespace { 11839 // A helper class to help with address of function resolution 11840 // - allows us to avoid passing around all those ugly parameters 11841 class AddressOfFunctionResolver { 11842 Sema& S; 11843 Expr* SourceExpr; 11844 const QualType& TargetType; 11845 QualType TargetFunctionType; // Extracted function type from target type 11846 11847 bool Complain; 11848 //DeclAccessPair& ResultFunctionAccessPair; 11849 ASTContext& Context; 11850 11851 bool TargetTypeIsNonStaticMemberFunction; 11852 bool FoundNonTemplateFunction; 11853 bool StaticMemberFunctionFromBoundPointer; 11854 bool HasComplained; 11855 11856 OverloadExpr::FindResult OvlExprInfo; 11857 OverloadExpr *OvlExpr; 11858 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11859 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11860 TemplateSpecCandidateSet FailedCandidates; 11861 11862 public: 11863 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11864 const QualType &TargetType, bool Complain) 11865 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11866 Complain(Complain), Context(S.getASTContext()), 11867 TargetTypeIsNonStaticMemberFunction( 11868 !!TargetType->getAs<MemberPointerType>()), 11869 FoundNonTemplateFunction(false), 11870 StaticMemberFunctionFromBoundPointer(false), 11871 HasComplained(false), 11872 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11873 OvlExpr(OvlExprInfo.Expression), 11874 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11875 ExtractUnqualifiedFunctionTypeFromTargetType(); 11876 11877 if (TargetFunctionType->isFunctionType()) { 11878 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11879 if (!UME->isImplicitAccess() && 11880 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11881 StaticMemberFunctionFromBoundPointer = true; 11882 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11883 DeclAccessPair dap; 11884 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11885 OvlExpr, false, &dap)) { 11886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11887 if (!Method->isStatic()) { 11888 // If the target type is a non-function type and the function found 11889 // is a non-static member function, pretend as if that was the 11890 // target, it's the only possible type to end up with. 11891 TargetTypeIsNonStaticMemberFunction = true; 11892 11893 // And skip adding the function if its not in the proper form. 11894 // We'll diagnose this due to an empty set of functions. 11895 if (!OvlExprInfo.HasFormOfMemberPointer) 11896 return; 11897 } 11898 11899 Matches.push_back(std::make_pair(dap, Fn)); 11900 } 11901 return; 11902 } 11903 11904 if (OvlExpr->hasExplicitTemplateArgs()) 11905 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11906 11907 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11908 // C++ [over.over]p4: 11909 // If more than one function is selected, [...] 11910 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11911 if (FoundNonTemplateFunction) 11912 EliminateAllTemplateMatches(); 11913 else 11914 EliminateAllExceptMostSpecializedTemplate(); 11915 } 11916 } 11917 11918 if (S.getLangOpts().CUDA && Matches.size() > 1) 11919 EliminateSuboptimalCudaMatches(); 11920 } 11921 11922 bool hasComplained() const { return HasComplained; } 11923 11924 private: 11925 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11926 QualType Discard; 11927 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11928 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11929 } 11930 11931 /// \return true if A is considered a better overload candidate for the 11932 /// desired type than B. 11933 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11934 // If A doesn't have exactly the correct type, we don't want to classify it 11935 // as "better" than anything else. This way, the user is required to 11936 // disambiguate for us if there are multiple candidates and no exact match. 11937 return candidateHasExactlyCorrectType(A) && 11938 (!candidateHasExactlyCorrectType(B) || 11939 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11940 } 11941 11942 /// \return true if we were able to eliminate all but one overload candidate, 11943 /// false otherwise. 11944 bool eliminiateSuboptimalOverloadCandidates() { 11945 // Same algorithm as overload resolution -- one pass to pick the "best", 11946 // another pass to be sure that nothing is better than the best. 11947 auto Best = Matches.begin(); 11948 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11949 if (isBetterCandidate(I->second, Best->second)) 11950 Best = I; 11951 11952 const FunctionDecl *BestFn = Best->second; 11953 auto IsBestOrInferiorToBest = [this, BestFn]( 11954 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11955 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11956 }; 11957 11958 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11959 // option, so we can potentially give the user a better error 11960 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11961 return false; 11962 Matches[0] = *Best; 11963 Matches.resize(1); 11964 return true; 11965 } 11966 11967 bool isTargetTypeAFunction() const { 11968 return TargetFunctionType->isFunctionType(); 11969 } 11970 11971 // [ToType] [Return] 11972 11973 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11974 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11975 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11976 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11977 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11978 } 11979 11980 // return true if any matching specializations were found 11981 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11982 const DeclAccessPair& CurAccessFunPair) { 11983 if (CXXMethodDecl *Method 11984 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11985 // Skip non-static function templates when converting to pointer, and 11986 // static when converting to member pointer. 11987 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11988 return false; 11989 } 11990 else if (TargetTypeIsNonStaticMemberFunction) 11991 return false; 11992 11993 // C++ [over.over]p2: 11994 // If the name is a function template, template argument deduction is 11995 // done (14.8.2.2), and if the argument deduction succeeds, the 11996 // resulting template argument list is used to generate a single 11997 // function template specialization, which is added to the set of 11998 // overloaded functions considered. 11999 FunctionDecl *Specialization = nullptr; 12000 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12001 if (Sema::TemplateDeductionResult Result 12002 = S.DeduceTemplateArguments(FunctionTemplate, 12003 &OvlExplicitTemplateArgs, 12004 TargetFunctionType, Specialization, 12005 Info, /*IsAddressOfFunction*/true)) { 12006 // Make a note of the failed deduction for diagnostics. 12007 FailedCandidates.addCandidate() 12008 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12009 MakeDeductionFailureInfo(Context, Result, Info)); 12010 return false; 12011 } 12012 12013 // Template argument deduction ensures that we have an exact match or 12014 // compatible pointer-to-function arguments that would be adjusted by ICS. 12015 // This function template specicalization works. 12016 assert(S.isSameOrCompatibleFunctionType( 12017 Context.getCanonicalType(Specialization->getType()), 12018 Context.getCanonicalType(TargetFunctionType))); 12019 12020 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12021 return false; 12022 12023 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12024 return true; 12025 } 12026 12027 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12028 const DeclAccessPair& CurAccessFunPair) { 12029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12030 // Skip non-static functions when converting to pointer, and static 12031 // when converting to member pointer. 12032 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12033 return false; 12034 } 12035 else if (TargetTypeIsNonStaticMemberFunction) 12036 return false; 12037 12038 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12039 if (S.getLangOpts().CUDA) 12040 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12041 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12042 return false; 12043 if (FunDecl->isMultiVersion()) { 12044 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12045 if (TA && !TA->isDefaultVersion()) 12046 return false; 12047 } 12048 12049 // If any candidate has a placeholder return type, trigger its deduction 12050 // now. 12051 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12052 Complain)) { 12053 HasComplained |= Complain; 12054 return false; 12055 } 12056 12057 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12058 return false; 12059 12060 // If we're in C, we need to support types that aren't exactly identical. 12061 if (!S.getLangOpts().CPlusPlus || 12062 candidateHasExactlyCorrectType(FunDecl)) { 12063 Matches.push_back(std::make_pair( 12064 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12065 FoundNonTemplateFunction = true; 12066 return true; 12067 } 12068 } 12069 12070 return false; 12071 } 12072 12073 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12074 bool Ret = false; 12075 12076 // If the overload expression doesn't have the form of a pointer to 12077 // member, don't try to convert it to a pointer-to-member type. 12078 if (IsInvalidFormOfPointerToMemberFunction()) 12079 return false; 12080 12081 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12082 E = OvlExpr->decls_end(); 12083 I != E; ++I) { 12084 // Look through any using declarations to find the underlying function. 12085 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12086 12087 // C++ [over.over]p3: 12088 // Non-member functions and static member functions match 12089 // targets of type "pointer-to-function" or "reference-to-function." 12090 // Nonstatic member functions match targets of 12091 // type "pointer-to-member-function." 12092 // Note that according to DR 247, the containing class does not matter. 12093 if (FunctionTemplateDecl *FunctionTemplate 12094 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12095 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12096 Ret = true; 12097 } 12098 // If we have explicit template arguments supplied, skip non-templates. 12099 else if (!OvlExpr->hasExplicitTemplateArgs() && 12100 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12101 Ret = true; 12102 } 12103 assert(Ret || Matches.empty()); 12104 return Ret; 12105 } 12106 12107 void EliminateAllExceptMostSpecializedTemplate() { 12108 // [...] and any given function template specialization F1 is 12109 // eliminated if the set contains a second function template 12110 // specialization whose function template is more specialized 12111 // than the function template of F1 according to the partial 12112 // ordering rules of 14.5.5.2. 12113 12114 // The algorithm specified above is quadratic. We instead use a 12115 // two-pass algorithm (similar to the one used to identify the 12116 // best viable function in an overload set) that identifies the 12117 // best function template (if it exists). 12118 12119 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12120 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12121 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12122 12123 // TODO: It looks like FailedCandidates does not serve much purpose 12124 // here, since the no_viable diagnostic has index 0. 12125 UnresolvedSetIterator Result = S.getMostSpecialized( 12126 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12127 SourceExpr->getBeginLoc(), S.PDiag(), 12128 S.PDiag(diag::err_addr_ovl_ambiguous) 12129 << Matches[0].second->getDeclName(), 12130 S.PDiag(diag::note_ovl_candidate) 12131 << (unsigned)oc_function << (unsigned)ocs_described_template, 12132 Complain, TargetFunctionType); 12133 12134 if (Result != MatchesCopy.end()) { 12135 // Make it the first and only element 12136 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12137 Matches[0].second = cast<FunctionDecl>(*Result); 12138 Matches.resize(1); 12139 } else 12140 HasComplained |= Complain; 12141 } 12142 12143 void EliminateAllTemplateMatches() { 12144 // [...] any function template specializations in the set are 12145 // eliminated if the set also contains a non-template function, [...] 12146 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12147 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12148 ++I; 12149 else { 12150 Matches[I] = Matches[--N]; 12151 Matches.resize(N); 12152 } 12153 } 12154 } 12155 12156 void EliminateSuboptimalCudaMatches() { 12157 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12158 } 12159 12160 public: 12161 void ComplainNoMatchesFound() const { 12162 assert(Matches.empty()); 12163 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12164 << OvlExpr->getName() << TargetFunctionType 12165 << OvlExpr->getSourceRange(); 12166 if (FailedCandidates.empty()) 12167 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12168 /*TakingAddress=*/true); 12169 else { 12170 // We have some deduction failure messages. Use them to diagnose 12171 // the function templates, and diagnose the non-template candidates 12172 // normally. 12173 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12174 IEnd = OvlExpr->decls_end(); 12175 I != IEnd; ++I) 12176 if (FunctionDecl *Fun = 12177 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12178 if (!functionHasPassObjectSizeParams(Fun)) 12179 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12180 /*TakingAddress=*/true); 12181 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12182 } 12183 } 12184 12185 bool IsInvalidFormOfPointerToMemberFunction() const { 12186 return TargetTypeIsNonStaticMemberFunction && 12187 !OvlExprInfo.HasFormOfMemberPointer; 12188 } 12189 12190 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12191 // TODO: Should we condition this on whether any functions might 12192 // have matched, or is it more appropriate to do that in callers? 12193 // TODO: a fixit wouldn't hurt. 12194 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12195 << TargetType << OvlExpr->getSourceRange(); 12196 } 12197 12198 bool IsStaticMemberFunctionFromBoundPointer() const { 12199 return StaticMemberFunctionFromBoundPointer; 12200 } 12201 12202 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12203 S.Diag(OvlExpr->getBeginLoc(), 12204 diag::err_invalid_form_pointer_member_function) 12205 << OvlExpr->getSourceRange(); 12206 } 12207 12208 void ComplainOfInvalidConversion() const { 12209 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12210 << OvlExpr->getName() << TargetType; 12211 } 12212 12213 void ComplainMultipleMatchesFound() const { 12214 assert(Matches.size() > 1); 12215 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12216 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12217 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12218 /*TakingAddress=*/true); 12219 } 12220 12221 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12222 12223 int getNumMatches() const { return Matches.size(); } 12224 12225 FunctionDecl* getMatchingFunctionDecl() const { 12226 if (Matches.size() != 1) return nullptr; 12227 return Matches[0].second; 12228 } 12229 12230 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12231 if (Matches.size() != 1) return nullptr; 12232 return &Matches[0].first; 12233 } 12234 }; 12235 } 12236 12237 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12238 /// an overloaded function (C++ [over.over]), where @p From is an 12239 /// expression with overloaded function type and @p ToType is the type 12240 /// we're trying to resolve to. For example: 12241 /// 12242 /// @code 12243 /// int f(double); 12244 /// int f(int); 12245 /// 12246 /// int (*pfd)(double) = f; // selects f(double) 12247 /// @endcode 12248 /// 12249 /// This routine returns the resulting FunctionDecl if it could be 12250 /// resolved, and NULL otherwise. When @p Complain is true, this 12251 /// routine will emit diagnostics if there is an error. 12252 FunctionDecl * 12253 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12254 QualType TargetType, 12255 bool Complain, 12256 DeclAccessPair &FoundResult, 12257 bool *pHadMultipleCandidates) { 12258 assert(AddressOfExpr->getType() == Context.OverloadTy); 12259 12260 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12261 Complain); 12262 int NumMatches = Resolver.getNumMatches(); 12263 FunctionDecl *Fn = nullptr; 12264 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12265 if (NumMatches == 0 && ShouldComplain) { 12266 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12267 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12268 else 12269 Resolver.ComplainNoMatchesFound(); 12270 } 12271 else if (NumMatches > 1 && ShouldComplain) 12272 Resolver.ComplainMultipleMatchesFound(); 12273 else if (NumMatches == 1) { 12274 Fn = Resolver.getMatchingFunctionDecl(); 12275 assert(Fn); 12276 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12277 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12278 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12279 if (Complain) { 12280 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12281 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12282 else 12283 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12284 } 12285 } 12286 12287 if (pHadMultipleCandidates) 12288 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12289 return Fn; 12290 } 12291 12292 /// Given an expression that refers to an overloaded function, try to 12293 /// resolve that function to a single function that can have its address taken. 12294 /// This will modify `Pair` iff it returns non-null. 12295 /// 12296 /// This routine can only succeed if from all of the candidates in the overload 12297 /// set for SrcExpr that can have their addresses taken, there is one candidate 12298 /// that is more constrained than the rest. 12299 FunctionDecl * 12300 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12301 OverloadExpr::FindResult R = OverloadExpr::find(E); 12302 OverloadExpr *Ovl = R.Expression; 12303 bool IsResultAmbiguous = false; 12304 FunctionDecl *Result = nullptr; 12305 DeclAccessPair DAP; 12306 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12307 12308 auto CheckMoreConstrained = 12309 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12310 SmallVector<const Expr *, 1> AC1, AC2; 12311 FD1->getAssociatedConstraints(AC1); 12312 FD2->getAssociatedConstraints(AC2); 12313 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12314 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12315 return None; 12316 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12317 return None; 12318 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12319 return None; 12320 return AtLeastAsConstrained1; 12321 }; 12322 12323 // Don't use the AddressOfResolver because we're specifically looking for 12324 // cases where we have one overload candidate that lacks 12325 // enable_if/pass_object_size/... 12326 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12327 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12328 if (!FD) 12329 return nullptr; 12330 12331 if (!checkAddressOfFunctionIsAvailable(FD)) 12332 continue; 12333 12334 // We have more than one result - see if it is more constrained than the 12335 // previous one. 12336 if (Result) { 12337 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12338 Result); 12339 if (!MoreConstrainedThanPrevious) { 12340 IsResultAmbiguous = true; 12341 AmbiguousDecls.push_back(FD); 12342 continue; 12343 } 12344 if (!*MoreConstrainedThanPrevious) 12345 continue; 12346 // FD is more constrained - replace Result with it. 12347 } 12348 IsResultAmbiguous = false; 12349 DAP = I.getPair(); 12350 Result = FD; 12351 } 12352 12353 if (IsResultAmbiguous) 12354 return nullptr; 12355 12356 if (Result) { 12357 SmallVector<const Expr *, 1> ResultAC; 12358 // We skipped over some ambiguous declarations which might be ambiguous with 12359 // the selected result. 12360 for (FunctionDecl *Skipped : AmbiguousDecls) 12361 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12362 return nullptr; 12363 Pair = DAP; 12364 } 12365 return Result; 12366 } 12367 12368 /// Given an overloaded function, tries to turn it into a non-overloaded 12369 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12370 /// will perform access checks, diagnose the use of the resultant decl, and, if 12371 /// requested, potentially perform a function-to-pointer decay. 12372 /// 12373 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12374 /// Otherwise, returns true. This may emit diagnostics and return true. 12375 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12376 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12377 Expr *E = SrcExpr.get(); 12378 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12379 12380 DeclAccessPair DAP; 12381 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12382 if (!Found || Found->isCPUDispatchMultiVersion() || 12383 Found->isCPUSpecificMultiVersion()) 12384 return false; 12385 12386 // Emitting multiple diagnostics for a function that is both inaccessible and 12387 // unavailable is consistent with our behavior elsewhere. So, always check 12388 // for both. 12389 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12390 CheckAddressOfMemberAccess(E, DAP); 12391 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12392 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12393 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12394 else 12395 SrcExpr = Fixed; 12396 return true; 12397 } 12398 12399 /// Given an expression that refers to an overloaded function, try to 12400 /// resolve that overloaded function expression down to a single function. 12401 /// 12402 /// This routine can only resolve template-ids that refer to a single function 12403 /// template, where that template-id refers to a single template whose template 12404 /// arguments are either provided by the template-id or have defaults, 12405 /// as described in C++0x [temp.arg.explicit]p3. 12406 /// 12407 /// If no template-ids are found, no diagnostics are emitted and NULL is 12408 /// returned. 12409 FunctionDecl * 12410 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12411 bool Complain, 12412 DeclAccessPair *FoundResult) { 12413 // C++ [over.over]p1: 12414 // [...] [Note: any redundant set of parentheses surrounding the 12415 // overloaded function name is ignored (5.1). ] 12416 // C++ [over.over]p1: 12417 // [...] The overloaded function name can be preceded by the & 12418 // operator. 12419 12420 // If we didn't actually find any template-ids, we're done. 12421 if (!ovl->hasExplicitTemplateArgs()) 12422 return nullptr; 12423 12424 TemplateArgumentListInfo ExplicitTemplateArgs; 12425 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12426 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12427 12428 // Look through all of the overloaded functions, searching for one 12429 // whose type matches exactly. 12430 FunctionDecl *Matched = nullptr; 12431 for (UnresolvedSetIterator I = ovl->decls_begin(), 12432 E = ovl->decls_end(); I != E; ++I) { 12433 // C++0x [temp.arg.explicit]p3: 12434 // [...] In contexts where deduction is done and fails, or in contexts 12435 // where deduction is not done, if a template argument list is 12436 // specified and it, along with any default template arguments, 12437 // identifies a single function template specialization, then the 12438 // template-id is an lvalue for the function template specialization. 12439 FunctionTemplateDecl *FunctionTemplate 12440 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12441 12442 // C++ [over.over]p2: 12443 // If the name is a function template, template argument deduction is 12444 // done (14.8.2.2), and if the argument deduction succeeds, the 12445 // resulting template argument list is used to generate a single 12446 // function template specialization, which is added to the set of 12447 // overloaded functions considered. 12448 FunctionDecl *Specialization = nullptr; 12449 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12450 if (TemplateDeductionResult Result 12451 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12452 Specialization, Info, 12453 /*IsAddressOfFunction*/true)) { 12454 // Make a note of the failed deduction for diagnostics. 12455 // TODO: Actually use the failed-deduction info? 12456 FailedCandidates.addCandidate() 12457 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12458 MakeDeductionFailureInfo(Context, Result, Info)); 12459 continue; 12460 } 12461 12462 assert(Specialization && "no specialization and no error?"); 12463 12464 // Multiple matches; we can't resolve to a single declaration. 12465 if (Matched) { 12466 if (Complain) { 12467 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12468 << ovl->getName(); 12469 NoteAllOverloadCandidates(ovl); 12470 } 12471 return nullptr; 12472 } 12473 12474 Matched = Specialization; 12475 if (FoundResult) *FoundResult = I.getPair(); 12476 } 12477 12478 if (Matched && 12479 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12480 return nullptr; 12481 12482 return Matched; 12483 } 12484 12485 // Resolve and fix an overloaded expression that can be resolved 12486 // because it identifies a single function template specialization. 12487 // 12488 // Last three arguments should only be supplied if Complain = true 12489 // 12490 // Return true if it was logically possible to so resolve the 12491 // expression, regardless of whether or not it succeeded. Always 12492 // returns true if 'complain' is set. 12493 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12494 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12495 bool complain, SourceRange OpRangeForComplaining, 12496 QualType DestTypeForComplaining, 12497 unsigned DiagIDForComplaining) { 12498 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12499 12500 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12501 12502 DeclAccessPair found; 12503 ExprResult SingleFunctionExpression; 12504 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12505 ovl.Expression, /*complain*/ false, &found)) { 12506 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12507 SrcExpr = ExprError(); 12508 return true; 12509 } 12510 12511 // It is only correct to resolve to an instance method if we're 12512 // resolving a form that's permitted to be a pointer to member. 12513 // Otherwise we'll end up making a bound member expression, which 12514 // is illegal in all the contexts we resolve like this. 12515 if (!ovl.HasFormOfMemberPointer && 12516 isa<CXXMethodDecl>(fn) && 12517 cast<CXXMethodDecl>(fn)->isInstance()) { 12518 if (!complain) return false; 12519 12520 Diag(ovl.Expression->getExprLoc(), 12521 diag::err_bound_member_function) 12522 << 0 << ovl.Expression->getSourceRange(); 12523 12524 // TODO: I believe we only end up here if there's a mix of 12525 // static and non-static candidates (otherwise the expression 12526 // would have 'bound member' type, not 'overload' type). 12527 // Ideally we would note which candidate was chosen and why 12528 // the static candidates were rejected. 12529 SrcExpr = ExprError(); 12530 return true; 12531 } 12532 12533 // Fix the expression to refer to 'fn'. 12534 SingleFunctionExpression = 12535 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12536 12537 // If desired, do function-to-pointer decay. 12538 if (doFunctionPointerConverion) { 12539 SingleFunctionExpression = 12540 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12541 if (SingleFunctionExpression.isInvalid()) { 12542 SrcExpr = ExprError(); 12543 return true; 12544 } 12545 } 12546 } 12547 12548 if (!SingleFunctionExpression.isUsable()) { 12549 if (complain) { 12550 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12551 << ovl.Expression->getName() 12552 << DestTypeForComplaining 12553 << OpRangeForComplaining 12554 << ovl.Expression->getQualifierLoc().getSourceRange(); 12555 NoteAllOverloadCandidates(SrcExpr.get()); 12556 12557 SrcExpr = ExprError(); 12558 return true; 12559 } 12560 12561 return false; 12562 } 12563 12564 SrcExpr = SingleFunctionExpression; 12565 return true; 12566 } 12567 12568 /// Add a single candidate to the overload set. 12569 static void AddOverloadedCallCandidate(Sema &S, 12570 DeclAccessPair FoundDecl, 12571 TemplateArgumentListInfo *ExplicitTemplateArgs, 12572 ArrayRef<Expr *> Args, 12573 OverloadCandidateSet &CandidateSet, 12574 bool PartialOverloading, 12575 bool KnownValid) { 12576 NamedDecl *Callee = FoundDecl.getDecl(); 12577 if (isa<UsingShadowDecl>(Callee)) 12578 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12579 12580 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12581 if (ExplicitTemplateArgs) { 12582 assert(!KnownValid && "Explicit template arguments?"); 12583 return; 12584 } 12585 // Prevent ill-formed function decls to be added as overload candidates. 12586 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12587 return; 12588 12589 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12590 /*SuppressUserConversions=*/false, 12591 PartialOverloading); 12592 return; 12593 } 12594 12595 if (FunctionTemplateDecl *FuncTemplate 12596 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12597 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12598 ExplicitTemplateArgs, Args, CandidateSet, 12599 /*SuppressUserConversions=*/false, 12600 PartialOverloading); 12601 return; 12602 } 12603 12604 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12605 } 12606 12607 /// Add the overload candidates named by callee and/or found by argument 12608 /// dependent lookup to the given overload set. 12609 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12610 ArrayRef<Expr *> Args, 12611 OverloadCandidateSet &CandidateSet, 12612 bool PartialOverloading) { 12613 12614 #ifndef NDEBUG 12615 // Verify that ArgumentDependentLookup is consistent with the rules 12616 // in C++0x [basic.lookup.argdep]p3: 12617 // 12618 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12619 // and let Y be the lookup set produced by argument dependent 12620 // lookup (defined as follows). If X contains 12621 // 12622 // -- a declaration of a class member, or 12623 // 12624 // -- a block-scope function declaration that is not a 12625 // using-declaration, or 12626 // 12627 // -- a declaration that is neither a function or a function 12628 // template 12629 // 12630 // then Y is empty. 12631 12632 if (ULE->requiresADL()) { 12633 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12634 E = ULE->decls_end(); I != E; ++I) { 12635 assert(!(*I)->getDeclContext()->isRecord()); 12636 assert(isa<UsingShadowDecl>(*I) || 12637 !(*I)->getDeclContext()->isFunctionOrMethod()); 12638 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12639 } 12640 } 12641 #endif 12642 12643 // It would be nice to avoid this copy. 12644 TemplateArgumentListInfo TABuffer; 12645 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12646 if (ULE->hasExplicitTemplateArgs()) { 12647 ULE->copyTemplateArgumentsInto(TABuffer); 12648 ExplicitTemplateArgs = &TABuffer; 12649 } 12650 12651 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12652 E = ULE->decls_end(); I != E; ++I) 12653 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12654 CandidateSet, PartialOverloading, 12655 /*KnownValid*/ true); 12656 12657 if (ULE->requiresADL()) 12658 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12659 Args, ExplicitTemplateArgs, 12660 CandidateSet, PartialOverloading); 12661 } 12662 12663 /// Determine whether a declaration with the specified name could be moved into 12664 /// a different namespace. 12665 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12666 switch (Name.getCXXOverloadedOperator()) { 12667 case OO_New: case OO_Array_New: 12668 case OO_Delete: case OO_Array_Delete: 12669 return false; 12670 12671 default: 12672 return true; 12673 } 12674 } 12675 12676 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12677 /// template, where the non-dependent name was declared after the template 12678 /// was defined. This is common in code written for a compilers which do not 12679 /// correctly implement two-stage name lookup. 12680 /// 12681 /// Returns true if a viable candidate was found and a diagnostic was issued. 12682 static bool 12683 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12684 const CXXScopeSpec &SS, LookupResult &R, 12685 OverloadCandidateSet::CandidateSetKind CSK, 12686 TemplateArgumentListInfo *ExplicitTemplateArgs, 12687 ArrayRef<Expr *> Args, 12688 bool *DoDiagnoseEmptyLookup = nullptr) { 12689 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12690 return false; 12691 12692 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12693 if (DC->isTransparentContext()) 12694 continue; 12695 12696 SemaRef.LookupQualifiedName(R, DC); 12697 12698 if (!R.empty()) { 12699 R.suppressDiagnostics(); 12700 12701 if (isa<CXXRecordDecl>(DC)) { 12702 // Don't diagnose names we find in classes; we get much better 12703 // diagnostics for these from DiagnoseEmptyLookup. 12704 R.clear(); 12705 if (DoDiagnoseEmptyLookup) 12706 *DoDiagnoseEmptyLookup = true; 12707 return false; 12708 } 12709 12710 OverloadCandidateSet Candidates(FnLoc, CSK); 12711 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12712 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12713 ExplicitTemplateArgs, Args, 12714 Candidates, false, /*KnownValid*/ false); 12715 12716 OverloadCandidateSet::iterator Best; 12717 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12718 // No viable functions. Don't bother the user with notes for functions 12719 // which don't work and shouldn't be found anyway. 12720 R.clear(); 12721 return false; 12722 } 12723 12724 // Find the namespaces where ADL would have looked, and suggest 12725 // declaring the function there instead. 12726 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12727 Sema::AssociatedClassSet AssociatedClasses; 12728 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12729 AssociatedNamespaces, 12730 AssociatedClasses); 12731 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12732 if (canBeDeclaredInNamespace(R.getLookupName())) { 12733 DeclContext *Std = SemaRef.getStdNamespace(); 12734 for (Sema::AssociatedNamespaceSet::iterator 12735 it = AssociatedNamespaces.begin(), 12736 end = AssociatedNamespaces.end(); it != end; ++it) { 12737 // Never suggest declaring a function within namespace 'std'. 12738 if (Std && Std->Encloses(*it)) 12739 continue; 12740 12741 // Never suggest declaring a function within a namespace with a 12742 // reserved name, like __gnu_cxx. 12743 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12744 if (NS && 12745 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12746 continue; 12747 12748 SuggestedNamespaces.insert(*it); 12749 } 12750 } 12751 12752 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12753 << R.getLookupName(); 12754 if (SuggestedNamespaces.empty()) { 12755 SemaRef.Diag(Best->Function->getLocation(), 12756 diag::note_not_found_by_two_phase_lookup) 12757 << R.getLookupName() << 0; 12758 } else if (SuggestedNamespaces.size() == 1) { 12759 SemaRef.Diag(Best->Function->getLocation(), 12760 diag::note_not_found_by_two_phase_lookup) 12761 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12762 } else { 12763 // FIXME: It would be useful to list the associated namespaces here, 12764 // but the diagnostics infrastructure doesn't provide a way to produce 12765 // a localized representation of a list of items. 12766 SemaRef.Diag(Best->Function->getLocation(), 12767 diag::note_not_found_by_two_phase_lookup) 12768 << R.getLookupName() << 2; 12769 } 12770 12771 // Try to recover by calling this function. 12772 return true; 12773 } 12774 12775 R.clear(); 12776 } 12777 12778 return false; 12779 } 12780 12781 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12782 /// template, where the non-dependent operator was declared after the template 12783 /// was defined. 12784 /// 12785 /// Returns true if a viable candidate was found and a diagnostic was issued. 12786 static bool 12787 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12788 SourceLocation OpLoc, 12789 ArrayRef<Expr *> Args) { 12790 DeclarationName OpName = 12791 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12792 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12793 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12794 OverloadCandidateSet::CSK_Operator, 12795 /*ExplicitTemplateArgs=*/nullptr, Args); 12796 } 12797 12798 namespace { 12799 class BuildRecoveryCallExprRAII { 12800 Sema &SemaRef; 12801 public: 12802 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12803 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12804 SemaRef.IsBuildingRecoveryCallExpr = true; 12805 } 12806 12807 ~BuildRecoveryCallExprRAII() { 12808 SemaRef.IsBuildingRecoveryCallExpr = false; 12809 } 12810 }; 12811 12812 } 12813 12814 /// Attempts to recover from a call where no functions were found. 12815 static ExprResult 12816 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12817 UnresolvedLookupExpr *ULE, 12818 SourceLocation LParenLoc, 12819 MutableArrayRef<Expr *> Args, 12820 SourceLocation RParenLoc, 12821 bool EmptyLookup, bool AllowTypoCorrection) { 12822 // Do not try to recover if it is already building a recovery call. 12823 // This stops infinite loops for template instantiations like 12824 // 12825 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12826 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12827 // 12828 if (SemaRef.IsBuildingRecoveryCallExpr) 12829 return ExprError(); 12830 BuildRecoveryCallExprRAII RCE(SemaRef); 12831 12832 CXXScopeSpec SS; 12833 SS.Adopt(ULE->getQualifierLoc()); 12834 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12835 12836 TemplateArgumentListInfo TABuffer; 12837 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12838 if (ULE->hasExplicitTemplateArgs()) { 12839 ULE->copyTemplateArgumentsInto(TABuffer); 12840 ExplicitTemplateArgs = &TABuffer; 12841 } 12842 12843 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12844 Sema::LookupOrdinaryName); 12845 bool DoDiagnoseEmptyLookup = EmptyLookup; 12846 if (!DiagnoseTwoPhaseLookup( 12847 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12848 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12849 NoTypoCorrectionCCC NoTypoValidator{}; 12850 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12851 ExplicitTemplateArgs != nullptr, 12852 dyn_cast<MemberExpr>(Fn)); 12853 CorrectionCandidateCallback &Validator = 12854 AllowTypoCorrection 12855 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12856 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12857 if (!DoDiagnoseEmptyLookup || 12858 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12859 Args)) 12860 return ExprError(); 12861 } 12862 12863 assert(!R.empty() && "lookup results empty despite recovery"); 12864 12865 // If recovery created an ambiguity, just bail out. 12866 if (R.isAmbiguous()) { 12867 R.suppressDiagnostics(); 12868 return ExprError(); 12869 } 12870 12871 // Build an implicit member access expression if appropriate. Just drop the 12872 // casts and such from the call, we don't really care. 12873 ExprResult NewFn = ExprError(); 12874 if ((*R.begin())->isCXXClassMember()) 12875 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12876 ExplicitTemplateArgs, S); 12877 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12878 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12879 ExplicitTemplateArgs); 12880 else 12881 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12882 12883 if (NewFn.isInvalid()) 12884 return ExprError(); 12885 12886 auto CallE = 12887 SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12888 MultiExprArg(Args.data(), Args.size()), RParenLoc); 12889 if (CallE.isInvalid()) 12890 return ExprError(); 12891 // We now have recovered a callee. However, building a real call may lead to 12892 // incorrect secondary diagnostics if our recovery wasn't correct. 12893 // We keep the recovery behavior but suppress all following diagnostics by 12894 // using RecoveryExpr. We deliberately drop the return type of the recovery 12895 // function, and rely on clang's dependent mechanism to suppress following 12896 // diagnostics. 12897 return SemaRef.CreateRecoveryExpr(CallE.get()->getBeginLoc(), 12898 CallE.get()->getEndLoc(), {CallE.get()}); 12899 } 12900 12901 /// Constructs and populates an OverloadedCandidateSet from 12902 /// the given function. 12903 /// \returns true when an the ExprResult output parameter has been set. 12904 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12905 UnresolvedLookupExpr *ULE, 12906 MultiExprArg Args, 12907 SourceLocation RParenLoc, 12908 OverloadCandidateSet *CandidateSet, 12909 ExprResult *Result) { 12910 #ifndef NDEBUG 12911 if (ULE->requiresADL()) { 12912 // To do ADL, we must have found an unqualified name. 12913 assert(!ULE->getQualifier() && "qualified name with ADL"); 12914 12915 // We don't perform ADL for implicit declarations of builtins. 12916 // Verify that this was correctly set up. 12917 FunctionDecl *F; 12918 if (ULE->decls_begin() != ULE->decls_end() && 12919 ULE->decls_begin() + 1 == ULE->decls_end() && 12920 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12921 F->getBuiltinID() && F->isImplicit()) 12922 llvm_unreachable("performing ADL for builtin"); 12923 12924 // We don't perform ADL in C. 12925 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12926 } 12927 #endif 12928 12929 UnbridgedCastsSet UnbridgedCasts; 12930 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12931 *Result = ExprError(); 12932 return true; 12933 } 12934 12935 // Add the functions denoted by the callee to the set of candidate 12936 // functions, including those from argument-dependent lookup. 12937 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12938 12939 if (getLangOpts().MSVCCompat && 12940 CurContext->isDependentContext() && !isSFINAEContext() && 12941 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12942 12943 OverloadCandidateSet::iterator Best; 12944 if (CandidateSet->empty() || 12945 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12946 OR_No_Viable_Function) { 12947 // In Microsoft mode, if we are inside a template class member function 12948 // then create a type dependent CallExpr. The goal is to postpone name 12949 // lookup to instantiation time to be able to search into type dependent 12950 // base classes. 12951 CallExpr *CE = 12952 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue, 12953 RParenLoc, CurFPFeatureOverrides()); 12954 CE->markDependentForPostponedNameLookup(); 12955 *Result = CE; 12956 return true; 12957 } 12958 } 12959 12960 if (CandidateSet->empty()) 12961 return false; 12962 12963 UnbridgedCasts.restore(); 12964 return false; 12965 } 12966 12967 // Guess at what the return type for an unresolvable overload should be. 12968 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12969 OverloadCandidateSet::iterator *Best) { 12970 llvm::Optional<QualType> Result; 12971 // Adjust Type after seeing a candidate. 12972 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12973 if (!Candidate.Function) 12974 return; 12975 if (Candidate.Function->isInvalidDecl()) 12976 return; 12977 QualType T = Candidate.Function->getReturnType(); 12978 if (T.isNull()) 12979 return; 12980 if (!Result) 12981 Result = T; 12982 else if (Result != T) 12983 Result = QualType(); 12984 }; 12985 12986 // Look for an unambiguous type from a progressively larger subset. 12987 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12988 // 12989 // First, consider only the best candidate. 12990 if (Best && *Best != CS.end()) 12991 ConsiderCandidate(**Best); 12992 // Next, consider only viable candidates. 12993 if (!Result) 12994 for (const auto &C : CS) 12995 if (C.Viable) 12996 ConsiderCandidate(C); 12997 // Finally, consider all candidates. 12998 if (!Result) 12999 for (const auto &C : CS) 13000 ConsiderCandidate(C); 13001 13002 if (!Result) 13003 return QualType(); 13004 auto Value = Result.getValue(); 13005 if (Value.isNull() || Value->isUndeducedType()) 13006 return QualType(); 13007 return Value; 13008 } 13009 13010 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13011 /// the completed call expression. If overload resolution fails, emits 13012 /// diagnostics and returns ExprError() 13013 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13014 UnresolvedLookupExpr *ULE, 13015 SourceLocation LParenLoc, 13016 MultiExprArg Args, 13017 SourceLocation RParenLoc, 13018 Expr *ExecConfig, 13019 OverloadCandidateSet *CandidateSet, 13020 OverloadCandidateSet::iterator *Best, 13021 OverloadingResult OverloadResult, 13022 bool AllowTypoCorrection) { 13023 if (CandidateSet->empty()) 13024 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 13025 RParenLoc, /*EmptyLookup=*/true, 13026 AllowTypoCorrection); 13027 13028 switch (OverloadResult) { 13029 case OR_Success: { 13030 FunctionDecl *FDecl = (*Best)->Function; 13031 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13032 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13033 return ExprError(); 13034 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13035 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13036 ExecConfig, /*IsExecConfig=*/false, 13037 (*Best)->IsADLCandidate); 13038 } 13039 13040 case OR_No_Viable_Function: { 13041 // Try to recover by looking for viable functions which the user might 13042 // have meant to call. 13043 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13044 Args, RParenLoc, 13045 /*EmptyLookup=*/false, 13046 AllowTypoCorrection); 13047 if (!Recovery.isInvalid()) 13048 return Recovery; 13049 13050 // If the user passes in a function that we can't take the address of, we 13051 // generally end up emitting really bad error messages. Here, we attempt to 13052 // emit better ones. 13053 for (const Expr *Arg : Args) { 13054 if (!Arg->getType()->isFunctionType()) 13055 continue; 13056 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13057 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13058 if (FD && 13059 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13060 Arg->getExprLoc())) 13061 return ExprError(); 13062 } 13063 } 13064 13065 CandidateSet->NoteCandidates( 13066 PartialDiagnosticAt( 13067 Fn->getBeginLoc(), 13068 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13069 << ULE->getName() << Fn->getSourceRange()), 13070 SemaRef, OCD_AllCandidates, Args); 13071 break; 13072 } 13073 13074 case OR_Ambiguous: 13075 CandidateSet->NoteCandidates( 13076 PartialDiagnosticAt(Fn->getBeginLoc(), 13077 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13078 << ULE->getName() << Fn->getSourceRange()), 13079 SemaRef, OCD_AmbiguousCandidates, Args); 13080 break; 13081 13082 case OR_Deleted: { 13083 CandidateSet->NoteCandidates( 13084 PartialDiagnosticAt(Fn->getBeginLoc(), 13085 SemaRef.PDiag(diag::err_ovl_deleted_call) 13086 << ULE->getName() << Fn->getSourceRange()), 13087 SemaRef, OCD_AllCandidates, Args); 13088 13089 // We emitted an error for the unavailable/deleted function call but keep 13090 // the call in the AST. 13091 FunctionDecl *FDecl = (*Best)->Function; 13092 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13093 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13094 ExecConfig, /*IsExecConfig=*/false, 13095 (*Best)->IsADLCandidate); 13096 } 13097 } 13098 13099 // Overload resolution failed, try to recover. 13100 SmallVector<Expr *, 8> SubExprs = {Fn}; 13101 SubExprs.append(Args.begin(), Args.end()); 13102 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13103 chooseRecoveryType(*CandidateSet, Best)); 13104 } 13105 13106 static void markUnaddressableCandidatesUnviable(Sema &S, 13107 OverloadCandidateSet &CS) { 13108 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13109 if (I->Viable && 13110 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13111 I->Viable = false; 13112 I->FailureKind = ovl_fail_addr_not_available; 13113 } 13114 } 13115 } 13116 13117 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13118 /// (which eventually refers to the declaration Func) and the call 13119 /// arguments Args/NumArgs, attempt to resolve the function call down 13120 /// to a specific function. If overload resolution succeeds, returns 13121 /// the call expression produced by overload resolution. 13122 /// Otherwise, emits diagnostics and returns ExprError. 13123 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13124 UnresolvedLookupExpr *ULE, 13125 SourceLocation LParenLoc, 13126 MultiExprArg Args, 13127 SourceLocation RParenLoc, 13128 Expr *ExecConfig, 13129 bool AllowTypoCorrection, 13130 bool CalleesAddressIsTaken) { 13131 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13132 OverloadCandidateSet::CSK_Normal); 13133 ExprResult result; 13134 13135 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13136 &result)) 13137 return result; 13138 13139 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13140 // functions that aren't addressible are considered unviable. 13141 if (CalleesAddressIsTaken) 13142 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13143 13144 OverloadCandidateSet::iterator Best; 13145 OverloadingResult OverloadResult = 13146 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13147 13148 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13149 ExecConfig, &CandidateSet, &Best, 13150 OverloadResult, AllowTypoCorrection); 13151 } 13152 13153 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13154 return Functions.size() > 1 || 13155 (Functions.size() == 1 && 13156 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13157 } 13158 13159 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13160 NestedNameSpecifierLoc NNSLoc, 13161 DeclarationNameInfo DNI, 13162 const UnresolvedSetImpl &Fns, 13163 bool PerformADL) { 13164 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13165 PerformADL, IsOverloaded(Fns), 13166 Fns.begin(), Fns.end()); 13167 } 13168 13169 /// Create a unary operation that may resolve to an overloaded 13170 /// operator. 13171 /// 13172 /// \param OpLoc The location of the operator itself (e.g., '*'). 13173 /// 13174 /// \param Opc The UnaryOperatorKind that describes this operator. 13175 /// 13176 /// \param Fns The set of non-member functions that will be 13177 /// considered by overload resolution. The caller needs to build this 13178 /// set based on the context using, e.g., 13179 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13180 /// set should not contain any member functions; those will be added 13181 /// by CreateOverloadedUnaryOp(). 13182 /// 13183 /// \param Input The input argument. 13184 ExprResult 13185 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13186 const UnresolvedSetImpl &Fns, 13187 Expr *Input, bool PerformADL) { 13188 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13189 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13190 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13191 // TODO: provide better source location info. 13192 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13193 13194 if (checkPlaceholderForOverload(*this, Input)) 13195 return ExprError(); 13196 13197 Expr *Args[2] = { Input, nullptr }; 13198 unsigned NumArgs = 1; 13199 13200 // For post-increment and post-decrement, add the implicit '0' as 13201 // the second argument, so that we know this is a post-increment or 13202 // post-decrement. 13203 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13204 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13205 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13206 SourceLocation()); 13207 NumArgs = 2; 13208 } 13209 13210 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13211 13212 if (Input->isTypeDependent()) { 13213 if (Fns.empty()) 13214 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13215 VK_RValue, OK_Ordinary, OpLoc, false, 13216 CurFPFeatureOverrides()); 13217 13218 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13219 ExprResult Fn = CreateUnresolvedLookupExpr( 13220 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13221 if (Fn.isInvalid()) 13222 return ExprError(); 13223 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13224 Context.DependentTy, VK_RValue, OpLoc, 13225 CurFPFeatureOverrides()); 13226 } 13227 13228 // Build an empty overload set. 13229 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13230 13231 // Add the candidates from the given function set. 13232 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13233 13234 // Add operator candidates that are member functions. 13235 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13236 13237 // Add candidates from ADL. 13238 if (PerformADL) { 13239 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13240 /*ExplicitTemplateArgs*/nullptr, 13241 CandidateSet); 13242 } 13243 13244 // Add builtin operator candidates. 13245 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13246 13247 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13248 13249 // Perform overload resolution. 13250 OverloadCandidateSet::iterator Best; 13251 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13252 case OR_Success: { 13253 // We found a built-in operator or an overloaded operator. 13254 FunctionDecl *FnDecl = Best->Function; 13255 13256 if (FnDecl) { 13257 Expr *Base = nullptr; 13258 // We matched an overloaded operator. Build a call to that 13259 // operator. 13260 13261 // Convert the arguments. 13262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13263 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13264 13265 ExprResult InputRes = 13266 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13267 Best->FoundDecl, Method); 13268 if (InputRes.isInvalid()) 13269 return ExprError(); 13270 Base = Input = InputRes.get(); 13271 } else { 13272 // Convert the arguments. 13273 ExprResult InputInit 13274 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13275 Context, 13276 FnDecl->getParamDecl(0)), 13277 SourceLocation(), 13278 Input); 13279 if (InputInit.isInvalid()) 13280 return ExprError(); 13281 Input = InputInit.get(); 13282 } 13283 13284 // Build the actual expression node. 13285 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13286 Base, HadMultipleCandidates, 13287 OpLoc); 13288 if (FnExpr.isInvalid()) 13289 return ExprError(); 13290 13291 // Determine the result type. 13292 QualType ResultTy = FnDecl->getReturnType(); 13293 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13294 ResultTy = ResultTy.getNonLValueExprType(Context); 13295 13296 Args[0] = Input; 13297 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13298 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13299 CurFPFeatureOverrides(), Best->IsADLCandidate); 13300 13301 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13302 return ExprError(); 13303 13304 if (CheckFunctionCall(FnDecl, TheCall, 13305 FnDecl->getType()->castAs<FunctionProtoType>())) 13306 return ExprError(); 13307 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13308 } else { 13309 // We matched a built-in operator. Convert the arguments, then 13310 // break out so that we will build the appropriate built-in 13311 // operator node. 13312 ExprResult InputRes = PerformImplicitConversion( 13313 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13314 CCK_ForBuiltinOverloadedOp); 13315 if (InputRes.isInvalid()) 13316 return ExprError(); 13317 Input = InputRes.get(); 13318 break; 13319 } 13320 } 13321 13322 case OR_No_Viable_Function: 13323 // This is an erroneous use of an operator which can be overloaded by 13324 // a non-member function. Check for non-member operators which were 13325 // defined too late to be candidates. 13326 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13327 // FIXME: Recover by calling the found function. 13328 return ExprError(); 13329 13330 // No viable function; fall through to handling this as a 13331 // built-in operator, which will produce an error message for us. 13332 break; 13333 13334 case OR_Ambiguous: 13335 CandidateSet.NoteCandidates( 13336 PartialDiagnosticAt(OpLoc, 13337 PDiag(diag::err_ovl_ambiguous_oper_unary) 13338 << UnaryOperator::getOpcodeStr(Opc) 13339 << Input->getType() << Input->getSourceRange()), 13340 *this, OCD_AmbiguousCandidates, ArgsArray, 13341 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13342 return ExprError(); 13343 13344 case OR_Deleted: 13345 CandidateSet.NoteCandidates( 13346 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13347 << UnaryOperator::getOpcodeStr(Opc) 13348 << Input->getSourceRange()), 13349 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13350 OpLoc); 13351 return ExprError(); 13352 } 13353 13354 // Either we found no viable overloaded operator or we matched a 13355 // built-in operator. In either case, fall through to trying to 13356 // build a built-in operation. 13357 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13358 } 13359 13360 /// Perform lookup for an overloaded binary operator. 13361 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13362 OverloadedOperatorKind Op, 13363 const UnresolvedSetImpl &Fns, 13364 ArrayRef<Expr *> Args, bool PerformADL) { 13365 SourceLocation OpLoc = CandidateSet.getLocation(); 13366 13367 OverloadedOperatorKind ExtraOp = 13368 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13369 ? getRewrittenOverloadedOperator(Op) 13370 : OO_None; 13371 13372 // Add the candidates from the given function set. This also adds the 13373 // rewritten candidates using these functions if necessary. 13374 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13375 13376 // Add operator candidates that are member functions. 13377 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13378 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13379 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13380 OverloadCandidateParamOrder::Reversed); 13381 13382 // In C++20, also add any rewritten member candidates. 13383 if (ExtraOp) { 13384 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13385 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13386 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13387 CandidateSet, 13388 OverloadCandidateParamOrder::Reversed); 13389 } 13390 13391 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13392 // performed for an assignment operator (nor for operator[] nor operator->, 13393 // which don't get here). 13394 if (Op != OO_Equal && PerformADL) { 13395 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13396 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13397 /*ExplicitTemplateArgs*/ nullptr, 13398 CandidateSet); 13399 if (ExtraOp) { 13400 DeclarationName ExtraOpName = 13401 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13402 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13403 /*ExplicitTemplateArgs*/ nullptr, 13404 CandidateSet); 13405 } 13406 } 13407 13408 // Add builtin operator candidates. 13409 // 13410 // FIXME: We don't add any rewritten candidates here. This is strictly 13411 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13412 // resulting in our selecting a rewritten builtin candidate. For example: 13413 // 13414 // enum class E { e }; 13415 // bool operator!=(E, E) requires false; 13416 // bool k = E::e != E::e; 13417 // 13418 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13419 // it seems unreasonable to consider rewritten builtin candidates. A core 13420 // issue has been filed proposing to removed this requirement. 13421 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13422 } 13423 13424 /// Create a binary operation that may resolve to an overloaded 13425 /// operator. 13426 /// 13427 /// \param OpLoc The location of the operator itself (e.g., '+'). 13428 /// 13429 /// \param Opc The BinaryOperatorKind that describes this operator. 13430 /// 13431 /// \param Fns The set of non-member functions that will be 13432 /// considered by overload resolution. The caller needs to build this 13433 /// set based on the context using, e.g., 13434 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13435 /// set should not contain any member functions; those will be added 13436 /// by CreateOverloadedBinOp(). 13437 /// 13438 /// \param LHS Left-hand argument. 13439 /// \param RHS Right-hand argument. 13440 /// \param PerformADL Whether to consider operator candidates found by ADL. 13441 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13442 /// C++20 operator rewrites. 13443 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13444 /// the function in question. Such a function is never a candidate in 13445 /// our overload resolution. This also enables synthesizing a three-way 13446 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13447 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13448 BinaryOperatorKind Opc, 13449 const UnresolvedSetImpl &Fns, Expr *LHS, 13450 Expr *RHS, bool PerformADL, 13451 bool AllowRewrittenCandidates, 13452 FunctionDecl *DefaultedFn) { 13453 Expr *Args[2] = { LHS, RHS }; 13454 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13455 13456 if (!getLangOpts().CPlusPlus20) 13457 AllowRewrittenCandidates = false; 13458 13459 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13460 13461 // If either side is type-dependent, create an appropriate dependent 13462 // expression. 13463 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13464 if (Fns.empty()) { 13465 // If there are no functions to store, just build a dependent 13466 // BinaryOperator or CompoundAssignment. 13467 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13468 return CompoundAssignOperator::Create( 13469 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13470 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13471 Context.DependentTy); 13472 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13473 Context.DependentTy, VK_RValue, OK_Ordinary, 13474 OpLoc, CurFPFeatureOverrides()); 13475 } 13476 13477 // FIXME: save results of ADL from here? 13478 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13479 // TODO: provide better source location info in DNLoc component. 13480 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13481 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13482 ExprResult Fn = CreateUnresolvedLookupExpr( 13483 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13484 if (Fn.isInvalid()) 13485 return ExprError(); 13486 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13487 Context.DependentTy, VK_RValue, OpLoc, 13488 CurFPFeatureOverrides()); 13489 } 13490 13491 // Always do placeholder-like conversions on the RHS. 13492 if (checkPlaceholderForOverload(*this, Args[1])) 13493 return ExprError(); 13494 13495 // Do placeholder-like conversion on the LHS; note that we should 13496 // not get here with a PseudoObject LHS. 13497 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13498 if (checkPlaceholderForOverload(*this, Args[0])) 13499 return ExprError(); 13500 13501 // If this is the assignment operator, we only perform overload resolution 13502 // if the left-hand side is a class or enumeration type. This is actually 13503 // a hack. The standard requires that we do overload resolution between the 13504 // various built-in candidates, but as DR507 points out, this can lead to 13505 // problems. So we do it this way, which pretty much follows what GCC does. 13506 // Note that we go the traditional code path for compound assignment forms. 13507 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13508 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13509 13510 // If this is the .* operator, which is not overloadable, just 13511 // create a built-in binary operator. 13512 if (Opc == BO_PtrMemD) 13513 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13514 13515 // Build the overload set. 13516 OverloadCandidateSet CandidateSet( 13517 OpLoc, OverloadCandidateSet::CSK_Operator, 13518 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13519 if (DefaultedFn) 13520 CandidateSet.exclude(DefaultedFn); 13521 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13522 13523 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13524 13525 // Perform overload resolution. 13526 OverloadCandidateSet::iterator Best; 13527 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13528 case OR_Success: { 13529 // We found a built-in operator or an overloaded operator. 13530 FunctionDecl *FnDecl = Best->Function; 13531 13532 bool IsReversed = Best->isReversed(); 13533 if (IsReversed) 13534 std::swap(Args[0], Args[1]); 13535 13536 if (FnDecl) { 13537 Expr *Base = nullptr; 13538 // We matched an overloaded operator. Build a call to that 13539 // operator. 13540 13541 OverloadedOperatorKind ChosenOp = 13542 FnDecl->getDeclName().getCXXOverloadedOperator(); 13543 13544 // C++2a [over.match.oper]p9: 13545 // If a rewritten operator== candidate is selected by overload 13546 // resolution for an operator@, its return type shall be cv bool 13547 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13548 !FnDecl->getReturnType()->isBooleanType()) { 13549 bool IsExtension = 13550 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13551 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13552 : diag::err_ovl_rewrite_equalequal_not_bool) 13553 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13554 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13555 Diag(FnDecl->getLocation(), diag::note_declared_at); 13556 if (!IsExtension) 13557 return ExprError(); 13558 } 13559 13560 if (AllowRewrittenCandidates && !IsReversed && 13561 CandidateSet.getRewriteInfo().isReversible()) { 13562 // We could have reversed this operator, but didn't. Check if some 13563 // reversed form was a viable candidate, and if so, if it had a 13564 // better conversion for either parameter. If so, this call is 13565 // formally ambiguous, and allowing it is an extension. 13566 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13567 for (OverloadCandidate &Cand : CandidateSet) { 13568 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13569 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13570 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13571 if (CompareImplicitConversionSequences( 13572 *this, OpLoc, Cand.Conversions[ArgIdx], 13573 Best->Conversions[ArgIdx]) == 13574 ImplicitConversionSequence::Better) { 13575 AmbiguousWith.push_back(Cand.Function); 13576 break; 13577 } 13578 } 13579 } 13580 } 13581 13582 if (!AmbiguousWith.empty()) { 13583 bool AmbiguousWithSelf = 13584 AmbiguousWith.size() == 1 && 13585 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13586 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13587 << BinaryOperator::getOpcodeStr(Opc) 13588 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13589 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13590 if (AmbiguousWithSelf) { 13591 Diag(FnDecl->getLocation(), 13592 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13593 } else { 13594 Diag(FnDecl->getLocation(), 13595 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13596 for (auto *F : AmbiguousWith) 13597 Diag(F->getLocation(), 13598 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13599 } 13600 } 13601 } 13602 13603 // Convert the arguments. 13604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13605 // Best->Access is only meaningful for class members. 13606 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13607 13608 ExprResult Arg1 = 13609 PerformCopyInitialization( 13610 InitializedEntity::InitializeParameter(Context, 13611 FnDecl->getParamDecl(0)), 13612 SourceLocation(), Args[1]); 13613 if (Arg1.isInvalid()) 13614 return ExprError(); 13615 13616 ExprResult Arg0 = 13617 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13618 Best->FoundDecl, Method); 13619 if (Arg0.isInvalid()) 13620 return ExprError(); 13621 Base = Args[0] = Arg0.getAs<Expr>(); 13622 Args[1] = RHS = Arg1.getAs<Expr>(); 13623 } else { 13624 // Convert the arguments. 13625 ExprResult Arg0 = PerformCopyInitialization( 13626 InitializedEntity::InitializeParameter(Context, 13627 FnDecl->getParamDecl(0)), 13628 SourceLocation(), Args[0]); 13629 if (Arg0.isInvalid()) 13630 return ExprError(); 13631 13632 ExprResult Arg1 = 13633 PerformCopyInitialization( 13634 InitializedEntity::InitializeParameter(Context, 13635 FnDecl->getParamDecl(1)), 13636 SourceLocation(), Args[1]); 13637 if (Arg1.isInvalid()) 13638 return ExprError(); 13639 Args[0] = LHS = Arg0.getAs<Expr>(); 13640 Args[1] = RHS = Arg1.getAs<Expr>(); 13641 } 13642 13643 // Build the actual expression node. 13644 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13645 Best->FoundDecl, Base, 13646 HadMultipleCandidates, OpLoc); 13647 if (FnExpr.isInvalid()) 13648 return ExprError(); 13649 13650 // Determine the result type. 13651 QualType ResultTy = FnDecl->getReturnType(); 13652 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13653 ResultTy = ResultTy.getNonLValueExprType(Context); 13654 13655 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13656 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13657 CurFPFeatureOverrides(), Best->IsADLCandidate); 13658 13659 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13660 FnDecl)) 13661 return ExprError(); 13662 13663 ArrayRef<const Expr *> ArgsArray(Args, 2); 13664 const Expr *ImplicitThis = nullptr; 13665 // Cut off the implicit 'this'. 13666 if (isa<CXXMethodDecl>(FnDecl)) { 13667 ImplicitThis = ArgsArray[0]; 13668 ArgsArray = ArgsArray.slice(1); 13669 } 13670 13671 // Check for a self move. 13672 if (Op == OO_Equal) 13673 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13674 13675 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13676 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13677 VariadicDoesNotApply); 13678 13679 ExprResult R = MaybeBindToTemporary(TheCall); 13680 if (R.isInvalid()) 13681 return ExprError(); 13682 13683 R = CheckForImmediateInvocation(R, FnDecl); 13684 if (R.isInvalid()) 13685 return ExprError(); 13686 13687 // For a rewritten candidate, we've already reversed the arguments 13688 // if needed. Perform the rest of the rewrite now. 13689 if ((Best->RewriteKind & CRK_DifferentOperator) || 13690 (Op == OO_Spaceship && IsReversed)) { 13691 if (Op == OO_ExclaimEqual) { 13692 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13693 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13694 } else { 13695 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13696 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13697 Expr *ZeroLiteral = 13698 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13699 13700 Sema::CodeSynthesisContext Ctx; 13701 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13702 Ctx.Entity = FnDecl; 13703 pushCodeSynthesisContext(Ctx); 13704 13705 R = CreateOverloadedBinOp( 13706 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13707 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13708 /*AllowRewrittenCandidates=*/false); 13709 13710 popCodeSynthesisContext(); 13711 } 13712 if (R.isInvalid()) 13713 return ExprError(); 13714 } else { 13715 assert(ChosenOp == Op && "unexpected operator name"); 13716 } 13717 13718 // Make a note in the AST if we did any rewriting. 13719 if (Best->RewriteKind != CRK_None) 13720 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13721 13722 return R; 13723 } else { 13724 // We matched a built-in operator. Convert the arguments, then 13725 // break out so that we will build the appropriate built-in 13726 // operator node. 13727 ExprResult ArgsRes0 = PerformImplicitConversion( 13728 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13729 AA_Passing, CCK_ForBuiltinOverloadedOp); 13730 if (ArgsRes0.isInvalid()) 13731 return ExprError(); 13732 Args[0] = ArgsRes0.get(); 13733 13734 ExprResult ArgsRes1 = PerformImplicitConversion( 13735 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13736 AA_Passing, CCK_ForBuiltinOverloadedOp); 13737 if (ArgsRes1.isInvalid()) 13738 return ExprError(); 13739 Args[1] = ArgsRes1.get(); 13740 break; 13741 } 13742 } 13743 13744 case OR_No_Viable_Function: { 13745 // C++ [over.match.oper]p9: 13746 // If the operator is the operator , [...] and there are no 13747 // viable functions, then the operator is assumed to be the 13748 // built-in operator and interpreted according to clause 5. 13749 if (Opc == BO_Comma) 13750 break; 13751 13752 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13753 // compare result using '==' and '<'. 13754 if (DefaultedFn && Opc == BO_Cmp) { 13755 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13756 Args[1], DefaultedFn); 13757 if (E.isInvalid() || E.isUsable()) 13758 return E; 13759 } 13760 13761 // For class as left operand for assignment or compound assignment 13762 // operator do not fall through to handling in built-in, but report that 13763 // no overloaded assignment operator found 13764 ExprResult Result = ExprError(); 13765 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13766 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13767 Args, OpLoc); 13768 if (Args[0]->getType()->isRecordType() && 13769 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13770 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13771 << BinaryOperator::getOpcodeStr(Opc) 13772 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13773 if (Args[0]->getType()->isIncompleteType()) { 13774 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13775 << Args[0]->getType() 13776 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13777 } 13778 } else { 13779 // This is an erroneous use of an operator which can be overloaded by 13780 // a non-member function. Check for non-member operators which were 13781 // defined too late to be candidates. 13782 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13783 // FIXME: Recover by calling the found function. 13784 return ExprError(); 13785 13786 // No viable function; try to create a built-in operation, which will 13787 // produce an error. Then, show the non-viable candidates. 13788 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13789 } 13790 assert(Result.isInvalid() && 13791 "C++ binary operator overloading is missing candidates!"); 13792 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13793 return Result; 13794 } 13795 13796 case OR_Ambiguous: 13797 CandidateSet.NoteCandidates( 13798 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13799 << BinaryOperator::getOpcodeStr(Opc) 13800 << Args[0]->getType() 13801 << Args[1]->getType() 13802 << Args[0]->getSourceRange() 13803 << Args[1]->getSourceRange()), 13804 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13805 OpLoc); 13806 return ExprError(); 13807 13808 case OR_Deleted: 13809 if (isImplicitlyDeleted(Best->Function)) { 13810 FunctionDecl *DeletedFD = Best->Function; 13811 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13812 if (DFK.isSpecialMember()) { 13813 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13814 << Args[0]->getType() << DFK.asSpecialMember(); 13815 } else { 13816 assert(DFK.isComparison()); 13817 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13818 << Args[0]->getType() << DeletedFD; 13819 } 13820 13821 // The user probably meant to call this special member. Just 13822 // explain why it's deleted. 13823 NoteDeletedFunction(DeletedFD); 13824 return ExprError(); 13825 } 13826 CandidateSet.NoteCandidates( 13827 PartialDiagnosticAt( 13828 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13829 << getOperatorSpelling(Best->Function->getDeclName() 13830 .getCXXOverloadedOperator()) 13831 << Args[0]->getSourceRange() 13832 << Args[1]->getSourceRange()), 13833 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13834 OpLoc); 13835 return ExprError(); 13836 } 13837 13838 // We matched a built-in operator; build it. 13839 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13840 } 13841 13842 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13843 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13844 FunctionDecl *DefaultedFn) { 13845 const ComparisonCategoryInfo *Info = 13846 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13847 // If we're not producing a known comparison category type, we can't 13848 // synthesize a three-way comparison. Let the caller diagnose this. 13849 if (!Info) 13850 return ExprResult((Expr*)nullptr); 13851 13852 // If we ever want to perform this synthesis more generally, we will need to 13853 // apply the temporary materialization conversion to the operands. 13854 assert(LHS->isGLValue() && RHS->isGLValue() && 13855 "cannot use prvalue expressions more than once"); 13856 Expr *OrigLHS = LHS; 13857 Expr *OrigRHS = RHS; 13858 13859 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13860 // each of them multiple times below. 13861 LHS = new (Context) 13862 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13863 LHS->getObjectKind(), LHS); 13864 RHS = new (Context) 13865 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13866 RHS->getObjectKind(), RHS); 13867 13868 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13869 DefaultedFn); 13870 if (Eq.isInvalid()) 13871 return ExprError(); 13872 13873 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13874 true, DefaultedFn); 13875 if (Less.isInvalid()) 13876 return ExprError(); 13877 13878 ExprResult Greater; 13879 if (Info->isPartial()) { 13880 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13881 DefaultedFn); 13882 if (Greater.isInvalid()) 13883 return ExprError(); 13884 } 13885 13886 // Form the list of comparisons we're going to perform. 13887 struct Comparison { 13888 ExprResult Cmp; 13889 ComparisonCategoryResult Result; 13890 } Comparisons[4] = 13891 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13892 : ComparisonCategoryResult::Equivalent}, 13893 {Less, ComparisonCategoryResult::Less}, 13894 {Greater, ComparisonCategoryResult::Greater}, 13895 {ExprResult(), ComparisonCategoryResult::Unordered}, 13896 }; 13897 13898 int I = Info->isPartial() ? 3 : 2; 13899 13900 // Combine the comparisons with suitable conditional expressions. 13901 ExprResult Result; 13902 for (; I >= 0; --I) { 13903 // Build a reference to the comparison category constant. 13904 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13905 // FIXME: Missing a constant for a comparison category. Diagnose this? 13906 if (!VI) 13907 return ExprResult((Expr*)nullptr); 13908 ExprResult ThisResult = 13909 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13910 if (ThisResult.isInvalid()) 13911 return ExprError(); 13912 13913 // Build a conditional unless this is the final case. 13914 if (Result.get()) { 13915 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13916 ThisResult.get(), Result.get()); 13917 if (Result.isInvalid()) 13918 return ExprError(); 13919 } else { 13920 Result = ThisResult; 13921 } 13922 } 13923 13924 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13925 // bind the OpaqueValueExprs before they're (repeatedly) used. 13926 Expr *SyntacticForm = BinaryOperator::Create( 13927 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13928 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13929 CurFPFeatureOverrides()); 13930 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13931 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13932 } 13933 13934 ExprResult 13935 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13936 SourceLocation RLoc, 13937 Expr *Base, Expr *Idx) { 13938 Expr *Args[2] = { Base, Idx }; 13939 DeclarationName OpName = 13940 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13941 13942 // If either side is type-dependent, create an appropriate dependent 13943 // expression. 13944 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13945 13946 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13947 // CHECKME: no 'operator' keyword? 13948 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13949 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13950 ExprResult Fn = CreateUnresolvedLookupExpr( 13951 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 13952 if (Fn.isInvalid()) 13953 return ExprError(); 13954 // Can't add any actual overloads yet 13955 13956 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 13957 Context.DependentTy, VK_RValue, RLoc, 13958 CurFPFeatureOverrides()); 13959 } 13960 13961 // Handle placeholders on both operands. 13962 if (checkPlaceholderForOverload(*this, Args[0])) 13963 return ExprError(); 13964 if (checkPlaceholderForOverload(*this, Args[1])) 13965 return ExprError(); 13966 13967 // Build an empty overload set. 13968 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13969 13970 // Subscript can only be overloaded as a member function. 13971 13972 // Add operator candidates that are member functions. 13973 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13974 13975 // Add builtin operator candidates. 13976 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13977 13978 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13979 13980 // Perform overload resolution. 13981 OverloadCandidateSet::iterator Best; 13982 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13983 case OR_Success: { 13984 // We found a built-in operator or an overloaded operator. 13985 FunctionDecl *FnDecl = Best->Function; 13986 13987 if (FnDecl) { 13988 // We matched an overloaded operator. Build a call to that 13989 // operator. 13990 13991 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13992 13993 // Convert the arguments. 13994 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13995 ExprResult Arg0 = 13996 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13997 Best->FoundDecl, Method); 13998 if (Arg0.isInvalid()) 13999 return ExprError(); 14000 Args[0] = Arg0.get(); 14001 14002 // Convert the arguments. 14003 ExprResult InputInit 14004 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14005 Context, 14006 FnDecl->getParamDecl(0)), 14007 SourceLocation(), 14008 Args[1]); 14009 if (InputInit.isInvalid()) 14010 return ExprError(); 14011 14012 Args[1] = InputInit.getAs<Expr>(); 14013 14014 // Build the actual expression node. 14015 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14016 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14017 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14018 Best->FoundDecl, 14019 Base, 14020 HadMultipleCandidates, 14021 OpLocInfo.getLoc(), 14022 OpLocInfo.getInfo()); 14023 if (FnExpr.isInvalid()) 14024 return ExprError(); 14025 14026 // Determine the result type 14027 QualType ResultTy = FnDecl->getReturnType(); 14028 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14029 ResultTy = ResultTy.getNonLValueExprType(Context); 14030 14031 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14032 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 14033 CurFPFeatureOverrides()); 14034 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14035 return ExprError(); 14036 14037 if (CheckFunctionCall(Method, TheCall, 14038 Method->getType()->castAs<FunctionProtoType>())) 14039 return ExprError(); 14040 14041 return MaybeBindToTemporary(TheCall); 14042 } else { 14043 // We matched a built-in operator. Convert the arguments, then 14044 // break out so that we will build the appropriate built-in 14045 // operator node. 14046 ExprResult ArgsRes0 = PerformImplicitConversion( 14047 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14048 AA_Passing, CCK_ForBuiltinOverloadedOp); 14049 if (ArgsRes0.isInvalid()) 14050 return ExprError(); 14051 Args[0] = ArgsRes0.get(); 14052 14053 ExprResult ArgsRes1 = PerformImplicitConversion( 14054 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14055 AA_Passing, CCK_ForBuiltinOverloadedOp); 14056 if (ArgsRes1.isInvalid()) 14057 return ExprError(); 14058 Args[1] = ArgsRes1.get(); 14059 14060 break; 14061 } 14062 } 14063 14064 case OR_No_Viable_Function: { 14065 PartialDiagnostic PD = CandidateSet.empty() 14066 ? (PDiag(diag::err_ovl_no_oper) 14067 << Args[0]->getType() << /*subscript*/ 0 14068 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 14069 : (PDiag(diag::err_ovl_no_viable_subscript) 14070 << Args[0]->getType() << Args[0]->getSourceRange() 14071 << Args[1]->getSourceRange()); 14072 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14073 OCD_AllCandidates, Args, "[]", LLoc); 14074 return ExprError(); 14075 } 14076 14077 case OR_Ambiguous: 14078 CandidateSet.NoteCandidates( 14079 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14080 << "[]" << Args[0]->getType() 14081 << Args[1]->getType() 14082 << Args[0]->getSourceRange() 14083 << Args[1]->getSourceRange()), 14084 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14085 return ExprError(); 14086 14087 case OR_Deleted: 14088 CandidateSet.NoteCandidates( 14089 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14090 << "[]" << Args[0]->getSourceRange() 14091 << Args[1]->getSourceRange()), 14092 *this, OCD_AllCandidates, Args, "[]", LLoc); 14093 return ExprError(); 14094 } 14095 14096 // We matched a built-in operator; build it. 14097 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14098 } 14099 14100 /// BuildCallToMemberFunction - Build a call to a member 14101 /// function. MemExpr is the expression that refers to the member 14102 /// function (and includes the object parameter), Args/NumArgs are the 14103 /// arguments to the function call (not including the object 14104 /// parameter). The caller needs to validate that the member 14105 /// expression refers to a non-static member function or an overloaded 14106 /// member function. 14107 ExprResult 14108 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14109 SourceLocation LParenLoc, 14110 MultiExprArg Args, 14111 SourceLocation RParenLoc) { 14112 assert(MemExprE->getType() == Context.BoundMemberTy || 14113 MemExprE->getType() == Context.OverloadTy); 14114 14115 // Dig out the member expression. This holds both the object 14116 // argument and the member function we're referring to. 14117 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14118 14119 // Determine whether this is a call to a pointer-to-member function. 14120 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14121 assert(op->getType() == Context.BoundMemberTy); 14122 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14123 14124 QualType fnType = 14125 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14126 14127 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14128 QualType resultType = proto->getCallResultType(Context); 14129 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14130 14131 // Check that the object type isn't more qualified than the 14132 // member function we're calling. 14133 Qualifiers funcQuals = proto->getMethodQuals(); 14134 14135 QualType objectType = op->getLHS()->getType(); 14136 if (op->getOpcode() == BO_PtrMemI) 14137 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14138 Qualifiers objectQuals = objectType.getQualifiers(); 14139 14140 Qualifiers difference = objectQuals - funcQuals; 14141 difference.removeObjCGCAttr(); 14142 difference.removeAddressSpace(); 14143 if (difference) { 14144 std::string qualsString = difference.getAsString(); 14145 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14146 << fnType.getUnqualifiedType() 14147 << qualsString 14148 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14149 } 14150 14151 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14152 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14153 CurFPFeatureOverrides(), proto->getNumParams()); 14154 14155 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14156 call, nullptr)) 14157 return ExprError(); 14158 14159 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14160 return ExprError(); 14161 14162 if (CheckOtherCall(call, proto)) 14163 return ExprError(); 14164 14165 return MaybeBindToTemporary(call); 14166 } 14167 14168 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14169 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14170 RParenLoc, CurFPFeatureOverrides()); 14171 14172 UnbridgedCastsSet UnbridgedCasts; 14173 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14174 return ExprError(); 14175 14176 MemberExpr *MemExpr; 14177 CXXMethodDecl *Method = nullptr; 14178 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14179 NestedNameSpecifier *Qualifier = nullptr; 14180 if (isa<MemberExpr>(NakedMemExpr)) { 14181 MemExpr = cast<MemberExpr>(NakedMemExpr); 14182 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14183 FoundDecl = MemExpr->getFoundDecl(); 14184 Qualifier = MemExpr->getQualifier(); 14185 UnbridgedCasts.restore(); 14186 } else { 14187 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14188 Qualifier = UnresExpr->getQualifier(); 14189 14190 QualType ObjectType = UnresExpr->getBaseType(); 14191 Expr::Classification ObjectClassification 14192 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14193 : UnresExpr->getBase()->Classify(Context); 14194 14195 // Add overload candidates 14196 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14197 OverloadCandidateSet::CSK_Normal); 14198 14199 // FIXME: avoid copy. 14200 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14201 if (UnresExpr->hasExplicitTemplateArgs()) { 14202 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14203 TemplateArgs = &TemplateArgsBuffer; 14204 } 14205 14206 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14207 E = UnresExpr->decls_end(); I != E; ++I) { 14208 14209 NamedDecl *Func = *I; 14210 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14211 if (isa<UsingShadowDecl>(Func)) 14212 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14213 14214 14215 // Microsoft supports direct constructor calls. 14216 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14217 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14218 CandidateSet, 14219 /*SuppressUserConversions*/ false); 14220 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14221 // If explicit template arguments were provided, we can't call a 14222 // non-template member function. 14223 if (TemplateArgs) 14224 continue; 14225 14226 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14227 ObjectClassification, Args, CandidateSet, 14228 /*SuppressUserConversions=*/false); 14229 } else { 14230 AddMethodTemplateCandidate( 14231 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14232 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14233 /*SuppressUserConversions=*/false); 14234 } 14235 } 14236 14237 DeclarationName DeclName = UnresExpr->getMemberName(); 14238 14239 UnbridgedCasts.restore(); 14240 14241 OverloadCandidateSet::iterator Best; 14242 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14243 Best)) { 14244 case OR_Success: 14245 Method = cast<CXXMethodDecl>(Best->Function); 14246 FoundDecl = Best->FoundDecl; 14247 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14248 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14249 return ExprError(); 14250 // If FoundDecl is different from Method (such as if one is a template 14251 // and the other a specialization), make sure DiagnoseUseOfDecl is 14252 // called on both. 14253 // FIXME: This would be more comprehensively addressed by modifying 14254 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14255 // being used. 14256 if (Method != FoundDecl.getDecl() && 14257 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14258 return ExprError(); 14259 break; 14260 14261 case OR_No_Viable_Function: 14262 CandidateSet.NoteCandidates( 14263 PartialDiagnosticAt( 14264 UnresExpr->getMemberLoc(), 14265 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14266 << DeclName << MemExprE->getSourceRange()), 14267 *this, OCD_AllCandidates, Args); 14268 // FIXME: Leaking incoming expressions! 14269 return ExprError(); 14270 14271 case OR_Ambiguous: 14272 CandidateSet.NoteCandidates( 14273 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14274 PDiag(diag::err_ovl_ambiguous_member_call) 14275 << DeclName << MemExprE->getSourceRange()), 14276 *this, OCD_AmbiguousCandidates, Args); 14277 // FIXME: Leaking incoming expressions! 14278 return ExprError(); 14279 14280 case OR_Deleted: 14281 CandidateSet.NoteCandidates( 14282 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14283 PDiag(diag::err_ovl_deleted_member_call) 14284 << DeclName << MemExprE->getSourceRange()), 14285 *this, OCD_AllCandidates, Args); 14286 // FIXME: Leaking incoming expressions! 14287 return ExprError(); 14288 } 14289 14290 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14291 14292 // If overload resolution picked a static member, build a 14293 // non-member call based on that function. 14294 if (Method->isStatic()) { 14295 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14296 RParenLoc); 14297 } 14298 14299 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14300 } 14301 14302 QualType ResultType = Method->getReturnType(); 14303 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14304 ResultType = ResultType.getNonLValueExprType(Context); 14305 14306 assert(Method && "Member call to something that isn't a method?"); 14307 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14308 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14309 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14310 CurFPFeatureOverrides(), Proto->getNumParams()); 14311 14312 // Check for a valid return type. 14313 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14314 TheCall, Method)) 14315 return ExprError(); 14316 14317 // Convert the object argument (for a non-static member function call). 14318 // We only need to do this if there was actually an overload; otherwise 14319 // it was done at lookup. 14320 if (!Method->isStatic()) { 14321 ExprResult ObjectArg = 14322 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14323 FoundDecl, Method); 14324 if (ObjectArg.isInvalid()) 14325 return ExprError(); 14326 MemExpr->setBase(ObjectArg.get()); 14327 } 14328 14329 // Convert the rest of the arguments 14330 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14331 RParenLoc)) 14332 return ExprError(); 14333 14334 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14335 14336 if (CheckFunctionCall(Method, TheCall, Proto)) 14337 return ExprError(); 14338 14339 // In the case the method to call was not selected by the overloading 14340 // resolution process, we still need to handle the enable_if attribute. Do 14341 // that here, so it will not hide previous -- and more relevant -- errors. 14342 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14343 if (const EnableIfAttr *Attr = 14344 CheckEnableIf(Method, LParenLoc, Args, true)) { 14345 Diag(MemE->getMemberLoc(), 14346 diag::err_ovl_no_viable_member_function_in_call) 14347 << Method << Method->getSourceRange(); 14348 Diag(Method->getLocation(), 14349 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14350 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14351 return ExprError(); 14352 } 14353 } 14354 14355 if ((isa<CXXConstructorDecl>(CurContext) || 14356 isa<CXXDestructorDecl>(CurContext)) && 14357 TheCall->getMethodDecl()->isPure()) { 14358 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14359 14360 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14361 MemExpr->performsVirtualDispatch(getLangOpts())) { 14362 Diag(MemExpr->getBeginLoc(), 14363 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14364 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14365 << MD->getParent(); 14366 14367 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14368 if (getLangOpts().AppleKext) 14369 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14370 << MD->getParent() << MD->getDeclName(); 14371 } 14372 } 14373 14374 if (CXXDestructorDecl *DD = 14375 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14376 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14377 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14378 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14379 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14380 MemExpr->getMemberLoc()); 14381 } 14382 14383 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14384 TheCall->getMethodDecl()); 14385 } 14386 14387 /// BuildCallToObjectOfClassType - Build a call to an object of class 14388 /// type (C++ [over.call.object]), which can end up invoking an 14389 /// overloaded function call operator (@c operator()) or performing a 14390 /// user-defined conversion on the object argument. 14391 ExprResult 14392 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14393 SourceLocation LParenLoc, 14394 MultiExprArg Args, 14395 SourceLocation RParenLoc) { 14396 if (checkPlaceholderForOverload(*this, Obj)) 14397 return ExprError(); 14398 ExprResult Object = Obj; 14399 14400 UnbridgedCastsSet UnbridgedCasts; 14401 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14402 return ExprError(); 14403 14404 assert(Object.get()->getType()->isRecordType() && 14405 "Requires object type argument"); 14406 14407 // C++ [over.call.object]p1: 14408 // If the primary-expression E in the function call syntax 14409 // evaluates to a class object of type "cv T", then the set of 14410 // candidate functions includes at least the function call 14411 // operators of T. The function call operators of T are obtained by 14412 // ordinary lookup of the name operator() in the context of 14413 // (E).operator(). 14414 OverloadCandidateSet CandidateSet(LParenLoc, 14415 OverloadCandidateSet::CSK_Operator); 14416 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14417 14418 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14419 diag::err_incomplete_object_call, Object.get())) 14420 return true; 14421 14422 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14423 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14424 LookupQualifiedName(R, Record->getDecl()); 14425 R.suppressDiagnostics(); 14426 14427 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14428 Oper != OperEnd; ++Oper) { 14429 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14430 Object.get()->Classify(Context), Args, CandidateSet, 14431 /*SuppressUserConversion=*/false); 14432 } 14433 14434 // C++ [over.call.object]p2: 14435 // In addition, for each (non-explicit in C++0x) conversion function 14436 // declared in T of the form 14437 // 14438 // operator conversion-type-id () cv-qualifier; 14439 // 14440 // where cv-qualifier is the same cv-qualification as, or a 14441 // greater cv-qualification than, cv, and where conversion-type-id 14442 // denotes the type "pointer to function of (P1,...,Pn) returning 14443 // R", or the type "reference to pointer to function of 14444 // (P1,...,Pn) returning R", or the type "reference to function 14445 // of (P1,...,Pn) returning R", a surrogate call function [...] 14446 // is also considered as a candidate function. Similarly, 14447 // surrogate call functions are added to the set of candidate 14448 // functions for each conversion function declared in an 14449 // accessible base class provided the function is not hidden 14450 // within T by another intervening declaration. 14451 const auto &Conversions = 14452 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14453 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14454 NamedDecl *D = *I; 14455 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14456 if (isa<UsingShadowDecl>(D)) 14457 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14458 14459 // Skip over templated conversion functions; they aren't 14460 // surrogates. 14461 if (isa<FunctionTemplateDecl>(D)) 14462 continue; 14463 14464 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14465 if (!Conv->isExplicit()) { 14466 // Strip the reference type (if any) and then the pointer type (if 14467 // any) to get down to what might be a function type. 14468 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14469 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14470 ConvType = ConvPtrType->getPointeeType(); 14471 14472 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14473 { 14474 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14475 Object.get(), Args, CandidateSet); 14476 } 14477 } 14478 } 14479 14480 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14481 14482 // Perform overload resolution. 14483 OverloadCandidateSet::iterator Best; 14484 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14485 Best)) { 14486 case OR_Success: 14487 // Overload resolution succeeded; we'll build the appropriate call 14488 // below. 14489 break; 14490 14491 case OR_No_Viable_Function: { 14492 PartialDiagnostic PD = 14493 CandidateSet.empty() 14494 ? (PDiag(diag::err_ovl_no_oper) 14495 << Object.get()->getType() << /*call*/ 1 14496 << Object.get()->getSourceRange()) 14497 : (PDiag(diag::err_ovl_no_viable_object_call) 14498 << Object.get()->getType() << Object.get()->getSourceRange()); 14499 CandidateSet.NoteCandidates( 14500 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14501 OCD_AllCandidates, Args); 14502 break; 14503 } 14504 case OR_Ambiguous: 14505 CandidateSet.NoteCandidates( 14506 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14507 PDiag(diag::err_ovl_ambiguous_object_call) 14508 << Object.get()->getType() 14509 << Object.get()->getSourceRange()), 14510 *this, OCD_AmbiguousCandidates, Args); 14511 break; 14512 14513 case OR_Deleted: 14514 CandidateSet.NoteCandidates( 14515 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14516 PDiag(diag::err_ovl_deleted_object_call) 14517 << Object.get()->getType() 14518 << Object.get()->getSourceRange()), 14519 *this, OCD_AllCandidates, Args); 14520 break; 14521 } 14522 14523 if (Best == CandidateSet.end()) 14524 return true; 14525 14526 UnbridgedCasts.restore(); 14527 14528 if (Best->Function == nullptr) { 14529 // Since there is no function declaration, this is one of the 14530 // surrogate candidates. Dig out the conversion function. 14531 CXXConversionDecl *Conv 14532 = cast<CXXConversionDecl>( 14533 Best->Conversions[0].UserDefined.ConversionFunction); 14534 14535 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14536 Best->FoundDecl); 14537 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14538 return ExprError(); 14539 assert(Conv == Best->FoundDecl.getDecl() && 14540 "Found Decl & conversion-to-functionptr should be same, right?!"); 14541 // We selected one of the surrogate functions that converts the 14542 // object parameter to a function pointer. Perform the conversion 14543 // on the object argument, then let BuildCallExpr finish the job. 14544 14545 // Create an implicit member expr to refer to the conversion operator. 14546 // and then call it. 14547 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14548 Conv, HadMultipleCandidates); 14549 if (Call.isInvalid()) 14550 return ExprError(); 14551 // Record usage of conversion in an implicit cast. 14552 Call = ImplicitCastExpr::Create( 14553 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14554 nullptr, VK_RValue, CurFPFeatureOverrides()); 14555 14556 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14557 } 14558 14559 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14560 14561 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14562 // that calls this method, using Object for the implicit object 14563 // parameter and passing along the remaining arguments. 14564 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14565 14566 // An error diagnostic has already been printed when parsing the declaration. 14567 if (Method->isInvalidDecl()) 14568 return ExprError(); 14569 14570 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14571 unsigned NumParams = Proto->getNumParams(); 14572 14573 DeclarationNameInfo OpLocInfo( 14574 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14575 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14576 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14577 Obj, HadMultipleCandidates, 14578 OpLocInfo.getLoc(), 14579 OpLocInfo.getInfo()); 14580 if (NewFn.isInvalid()) 14581 return true; 14582 14583 // The number of argument slots to allocate in the call. If we have default 14584 // arguments we need to allocate space for them as well. We additionally 14585 // need one more slot for the object parameter. 14586 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14587 14588 // Build the full argument list for the method call (the implicit object 14589 // parameter is placed at the beginning of the list). 14590 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14591 14592 bool IsError = false; 14593 14594 // Initialize the implicit object parameter. 14595 ExprResult ObjRes = 14596 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14597 Best->FoundDecl, Method); 14598 if (ObjRes.isInvalid()) 14599 IsError = true; 14600 else 14601 Object = ObjRes; 14602 MethodArgs[0] = Object.get(); 14603 14604 // Check the argument types. 14605 for (unsigned i = 0; i != NumParams; i++) { 14606 Expr *Arg; 14607 if (i < Args.size()) { 14608 Arg = Args[i]; 14609 14610 // Pass the argument. 14611 14612 ExprResult InputInit 14613 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14614 Context, 14615 Method->getParamDecl(i)), 14616 SourceLocation(), Arg); 14617 14618 IsError |= InputInit.isInvalid(); 14619 Arg = InputInit.getAs<Expr>(); 14620 } else { 14621 ExprResult DefArg 14622 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14623 if (DefArg.isInvalid()) { 14624 IsError = true; 14625 break; 14626 } 14627 14628 Arg = DefArg.getAs<Expr>(); 14629 } 14630 14631 MethodArgs[i + 1] = Arg; 14632 } 14633 14634 // If this is a variadic call, handle args passed through "...". 14635 if (Proto->isVariadic()) { 14636 // Promote the arguments (C99 6.5.2.2p7). 14637 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14638 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14639 nullptr); 14640 IsError |= Arg.isInvalid(); 14641 MethodArgs[i + 1] = Arg.get(); 14642 } 14643 } 14644 14645 if (IsError) 14646 return true; 14647 14648 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14649 14650 // Once we've built TheCall, all of the expressions are properly owned. 14651 QualType ResultTy = Method->getReturnType(); 14652 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14653 ResultTy = ResultTy.getNonLValueExprType(Context); 14654 14655 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14656 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14657 CurFPFeatureOverrides()); 14658 14659 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14660 return true; 14661 14662 if (CheckFunctionCall(Method, TheCall, Proto)) 14663 return true; 14664 14665 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14666 } 14667 14668 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14669 /// (if one exists), where @c Base is an expression of class type and 14670 /// @c Member is the name of the member we're trying to find. 14671 ExprResult 14672 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14673 bool *NoArrowOperatorFound) { 14674 assert(Base->getType()->isRecordType() && 14675 "left-hand side must have class type"); 14676 14677 if (checkPlaceholderForOverload(*this, Base)) 14678 return ExprError(); 14679 14680 SourceLocation Loc = Base->getExprLoc(); 14681 14682 // C++ [over.ref]p1: 14683 // 14684 // [...] An expression x->m is interpreted as (x.operator->())->m 14685 // for a class object x of type T if T::operator->() exists and if 14686 // the operator is selected as the best match function by the 14687 // overload resolution mechanism (13.3). 14688 DeclarationName OpName = 14689 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14690 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14691 14692 if (RequireCompleteType(Loc, Base->getType(), 14693 diag::err_typecheck_incomplete_tag, Base)) 14694 return ExprError(); 14695 14696 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14697 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14698 R.suppressDiagnostics(); 14699 14700 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14701 Oper != OperEnd; ++Oper) { 14702 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14703 None, CandidateSet, /*SuppressUserConversion=*/false); 14704 } 14705 14706 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14707 14708 // Perform overload resolution. 14709 OverloadCandidateSet::iterator Best; 14710 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14711 case OR_Success: 14712 // Overload resolution succeeded; we'll build the call below. 14713 break; 14714 14715 case OR_No_Viable_Function: { 14716 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14717 if (CandidateSet.empty()) { 14718 QualType BaseType = Base->getType(); 14719 if (NoArrowOperatorFound) { 14720 // Report this specific error to the caller instead of emitting a 14721 // diagnostic, as requested. 14722 *NoArrowOperatorFound = true; 14723 return ExprError(); 14724 } 14725 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14726 << BaseType << Base->getSourceRange(); 14727 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14728 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14729 << FixItHint::CreateReplacement(OpLoc, "."); 14730 } 14731 } else 14732 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14733 << "operator->" << Base->getSourceRange(); 14734 CandidateSet.NoteCandidates(*this, Base, Cands); 14735 return ExprError(); 14736 } 14737 case OR_Ambiguous: 14738 CandidateSet.NoteCandidates( 14739 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14740 << "->" << Base->getType() 14741 << Base->getSourceRange()), 14742 *this, OCD_AmbiguousCandidates, Base); 14743 return ExprError(); 14744 14745 case OR_Deleted: 14746 CandidateSet.NoteCandidates( 14747 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14748 << "->" << Base->getSourceRange()), 14749 *this, OCD_AllCandidates, Base); 14750 return ExprError(); 14751 } 14752 14753 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14754 14755 // Convert the object parameter. 14756 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14757 ExprResult BaseResult = 14758 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14759 Best->FoundDecl, Method); 14760 if (BaseResult.isInvalid()) 14761 return ExprError(); 14762 Base = BaseResult.get(); 14763 14764 // Build the operator call. 14765 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14766 Base, HadMultipleCandidates, OpLoc); 14767 if (FnExpr.isInvalid()) 14768 return ExprError(); 14769 14770 QualType ResultTy = Method->getReturnType(); 14771 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14772 ResultTy = ResultTy.getNonLValueExprType(Context); 14773 CXXOperatorCallExpr *TheCall = 14774 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14775 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14776 14777 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14778 return ExprError(); 14779 14780 if (CheckFunctionCall(Method, TheCall, 14781 Method->getType()->castAs<FunctionProtoType>())) 14782 return ExprError(); 14783 14784 return MaybeBindToTemporary(TheCall); 14785 } 14786 14787 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14788 /// a literal operator described by the provided lookup results. 14789 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14790 DeclarationNameInfo &SuffixInfo, 14791 ArrayRef<Expr*> Args, 14792 SourceLocation LitEndLoc, 14793 TemplateArgumentListInfo *TemplateArgs) { 14794 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14795 14796 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14797 OverloadCandidateSet::CSK_Normal); 14798 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14799 TemplateArgs); 14800 14801 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14802 14803 // Perform overload resolution. This will usually be trivial, but might need 14804 // to perform substitutions for a literal operator template. 14805 OverloadCandidateSet::iterator Best; 14806 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14807 case OR_Success: 14808 case OR_Deleted: 14809 break; 14810 14811 case OR_No_Viable_Function: 14812 CandidateSet.NoteCandidates( 14813 PartialDiagnosticAt(UDSuffixLoc, 14814 PDiag(diag::err_ovl_no_viable_function_in_call) 14815 << R.getLookupName()), 14816 *this, OCD_AllCandidates, Args); 14817 return ExprError(); 14818 14819 case OR_Ambiguous: 14820 CandidateSet.NoteCandidates( 14821 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14822 << R.getLookupName()), 14823 *this, OCD_AmbiguousCandidates, Args); 14824 return ExprError(); 14825 } 14826 14827 FunctionDecl *FD = Best->Function; 14828 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14829 nullptr, HadMultipleCandidates, 14830 SuffixInfo.getLoc(), 14831 SuffixInfo.getInfo()); 14832 if (Fn.isInvalid()) 14833 return true; 14834 14835 // Check the argument types. This should almost always be a no-op, except 14836 // that array-to-pointer decay is applied to string literals. 14837 Expr *ConvArgs[2]; 14838 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14839 ExprResult InputInit = PerformCopyInitialization( 14840 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14841 SourceLocation(), Args[ArgIdx]); 14842 if (InputInit.isInvalid()) 14843 return true; 14844 ConvArgs[ArgIdx] = InputInit.get(); 14845 } 14846 14847 QualType ResultTy = FD->getReturnType(); 14848 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14849 ResultTy = ResultTy.getNonLValueExprType(Context); 14850 14851 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14852 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14853 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14854 14855 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14856 return ExprError(); 14857 14858 if (CheckFunctionCall(FD, UDL, nullptr)) 14859 return ExprError(); 14860 14861 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14862 } 14863 14864 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14865 /// given LookupResult is non-empty, it is assumed to describe a member which 14866 /// will be invoked. Otherwise, the function will be found via argument 14867 /// dependent lookup. 14868 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14869 /// otherwise CallExpr is set to ExprError() and some non-success value 14870 /// is returned. 14871 Sema::ForRangeStatus 14872 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14873 SourceLocation RangeLoc, 14874 const DeclarationNameInfo &NameInfo, 14875 LookupResult &MemberLookup, 14876 OverloadCandidateSet *CandidateSet, 14877 Expr *Range, ExprResult *CallExpr) { 14878 Scope *S = nullptr; 14879 14880 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14881 if (!MemberLookup.empty()) { 14882 ExprResult MemberRef = 14883 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14884 /*IsPtr=*/false, CXXScopeSpec(), 14885 /*TemplateKWLoc=*/SourceLocation(), 14886 /*FirstQualifierInScope=*/nullptr, 14887 MemberLookup, 14888 /*TemplateArgs=*/nullptr, S); 14889 if (MemberRef.isInvalid()) { 14890 *CallExpr = ExprError(); 14891 return FRS_DiagnosticIssued; 14892 } 14893 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14894 if (CallExpr->isInvalid()) { 14895 *CallExpr = ExprError(); 14896 return FRS_DiagnosticIssued; 14897 } 14898 } else { 14899 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14900 NestedNameSpecifierLoc(), 14901 NameInfo, UnresolvedSet<0>()); 14902 if (FnR.isInvalid()) 14903 return FRS_DiagnosticIssued; 14904 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14905 14906 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14907 CandidateSet, CallExpr); 14908 if (CandidateSet->empty() || CandidateSetError) { 14909 *CallExpr = ExprError(); 14910 return FRS_NoViableFunction; 14911 } 14912 OverloadCandidateSet::iterator Best; 14913 OverloadingResult OverloadResult = 14914 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14915 14916 if (OverloadResult == OR_No_Viable_Function) { 14917 *CallExpr = ExprError(); 14918 return FRS_NoViableFunction; 14919 } 14920 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14921 Loc, nullptr, CandidateSet, &Best, 14922 OverloadResult, 14923 /*AllowTypoCorrection=*/false); 14924 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14925 *CallExpr = ExprError(); 14926 return FRS_DiagnosticIssued; 14927 } 14928 } 14929 return FRS_Success; 14930 } 14931 14932 14933 /// FixOverloadedFunctionReference - E is an expression that refers to 14934 /// a C++ overloaded function (possibly with some parentheses and 14935 /// perhaps a '&' around it). We have resolved the overloaded function 14936 /// to the function declaration Fn, so patch up the expression E to 14937 /// refer (possibly indirectly) to Fn. Returns the new expr. 14938 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14939 FunctionDecl *Fn) { 14940 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14941 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14942 Found, Fn); 14943 if (SubExpr == PE->getSubExpr()) 14944 return PE; 14945 14946 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14947 } 14948 14949 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14950 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14951 Found, Fn); 14952 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14953 SubExpr->getType()) && 14954 "Implicit cast type cannot be determined from overload"); 14955 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14956 if (SubExpr == ICE->getSubExpr()) 14957 return ICE; 14958 14959 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 14960 SubExpr, nullptr, ICE->getValueKind(), 14961 CurFPFeatureOverrides()); 14962 } 14963 14964 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14965 if (!GSE->isResultDependent()) { 14966 Expr *SubExpr = 14967 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14968 if (SubExpr == GSE->getResultExpr()) 14969 return GSE; 14970 14971 // Replace the resulting type information before rebuilding the generic 14972 // selection expression. 14973 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14974 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14975 unsigned ResultIdx = GSE->getResultIndex(); 14976 AssocExprs[ResultIdx] = SubExpr; 14977 14978 return GenericSelectionExpr::Create( 14979 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14980 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14981 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14982 ResultIdx); 14983 } 14984 // Rather than fall through to the unreachable, return the original generic 14985 // selection expression. 14986 return GSE; 14987 } 14988 14989 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14990 assert(UnOp->getOpcode() == UO_AddrOf && 14991 "Can only take the address of an overloaded function"); 14992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14993 if (Method->isStatic()) { 14994 // Do nothing: static member functions aren't any different 14995 // from non-member functions. 14996 } else { 14997 // Fix the subexpression, which really has to be an 14998 // UnresolvedLookupExpr holding an overloaded member function 14999 // or template. 15000 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15001 Found, Fn); 15002 if (SubExpr == UnOp->getSubExpr()) 15003 return UnOp; 15004 15005 assert(isa<DeclRefExpr>(SubExpr) 15006 && "fixed to something other than a decl ref"); 15007 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15008 && "fixed to a member ref with no nested name qualifier"); 15009 15010 // We have taken the address of a pointer to member 15011 // function. Perform the computation here so that we get the 15012 // appropriate pointer to member type. 15013 QualType ClassType 15014 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15015 QualType MemPtrType 15016 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15017 // Under the MS ABI, lock down the inheritance model now. 15018 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15019 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15020 15021 return UnaryOperator::Create( 15022 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 15023 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15024 } 15025 } 15026 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15027 Found, Fn); 15028 if (SubExpr == UnOp->getSubExpr()) 15029 return UnOp; 15030 15031 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf, 15032 Context.getPointerType(SubExpr->getType()), 15033 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), 15034 false, CurFPFeatureOverrides()); 15035 } 15036 15037 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15038 // FIXME: avoid copy. 15039 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15040 if (ULE->hasExplicitTemplateArgs()) { 15041 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15042 TemplateArgs = &TemplateArgsBuffer; 15043 } 15044 15045 DeclRefExpr *DRE = 15046 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15047 ULE->getQualifierLoc(), Found.getDecl(), 15048 ULE->getTemplateKeywordLoc(), TemplateArgs); 15049 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15050 return DRE; 15051 } 15052 15053 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15054 // FIXME: avoid copy. 15055 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15056 if (MemExpr->hasExplicitTemplateArgs()) { 15057 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15058 TemplateArgs = &TemplateArgsBuffer; 15059 } 15060 15061 Expr *Base; 15062 15063 // If we're filling in a static method where we used to have an 15064 // implicit member access, rewrite to a simple decl ref. 15065 if (MemExpr->isImplicitAccess()) { 15066 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15067 DeclRefExpr *DRE = BuildDeclRefExpr( 15068 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15069 MemExpr->getQualifierLoc(), Found.getDecl(), 15070 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15071 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15072 return DRE; 15073 } else { 15074 SourceLocation Loc = MemExpr->getMemberLoc(); 15075 if (MemExpr->getQualifier()) 15076 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15077 Base = 15078 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15079 } 15080 } else 15081 Base = MemExpr->getBase(); 15082 15083 ExprValueKind valueKind; 15084 QualType type; 15085 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15086 valueKind = VK_LValue; 15087 type = Fn->getType(); 15088 } else { 15089 valueKind = VK_RValue; 15090 type = Context.BoundMemberTy; 15091 } 15092 15093 return BuildMemberExpr( 15094 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15095 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15096 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15097 type, valueKind, OK_Ordinary, TemplateArgs); 15098 } 15099 15100 llvm_unreachable("Invalid reference to overloaded function"); 15101 } 15102 15103 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15104 DeclAccessPair Found, 15105 FunctionDecl *Fn) { 15106 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15107 } 15108