1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult CreateFunctionRefExpr( 53 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 54 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 55 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 56 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 57 return ExprError(); 58 // If FoundDecl is different from Fn (such as if one is a template 59 // and the other a specialization), make sure DiagnoseUseOfDecl is 60 // called on both. 61 // FIXME: This would be more comprehensively addressed by modifying 62 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 63 // being used. 64 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 65 return ExprError(); 66 DeclRefExpr *DRE = new (S.Context) 67 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 68 if (HadMultipleCandidates) 69 DRE->setHadMultipleCandidates(true); 70 71 S.MarkDeclRefReferenced(DRE, Base); 72 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 73 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 74 S.ResolveExceptionSpec(Loc, FPT); 75 DRE->setType(Fn->getType()); 76 } 77 } 78 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 79 CK_FunctionToPointerDecay); 80 } 81 82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle, 86 bool AllowObjCWritebackConversion); 87 88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 89 QualType &ToType, 90 bool InOverloadResolution, 91 StandardConversionSequence &SCS, 92 bool CStyle); 93 static OverloadingResult 94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 95 UserDefinedConversionSequence& User, 96 OverloadCandidateSet& Conversions, 97 AllowedExplicit AllowExplicit, 98 bool AllowObjCConversionOnExplicit); 99 100 static ImplicitConversionSequence::CompareKind 101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 102 const StandardConversionSequence& SCS1, 103 const StandardConversionSequence& SCS2); 104 105 static ImplicitConversionSequence::CompareKind 106 CompareQualificationConversions(Sema &S, 107 const StandardConversionSequence& SCS1, 108 const StandardConversionSequence& SCS2); 109 110 static ImplicitConversionSequence::CompareKind 111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 112 const StandardConversionSequence& SCS1, 113 const StandardConversionSequence& SCS2); 114 115 /// GetConversionRank - Retrieve the implicit conversion rank 116 /// corresponding to the given implicit conversion kind. 117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 118 static const ImplicitConversionRank 119 Rank[(int)ICK_Num_Conversion_Kinds] = { 120 ICR_Exact_Match, 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Promotion, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_OCL_Scalar_Widening, 141 ICR_Complex_Real_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Writeback_Conversion, 145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 146 // it was omitted by the patch that added 147 // ICK_Zero_Event_Conversion 148 ICR_C_Conversion, 149 ICR_C_Conversion_Extension 150 }; 151 return Rank[(int)Kind]; 152 } 153 154 /// GetImplicitConversionName - Return the name of this kind of 155 /// implicit conversion. 156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 158 "No conversion", 159 "Lvalue-to-rvalue", 160 "Array-to-pointer", 161 "Function-to-pointer", 162 "Function pointer conversion", 163 "Qualification", 164 "Integral promotion", 165 "Floating point promotion", 166 "Complex promotion", 167 "Integral conversion", 168 "Floating conversion", 169 "Complex conversion", 170 "Floating-integral conversion", 171 "Pointer conversion", 172 "Pointer-to-member conversion", 173 "Boolean conversion", 174 "Compatible-types conversion", 175 "Derived-to-base conversion", 176 "Vector conversion", 177 "SVE Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion", 182 "Writeback conversion", 183 "OpenCL Zero Event Conversion", 184 "C specific type conversion", 185 "Incompatible pointer conversion" 186 }; 187 return Name[Kind]; 188 } 189 190 /// StandardConversionSequence - Set the standard conversion 191 /// sequence to the identity conversion. 192 void StandardConversionSequence::setAsIdentityConversion() { 193 First = ICK_Identity; 194 Second = ICK_Identity; 195 Third = ICK_Identity; 196 DeprecatedStringLiteralToCharPtr = false; 197 QualificationIncludesObjCLifetime = false; 198 ReferenceBinding = false; 199 DirectBinding = false; 200 IsLvalueReference = true; 201 BindsToFunctionLvalue = false; 202 BindsToRvalue = false; 203 BindsImplicitObjectArgumentWithoutRefQualifier = false; 204 ObjCLifetimeConversionBinding = false; 205 CopyConstructor = nullptr; 206 } 207 208 /// getRank - Retrieve the rank of this standard conversion sequence 209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 210 /// implicit conversions. 211 ImplicitConversionRank StandardConversionSequence::getRank() const { 212 ImplicitConversionRank Rank = ICR_Exact_Match; 213 if (GetConversionRank(First) > Rank) 214 Rank = GetConversionRank(First); 215 if (GetConversionRank(Second) > Rank) 216 Rank = GetConversionRank(Second); 217 if (GetConversionRank(Third) > Rank) 218 Rank = GetConversionRank(Third); 219 return Rank; 220 } 221 222 /// isPointerConversionToBool - Determines whether this conversion is 223 /// a conversion of a pointer or pointer-to-member to bool. This is 224 /// used as part of the ranking of standard conversion sequences 225 /// (C++ 13.3.3.2p4). 226 bool StandardConversionSequence::isPointerConversionToBool() const { 227 // Note that FromType has not necessarily been transformed by the 228 // array-to-pointer or function-to-pointer implicit conversions, so 229 // check for their presence as well as checking whether FromType is 230 // a pointer. 231 if (getToType(1)->isBooleanType() && 232 (getFromType()->isPointerType() || 233 getFromType()->isMemberPointerType() || 234 getFromType()->isObjCObjectPointerType() || 235 getFromType()->isBlockPointerType() || 236 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 237 return true; 238 239 return false; 240 } 241 242 /// isPointerConversionToVoidPointer - Determines whether this 243 /// conversion is a conversion of a pointer to a void pointer. This is 244 /// used as part of the ranking of standard conversion sequences (C++ 245 /// 13.3.3.2p4). 246 bool 247 StandardConversionSequence:: 248 isPointerConversionToVoidPointer(ASTContext& Context) const { 249 QualType FromType = getFromType(); 250 QualType ToType = getToType(1); 251 252 // Note that FromType has not necessarily been transformed by the 253 // array-to-pointer implicit conversion, so check for its presence 254 // and redo the conversion to get a pointer. 255 if (First == ICK_Array_To_Pointer) 256 FromType = Context.getArrayDecayedType(FromType); 257 258 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 259 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 260 return ToPtrType->getPointeeType()->isVoidType(); 261 262 return false; 263 } 264 265 /// Skip any implicit casts which could be either part of a narrowing conversion 266 /// or after one in an implicit conversion. 267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 268 const Expr *Converted) { 269 // We can have cleanups wrapping the converted expression; these need to be 270 // preserved so that destructors run if necessary. 271 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 272 Expr *Inner = 273 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 274 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 275 EWC->getObjects()); 276 } 277 278 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 279 switch (ICE->getCastKind()) { 280 case CK_NoOp: 281 case CK_IntegralCast: 282 case CK_IntegralToBoolean: 283 case CK_IntegralToFloating: 284 case CK_BooleanToSignedIntegral: 285 case CK_FloatingToIntegral: 286 case CK_FloatingToBoolean: 287 case CK_FloatingCast: 288 Converted = ICE->getSubExpr(); 289 continue; 290 291 default: 292 return Converted; 293 } 294 } 295 296 return Converted; 297 } 298 299 /// Check if this standard conversion sequence represents a narrowing 300 /// conversion, according to C++11 [dcl.init.list]p7. 301 /// 302 /// \param Ctx The AST context. 303 /// \param Converted The result of applying this standard conversion sequence. 304 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 305 /// value of the expression prior to the narrowing conversion. 306 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 307 /// type of the expression prior to the narrowing conversion. 308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 309 /// from floating point types to integral types should be ignored. 310 NarrowingKind StandardConversionSequence::getNarrowingKind( 311 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 312 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 314 315 // C++11 [dcl.init.list]p7: 316 // A narrowing conversion is an implicit conversion ... 317 QualType FromType = getToType(0); 318 QualType ToType = getToType(1); 319 320 // A conversion to an enumeration type is narrowing if the conversion to 321 // the underlying type is narrowing. This only arises for expressions of 322 // the form 'Enum{init}'. 323 if (auto *ET = ToType->getAs<EnumType>()) 324 ToType = ET->getDecl()->getIntegerType(); 325 326 switch (Second) { 327 // 'bool' is an integral type; dispatch to the right place to handle it. 328 case ICK_Boolean_Conversion: 329 if (FromType->isRealFloatingType()) 330 goto FloatingIntegralConversion; 331 if (FromType->isIntegralOrUnscopedEnumerationType()) 332 goto IntegralConversion; 333 // -- from a pointer type or pointer-to-member type to bool, or 334 return NK_Type_Narrowing; 335 336 // -- from a floating-point type to an integer type, or 337 // 338 // -- from an integer type or unscoped enumeration type to a floating-point 339 // type, except where the source is a constant expression and the actual 340 // value after conversion will fit into the target type and will produce 341 // the original value when converted back to the original type, or 342 case ICK_Floating_Integral: 343 FloatingIntegralConversion: 344 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 345 return NK_Type_Narrowing; 346 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 347 ToType->isRealFloatingType()) { 348 if (IgnoreFloatToIntegralConversion) 349 return NK_Not_Narrowing; 350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 351 assert(Initializer && "Unknown conversion expression"); 352 353 // If it's value-dependent, we can't tell whether it's narrowing. 354 if (Initializer->isValueDependent()) 355 return NK_Dependent_Narrowing; 356 357 if (Optional<llvm::APSInt> IntConstantValue = 358 Initializer->getIntegerConstantExpr(Ctx)) { 359 // Convert the integer to the floating type. 360 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 361 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 362 llvm::APFloat::rmNearestTiesToEven); 363 // And back. 364 llvm::APSInt ConvertedValue = *IntConstantValue; 365 bool ignored; 366 Result.convertToInteger(ConvertedValue, 367 llvm::APFloat::rmTowardZero, &ignored); 368 // If the resulting value is different, this was a narrowing conversion. 369 if (*IntConstantValue != ConvertedValue) { 370 ConstantValue = APValue(*IntConstantValue); 371 ConstantType = Initializer->getType(); 372 return NK_Constant_Narrowing; 373 } 374 } else { 375 // Variables are always narrowings. 376 return NK_Variable_Narrowing; 377 } 378 } 379 return NK_Not_Narrowing; 380 381 // -- from long double to double or float, or from double to float, except 382 // where the source is a constant expression and the actual value after 383 // conversion is within the range of values that can be represented (even 384 // if it cannot be represented exactly), or 385 case ICK_Floating_Conversion: 386 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 387 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 388 // FromType is larger than ToType. 389 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 390 391 // If it's value-dependent, we can't tell whether it's narrowing. 392 if (Initializer->isValueDependent()) 393 return NK_Dependent_Narrowing; 394 395 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 396 // Constant! 397 assert(ConstantValue.isFloat()); 398 llvm::APFloat FloatVal = ConstantValue.getFloat(); 399 // Convert the source value into the target type. 400 bool ignored; 401 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 402 Ctx.getFloatTypeSemantics(ToType), 403 llvm::APFloat::rmNearestTiesToEven, &ignored); 404 // If there was no overflow, the source value is within the range of 405 // values that can be represented. 406 if (ConvertStatus & llvm::APFloat::opOverflow) { 407 ConstantType = Initializer->getType(); 408 return NK_Constant_Narrowing; 409 } 410 } else { 411 return NK_Variable_Narrowing; 412 } 413 } 414 return NK_Not_Narrowing; 415 416 // -- from an integer type or unscoped enumeration type to an integer type 417 // that cannot represent all the values of the original type, except where 418 // the source is a constant expression and the actual value after 419 // conversion will fit into the target type and will produce the original 420 // value when converted back to the original type. 421 case ICK_Integral_Conversion: 422 IntegralConversion: { 423 assert(FromType->isIntegralOrUnscopedEnumerationType()); 424 assert(ToType->isIntegralOrUnscopedEnumerationType()); 425 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 426 const unsigned FromWidth = Ctx.getIntWidth(FromType); 427 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 428 const unsigned ToWidth = Ctx.getIntWidth(ToType); 429 430 if (FromWidth > ToWidth || 431 (FromWidth == ToWidth && FromSigned != ToSigned) || 432 (FromSigned && !ToSigned)) { 433 // Not all values of FromType can be represented in ToType. 434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 435 436 // If it's value-dependent, we can't tell whether it's narrowing. 437 if (Initializer->isValueDependent()) 438 return NK_Dependent_Narrowing; 439 440 Optional<llvm::APSInt> OptInitializerValue; 441 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 442 // Such conversions on variables are always narrowing. 443 return NK_Variable_Narrowing; 444 } 445 llvm::APSInt &InitializerValue = *OptInitializerValue; 446 bool Narrowing = false; 447 if (FromWidth < ToWidth) { 448 // Negative -> unsigned is narrowing. Otherwise, more bits is never 449 // narrowing. 450 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 451 Narrowing = true; 452 } else { 453 // Add a bit to the InitializerValue so we don't have to worry about 454 // signed vs. unsigned comparisons. 455 InitializerValue = InitializerValue.extend( 456 InitializerValue.getBitWidth() + 1); 457 // Convert the initializer to and from the target width and signed-ness. 458 llvm::APSInt ConvertedValue = InitializerValue; 459 ConvertedValue = ConvertedValue.trunc(ToWidth); 460 ConvertedValue.setIsSigned(ToSigned); 461 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 462 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 463 // If the result is different, this was a narrowing conversion. 464 if (ConvertedValue != InitializerValue) 465 Narrowing = true; 466 } 467 if (Narrowing) { 468 ConstantType = Initializer->getType(); 469 ConstantValue = APValue(InitializerValue); 470 return NK_Constant_Narrowing; 471 } 472 } 473 return NK_Not_Narrowing; 474 } 475 476 default: 477 // Other kinds of conversions are not narrowings. 478 return NK_Not_Narrowing; 479 } 480 } 481 482 /// dump - Print this standard conversion sequence to standard 483 /// error. Useful for debugging overloading issues. 484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 485 raw_ostream &OS = llvm::errs(); 486 bool PrintedSomething = false; 487 if (First != ICK_Identity) { 488 OS << GetImplicitConversionName(First); 489 PrintedSomething = true; 490 } 491 492 if (Second != ICK_Identity) { 493 if (PrintedSomething) { 494 OS << " -> "; 495 } 496 OS << GetImplicitConversionName(Second); 497 498 if (CopyConstructor) { 499 OS << " (by copy constructor)"; 500 } else if (DirectBinding) { 501 OS << " (direct reference binding)"; 502 } else if (ReferenceBinding) { 503 OS << " (reference binding)"; 504 } 505 PrintedSomething = true; 506 } 507 508 if (Third != ICK_Identity) { 509 if (PrintedSomething) { 510 OS << " -> "; 511 } 512 OS << GetImplicitConversionName(Third); 513 PrintedSomething = true; 514 } 515 516 if (!PrintedSomething) { 517 OS << "No conversions required"; 518 } 519 } 520 521 /// dump - Print this user-defined conversion sequence to standard 522 /// error. Useful for debugging overloading issues. 523 void UserDefinedConversionSequence::dump() const { 524 raw_ostream &OS = llvm::errs(); 525 if (Before.First || Before.Second || Before.Third) { 526 Before.dump(); 527 OS << " -> "; 528 } 529 if (ConversionFunction) 530 OS << '\'' << *ConversionFunction << '\''; 531 else 532 OS << "aggregate initialization"; 533 if (After.First || After.Second || After.Third) { 534 OS << " -> "; 535 After.dump(); 536 } 537 } 538 539 /// dump - Print this implicit conversion sequence to standard 540 /// error. Useful for debugging overloading issues. 541 void ImplicitConversionSequence::dump() const { 542 raw_ostream &OS = llvm::errs(); 543 if (hasInitializerListContainerType()) 544 OS << "Worst list element conversion: "; 545 switch (ConversionKind) { 546 case StandardConversion: 547 OS << "Standard conversion: "; 548 Standard.dump(); 549 break; 550 case UserDefinedConversion: 551 OS << "User-defined conversion: "; 552 UserDefined.dump(); 553 break; 554 case EllipsisConversion: 555 OS << "Ellipsis conversion"; 556 break; 557 case AmbiguousConversion: 558 OS << "Ambiguous conversion"; 559 break; 560 case BadConversion: 561 OS << "Bad conversion"; 562 break; 563 } 564 565 OS << "\n"; 566 } 567 568 void AmbiguousConversionSequence::construct() { 569 new (&conversions()) ConversionSet(); 570 } 571 572 void AmbiguousConversionSequence::destruct() { 573 conversions().~ConversionSet(); 574 } 575 576 void 577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 578 FromTypePtr = O.FromTypePtr; 579 ToTypePtr = O.ToTypePtr; 580 new (&conversions()) ConversionSet(O.conversions()); 581 } 582 583 namespace { 584 // Structure used by DeductionFailureInfo to store 585 // template argument information. 586 struct DFIArguments { 587 TemplateArgument FirstArg; 588 TemplateArgument SecondArg; 589 }; 590 // Structure used by DeductionFailureInfo to store 591 // template parameter and template argument information. 592 struct DFIParamWithArguments : DFIArguments { 593 TemplateParameter Param; 594 }; 595 // Structure used by DeductionFailureInfo to store template argument 596 // information and the index of the problematic call argument. 597 struct DFIDeducedMismatchArgs : DFIArguments { 598 TemplateArgumentList *TemplateArgs; 599 unsigned CallArgIndex; 600 }; 601 // Structure used by DeductionFailureInfo to store information about 602 // unsatisfied constraints. 603 struct CNSInfo { 604 TemplateArgumentList *TemplateArgs; 605 ConstraintSatisfaction Satisfaction; 606 }; 607 } 608 609 /// Convert from Sema's representation of template deduction information 610 /// to the form used in overload-candidate information. 611 DeductionFailureInfo 612 clang::MakeDeductionFailureInfo(ASTContext &Context, 613 Sema::TemplateDeductionResult TDK, 614 TemplateDeductionInfo &Info) { 615 DeductionFailureInfo Result; 616 Result.Result = static_cast<unsigned>(TDK); 617 Result.HasDiagnostic = false; 618 switch (TDK) { 619 case Sema::TDK_Invalid: 620 case Sema::TDK_InstantiationDepth: 621 case Sema::TDK_TooManyArguments: 622 case Sema::TDK_TooFewArguments: 623 case Sema::TDK_MiscellaneousDeductionFailure: 624 case Sema::TDK_CUDATargetMismatch: 625 Result.Data = nullptr; 626 break; 627 628 case Sema::TDK_Incomplete: 629 case Sema::TDK_InvalidExplicitArguments: 630 Result.Data = Info.Param.getOpaqueValue(); 631 break; 632 633 case Sema::TDK_DeducedMismatch: 634 case Sema::TDK_DeducedMismatchNested: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 auto *Saved = new (Context) DFIDeducedMismatchArgs; 637 Saved->FirstArg = Info.FirstArg; 638 Saved->SecondArg = Info.SecondArg; 639 Saved->TemplateArgs = Info.take(); 640 Saved->CallArgIndex = Info.CallArgIndex; 641 Result.Data = Saved; 642 break; 643 } 644 645 case Sema::TDK_NonDeducedMismatch: { 646 // FIXME: Should allocate from normal heap so that we can free this later. 647 DFIArguments *Saved = new (Context) DFIArguments; 648 Saved->FirstArg = Info.FirstArg; 649 Saved->SecondArg = Info.SecondArg; 650 Result.Data = Saved; 651 break; 652 } 653 654 case Sema::TDK_IncompletePack: 655 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 656 case Sema::TDK_Inconsistent: 657 case Sema::TDK_Underqualified: { 658 // FIXME: Should allocate from normal heap so that we can free this later. 659 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 660 Saved->Param = Info.Param; 661 Saved->FirstArg = Info.FirstArg; 662 Saved->SecondArg = Info.SecondArg; 663 Result.Data = Saved; 664 break; 665 } 666 667 case Sema::TDK_SubstitutionFailure: 668 Result.Data = Info.take(); 669 if (Info.hasSFINAEDiagnostic()) { 670 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 671 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 672 Info.takeSFINAEDiagnostic(*Diag); 673 Result.HasDiagnostic = true; 674 } 675 break; 676 677 case Sema::TDK_ConstraintsNotSatisfied: { 678 CNSInfo *Saved = new (Context) CNSInfo; 679 Saved->TemplateArgs = Info.take(); 680 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 681 Result.Data = Saved; 682 break; 683 } 684 685 case Sema::TDK_Success: 686 case Sema::TDK_NonDependentConversionFailure: 687 llvm_unreachable("not a deduction failure"); 688 } 689 690 return Result; 691 } 692 693 void DeductionFailureInfo::Destroy() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_CUDATargetMismatch: 703 case Sema::TDK_NonDependentConversionFailure: 704 break; 705 706 case Sema::TDK_IncompletePack: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_DeducedMismatch: 710 case Sema::TDK_DeducedMismatchNested: 711 case Sema::TDK_NonDeducedMismatch: 712 // FIXME: Destroy the data? 713 Data = nullptr; 714 break; 715 716 case Sema::TDK_SubstitutionFailure: 717 // FIXME: Destroy the template argument list? 718 Data = nullptr; 719 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 720 Diag->~PartialDiagnosticAt(); 721 HasDiagnostic = false; 722 } 723 break; 724 725 case Sema::TDK_ConstraintsNotSatisfied: 726 // FIXME: Destroy the template argument list? 727 Data = nullptr; 728 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 729 Diag->~PartialDiagnosticAt(); 730 HasDiagnostic = false; 731 } 732 break; 733 734 // Unhandled 735 case Sema::TDK_MiscellaneousDeductionFailure: 736 break; 737 } 738 } 739 740 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 741 if (HasDiagnostic) 742 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 743 return nullptr; 744 } 745 746 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 747 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 748 case Sema::TDK_Success: 749 case Sema::TDK_Invalid: 750 case Sema::TDK_InstantiationDepth: 751 case Sema::TDK_TooManyArguments: 752 case Sema::TDK_TooFewArguments: 753 case Sema::TDK_SubstitutionFailure: 754 case Sema::TDK_DeducedMismatch: 755 case Sema::TDK_DeducedMismatchNested: 756 case Sema::TDK_NonDeducedMismatch: 757 case Sema::TDK_CUDATargetMismatch: 758 case Sema::TDK_NonDependentConversionFailure: 759 case Sema::TDK_ConstraintsNotSatisfied: 760 return TemplateParameter(); 761 762 case Sema::TDK_Incomplete: 763 case Sema::TDK_InvalidExplicitArguments: 764 return TemplateParameter::getFromOpaqueValue(Data); 765 766 case Sema::TDK_IncompletePack: 767 case Sema::TDK_Inconsistent: 768 case Sema::TDK_Underqualified: 769 return static_cast<DFIParamWithArguments*>(Data)->Param; 770 771 // Unhandled 772 case Sema::TDK_MiscellaneousDeductionFailure: 773 break; 774 } 775 776 return TemplateParameter(); 777 } 778 779 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 780 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 781 case Sema::TDK_Success: 782 case Sema::TDK_Invalid: 783 case Sema::TDK_InstantiationDepth: 784 case Sema::TDK_TooManyArguments: 785 case Sema::TDK_TooFewArguments: 786 case Sema::TDK_Incomplete: 787 case Sema::TDK_IncompletePack: 788 case Sema::TDK_InvalidExplicitArguments: 789 case Sema::TDK_Inconsistent: 790 case Sema::TDK_Underqualified: 791 case Sema::TDK_NonDeducedMismatch: 792 case Sema::TDK_CUDATargetMismatch: 793 case Sema::TDK_NonDependentConversionFailure: 794 return nullptr; 795 796 case Sema::TDK_DeducedMismatch: 797 case Sema::TDK_DeducedMismatchNested: 798 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 799 800 case Sema::TDK_SubstitutionFailure: 801 return static_cast<TemplateArgumentList*>(Data); 802 803 case Sema::TDK_ConstraintsNotSatisfied: 804 return static_cast<CNSInfo*>(Data)->TemplateArgs; 805 806 // Unhandled 807 case Sema::TDK_MiscellaneousDeductionFailure: 808 break; 809 } 810 811 return nullptr; 812 } 813 814 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 815 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 816 case Sema::TDK_Success: 817 case Sema::TDK_Invalid: 818 case Sema::TDK_InstantiationDepth: 819 case Sema::TDK_Incomplete: 820 case Sema::TDK_TooManyArguments: 821 case Sema::TDK_TooFewArguments: 822 case Sema::TDK_InvalidExplicitArguments: 823 case Sema::TDK_SubstitutionFailure: 824 case Sema::TDK_CUDATargetMismatch: 825 case Sema::TDK_NonDependentConversionFailure: 826 case Sema::TDK_ConstraintsNotSatisfied: 827 return nullptr; 828 829 case Sema::TDK_IncompletePack: 830 case Sema::TDK_Inconsistent: 831 case Sema::TDK_Underqualified: 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 case Sema::TDK_NonDeducedMismatch: 835 return &static_cast<DFIArguments*>(Data)->FirstArg; 836 837 // Unhandled 838 case Sema::TDK_MiscellaneousDeductionFailure: 839 break; 840 } 841 842 return nullptr; 843 } 844 845 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 846 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 847 case Sema::TDK_Success: 848 case Sema::TDK_Invalid: 849 case Sema::TDK_InstantiationDepth: 850 case Sema::TDK_Incomplete: 851 case Sema::TDK_IncompletePack: 852 case Sema::TDK_TooManyArguments: 853 case Sema::TDK_TooFewArguments: 854 case Sema::TDK_InvalidExplicitArguments: 855 case Sema::TDK_SubstitutionFailure: 856 case Sema::TDK_CUDATargetMismatch: 857 case Sema::TDK_NonDependentConversionFailure: 858 case Sema::TDK_ConstraintsNotSatisfied: 859 return nullptr; 860 861 case Sema::TDK_Inconsistent: 862 case Sema::TDK_Underqualified: 863 case Sema::TDK_DeducedMismatch: 864 case Sema::TDK_DeducedMismatchNested: 865 case Sema::TDK_NonDeducedMismatch: 866 return &static_cast<DFIArguments*>(Data)->SecondArg; 867 868 // Unhandled 869 case Sema::TDK_MiscellaneousDeductionFailure: 870 break; 871 } 872 873 return nullptr; 874 } 875 876 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 877 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 878 case Sema::TDK_DeducedMismatch: 879 case Sema::TDK_DeducedMismatchNested: 880 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 881 882 default: 883 return llvm::None; 884 } 885 } 886 887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 888 OverloadedOperatorKind Op) { 889 if (!AllowRewrittenCandidates) 890 return false; 891 return Op == OO_EqualEqual || Op == OO_Spaceship; 892 } 893 894 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 895 ASTContext &Ctx, const FunctionDecl *FD) { 896 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 897 return false; 898 // Don't bother adding a reversed candidate that can never be a better 899 // match than the non-reversed version. 900 return FD->getNumParams() != 2 || 901 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 902 FD->getParamDecl(1)->getType()) || 903 FD->hasAttr<EnableIfAttr>(); 904 } 905 906 void OverloadCandidateSet::destroyCandidates() { 907 for (iterator i = begin(), e = end(); i != e; ++i) { 908 for (auto &C : i->Conversions) 909 C.~ImplicitConversionSequence(); 910 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 911 i->DeductionFailure.Destroy(); 912 } 913 } 914 915 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 916 destroyCandidates(); 917 SlabAllocator.Reset(); 918 NumInlineBytesUsed = 0; 919 Candidates.clear(); 920 Functions.clear(); 921 Kind = CSK; 922 } 923 924 namespace { 925 class UnbridgedCastsSet { 926 struct Entry { 927 Expr **Addr; 928 Expr *Saved; 929 }; 930 SmallVector<Entry, 2> Entries; 931 932 public: 933 void save(Sema &S, Expr *&E) { 934 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 935 Entry entry = { &E, E }; 936 Entries.push_back(entry); 937 E = S.stripARCUnbridgedCast(E); 938 } 939 940 void restore() { 941 for (SmallVectorImpl<Entry>::iterator 942 i = Entries.begin(), e = Entries.end(); i != e; ++i) 943 *i->Addr = i->Saved; 944 } 945 }; 946 } 947 948 /// checkPlaceholderForOverload - Do any interesting placeholder-like 949 /// preprocessing on the given expression. 950 /// 951 /// \param unbridgedCasts a collection to which to add unbridged casts; 952 /// without this, they will be immediately diagnosed as errors 953 /// 954 /// Return true on unrecoverable error. 955 static bool 956 checkPlaceholderForOverload(Sema &S, Expr *&E, 957 UnbridgedCastsSet *unbridgedCasts = nullptr) { 958 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 959 // We can't handle overloaded expressions here because overload 960 // resolution might reasonably tweak them. 961 if (placeholder->getKind() == BuiltinType::Overload) return false; 962 963 // If the context potentially accepts unbridged ARC casts, strip 964 // the unbridged cast and add it to the collection for later restoration. 965 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 966 unbridgedCasts) { 967 unbridgedCasts->save(S, E); 968 return false; 969 } 970 971 // Go ahead and check everything else. 972 ExprResult result = S.CheckPlaceholderExpr(E); 973 if (result.isInvalid()) 974 return true; 975 976 E = result.get(); 977 return false; 978 } 979 980 // Nothing to do. 981 return false; 982 } 983 984 /// checkArgPlaceholdersForOverload - Check a set of call operands for 985 /// placeholders. 986 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 987 UnbridgedCastsSet &unbridged) { 988 for (unsigned i = 0, e = Args.size(); i != e; ++i) 989 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 990 return true; 991 992 return false; 993 } 994 995 /// Determine whether the given New declaration is an overload of the 996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 997 /// New and Old cannot be overloaded, e.g., if New has the same signature as 998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 999 /// functions (or function templates) at all. When it does return Ovl_Match or 1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1002 /// declaration. 1003 /// 1004 /// Example: Given the following input: 1005 /// 1006 /// void f(int, float); // #1 1007 /// void f(int, int); // #2 1008 /// int f(int, int); // #3 1009 /// 1010 /// When we process #1, there is no previous declaration of "f", so IsOverload 1011 /// will not be used. 1012 /// 1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1016 /// unchanged. 1017 /// 1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1022 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1023 /// 1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1025 /// by a using declaration. The rules for whether to hide shadow declarations 1026 /// ignore some properties which otherwise figure into a function template's 1027 /// signature. 1028 Sema::OverloadKind 1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1030 NamedDecl *&Match, bool NewIsUsingDecl) { 1031 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1032 I != E; ++I) { 1033 NamedDecl *OldD = *I; 1034 1035 bool OldIsUsingDecl = false; 1036 if (isa<UsingShadowDecl>(OldD)) { 1037 OldIsUsingDecl = true; 1038 1039 // We can always introduce two using declarations into the same 1040 // context, even if they have identical signatures. 1041 if (NewIsUsingDecl) continue; 1042 1043 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1044 } 1045 1046 // A using-declaration does not conflict with another declaration 1047 // if one of them is hidden. 1048 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1049 continue; 1050 1051 // If either declaration was introduced by a using declaration, 1052 // we'll need to use slightly different rules for matching. 1053 // Essentially, these rules are the normal rules, except that 1054 // function templates hide function templates with different 1055 // return types or template parameter lists. 1056 bool UseMemberUsingDeclRules = 1057 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1058 !New->getFriendObjectKind(); 1059 1060 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1061 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1062 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1063 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1064 continue; 1065 } 1066 1067 if (!isa<FunctionTemplateDecl>(OldD) && 1068 !shouldLinkPossiblyHiddenDecl(*I, New)) 1069 continue; 1070 1071 Match = *I; 1072 return Ovl_Match; 1073 } 1074 1075 // Builtins that have custom typechecking or have a reference should 1076 // not be overloadable or redeclarable. 1077 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1078 Match = *I; 1079 return Ovl_NonFunction; 1080 } 1081 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1082 // We can overload with these, which can show up when doing 1083 // redeclaration checks for UsingDecls. 1084 assert(Old.getLookupKind() == LookupUsingDeclName); 1085 } else if (isa<TagDecl>(OldD)) { 1086 // We can always overload with tags by hiding them. 1087 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1088 // Optimistically assume that an unresolved using decl will 1089 // overload; if it doesn't, we'll have to diagnose during 1090 // template instantiation. 1091 // 1092 // Exception: if the scope is dependent and this is not a class 1093 // member, the using declaration can only introduce an enumerator. 1094 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1095 Match = *I; 1096 return Ovl_NonFunction; 1097 } 1098 } else { 1099 // (C++ 13p1): 1100 // Only function declarations can be overloaded; object and type 1101 // declarations cannot be overloaded. 1102 Match = *I; 1103 return Ovl_NonFunction; 1104 } 1105 } 1106 1107 // C++ [temp.friend]p1: 1108 // For a friend function declaration that is not a template declaration: 1109 // -- if the name of the friend is a qualified or unqualified template-id, 1110 // [...], otherwise 1111 // -- if the name of the friend is a qualified-id and a matching 1112 // non-template function is found in the specified class or namespace, 1113 // the friend declaration refers to that function, otherwise, 1114 // -- if the name of the friend is a qualified-id and a matching function 1115 // template is found in the specified class or namespace, the friend 1116 // declaration refers to the deduced specialization of that function 1117 // template, otherwise 1118 // -- the name shall be an unqualified-id [...] 1119 // If we get here for a qualified friend declaration, we've just reached the 1120 // third bullet. If the type of the friend is dependent, skip this lookup 1121 // until instantiation. 1122 if (New->getFriendObjectKind() && New->getQualifier() && 1123 !New->getDescribedFunctionTemplate() && 1124 !New->getDependentSpecializationInfo() && 1125 !New->getType()->isDependentType()) { 1126 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1127 TemplateSpecResult.addAllDecls(Old); 1128 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1129 /*QualifiedFriend*/true)) { 1130 New->setInvalidDecl(); 1131 return Ovl_Overload; 1132 } 1133 1134 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1135 return Ovl_Match; 1136 } 1137 1138 return Ovl_Overload; 1139 } 1140 1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1142 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1143 bool ConsiderRequiresClauses) { 1144 // C++ [basic.start.main]p2: This function shall not be overloaded. 1145 if (New->isMain()) 1146 return false; 1147 1148 // MSVCRT user defined entry points cannot be overloaded. 1149 if (New->isMSVCRTEntryPoint()) 1150 return false; 1151 1152 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1153 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1154 1155 // C++ [temp.fct]p2: 1156 // A function template can be overloaded with other function templates 1157 // and with normal (non-template) functions. 1158 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1159 return true; 1160 1161 // Is the function New an overload of the function Old? 1162 QualType OldQType = Context.getCanonicalType(Old->getType()); 1163 QualType NewQType = Context.getCanonicalType(New->getType()); 1164 1165 // Compare the signatures (C++ 1.3.10) of the two functions to 1166 // determine whether they are overloads. If we find any mismatch 1167 // in the signature, they are overloads. 1168 1169 // If either of these functions is a K&R-style function (no 1170 // prototype), then we consider them to have matching signatures. 1171 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1172 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1173 return false; 1174 1175 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1176 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1177 1178 // The signature of a function includes the types of its 1179 // parameters (C++ 1.3.10), which includes the presence or absence 1180 // of the ellipsis; see C++ DR 357). 1181 if (OldQType != NewQType && 1182 (OldType->getNumParams() != NewType->getNumParams() || 1183 OldType->isVariadic() != NewType->isVariadic() || 1184 !FunctionParamTypesAreEqual(OldType, NewType))) 1185 return true; 1186 1187 // C++ [temp.over.link]p4: 1188 // The signature of a function template consists of its function 1189 // signature, its return type and its template parameter list. The names 1190 // of the template parameters are significant only for establishing the 1191 // relationship between the template parameters and the rest of the 1192 // signature. 1193 // 1194 // We check the return type and template parameter lists for function 1195 // templates first; the remaining checks follow. 1196 // 1197 // However, we don't consider either of these when deciding whether 1198 // a member introduced by a shadow declaration is hidden. 1199 if (!UseMemberUsingDeclRules && NewTemplate && 1200 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1201 OldTemplate->getTemplateParameters(), 1202 false, TPL_TemplateMatch) || 1203 !Context.hasSameType(Old->getDeclaredReturnType(), 1204 New->getDeclaredReturnType()))) 1205 return true; 1206 1207 // If the function is a class member, its signature includes the 1208 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1209 // 1210 // As part of this, also check whether one of the member functions 1211 // is static, in which case they are not overloads (C++ 1212 // 13.1p2). While not part of the definition of the signature, 1213 // this check is important to determine whether these functions 1214 // can be overloaded. 1215 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1216 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1217 if (OldMethod && NewMethod && 1218 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1219 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1220 if (!UseMemberUsingDeclRules && 1221 (OldMethod->getRefQualifier() == RQ_None || 1222 NewMethod->getRefQualifier() == RQ_None)) { 1223 // C++0x [over.load]p2: 1224 // - Member function declarations with the same name and the same 1225 // parameter-type-list as well as member function template 1226 // declarations with the same name, the same parameter-type-list, and 1227 // the same template parameter lists cannot be overloaded if any of 1228 // them, but not all, have a ref-qualifier (8.3.5). 1229 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1230 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1231 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1232 } 1233 return true; 1234 } 1235 1236 // We may not have applied the implicit const for a constexpr member 1237 // function yet (because we haven't yet resolved whether this is a static 1238 // or non-static member function). Add it now, on the assumption that this 1239 // is a redeclaration of OldMethod. 1240 auto OldQuals = OldMethod->getMethodQualifiers(); 1241 auto NewQuals = NewMethod->getMethodQualifiers(); 1242 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1243 !isa<CXXConstructorDecl>(NewMethod)) 1244 NewQuals.addConst(); 1245 // We do not allow overloading based off of '__restrict'. 1246 OldQuals.removeRestrict(); 1247 NewQuals.removeRestrict(); 1248 if (OldQuals != NewQuals) 1249 return true; 1250 } 1251 1252 // Though pass_object_size is placed on parameters and takes an argument, we 1253 // consider it to be a function-level modifier for the sake of function 1254 // identity. Either the function has one or more parameters with 1255 // pass_object_size or it doesn't. 1256 if (functionHasPassObjectSizeParams(New) != 1257 functionHasPassObjectSizeParams(Old)) 1258 return true; 1259 1260 // enable_if attributes are an order-sensitive part of the signature. 1261 for (specific_attr_iterator<EnableIfAttr> 1262 NewI = New->specific_attr_begin<EnableIfAttr>(), 1263 NewE = New->specific_attr_end<EnableIfAttr>(), 1264 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1265 OldE = Old->specific_attr_end<EnableIfAttr>(); 1266 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1267 if (NewI == NewE || OldI == OldE) 1268 return true; 1269 llvm::FoldingSetNodeID NewID, OldID; 1270 NewI->getCond()->Profile(NewID, Context, true); 1271 OldI->getCond()->Profile(OldID, Context, true); 1272 if (NewID != OldID) 1273 return true; 1274 } 1275 1276 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1277 // Don't allow overloading of destructors. (In theory we could, but it 1278 // would be a giant change to clang.) 1279 if (!isa<CXXDestructorDecl>(New)) { 1280 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1281 OldTarget = IdentifyCUDATarget(Old); 1282 if (NewTarget != CFT_InvalidTarget) { 1283 assert((OldTarget != CFT_InvalidTarget) && 1284 "Unexpected invalid target."); 1285 1286 // Allow overloading of functions with same signature and different CUDA 1287 // target attributes. 1288 if (NewTarget != OldTarget) 1289 return true; 1290 } 1291 } 1292 } 1293 1294 if (ConsiderRequiresClauses) { 1295 Expr *NewRC = New->getTrailingRequiresClause(), 1296 *OldRC = Old->getTrailingRequiresClause(); 1297 if ((NewRC != nullptr) != (OldRC != nullptr)) 1298 // RC are most certainly different - these are overloads. 1299 return true; 1300 1301 if (NewRC) { 1302 llvm::FoldingSetNodeID NewID, OldID; 1303 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1304 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1305 if (NewID != OldID) 1306 // RCs are not equivalent - these are overloads. 1307 return true; 1308 } 1309 } 1310 1311 // The signatures match; this is not an overload. 1312 return false; 1313 } 1314 1315 /// Tries a user-defined conversion from From to ToType. 1316 /// 1317 /// Produces an implicit conversion sequence for when a standard conversion 1318 /// is not an option. See TryImplicitConversion for more information. 1319 static ImplicitConversionSequence 1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1321 bool SuppressUserConversions, 1322 AllowedExplicit AllowExplicit, 1323 bool InOverloadResolution, 1324 bool CStyle, 1325 bool AllowObjCWritebackConversion, 1326 bool AllowObjCConversionOnExplicit) { 1327 ImplicitConversionSequence ICS; 1328 1329 if (SuppressUserConversions) { 1330 // We're not in the case above, so there is no conversion that 1331 // we can perform. 1332 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1333 return ICS; 1334 } 1335 1336 // Attempt user-defined conversion. 1337 OverloadCandidateSet Conversions(From->getExprLoc(), 1338 OverloadCandidateSet::CSK_Normal); 1339 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1340 Conversions, AllowExplicit, 1341 AllowObjCConversionOnExplicit)) { 1342 case OR_Success: 1343 case OR_Deleted: 1344 ICS.setUserDefined(); 1345 // C++ [over.ics.user]p4: 1346 // A conversion of an expression of class type to the same class 1347 // type is given Exact Match rank, and a conversion of an 1348 // expression of class type to a base class of that type is 1349 // given Conversion rank, in spite of the fact that a copy 1350 // constructor (i.e., a user-defined conversion function) is 1351 // called for those cases. 1352 if (CXXConstructorDecl *Constructor 1353 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1354 QualType FromCanon 1355 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1356 QualType ToCanon 1357 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1358 if (Constructor->isCopyConstructor() && 1359 (FromCanon == ToCanon || 1360 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1361 // Turn this into a "standard" conversion sequence, so that it 1362 // gets ranked with standard conversion sequences. 1363 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1364 ICS.setStandard(); 1365 ICS.Standard.setAsIdentityConversion(); 1366 ICS.Standard.setFromType(From->getType()); 1367 ICS.Standard.setAllToTypes(ToType); 1368 ICS.Standard.CopyConstructor = Constructor; 1369 ICS.Standard.FoundCopyConstructor = Found; 1370 if (ToCanon != FromCanon) 1371 ICS.Standard.Second = ICK_Derived_To_Base; 1372 } 1373 } 1374 break; 1375 1376 case OR_Ambiguous: 1377 ICS.setAmbiguous(); 1378 ICS.Ambiguous.setFromType(From->getType()); 1379 ICS.Ambiguous.setToType(ToType); 1380 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1381 Cand != Conversions.end(); ++Cand) 1382 if (Cand->Best) 1383 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1384 break; 1385 1386 // Fall through. 1387 case OR_No_Viable_Function: 1388 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1389 break; 1390 } 1391 1392 return ICS; 1393 } 1394 1395 /// TryImplicitConversion - Attempt to perform an implicit conversion 1396 /// from the given expression (Expr) to the given type (ToType). This 1397 /// function returns an implicit conversion sequence that can be used 1398 /// to perform the initialization. Given 1399 /// 1400 /// void f(float f); 1401 /// void g(int i) { f(i); } 1402 /// 1403 /// this routine would produce an implicit conversion sequence to 1404 /// describe the initialization of f from i, which will be a standard 1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1407 // 1408 /// Note that this routine only determines how the conversion can be 1409 /// performed; it does not actually perform the conversion. As such, 1410 /// it will not produce any diagnostics if no conversion is available, 1411 /// but will instead return an implicit conversion sequence of kind 1412 /// "BadConversion". 1413 /// 1414 /// If @p SuppressUserConversions, then user-defined conversions are 1415 /// not permitted. 1416 /// If @p AllowExplicit, then explicit user-defined conversions are 1417 /// permitted. 1418 /// 1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1420 /// writeback conversion, which allows __autoreleasing id* parameters to 1421 /// be initialized with __strong id* or __weak id* arguments. 1422 static ImplicitConversionSequence 1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1424 bool SuppressUserConversions, 1425 AllowedExplicit AllowExplicit, 1426 bool InOverloadResolution, 1427 bool CStyle, 1428 bool AllowObjCWritebackConversion, 1429 bool AllowObjCConversionOnExplicit) { 1430 ImplicitConversionSequence ICS; 1431 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1432 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1433 ICS.setStandard(); 1434 return ICS; 1435 } 1436 1437 if (!S.getLangOpts().CPlusPlus) { 1438 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1439 return ICS; 1440 } 1441 1442 // C++ [over.ics.user]p4: 1443 // A conversion of an expression of class type to the same class 1444 // type is given Exact Match rank, and a conversion of an 1445 // expression of class type to a base class of that type is 1446 // given Conversion rank, in spite of the fact that a copy/move 1447 // constructor (i.e., a user-defined conversion function) is 1448 // called for those cases. 1449 QualType FromType = From->getType(); 1450 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1451 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1452 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1453 ICS.setStandard(); 1454 ICS.Standard.setAsIdentityConversion(); 1455 ICS.Standard.setFromType(FromType); 1456 ICS.Standard.setAllToTypes(ToType); 1457 1458 // We don't actually check at this point whether there is a valid 1459 // copy/move constructor, since overloading just assumes that it 1460 // exists. When we actually perform initialization, we'll find the 1461 // appropriate constructor to copy the returned object, if needed. 1462 ICS.Standard.CopyConstructor = nullptr; 1463 1464 // Determine whether this is considered a derived-to-base conversion. 1465 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1466 ICS.Standard.Second = ICK_Derived_To_Base; 1467 1468 return ICS; 1469 } 1470 1471 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1472 AllowExplicit, InOverloadResolution, CStyle, 1473 AllowObjCWritebackConversion, 1474 AllowObjCConversionOnExplicit); 1475 } 1476 1477 ImplicitConversionSequence 1478 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1479 bool SuppressUserConversions, 1480 AllowedExplicit AllowExplicit, 1481 bool InOverloadResolution, 1482 bool CStyle, 1483 bool AllowObjCWritebackConversion) { 1484 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1485 AllowExplicit, InOverloadResolution, CStyle, 1486 AllowObjCWritebackConversion, 1487 /*AllowObjCConversionOnExplicit=*/false); 1488 } 1489 1490 /// PerformImplicitConversion - Perform an implicit conversion of the 1491 /// expression From to the type ToType. Returns the 1492 /// converted expression. Flavor is the kind of conversion we're 1493 /// performing, used in the error message. If @p AllowExplicit, 1494 /// explicit user-defined conversions are permitted. 1495 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, 1497 bool AllowExplicit) { 1498 if (checkPlaceholderForOverload(*this, From)) 1499 return ExprError(); 1500 1501 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1502 bool AllowObjCWritebackConversion 1503 = getLangOpts().ObjCAutoRefCount && 1504 (Action == AA_Passing || Action == AA_Sending); 1505 if (getLangOpts().ObjC) 1506 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1507 From->getType(), From); 1508 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1509 *this, From, ToType, 1510 /*SuppressUserConversions=*/false, 1511 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1512 /*InOverloadResolution=*/false, 1513 /*CStyle=*/false, AllowObjCWritebackConversion, 1514 /*AllowObjCConversionOnExplicit=*/false); 1515 return PerformImplicitConversion(From, ToType, ICS, Action); 1516 } 1517 1518 /// Determine whether the conversion from FromType to ToType is a valid 1519 /// conversion that strips "noexcept" or "noreturn" off the nested function 1520 /// type. 1521 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1522 QualType &ResultTy) { 1523 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1524 return false; 1525 1526 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1527 // or F(t noexcept) -> F(t) 1528 // where F adds one of the following at most once: 1529 // - a pointer 1530 // - a member pointer 1531 // - a block pointer 1532 // Changes here need matching changes in FindCompositePointerType. 1533 CanQualType CanTo = Context.getCanonicalType(ToType); 1534 CanQualType CanFrom = Context.getCanonicalType(FromType); 1535 Type::TypeClass TyClass = CanTo->getTypeClass(); 1536 if (TyClass != CanFrom->getTypeClass()) return false; 1537 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1538 if (TyClass == Type::Pointer) { 1539 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1540 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1541 } else if (TyClass == Type::BlockPointer) { 1542 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1543 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1544 } else if (TyClass == Type::MemberPointer) { 1545 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1546 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1547 // A function pointer conversion cannot change the class of the function. 1548 if (ToMPT->getClass() != FromMPT->getClass()) 1549 return false; 1550 CanTo = ToMPT->getPointeeType(); 1551 CanFrom = FromMPT->getPointeeType(); 1552 } else { 1553 return false; 1554 } 1555 1556 TyClass = CanTo->getTypeClass(); 1557 if (TyClass != CanFrom->getTypeClass()) return false; 1558 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1559 return false; 1560 } 1561 1562 const auto *FromFn = cast<FunctionType>(CanFrom); 1563 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1564 1565 const auto *ToFn = cast<FunctionType>(CanTo); 1566 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1567 1568 bool Changed = false; 1569 1570 // Drop 'noreturn' if not present in target type. 1571 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1572 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1573 Changed = true; 1574 } 1575 1576 // Drop 'noexcept' if not present in target type. 1577 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1578 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1579 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1580 FromFn = cast<FunctionType>( 1581 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1582 EST_None) 1583 .getTypePtr()); 1584 Changed = true; 1585 } 1586 1587 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1588 // only if the ExtParameterInfo lists of the two function prototypes can be 1589 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1590 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1591 bool CanUseToFPT, CanUseFromFPT; 1592 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1593 CanUseFromFPT, NewParamInfos) && 1594 CanUseToFPT && !CanUseFromFPT) { 1595 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1596 ExtInfo.ExtParameterInfos = 1597 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1598 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1599 FromFPT->getParamTypes(), ExtInfo); 1600 FromFn = QT->getAs<FunctionType>(); 1601 Changed = true; 1602 } 1603 } 1604 1605 if (!Changed) 1606 return false; 1607 1608 assert(QualType(FromFn, 0).isCanonical()); 1609 if (QualType(FromFn, 0) != CanTo) return false; 1610 1611 ResultTy = ToType; 1612 return true; 1613 } 1614 1615 /// Determine whether the conversion from FromType to ToType is a valid 1616 /// vector conversion. 1617 /// 1618 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1619 /// conversion. 1620 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, 1621 ImplicitConversionKind &ICK, Expr *From, 1622 bool InOverloadResolution) { 1623 // We need at least one of these types to be a vector type to have a vector 1624 // conversion. 1625 if (!ToType->isVectorType() && !FromType->isVectorType()) 1626 return false; 1627 1628 // Identical types require no conversions. 1629 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1630 return false; 1631 1632 // There are no conversions between extended vector types, only identity. 1633 if (ToType->isExtVectorType()) { 1634 // There are no conversions between extended vector types other than the 1635 // identity conversion. 1636 if (FromType->isExtVectorType()) 1637 return false; 1638 1639 // Vector splat from any arithmetic type to a vector. 1640 if (FromType->isArithmeticType()) { 1641 ICK = ICK_Vector_Splat; 1642 return true; 1643 } 1644 } 1645 1646 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1647 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1648 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1649 ICK = ICK_SVE_Vector_Conversion; 1650 return true; 1651 } 1652 1653 // We can perform the conversion between vector types in the following cases: 1654 // 1)vector types are equivalent AltiVec and GCC vector types 1655 // 2)lax vector conversions are permitted and the vector types are of the 1656 // same size 1657 // 3)the destination type does not have the ARM MVE strict-polymorphism 1658 // attribute, which inhibits lax vector conversion for overload resolution 1659 // only 1660 if (ToType->isVectorType() && FromType->isVectorType()) { 1661 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1662 (S.isLaxVectorConversion(FromType, ToType) && 1663 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1664 if (S.isLaxVectorConversion(FromType, ToType) && 1665 S.anyAltivecTypes(FromType, ToType) && 1666 !S.areSameVectorElemTypes(FromType, ToType) && 1667 !InOverloadResolution) { 1668 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) 1669 << FromType << ToType; 1670 } 1671 ICK = ICK_Vector_Conversion; 1672 return true; 1673 } 1674 } 1675 1676 return false; 1677 } 1678 1679 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1680 bool InOverloadResolution, 1681 StandardConversionSequence &SCS, 1682 bool CStyle); 1683 1684 /// IsStandardConversion - Determines whether there is a standard 1685 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1686 /// expression From to the type ToType. Standard conversion sequences 1687 /// only consider non-class types; for conversions that involve class 1688 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1689 /// contain the standard conversion sequence required to perform this 1690 /// conversion and this routine will return true. Otherwise, this 1691 /// routine will return false and the value of SCS is unspecified. 1692 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1693 bool InOverloadResolution, 1694 StandardConversionSequence &SCS, 1695 bool CStyle, 1696 bool AllowObjCWritebackConversion) { 1697 QualType FromType = From->getType(); 1698 1699 // Standard conversions (C++ [conv]) 1700 SCS.setAsIdentityConversion(); 1701 SCS.IncompatibleObjC = false; 1702 SCS.setFromType(FromType); 1703 SCS.CopyConstructor = nullptr; 1704 1705 // There are no standard conversions for class types in C++, so 1706 // abort early. When overloading in C, however, we do permit them. 1707 if (S.getLangOpts().CPlusPlus && 1708 (FromType->isRecordType() || ToType->isRecordType())) 1709 return false; 1710 1711 // The first conversion can be an lvalue-to-rvalue conversion, 1712 // array-to-pointer conversion, or function-to-pointer conversion 1713 // (C++ 4p1). 1714 1715 if (FromType == S.Context.OverloadTy) { 1716 DeclAccessPair AccessPair; 1717 if (FunctionDecl *Fn 1718 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1719 AccessPair)) { 1720 // We were able to resolve the address of the overloaded function, 1721 // so we can convert to the type of that function. 1722 FromType = Fn->getType(); 1723 SCS.setFromType(FromType); 1724 1725 // we can sometimes resolve &foo<int> regardless of ToType, so check 1726 // if the type matches (identity) or we are converting to bool 1727 if (!S.Context.hasSameUnqualifiedType( 1728 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1729 QualType resultTy; 1730 // if the function type matches except for [[noreturn]], it's ok 1731 if (!S.IsFunctionConversion(FromType, 1732 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1733 // otherwise, only a boolean conversion is standard 1734 if (!ToType->isBooleanType()) 1735 return false; 1736 } 1737 1738 // Check if the "from" expression is taking the address of an overloaded 1739 // function and recompute the FromType accordingly. Take advantage of the 1740 // fact that non-static member functions *must* have such an address-of 1741 // expression. 1742 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1743 if (Method && !Method->isStatic()) { 1744 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1745 "Non-unary operator on non-static member address"); 1746 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1747 == UO_AddrOf && 1748 "Non-address-of operator on non-static member address"); 1749 const Type *ClassType 1750 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1751 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1752 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1753 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1754 UO_AddrOf && 1755 "Non-address-of operator for overloaded function expression"); 1756 FromType = S.Context.getPointerType(FromType); 1757 } 1758 } else { 1759 return false; 1760 } 1761 } 1762 // Lvalue-to-rvalue conversion (C++11 4.1): 1763 // A glvalue (3.10) of a non-function, non-array type T can 1764 // be converted to a prvalue. 1765 bool argIsLValue = From->isGLValue(); 1766 if (argIsLValue && 1767 !FromType->isFunctionType() && !FromType->isArrayType() && 1768 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1769 SCS.First = ICK_Lvalue_To_Rvalue; 1770 1771 // C11 6.3.2.1p2: 1772 // ... if the lvalue has atomic type, the value has the non-atomic version 1773 // of the type of the lvalue ... 1774 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1775 FromType = Atomic->getValueType(); 1776 1777 // If T is a non-class type, the type of the rvalue is the 1778 // cv-unqualified version of T. Otherwise, the type of the rvalue 1779 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1780 // just strip the qualifiers because they don't matter. 1781 FromType = FromType.getUnqualifiedType(); 1782 } else if (FromType->isArrayType()) { 1783 // Array-to-pointer conversion (C++ 4.2) 1784 SCS.First = ICK_Array_To_Pointer; 1785 1786 // An lvalue or rvalue of type "array of N T" or "array of unknown 1787 // bound of T" can be converted to an rvalue of type "pointer to 1788 // T" (C++ 4.2p1). 1789 FromType = S.Context.getArrayDecayedType(FromType); 1790 1791 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1792 // This conversion is deprecated in C++03 (D.4) 1793 SCS.DeprecatedStringLiteralToCharPtr = true; 1794 1795 // For the purpose of ranking in overload resolution 1796 // (13.3.3.1.1), this conversion is considered an 1797 // array-to-pointer conversion followed by a qualification 1798 // conversion (4.4). (C++ 4.2p2) 1799 SCS.Second = ICK_Identity; 1800 SCS.Third = ICK_Qualification; 1801 SCS.QualificationIncludesObjCLifetime = false; 1802 SCS.setAllToTypes(FromType); 1803 return true; 1804 } 1805 } else if (FromType->isFunctionType() && argIsLValue) { 1806 // Function-to-pointer conversion (C++ 4.3). 1807 SCS.First = ICK_Function_To_Pointer; 1808 1809 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1810 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1811 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1812 return false; 1813 1814 // An lvalue of function type T can be converted to an rvalue of 1815 // type "pointer to T." The result is a pointer to the 1816 // function. (C++ 4.3p1). 1817 FromType = S.Context.getPointerType(FromType); 1818 } else { 1819 // We don't require any conversions for the first step. 1820 SCS.First = ICK_Identity; 1821 } 1822 SCS.setToType(0, FromType); 1823 1824 // The second conversion can be an integral promotion, floating 1825 // point promotion, integral conversion, floating point conversion, 1826 // floating-integral conversion, pointer conversion, 1827 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1828 // For overloading in C, this can also be a "compatible-type" 1829 // conversion. 1830 bool IncompatibleObjC = false; 1831 ImplicitConversionKind SecondICK = ICK_Identity; 1832 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1833 // The unqualified versions of the types are the same: there's no 1834 // conversion to do. 1835 SCS.Second = ICK_Identity; 1836 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1837 // Integral promotion (C++ 4.5). 1838 SCS.Second = ICK_Integral_Promotion; 1839 FromType = ToType.getUnqualifiedType(); 1840 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1841 // Floating point promotion (C++ 4.6). 1842 SCS.Second = ICK_Floating_Promotion; 1843 FromType = ToType.getUnqualifiedType(); 1844 } else if (S.IsComplexPromotion(FromType, ToType)) { 1845 // Complex promotion (Clang extension) 1846 SCS.Second = ICK_Complex_Promotion; 1847 FromType = ToType.getUnqualifiedType(); 1848 } else if (ToType->isBooleanType() && 1849 (FromType->isArithmeticType() || 1850 FromType->isAnyPointerType() || 1851 FromType->isBlockPointerType() || 1852 FromType->isMemberPointerType())) { 1853 // Boolean conversions (C++ 4.12). 1854 SCS.Second = ICK_Boolean_Conversion; 1855 FromType = S.Context.BoolTy; 1856 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1857 ToType->isIntegralType(S.Context)) { 1858 // Integral conversions (C++ 4.7). 1859 SCS.Second = ICK_Integral_Conversion; 1860 FromType = ToType.getUnqualifiedType(); 1861 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1862 // Complex conversions (C99 6.3.1.6) 1863 SCS.Second = ICK_Complex_Conversion; 1864 FromType = ToType.getUnqualifiedType(); 1865 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1866 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1867 // Complex-real conversions (C99 6.3.1.7) 1868 SCS.Second = ICK_Complex_Real; 1869 FromType = ToType.getUnqualifiedType(); 1870 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1871 // FIXME: disable conversions between long double, __ibm128 and __float128 1872 // if their representation is different until there is back end support 1873 // We of course allow this conversion if long double is really double. 1874 1875 // Conversions between bfloat and other floats are not permitted. 1876 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1877 return false; 1878 1879 // Conversions between IEEE-quad and IBM-extended semantics are not 1880 // permitted. 1881 const llvm::fltSemantics &FromSem = 1882 S.Context.getFloatTypeSemantics(FromType); 1883 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 1884 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 1885 &ToSem == &llvm::APFloat::IEEEquad()) || 1886 (&FromSem == &llvm::APFloat::IEEEquad() && 1887 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 1888 return false; 1889 1890 // Floating point conversions (C++ 4.8). 1891 SCS.Second = ICK_Floating_Conversion; 1892 FromType = ToType.getUnqualifiedType(); 1893 } else if ((FromType->isRealFloatingType() && 1894 ToType->isIntegralType(S.Context)) || 1895 (FromType->isIntegralOrUnscopedEnumerationType() && 1896 ToType->isRealFloatingType())) { 1897 // Conversions between bfloat and int are not permitted. 1898 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1899 return false; 1900 1901 // Floating-integral conversions (C++ 4.9). 1902 SCS.Second = ICK_Floating_Integral; 1903 FromType = ToType.getUnqualifiedType(); 1904 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1905 SCS.Second = ICK_Block_Pointer_Conversion; 1906 } else if (AllowObjCWritebackConversion && 1907 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1908 SCS.Second = ICK_Writeback_Conversion; 1909 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1910 FromType, IncompatibleObjC)) { 1911 // Pointer conversions (C++ 4.10). 1912 SCS.Second = ICK_Pointer_Conversion; 1913 SCS.IncompatibleObjC = IncompatibleObjC; 1914 FromType = FromType.getUnqualifiedType(); 1915 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1916 InOverloadResolution, FromType)) { 1917 // Pointer to member conversions (4.11). 1918 SCS.Second = ICK_Pointer_Member; 1919 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, 1920 InOverloadResolution)) { 1921 SCS.Second = SecondICK; 1922 FromType = ToType.getUnqualifiedType(); 1923 } else if (!S.getLangOpts().CPlusPlus && 1924 S.Context.typesAreCompatible(ToType, FromType)) { 1925 // Compatible conversions (Clang extension for C function overloading) 1926 SCS.Second = ICK_Compatible_Conversion; 1927 FromType = ToType.getUnqualifiedType(); 1928 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1929 InOverloadResolution, 1930 SCS, CStyle)) { 1931 SCS.Second = ICK_TransparentUnionConversion; 1932 FromType = ToType; 1933 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1934 CStyle)) { 1935 // tryAtomicConversion has updated the standard conversion sequence 1936 // appropriately. 1937 return true; 1938 } else if (ToType->isEventT() && 1939 From->isIntegerConstantExpr(S.getASTContext()) && 1940 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1941 SCS.Second = ICK_Zero_Event_Conversion; 1942 FromType = ToType; 1943 } else if (ToType->isQueueT() && 1944 From->isIntegerConstantExpr(S.getASTContext()) && 1945 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1946 SCS.Second = ICK_Zero_Queue_Conversion; 1947 FromType = ToType; 1948 } else if (ToType->isSamplerT() && 1949 From->isIntegerConstantExpr(S.getASTContext())) { 1950 SCS.Second = ICK_Compatible_Conversion; 1951 FromType = ToType; 1952 } else { 1953 // No second conversion required. 1954 SCS.Second = ICK_Identity; 1955 } 1956 SCS.setToType(1, FromType); 1957 1958 // The third conversion can be a function pointer conversion or a 1959 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1960 bool ObjCLifetimeConversion; 1961 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1962 // Function pointer conversions (removing 'noexcept') including removal of 1963 // 'noreturn' (Clang extension). 1964 SCS.Third = ICK_Function_Conversion; 1965 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1966 ObjCLifetimeConversion)) { 1967 SCS.Third = ICK_Qualification; 1968 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1969 FromType = ToType; 1970 } else { 1971 // No conversion required 1972 SCS.Third = ICK_Identity; 1973 } 1974 1975 // C++ [over.best.ics]p6: 1976 // [...] Any difference in top-level cv-qualification is 1977 // subsumed by the initialization itself and does not constitute 1978 // a conversion. [...] 1979 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1980 QualType CanonTo = S.Context.getCanonicalType(ToType); 1981 if (CanonFrom.getLocalUnqualifiedType() 1982 == CanonTo.getLocalUnqualifiedType() && 1983 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1984 FromType = ToType; 1985 CanonFrom = CanonTo; 1986 } 1987 1988 SCS.setToType(2, FromType); 1989 1990 if (CanonFrom == CanonTo) 1991 return true; 1992 1993 // If we have not converted the argument type to the parameter type, 1994 // this is a bad conversion sequence, unless we're resolving an overload in C. 1995 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1996 return false; 1997 1998 ExprResult ER = ExprResult{From}; 1999 Sema::AssignConvertType Conv = 2000 S.CheckSingleAssignmentConstraints(ToType, ER, 2001 /*Diagnose=*/false, 2002 /*DiagnoseCFAudited=*/false, 2003 /*ConvertRHS=*/false); 2004 ImplicitConversionKind SecondConv; 2005 switch (Conv) { 2006 case Sema::Compatible: 2007 SecondConv = ICK_C_Only_Conversion; 2008 break; 2009 // For our purposes, discarding qualifiers is just as bad as using an 2010 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2011 // qualifiers, as well. 2012 case Sema::CompatiblePointerDiscardsQualifiers: 2013 case Sema::IncompatiblePointer: 2014 case Sema::IncompatiblePointerSign: 2015 SecondConv = ICK_Incompatible_Pointer_Conversion; 2016 break; 2017 default: 2018 return false; 2019 } 2020 2021 // First can only be an lvalue conversion, so we pretend that this was the 2022 // second conversion. First should already be valid from earlier in the 2023 // function. 2024 SCS.Second = SecondConv; 2025 SCS.setToType(1, ToType); 2026 2027 // Third is Identity, because Second should rank us worse than any other 2028 // conversion. This could also be ICK_Qualification, but it's simpler to just 2029 // lump everything in with the second conversion, and we don't gain anything 2030 // from making this ICK_Qualification. 2031 SCS.Third = ICK_Identity; 2032 SCS.setToType(2, ToType); 2033 return true; 2034 } 2035 2036 static bool 2037 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2038 QualType &ToType, 2039 bool InOverloadResolution, 2040 StandardConversionSequence &SCS, 2041 bool CStyle) { 2042 2043 const RecordType *UT = ToType->getAsUnionType(); 2044 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2045 return false; 2046 // The field to initialize within the transparent union. 2047 RecordDecl *UD = UT->getDecl(); 2048 // It's compatible if the expression matches any of the fields. 2049 for (const auto *it : UD->fields()) { 2050 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2051 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2052 ToType = it->getType(); 2053 return true; 2054 } 2055 } 2056 return false; 2057 } 2058 2059 /// IsIntegralPromotion - Determines whether the conversion from the 2060 /// expression From (whose potentially-adjusted type is FromType) to 2061 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2062 /// sets PromotedType to the promoted type. 2063 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2064 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2065 // All integers are built-in. 2066 if (!To) { 2067 return false; 2068 } 2069 2070 // An rvalue of type char, signed char, unsigned char, short int, or 2071 // unsigned short int can be converted to an rvalue of type int if 2072 // int can represent all the values of the source type; otherwise, 2073 // the source rvalue can be converted to an rvalue of type unsigned 2074 // int (C++ 4.5p1). 2075 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2076 !FromType->isEnumeralType()) { 2077 if (// We can promote any signed, promotable integer type to an int 2078 (FromType->isSignedIntegerType() || 2079 // We can promote any unsigned integer type whose size is 2080 // less than int to an int. 2081 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2082 return To->getKind() == BuiltinType::Int; 2083 } 2084 2085 return To->getKind() == BuiltinType::UInt; 2086 } 2087 2088 // C++11 [conv.prom]p3: 2089 // A prvalue of an unscoped enumeration type whose underlying type is not 2090 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2091 // following types that can represent all the values of the enumeration 2092 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2093 // unsigned int, long int, unsigned long int, long long int, or unsigned 2094 // long long int. If none of the types in that list can represent all the 2095 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2096 // type can be converted to an rvalue a prvalue of the extended integer type 2097 // with lowest integer conversion rank (4.13) greater than the rank of long 2098 // long in which all the values of the enumeration can be represented. If 2099 // there are two such extended types, the signed one is chosen. 2100 // C++11 [conv.prom]p4: 2101 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2102 // can be converted to a prvalue of its underlying type. Moreover, if 2103 // integral promotion can be applied to its underlying type, a prvalue of an 2104 // unscoped enumeration type whose underlying type is fixed can also be 2105 // converted to a prvalue of the promoted underlying type. 2106 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2107 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2108 // provided for a scoped enumeration. 2109 if (FromEnumType->getDecl()->isScoped()) 2110 return false; 2111 2112 // We can perform an integral promotion to the underlying type of the enum, 2113 // even if that's not the promoted type. Note that the check for promoting 2114 // the underlying type is based on the type alone, and does not consider 2115 // the bitfield-ness of the actual source expression. 2116 if (FromEnumType->getDecl()->isFixed()) { 2117 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2118 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2119 IsIntegralPromotion(nullptr, Underlying, ToType); 2120 } 2121 2122 // We have already pre-calculated the promotion type, so this is trivial. 2123 if (ToType->isIntegerType() && 2124 isCompleteType(From->getBeginLoc(), FromType)) 2125 return Context.hasSameUnqualifiedType( 2126 ToType, FromEnumType->getDecl()->getPromotionType()); 2127 2128 // C++ [conv.prom]p5: 2129 // If the bit-field has an enumerated type, it is treated as any other 2130 // value of that type for promotion purposes. 2131 // 2132 // ... so do not fall through into the bit-field checks below in C++. 2133 if (getLangOpts().CPlusPlus) 2134 return false; 2135 } 2136 2137 // C++0x [conv.prom]p2: 2138 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2139 // to an rvalue a prvalue of the first of the following types that can 2140 // represent all the values of its underlying type: int, unsigned int, 2141 // long int, unsigned long int, long long int, or unsigned long long int. 2142 // If none of the types in that list can represent all the values of its 2143 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2144 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2145 // type. 2146 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2147 ToType->isIntegerType()) { 2148 // Determine whether the type we're converting from is signed or 2149 // unsigned. 2150 bool FromIsSigned = FromType->isSignedIntegerType(); 2151 uint64_t FromSize = Context.getTypeSize(FromType); 2152 2153 // The types we'll try to promote to, in the appropriate 2154 // order. Try each of these types. 2155 QualType PromoteTypes[6] = { 2156 Context.IntTy, Context.UnsignedIntTy, 2157 Context.LongTy, Context.UnsignedLongTy , 2158 Context.LongLongTy, Context.UnsignedLongLongTy 2159 }; 2160 for (int Idx = 0; Idx < 6; ++Idx) { 2161 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2162 if (FromSize < ToSize || 2163 (FromSize == ToSize && 2164 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2165 // We found the type that we can promote to. If this is the 2166 // type we wanted, we have a promotion. Otherwise, no 2167 // promotion. 2168 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2169 } 2170 } 2171 } 2172 2173 // An rvalue for an integral bit-field (9.6) can be converted to an 2174 // rvalue of type int if int can represent all the values of the 2175 // bit-field; otherwise, it can be converted to unsigned int if 2176 // unsigned int can represent all the values of the bit-field. If 2177 // the bit-field is larger yet, no integral promotion applies to 2178 // it. If the bit-field has an enumerated type, it is treated as any 2179 // other value of that type for promotion purposes (C++ 4.5p3). 2180 // FIXME: We should delay checking of bit-fields until we actually perform the 2181 // conversion. 2182 // 2183 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2184 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2185 // bit-fields and those whose underlying type is larger than int) for GCC 2186 // compatibility. 2187 if (From) { 2188 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2189 Optional<llvm::APSInt> BitWidth; 2190 if (FromType->isIntegralType(Context) && 2191 (BitWidth = 2192 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2193 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2194 ToSize = Context.getTypeSize(ToType); 2195 2196 // Are we promoting to an int from a bitfield that fits in an int? 2197 if (*BitWidth < ToSize || 2198 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2199 return To->getKind() == BuiltinType::Int; 2200 } 2201 2202 // Are we promoting to an unsigned int from an unsigned bitfield 2203 // that fits into an unsigned int? 2204 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2205 return To->getKind() == BuiltinType::UInt; 2206 } 2207 2208 return false; 2209 } 2210 } 2211 } 2212 2213 // An rvalue of type bool can be converted to an rvalue of type int, 2214 // with false becoming zero and true becoming one (C++ 4.5p4). 2215 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2216 return true; 2217 } 2218 2219 return false; 2220 } 2221 2222 /// IsFloatingPointPromotion - Determines whether the conversion from 2223 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2224 /// returns true and sets PromotedType to the promoted type. 2225 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2226 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2227 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2228 /// An rvalue of type float can be converted to an rvalue of type 2229 /// double. (C++ 4.6p1). 2230 if (FromBuiltin->getKind() == BuiltinType::Float && 2231 ToBuiltin->getKind() == BuiltinType::Double) 2232 return true; 2233 2234 // C99 6.3.1.5p1: 2235 // When a float is promoted to double or long double, or a 2236 // double is promoted to long double [...]. 2237 if (!getLangOpts().CPlusPlus && 2238 (FromBuiltin->getKind() == BuiltinType::Float || 2239 FromBuiltin->getKind() == BuiltinType::Double) && 2240 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2241 ToBuiltin->getKind() == BuiltinType::Float128 || 2242 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2243 return true; 2244 2245 // Half can be promoted to float. 2246 if (!getLangOpts().NativeHalfType && 2247 FromBuiltin->getKind() == BuiltinType::Half && 2248 ToBuiltin->getKind() == BuiltinType::Float) 2249 return true; 2250 } 2251 2252 return false; 2253 } 2254 2255 /// Determine if a conversion is a complex promotion. 2256 /// 2257 /// A complex promotion is defined as a complex -> complex conversion 2258 /// where the conversion between the underlying real types is a 2259 /// floating-point or integral promotion. 2260 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2261 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2262 if (!FromComplex) 2263 return false; 2264 2265 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2266 if (!ToComplex) 2267 return false; 2268 2269 return IsFloatingPointPromotion(FromComplex->getElementType(), 2270 ToComplex->getElementType()) || 2271 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2272 ToComplex->getElementType()); 2273 } 2274 2275 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2276 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2277 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2278 /// if non-empty, will be a pointer to ToType that may or may not have 2279 /// the right set of qualifiers on its pointee. 2280 /// 2281 static QualType 2282 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2283 QualType ToPointee, QualType ToType, 2284 ASTContext &Context, 2285 bool StripObjCLifetime = false) { 2286 assert((FromPtr->getTypeClass() == Type::Pointer || 2287 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2288 "Invalid similarly-qualified pointer type"); 2289 2290 /// Conversions to 'id' subsume cv-qualifier conversions. 2291 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2292 return ToType.getUnqualifiedType(); 2293 2294 QualType CanonFromPointee 2295 = Context.getCanonicalType(FromPtr->getPointeeType()); 2296 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2297 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2298 2299 if (StripObjCLifetime) 2300 Quals.removeObjCLifetime(); 2301 2302 // Exact qualifier match -> return the pointer type we're converting to. 2303 if (CanonToPointee.getLocalQualifiers() == Quals) { 2304 // ToType is exactly what we need. Return it. 2305 if (!ToType.isNull()) 2306 return ToType.getUnqualifiedType(); 2307 2308 // Build a pointer to ToPointee. It has the right qualifiers 2309 // already. 2310 if (isa<ObjCObjectPointerType>(ToType)) 2311 return Context.getObjCObjectPointerType(ToPointee); 2312 return Context.getPointerType(ToPointee); 2313 } 2314 2315 // Just build a canonical type that has the right qualifiers. 2316 QualType QualifiedCanonToPointee 2317 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2318 2319 if (isa<ObjCObjectPointerType>(ToType)) 2320 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2321 return Context.getPointerType(QualifiedCanonToPointee); 2322 } 2323 2324 static bool isNullPointerConstantForConversion(Expr *Expr, 2325 bool InOverloadResolution, 2326 ASTContext &Context) { 2327 // Handle value-dependent integral null pointer constants correctly. 2328 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2329 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2330 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2331 return !InOverloadResolution; 2332 2333 return Expr->isNullPointerConstant(Context, 2334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2335 : Expr::NPC_ValueDependentIsNull); 2336 } 2337 2338 /// IsPointerConversion - Determines whether the conversion of the 2339 /// expression From, which has the (possibly adjusted) type FromType, 2340 /// can be converted to the type ToType via a pointer conversion (C++ 2341 /// 4.10). If so, returns true and places the converted type (that 2342 /// might differ from ToType in its cv-qualifiers at some level) into 2343 /// ConvertedType. 2344 /// 2345 /// This routine also supports conversions to and from block pointers 2346 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2347 /// pointers to interfaces. FIXME: Once we've determined the 2348 /// appropriate overloading rules for Objective-C, we may want to 2349 /// split the Objective-C checks into a different routine; however, 2350 /// GCC seems to consider all of these conversions to be pointer 2351 /// conversions, so for now they live here. IncompatibleObjC will be 2352 /// set if the conversion is an allowed Objective-C conversion that 2353 /// should result in a warning. 2354 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2355 bool InOverloadResolution, 2356 QualType& ConvertedType, 2357 bool &IncompatibleObjC) { 2358 IncompatibleObjC = false; 2359 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2360 IncompatibleObjC)) 2361 return true; 2362 2363 // Conversion from a null pointer constant to any Objective-C pointer type. 2364 if (ToType->isObjCObjectPointerType() && 2365 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2366 ConvertedType = ToType; 2367 return true; 2368 } 2369 2370 // Blocks: Block pointers can be converted to void*. 2371 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2372 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2373 ConvertedType = ToType; 2374 return true; 2375 } 2376 // Blocks: A null pointer constant can be converted to a block 2377 // pointer type. 2378 if (ToType->isBlockPointerType() && 2379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2380 ConvertedType = ToType; 2381 return true; 2382 } 2383 2384 // If the left-hand-side is nullptr_t, the right side can be a null 2385 // pointer constant. 2386 if (ToType->isNullPtrType() && 2387 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2388 ConvertedType = ToType; 2389 return true; 2390 } 2391 2392 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2393 if (!ToTypePtr) 2394 return false; 2395 2396 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2397 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2398 ConvertedType = ToType; 2399 return true; 2400 } 2401 2402 // Beyond this point, both types need to be pointers 2403 // , including objective-c pointers. 2404 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2405 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2406 !getLangOpts().ObjCAutoRefCount) { 2407 ConvertedType = BuildSimilarlyQualifiedPointerType( 2408 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2409 Context); 2410 return true; 2411 } 2412 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2413 if (!FromTypePtr) 2414 return false; 2415 2416 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2417 2418 // If the unqualified pointee types are the same, this can't be a 2419 // pointer conversion, so don't do all of the work below. 2420 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2421 return false; 2422 2423 // An rvalue of type "pointer to cv T," where T is an object type, 2424 // can be converted to an rvalue of type "pointer to cv void" (C++ 2425 // 4.10p2). 2426 if (FromPointeeType->isIncompleteOrObjectType() && 2427 ToPointeeType->isVoidType()) { 2428 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2429 ToPointeeType, 2430 ToType, Context, 2431 /*StripObjCLifetime=*/true); 2432 return true; 2433 } 2434 2435 // MSVC allows implicit function to void* type conversion. 2436 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2437 ToPointeeType->isVoidType()) { 2438 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2439 ToPointeeType, 2440 ToType, Context); 2441 return true; 2442 } 2443 2444 // When we're overloading in C, we allow a special kind of pointer 2445 // conversion for compatible-but-not-identical pointee types. 2446 if (!getLangOpts().CPlusPlus && 2447 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2449 ToPointeeType, 2450 ToType, Context); 2451 return true; 2452 } 2453 2454 // C++ [conv.ptr]p3: 2455 // 2456 // An rvalue of type "pointer to cv D," where D is a class type, 2457 // can be converted to an rvalue of type "pointer to cv B," where 2458 // B is a base class (clause 10) of D. If B is an inaccessible 2459 // (clause 11) or ambiguous (10.2) base class of D, a program that 2460 // necessitates this conversion is ill-formed. The result of the 2461 // conversion is a pointer to the base class sub-object of the 2462 // derived class object. The null pointer value is converted to 2463 // the null pointer value of the destination type. 2464 // 2465 // Note that we do not check for ambiguity or inaccessibility 2466 // here. That is handled by CheckPointerConversion. 2467 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2468 ToPointeeType->isRecordType() && 2469 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2470 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2471 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2472 ToPointeeType, 2473 ToType, Context); 2474 return true; 2475 } 2476 2477 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2478 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2479 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2480 ToPointeeType, 2481 ToType, Context); 2482 return true; 2483 } 2484 2485 return false; 2486 } 2487 2488 /// Adopt the given qualifiers for the given type. 2489 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2490 Qualifiers TQs = T.getQualifiers(); 2491 2492 // Check whether qualifiers already match. 2493 if (TQs == Qs) 2494 return T; 2495 2496 if (Qs.compatiblyIncludes(TQs)) 2497 return Context.getQualifiedType(T, Qs); 2498 2499 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2500 } 2501 2502 /// isObjCPointerConversion - Determines whether this is an 2503 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2504 /// with the same arguments and return values. 2505 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2506 QualType& ConvertedType, 2507 bool &IncompatibleObjC) { 2508 if (!getLangOpts().ObjC) 2509 return false; 2510 2511 // The set of qualifiers on the type we're converting from. 2512 Qualifiers FromQualifiers = FromType.getQualifiers(); 2513 2514 // First, we handle all conversions on ObjC object pointer types. 2515 const ObjCObjectPointerType* ToObjCPtr = 2516 ToType->getAs<ObjCObjectPointerType>(); 2517 const ObjCObjectPointerType *FromObjCPtr = 2518 FromType->getAs<ObjCObjectPointerType>(); 2519 2520 if (ToObjCPtr && FromObjCPtr) { 2521 // If the pointee types are the same (ignoring qualifications), 2522 // then this is not a pointer conversion. 2523 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2524 FromObjCPtr->getPointeeType())) 2525 return false; 2526 2527 // Conversion between Objective-C pointers. 2528 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2529 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2530 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2531 if (getLangOpts().CPlusPlus && LHS && RHS && 2532 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2533 FromObjCPtr->getPointeeType())) 2534 return false; 2535 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2536 ToObjCPtr->getPointeeType(), 2537 ToType, Context); 2538 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2539 return true; 2540 } 2541 2542 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2543 // Okay: this is some kind of implicit downcast of Objective-C 2544 // interfaces, which is permitted. However, we're going to 2545 // complain about it. 2546 IncompatibleObjC = true; 2547 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2548 ToObjCPtr->getPointeeType(), 2549 ToType, Context); 2550 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2551 return true; 2552 } 2553 } 2554 // Beyond this point, both types need to be C pointers or block pointers. 2555 QualType ToPointeeType; 2556 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2557 ToPointeeType = ToCPtr->getPointeeType(); 2558 else if (const BlockPointerType *ToBlockPtr = 2559 ToType->getAs<BlockPointerType>()) { 2560 // Objective C++: We're able to convert from a pointer to any object 2561 // to a block pointer type. 2562 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2563 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2564 return true; 2565 } 2566 ToPointeeType = ToBlockPtr->getPointeeType(); 2567 } 2568 else if (FromType->getAs<BlockPointerType>() && 2569 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2570 // Objective C++: We're able to convert from a block pointer type to a 2571 // pointer to any object. 2572 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2573 return true; 2574 } 2575 else 2576 return false; 2577 2578 QualType FromPointeeType; 2579 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2580 FromPointeeType = FromCPtr->getPointeeType(); 2581 else if (const BlockPointerType *FromBlockPtr = 2582 FromType->getAs<BlockPointerType>()) 2583 FromPointeeType = FromBlockPtr->getPointeeType(); 2584 else 2585 return false; 2586 2587 // If we have pointers to pointers, recursively check whether this 2588 // is an Objective-C conversion. 2589 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2590 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2591 IncompatibleObjC)) { 2592 // We always complain about this conversion. 2593 IncompatibleObjC = true; 2594 ConvertedType = Context.getPointerType(ConvertedType); 2595 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2596 return true; 2597 } 2598 // Allow conversion of pointee being objective-c pointer to another one; 2599 // as in I* to id. 2600 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2601 ToPointeeType->getAs<ObjCObjectPointerType>() && 2602 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2603 IncompatibleObjC)) { 2604 2605 ConvertedType = Context.getPointerType(ConvertedType); 2606 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2607 return true; 2608 } 2609 2610 // If we have pointers to functions or blocks, check whether the only 2611 // differences in the argument and result types are in Objective-C 2612 // pointer conversions. If so, we permit the conversion (but 2613 // complain about it). 2614 const FunctionProtoType *FromFunctionType 2615 = FromPointeeType->getAs<FunctionProtoType>(); 2616 const FunctionProtoType *ToFunctionType 2617 = ToPointeeType->getAs<FunctionProtoType>(); 2618 if (FromFunctionType && ToFunctionType) { 2619 // If the function types are exactly the same, this isn't an 2620 // Objective-C pointer conversion. 2621 if (Context.getCanonicalType(FromPointeeType) 2622 == Context.getCanonicalType(ToPointeeType)) 2623 return false; 2624 2625 // Perform the quick checks that will tell us whether these 2626 // function types are obviously different. 2627 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2628 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2629 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2630 return false; 2631 2632 bool HasObjCConversion = false; 2633 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2634 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2635 // Okay, the types match exactly. Nothing to do. 2636 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2637 ToFunctionType->getReturnType(), 2638 ConvertedType, IncompatibleObjC)) { 2639 // Okay, we have an Objective-C pointer conversion. 2640 HasObjCConversion = true; 2641 } else { 2642 // Function types are too different. Abort. 2643 return false; 2644 } 2645 2646 // Check argument types. 2647 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2648 ArgIdx != NumArgs; ++ArgIdx) { 2649 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2650 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2651 if (Context.getCanonicalType(FromArgType) 2652 == Context.getCanonicalType(ToArgType)) { 2653 // Okay, the types match exactly. Nothing to do. 2654 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2655 ConvertedType, IncompatibleObjC)) { 2656 // Okay, we have an Objective-C pointer conversion. 2657 HasObjCConversion = true; 2658 } else { 2659 // Argument types are too different. Abort. 2660 return false; 2661 } 2662 } 2663 2664 if (HasObjCConversion) { 2665 // We had an Objective-C conversion. Allow this pointer 2666 // conversion, but complain about it. 2667 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2668 IncompatibleObjC = true; 2669 return true; 2670 } 2671 } 2672 2673 return false; 2674 } 2675 2676 /// Determine whether this is an Objective-C writeback conversion, 2677 /// used for parameter passing when performing automatic reference counting. 2678 /// 2679 /// \param FromType The type we're converting form. 2680 /// 2681 /// \param ToType The type we're converting to. 2682 /// 2683 /// \param ConvertedType The type that will be produced after applying 2684 /// this conversion. 2685 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2686 QualType &ConvertedType) { 2687 if (!getLangOpts().ObjCAutoRefCount || 2688 Context.hasSameUnqualifiedType(FromType, ToType)) 2689 return false; 2690 2691 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2692 QualType ToPointee; 2693 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2694 ToPointee = ToPointer->getPointeeType(); 2695 else 2696 return false; 2697 2698 Qualifiers ToQuals = ToPointee.getQualifiers(); 2699 if (!ToPointee->isObjCLifetimeType() || 2700 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2701 !ToQuals.withoutObjCLifetime().empty()) 2702 return false; 2703 2704 // Argument must be a pointer to __strong to __weak. 2705 QualType FromPointee; 2706 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2707 FromPointee = FromPointer->getPointeeType(); 2708 else 2709 return false; 2710 2711 Qualifiers FromQuals = FromPointee.getQualifiers(); 2712 if (!FromPointee->isObjCLifetimeType() || 2713 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2714 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2715 return false; 2716 2717 // Make sure that we have compatible qualifiers. 2718 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2719 if (!ToQuals.compatiblyIncludes(FromQuals)) 2720 return false; 2721 2722 // Remove qualifiers from the pointee type we're converting from; they 2723 // aren't used in the compatibility check belong, and we'll be adding back 2724 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2725 FromPointee = FromPointee.getUnqualifiedType(); 2726 2727 // The unqualified form of the pointee types must be compatible. 2728 ToPointee = ToPointee.getUnqualifiedType(); 2729 bool IncompatibleObjC; 2730 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2731 FromPointee = ToPointee; 2732 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2733 IncompatibleObjC)) 2734 return false; 2735 2736 /// Construct the type we're converting to, which is a pointer to 2737 /// __autoreleasing pointee. 2738 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2739 ConvertedType = Context.getPointerType(FromPointee); 2740 return true; 2741 } 2742 2743 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2744 QualType& ConvertedType) { 2745 QualType ToPointeeType; 2746 if (const BlockPointerType *ToBlockPtr = 2747 ToType->getAs<BlockPointerType>()) 2748 ToPointeeType = ToBlockPtr->getPointeeType(); 2749 else 2750 return false; 2751 2752 QualType FromPointeeType; 2753 if (const BlockPointerType *FromBlockPtr = 2754 FromType->getAs<BlockPointerType>()) 2755 FromPointeeType = FromBlockPtr->getPointeeType(); 2756 else 2757 return false; 2758 // We have pointer to blocks, check whether the only 2759 // differences in the argument and result types are in Objective-C 2760 // pointer conversions. If so, we permit the conversion. 2761 2762 const FunctionProtoType *FromFunctionType 2763 = FromPointeeType->getAs<FunctionProtoType>(); 2764 const FunctionProtoType *ToFunctionType 2765 = ToPointeeType->getAs<FunctionProtoType>(); 2766 2767 if (!FromFunctionType || !ToFunctionType) 2768 return false; 2769 2770 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2771 return true; 2772 2773 // Perform the quick checks that will tell us whether these 2774 // function types are obviously different. 2775 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2776 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2777 return false; 2778 2779 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2780 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2781 if (FromEInfo != ToEInfo) 2782 return false; 2783 2784 bool IncompatibleObjC = false; 2785 if (Context.hasSameType(FromFunctionType->getReturnType(), 2786 ToFunctionType->getReturnType())) { 2787 // Okay, the types match exactly. Nothing to do. 2788 } else { 2789 QualType RHS = FromFunctionType->getReturnType(); 2790 QualType LHS = ToFunctionType->getReturnType(); 2791 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2792 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2793 LHS = LHS.getUnqualifiedType(); 2794 2795 if (Context.hasSameType(RHS,LHS)) { 2796 // OK exact match. 2797 } else if (isObjCPointerConversion(RHS, LHS, 2798 ConvertedType, IncompatibleObjC)) { 2799 if (IncompatibleObjC) 2800 return false; 2801 // Okay, we have an Objective-C pointer conversion. 2802 } 2803 else 2804 return false; 2805 } 2806 2807 // Check argument types. 2808 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2809 ArgIdx != NumArgs; ++ArgIdx) { 2810 IncompatibleObjC = false; 2811 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2812 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2813 if (Context.hasSameType(FromArgType, ToArgType)) { 2814 // Okay, the types match exactly. Nothing to do. 2815 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2816 ConvertedType, IncompatibleObjC)) { 2817 if (IncompatibleObjC) 2818 return false; 2819 // Okay, we have an Objective-C pointer conversion. 2820 } else 2821 // Argument types are too different. Abort. 2822 return false; 2823 } 2824 2825 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2826 bool CanUseToFPT, CanUseFromFPT; 2827 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2828 CanUseToFPT, CanUseFromFPT, 2829 NewParamInfos)) 2830 return false; 2831 2832 ConvertedType = ToType; 2833 return true; 2834 } 2835 2836 enum { 2837 ft_default, 2838 ft_different_class, 2839 ft_parameter_arity, 2840 ft_parameter_mismatch, 2841 ft_return_type, 2842 ft_qualifer_mismatch, 2843 ft_noexcept 2844 }; 2845 2846 /// Attempts to get the FunctionProtoType from a Type. Handles 2847 /// MemberFunctionPointers properly. 2848 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2849 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2850 return FPT; 2851 2852 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2853 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2854 2855 return nullptr; 2856 } 2857 2858 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2859 /// function types. Catches different number of parameter, mismatch in 2860 /// parameter types, and different return types. 2861 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2862 QualType FromType, QualType ToType) { 2863 // If either type is not valid, include no extra info. 2864 if (FromType.isNull() || ToType.isNull()) { 2865 PDiag << ft_default; 2866 return; 2867 } 2868 2869 // Get the function type from the pointers. 2870 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2871 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2872 *ToMember = ToType->castAs<MemberPointerType>(); 2873 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2874 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2875 << QualType(FromMember->getClass(), 0); 2876 return; 2877 } 2878 FromType = FromMember->getPointeeType(); 2879 ToType = ToMember->getPointeeType(); 2880 } 2881 2882 if (FromType->isPointerType()) 2883 FromType = FromType->getPointeeType(); 2884 if (ToType->isPointerType()) 2885 ToType = ToType->getPointeeType(); 2886 2887 // Remove references. 2888 FromType = FromType.getNonReferenceType(); 2889 ToType = ToType.getNonReferenceType(); 2890 2891 // Don't print extra info for non-specialized template functions. 2892 if (FromType->isInstantiationDependentType() && 2893 !FromType->getAs<TemplateSpecializationType>()) { 2894 PDiag << ft_default; 2895 return; 2896 } 2897 2898 // No extra info for same types. 2899 if (Context.hasSameType(FromType, ToType)) { 2900 PDiag << ft_default; 2901 return; 2902 } 2903 2904 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2905 *ToFunction = tryGetFunctionProtoType(ToType); 2906 2907 // Both types need to be function types. 2908 if (!FromFunction || !ToFunction) { 2909 PDiag << ft_default; 2910 return; 2911 } 2912 2913 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2914 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2915 << FromFunction->getNumParams(); 2916 return; 2917 } 2918 2919 // Handle different parameter types. 2920 unsigned ArgPos; 2921 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2922 PDiag << ft_parameter_mismatch << ArgPos + 1 2923 << ToFunction->getParamType(ArgPos) 2924 << FromFunction->getParamType(ArgPos); 2925 return; 2926 } 2927 2928 // Handle different return type. 2929 if (!Context.hasSameType(FromFunction->getReturnType(), 2930 ToFunction->getReturnType())) { 2931 PDiag << ft_return_type << ToFunction->getReturnType() 2932 << FromFunction->getReturnType(); 2933 return; 2934 } 2935 2936 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2937 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2938 << FromFunction->getMethodQuals(); 2939 return; 2940 } 2941 2942 // Handle exception specification differences on canonical type (in C++17 2943 // onwards). 2944 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2945 ->isNothrow() != 2946 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2947 ->isNothrow()) { 2948 PDiag << ft_noexcept; 2949 return; 2950 } 2951 2952 // Unable to find a difference, so add no extra info. 2953 PDiag << ft_default; 2954 } 2955 2956 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2957 /// for equality of their parameter types. Caller has already checked that 2958 /// they have same number of parameters. If the parameters are different, 2959 /// ArgPos will have the parameter index of the first different parameter. 2960 /// If `Reversed` is true, the parameters of `NewType` will be compared in 2961 /// reverse order. That's useful if one of the functions is being used as a C++20 2962 /// synthesized operator overload with a reversed parameter order. 2963 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2964 const FunctionProtoType *NewType, 2965 unsigned *ArgPos, bool Reversed) { 2966 assert(OldType->getNumParams() == NewType->getNumParams() && 2967 "Can't compare parameters of functions with different number of " 2968 "parameters!"); 2969 for (size_t I = 0; I < OldType->getNumParams(); I++) { 2970 // Reverse iterate over the parameters of `OldType` if `Reversed` is true. 2971 size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I; 2972 2973 // Ignore address spaces in pointee type. This is to disallow overloading 2974 // on __ptr32/__ptr64 address spaces. 2975 QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType()); 2976 QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType()); 2977 2978 if (!Context.hasSameType(Old, New)) { 2979 if (ArgPos) 2980 *ArgPos = I; 2981 return false; 2982 } 2983 } 2984 return true; 2985 } 2986 2987 /// CheckPointerConversion - Check the pointer conversion from the 2988 /// expression From to the type ToType. This routine checks for 2989 /// ambiguous or inaccessible derived-to-base pointer 2990 /// conversions for which IsPointerConversion has already returned 2991 /// true. It returns true and produces a diagnostic if there was an 2992 /// error, or returns false otherwise. 2993 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2994 CastKind &Kind, 2995 CXXCastPath& BasePath, 2996 bool IgnoreBaseAccess, 2997 bool Diagnose) { 2998 QualType FromType = From->getType(); 2999 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3000 3001 Kind = CK_BitCast; 3002 3003 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3004 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3005 Expr::NPCK_ZeroExpression) { 3006 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3007 DiagRuntimeBehavior(From->getExprLoc(), From, 3008 PDiag(diag::warn_impcast_bool_to_null_pointer) 3009 << ToType << From->getSourceRange()); 3010 else if (!isUnevaluatedContext()) 3011 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3012 << ToType << From->getSourceRange(); 3013 } 3014 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3015 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3016 QualType FromPointeeType = FromPtrType->getPointeeType(), 3017 ToPointeeType = ToPtrType->getPointeeType(); 3018 3019 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3020 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3021 // We must have a derived-to-base conversion. Check an 3022 // ambiguous or inaccessible conversion. 3023 unsigned InaccessibleID = 0; 3024 unsigned AmbiguousID = 0; 3025 if (Diagnose) { 3026 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3027 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3028 } 3029 if (CheckDerivedToBaseConversion( 3030 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3031 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3032 &BasePath, IgnoreBaseAccess)) 3033 return true; 3034 3035 // The conversion was successful. 3036 Kind = CK_DerivedToBase; 3037 } 3038 3039 if (Diagnose && !IsCStyleOrFunctionalCast && 3040 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3041 assert(getLangOpts().MSVCCompat && 3042 "this should only be possible with MSVCCompat!"); 3043 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3044 << From->getSourceRange(); 3045 } 3046 } 3047 } else if (const ObjCObjectPointerType *ToPtrType = 3048 ToType->getAs<ObjCObjectPointerType>()) { 3049 if (const ObjCObjectPointerType *FromPtrType = 3050 FromType->getAs<ObjCObjectPointerType>()) { 3051 // Objective-C++ conversions are always okay. 3052 // FIXME: We should have a different class of conversions for the 3053 // Objective-C++ implicit conversions. 3054 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3055 return false; 3056 } else if (FromType->isBlockPointerType()) { 3057 Kind = CK_BlockPointerToObjCPointerCast; 3058 } else { 3059 Kind = CK_CPointerToObjCPointerCast; 3060 } 3061 } else if (ToType->isBlockPointerType()) { 3062 if (!FromType->isBlockPointerType()) 3063 Kind = CK_AnyPointerToBlockPointerCast; 3064 } 3065 3066 // We shouldn't fall into this case unless it's valid for other 3067 // reasons. 3068 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3069 Kind = CK_NullToPointer; 3070 3071 return false; 3072 } 3073 3074 /// IsMemberPointerConversion - Determines whether the conversion of the 3075 /// expression From, which has the (possibly adjusted) type FromType, can be 3076 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3077 /// If so, returns true and places the converted type (that might differ from 3078 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3079 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3080 QualType ToType, 3081 bool InOverloadResolution, 3082 QualType &ConvertedType) { 3083 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3084 if (!ToTypePtr) 3085 return false; 3086 3087 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3088 if (From->isNullPointerConstant(Context, 3089 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3090 : Expr::NPC_ValueDependentIsNull)) { 3091 ConvertedType = ToType; 3092 return true; 3093 } 3094 3095 // Otherwise, both types have to be member pointers. 3096 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3097 if (!FromTypePtr) 3098 return false; 3099 3100 // A pointer to member of B can be converted to a pointer to member of D, 3101 // where D is derived from B (C++ 4.11p2). 3102 QualType FromClass(FromTypePtr->getClass(), 0); 3103 QualType ToClass(ToTypePtr->getClass(), 0); 3104 3105 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3106 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3107 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3108 ToClass.getTypePtr()); 3109 return true; 3110 } 3111 3112 return false; 3113 } 3114 3115 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3116 /// expression From to the type ToType. This routine checks for ambiguous or 3117 /// virtual or inaccessible base-to-derived member pointer conversions 3118 /// for which IsMemberPointerConversion has already returned true. It returns 3119 /// true and produces a diagnostic if there was an error, or returns false 3120 /// otherwise. 3121 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3122 CastKind &Kind, 3123 CXXCastPath &BasePath, 3124 bool IgnoreBaseAccess) { 3125 QualType FromType = From->getType(); 3126 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3127 if (!FromPtrType) { 3128 // This must be a null pointer to member pointer conversion 3129 assert(From->isNullPointerConstant(Context, 3130 Expr::NPC_ValueDependentIsNull) && 3131 "Expr must be null pointer constant!"); 3132 Kind = CK_NullToMemberPointer; 3133 return false; 3134 } 3135 3136 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3137 assert(ToPtrType && "No member pointer cast has a target type " 3138 "that is not a member pointer."); 3139 3140 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3141 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3142 3143 // FIXME: What about dependent types? 3144 assert(FromClass->isRecordType() && "Pointer into non-class."); 3145 assert(ToClass->isRecordType() && "Pointer into non-class."); 3146 3147 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3148 /*DetectVirtual=*/true); 3149 bool DerivationOkay = 3150 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3151 assert(DerivationOkay && 3152 "Should not have been called if derivation isn't OK."); 3153 (void)DerivationOkay; 3154 3155 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3156 getUnqualifiedType())) { 3157 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3158 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3159 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3160 return true; 3161 } 3162 3163 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3164 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3165 << FromClass << ToClass << QualType(VBase, 0) 3166 << From->getSourceRange(); 3167 return true; 3168 } 3169 3170 if (!IgnoreBaseAccess) 3171 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3172 Paths.front(), 3173 diag::err_downcast_from_inaccessible_base); 3174 3175 // Must be a base to derived member conversion. 3176 BuildBasePathArray(Paths, BasePath); 3177 Kind = CK_BaseToDerivedMemberPointer; 3178 return false; 3179 } 3180 3181 /// Determine whether the lifetime conversion between the two given 3182 /// qualifiers sets is nontrivial. 3183 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3184 Qualifiers ToQuals) { 3185 // Converting anything to const __unsafe_unretained is trivial. 3186 if (ToQuals.hasConst() && 3187 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3188 return false; 3189 3190 return true; 3191 } 3192 3193 /// Perform a single iteration of the loop for checking if a qualification 3194 /// conversion is valid. 3195 /// 3196 /// Specifically, check whether any change between the qualifiers of \p 3197 /// FromType and \p ToType is permissible, given knowledge about whether every 3198 /// outer layer is const-qualified. 3199 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3200 bool CStyle, bool IsTopLevel, 3201 bool &PreviousToQualsIncludeConst, 3202 bool &ObjCLifetimeConversion) { 3203 Qualifiers FromQuals = FromType.getQualifiers(); 3204 Qualifiers ToQuals = ToType.getQualifiers(); 3205 3206 // Ignore __unaligned qualifier. 3207 FromQuals.removeUnaligned(); 3208 3209 // Objective-C ARC: 3210 // Check Objective-C lifetime conversions. 3211 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3212 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3213 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3214 ObjCLifetimeConversion = true; 3215 FromQuals.removeObjCLifetime(); 3216 ToQuals.removeObjCLifetime(); 3217 } else { 3218 // Qualification conversions cannot cast between different 3219 // Objective-C lifetime qualifiers. 3220 return false; 3221 } 3222 } 3223 3224 // Allow addition/removal of GC attributes but not changing GC attributes. 3225 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3226 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3227 FromQuals.removeObjCGCAttr(); 3228 ToQuals.removeObjCGCAttr(); 3229 } 3230 3231 // -- for every j > 0, if const is in cv 1,j then const is in cv 3232 // 2,j, and similarly for volatile. 3233 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3234 return false; 3235 3236 // If address spaces mismatch: 3237 // - in top level it is only valid to convert to addr space that is a 3238 // superset in all cases apart from C-style casts where we allow 3239 // conversions between overlapping address spaces. 3240 // - in non-top levels it is not a valid conversion. 3241 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3242 (!IsTopLevel || 3243 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3244 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3245 return false; 3246 3247 // -- if the cv 1,j and cv 2,j are different, then const is in 3248 // every cv for 0 < k < j. 3249 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3250 !PreviousToQualsIncludeConst) 3251 return false; 3252 3253 // The following wording is from C++20, where the result of the conversion 3254 // is T3, not T2. 3255 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3256 // "array of unknown bound of" 3257 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3258 return false; 3259 3260 // -- if the resulting P3,i is different from P1,i [...], then const is 3261 // added to every cv 3_k for 0 < k < i. 3262 if (!CStyle && FromType->isConstantArrayType() && 3263 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3264 return false; 3265 3266 // Keep track of whether all prior cv-qualifiers in the "to" type 3267 // include const. 3268 PreviousToQualsIncludeConst = 3269 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3270 return true; 3271 } 3272 3273 /// IsQualificationConversion - Determines whether the conversion from 3274 /// an rvalue of type FromType to ToType is a qualification conversion 3275 /// (C++ 4.4). 3276 /// 3277 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3278 /// when the qualification conversion involves a change in the Objective-C 3279 /// object lifetime. 3280 bool 3281 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3282 bool CStyle, bool &ObjCLifetimeConversion) { 3283 FromType = Context.getCanonicalType(FromType); 3284 ToType = Context.getCanonicalType(ToType); 3285 ObjCLifetimeConversion = false; 3286 3287 // If FromType and ToType are the same type, this is not a 3288 // qualification conversion. 3289 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3290 return false; 3291 3292 // (C++ 4.4p4): 3293 // A conversion can add cv-qualifiers at levels other than the first 3294 // in multi-level pointers, subject to the following rules: [...] 3295 bool PreviousToQualsIncludeConst = true; 3296 bool UnwrappedAnyPointer = false; 3297 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3298 if (!isQualificationConversionStep( 3299 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3300 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3301 return false; 3302 UnwrappedAnyPointer = true; 3303 } 3304 3305 // We are left with FromType and ToType being the pointee types 3306 // after unwrapping the original FromType and ToType the same number 3307 // of times. If we unwrapped any pointers, and if FromType and 3308 // ToType have the same unqualified type (since we checked 3309 // qualifiers above), then this is a qualification conversion. 3310 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3311 } 3312 3313 /// - Determine whether this is a conversion from a scalar type to an 3314 /// atomic type. 3315 /// 3316 /// If successful, updates \c SCS's second and third steps in the conversion 3317 /// sequence to finish the conversion. 3318 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3319 bool InOverloadResolution, 3320 StandardConversionSequence &SCS, 3321 bool CStyle) { 3322 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3323 if (!ToAtomic) 3324 return false; 3325 3326 StandardConversionSequence InnerSCS; 3327 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3328 InOverloadResolution, InnerSCS, 3329 CStyle, /*AllowObjCWritebackConversion=*/false)) 3330 return false; 3331 3332 SCS.Second = InnerSCS.Second; 3333 SCS.setToType(1, InnerSCS.getToType(1)); 3334 SCS.Third = InnerSCS.Third; 3335 SCS.QualificationIncludesObjCLifetime 3336 = InnerSCS.QualificationIncludesObjCLifetime; 3337 SCS.setToType(2, InnerSCS.getToType(2)); 3338 return true; 3339 } 3340 3341 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3342 CXXConstructorDecl *Constructor, 3343 QualType Type) { 3344 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3345 if (CtorType->getNumParams() > 0) { 3346 QualType FirstArg = CtorType->getParamType(0); 3347 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3348 return true; 3349 } 3350 return false; 3351 } 3352 3353 static OverloadingResult 3354 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3355 CXXRecordDecl *To, 3356 UserDefinedConversionSequence &User, 3357 OverloadCandidateSet &CandidateSet, 3358 bool AllowExplicit) { 3359 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3360 for (auto *D : S.LookupConstructors(To)) { 3361 auto Info = getConstructorInfo(D); 3362 if (!Info) 3363 continue; 3364 3365 bool Usable = !Info.Constructor->isInvalidDecl() && 3366 S.isInitListConstructor(Info.Constructor); 3367 if (Usable) { 3368 bool SuppressUserConversions = false; 3369 if (Info.ConstructorTmpl) 3370 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3371 /*ExplicitArgs*/ nullptr, From, 3372 CandidateSet, SuppressUserConversions, 3373 /*PartialOverloading*/ false, 3374 AllowExplicit); 3375 else 3376 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3377 CandidateSet, SuppressUserConversions, 3378 /*PartialOverloading*/ false, AllowExplicit); 3379 } 3380 } 3381 3382 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3383 3384 OverloadCandidateSet::iterator Best; 3385 switch (auto Result = 3386 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3387 case OR_Deleted: 3388 case OR_Success: { 3389 // Record the standard conversion we used and the conversion function. 3390 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3391 QualType ThisType = Constructor->getThisType(); 3392 // Initializer lists don't have conversions as such. 3393 User.Before.setAsIdentityConversion(); 3394 User.HadMultipleCandidates = HadMultipleCandidates; 3395 User.ConversionFunction = Constructor; 3396 User.FoundConversionFunction = Best->FoundDecl; 3397 User.After.setAsIdentityConversion(); 3398 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3399 User.After.setAllToTypes(ToType); 3400 return Result; 3401 } 3402 3403 case OR_No_Viable_Function: 3404 return OR_No_Viable_Function; 3405 case OR_Ambiguous: 3406 return OR_Ambiguous; 3407 } 3408 3409 llvm_unreachable("Invalid OverloadResult!"); 3410 } 3411 3412 /// Determines whether there is a user-defined conversion sequence 3413 /// (C++ [over.ics.user]) that converts expression From to the type 3414 /// ToType. If such a conversion exists, User will contain the 3415 /// user-defined conversion sequence that performs such a conversion 3416 /// and this routine will return true. Otherwise, this routine returns 3417 /// false and User is unspecified. 3418 /// 3419 /// \param AllowExplicit true if the conversion should consider C++0x 3420 /// "explicit" conversion functions as well as non-explicit conversion 3421 /// functions (C++0x [class.conv.fct]p2). 3422 /// 3423 /// \param AllowObjCConversionOnExplicit true if the conversion should 3424 /// allow an extra Objective-C pointer conversion on uses of explicit 3425 /// constructors. Requires \c AllowExplicit to also be set. 3426 static OverloadingResult 3427 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3428 UserDefinedConversionSequence &User, 3429 OverloadCandidateSet &CandidateSet, 3430 AllowedExplicit AllowExplicit, 3431 bool AllowObjCConversionOnExplicit) { 3432 assert(AllowExplicit != AllowedExplicit::None || 3433 !AllowObjCConversionOnExplicit); 3434 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3435 3436 // Whether we will only visit constructors. 3437 bool ConstructorsOnly = false; 3438 3439 // If the type we are conversion to is a class type, enumerate its 3440 // constructors. 3441 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3442 // C++ [over.match.ctor]p1: 3443 // When objects of class type are direct-initialized (8.5), or 3444 // copy-initialized from an expression of the same or a 3445 // derived class type (8.5), overload resolution selects the 3446 // constructor. [...] For copy-initialization, the candidate 3447 // functions are all the converting constructors (12.3.1) of 3448 // that class. The argument list is the expression-list within 3449 // the parentheses of the initializer. 3450 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3451 (From->getType()->getAs<RecordType>() && 3452 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3453 ConstructorsOnly = true; 3454 3455 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3456 // We're not going to find any constructors. 3457 } else if (CXXRecordDecl *ToRecordDecl 3458 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3459 3460 Expr **Args = &From; 3461 unsigned NumArgs = 1; 3462 bool ListInitializing = false; 3463 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3464 // But first, see if there is an init-list-constructor that will work. 3465 OverloadingResult Result = IsInitializerListConstructorConversion( 3466 S, From, ToType, ToRecordDecl, User, CandidateSet, 3467 AllowExplicit == AllowedExplicit::All); 3468 if (Result != OR_No_Viable_Function) 3469 return Result; 3470 // Never mind. 3471 CandidateSet.clear( 3472 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3473 3474 // If we're list-initializing, we pass the individual elements as 3475 // arguments, not the entire list. 3476 Args = InitList->getInits(); 3477 NumArgs = InitList->getNumInits(); 3478 ListInitializing = true; 3479 } 3480 3481 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3482 auto Info = getConstructorInfo(D); 3483 if (!Info) 3484 continue; 3485 3486 bool Usable = !Info.Constructor->isInvalidDecl(); 3487 if (!ListInitializing) 3488 Usable = Usable && Info.Constructor->isConvertingConstructor( 3489 /*AllowExplicit*/ true); 3490 if (Usable) { 3491 bool SuppressUserConversions = !ConstructorsOnly; 3492 // C++20 [over.best.ics.general]/4.5: 3493 // if the target is the first parameter of a constructor [of class 3494 // X] and the constructor [...] is a candidate by [...] the second 3495 // phase of [over.match.list] when the initializer list has exactly 3496 // one element that is itself an initializer list, [...] and the 3497 // conversion is to X or reference to cv X, user-defined conversion 3498 // sequences are not cnosidered. 3499 if (SuppressUserConversions && ListInitializing) { 3500 SuppressUserConversions = 3501 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3502 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3503 ToType); 3504 } 3505 if (Info.ConstructorTmpl) 3506 S.AddTemplateOverloadCandidate( 3507 Info.ConstructorTmpl, Info.FoundDecl, 3508 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3509 CandidateSet, SuppressUserConversions, 3510 /*PartialOverloading*/ false, 3511 AllowExplicit == AllowedExplicit::All); 3512 else 3513 // Allow one user-defined conversion when user specifies a 3514 // From->ToType conversion via an static cast (c-style, etc). 3515 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3516 llvm::makeArrayRef(Args, NumArgs), 3517 CandidateSet, SuppressUserConversions, 3518 /*PartialOverloading*/ false, 3519 AllowExplicit == AllowedExplicit::All); 3520 } 3521 } 3522 } 3523 } 3524 3525 // Enumerate conversion functions, if we're allowed to. 3526 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3527 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3528 // No conversion functions from incomplete types. 3529 } else if (const RecordType *FromRecordType = 3530 From->getType()->getAs<RecordType>()) { 3531 if (CXXRecordDecl *FromRecordDecl 3532 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3533 // Add all of the conversion functions as candidates. 3534 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3535 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3536 DeclAccessPair FoundDecl = I.getPair(); 3537 NamedDecl *D = FoundDecl.getDecl(); 3538 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3539 if (isa<UsingShadowDecl>(D)) 3540 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3541 3542 CXXConversionDecl *Conv; 3543 FunctionTemplateDecl *ConvTemplate; 3544 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3545 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3546 else 3547 Conv = cast<CXXConversionDecl>(D); 3548 3549 if (ConvTemplate) 3550 S.AddTemplateConversionCandidate( 3551 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3552 CandidateSet, AllowObjCConversionOnExplicit, 3553 AllowExplicit != AllowedExplicit::None); 3554 else 3555 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3556 CandidateSet, AllowObjCConversionOnExplicit, 3557 AllowExplicit != AllowedExplicit::None); 3558 } 3559 } 3560 } 3561 3562 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3563 3564 OverloadCandidateSet::iterator Best; 3565 switch (auto Result = 3566 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3567 case OR_Success: 3568 case OR_Deleted: 3569 // Record the standard conversion we used and the conversion function. 3570 if (CXXConstructorDecl *Constructor 3571 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3572 // C++ [over.ics.user]p1: 3573 // If the user-defined conversion is specified by a 3574 // constructor (12.3.1), the initial standard conversion 3575 // sequence converts the source type to the type required by 3576 // the argument of the constructor. 3577 // 3578 QualType ThisType = Constructor->getThisType(); 3579 if (isa<InitListExpr>(From)) { 3580 // Initializer lists don't have conversions as such. 3581 User.Before.setAsIdentityConversion(); 3582 } else { 3583 if (Best->Conversions[0].isEllipsis()) 3584 User.EllipsisConversion = true; 3585 else { 3586 User.Before = Best->Conversions[0].Standard; 3587 User.EllipsisConversion = false; 3588 } 3589 } 3590 User.HadMultipleCandidates = HadMultipleCandidates; 3591 User.ConversionFunction = Constructor; 3592 User.FoundConversionFunction = Best->FoundDecl; 3593 User.After.setAsIdentityConversion(); 3594 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3595 User.After.setAllToTypes(ToType); 3596 return Result; 3597 } 3598 if (CXXConversionDecl *Conversion 3599 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3600 // C++ [over.ics.user]p1: 3601 // 3602 // [...] If the user-defined conversion is specified by a 3603 // conversion function (12.3.2), the initial standard 3604 // conversion sequence converts the source type to the 3605 // implicit object parameter of the conversion function. 3606 User.Before = Best->Conversions[0].Standard; 3607 User.HadMultipleCandidates = HadMultipleCandidates; 3608 User.ConversionFunction = Conversion; 3609 User.FoundConversionFunction = Best->FoundDecl; 3610 User.EllipsisConversion = false; 3611 3612 // C++ [over.ics.user]p2: 3613 // The second standard conversion sequence converts the 3614 // result of the user-defined conversion to the target type 3615 // for the sequence. Since an implicit conversion sequence 3616 // is an initialization, the special rules for 3617 // initialization by user-defined conversion apply when 3618 // selecting the best user-defined conversion for a 3619 // user-defined conversion sequence (see 13.3.3 and 3620 // 13.3.3.1). 3621 User.After = Best->FinalConversion; 3622 return Result; 3623 } 3624 llvm_unreachable("Not a constructor or conversion function?"); 3625 3626 case OR_No_Viable_Function: 3627 return OR_No_Viable_Function; 3628 3629 case OR_Ambiguous: 3630 return OR_Ambiguous; 3631 } 3632 3633 llvm_unreachable("Invalid OverloadResult!"); 3634 } 3635 3636 bool 3637 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3638 ImplicitConversionSequence ICS; 3639 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3640 OverloadCandidateSet::CSK_Normal); 3641 OverloadingResult OvResult = 3642 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3643 CandidateSet, AllowedExplicit::None, false); 3644 3645 if (!(OvResult == OR_Ambiguous || 3646 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3647 return false; 3648 3649 auto Cands = CandidateSet.CompleteCandidates( 3650 *this, 3651 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3652 From); 3653 if (OvResult == OR_Ambiguous) 3654 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3655 << From->getType() << ToType << From->getSourceRange(); 3656 else { // OR_No_Viable_Function && !CandidateSet.empty() 3657 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3658 diag::err_typecheck_nonviable_condition_incomplete, 3659 From->getType(), From->getSourceRange())) 3660 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3661 << false << From->getType() << From->getSourceRange() << ToType; 3662 } 3663 3664 CandidateSet.NoteCandidates( 3665 *this, From, Cands); 3666 return true; 3667 } 3668 3669 // Helper for compareConversionFunctions that gets the FunctionType that the 3670 // conversion-operator return value 'points' to, or nullptr. 3671 static const FunctionType * 3672 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3673 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3674 const PointerType *RetPtrTy = 3675 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3676 3677 if (!RetPtrTy) 3678 return nullptr; 3679 3680 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3681 } 3682 3683 /// Compare the user-defined conversion functions or constructors 3684 /// of two user-defined conversion sequences to determine whether any ordering 3685 /// is possible. 3686 static ImplicitConversionSequence::CompareKind 3687 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3688 FunctionDecl *Function2) { 3689 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3690 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3691 if (!Conv1 || !Conv2) 3692 return ImplicitConversionSequence::Indistinguishable; 3693 3694 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3695 return ImplicitConversionSequence::Indistinguishable; 3696 3697 // Objective-C++: 3698 // If both conversion functions are implicitly-declared conversions from 3699 // a lambda closure type to a function pointer and a block pointer, 3700 // respectively, always prefer the conversion to a function pointer, 3701 // because the function pointer is more lightweight and is more likely 3702 // to keep code working. 3703 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3704 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3705 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3706 if (Block1 != Block2) 3707 return Block1 ? ImplicitConversionSequence::Worse 3708 : ImplicitConversionSequence::Better; 3709 } 3710 3711 // In order to support multiple calling conventions for the lambda conversion 3712 // operator (such as when the free and member function calling convention is 3713 // different), prefer the 'free' mechanism, followed by the calling-convention 3714 // of operator(). The latter is in place to support the MSVC-like solution of 3715 // defining ALL of the possible conversions in regards to calling-convention. 3716 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3717 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3718 3719 if (Conv1FuncRet && Conv2FuncRet && 3720 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3721 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3722 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3723 3724 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3725 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 3726 3727 CallingConv CallOpCC = 3728 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3729 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3730 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3731 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3732 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3733 3734 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3735 for (CallingConv CC : PrefOrder) { 3736 if (Conv1CC == CC) 3737 return ImplicitConversionSequence::Better; 3738 if (Conv2CC == CC) 3739 return ImplicitConversionSequence::Worse; 3740 } 3741 } 3742 3743 return ImplicitConversionSequence::Indistinguishable; 3744 } 3745 3746 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3747 const ImplicitConversionSequence &ICS) { 3748 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3749 (ICS.isUserDefined() && 3750 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3751 } 3752 3753 /// CompareImplicitConversionSequences - Compare two implicit 3754 /// conversion sequences to determine whether one is better than the 3755 /// other or if they are indistinguishable (C++ 13.3.3.2). 3756 static ImplicitConversionSequence::CompareKind 3757 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3758 const ImplicitConversionSequence& ICS1, 3759 const ImplicitConversionSequence& ICS2) 3760 { 3761 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3762 // conversion sequences (as defined in 13.3.3.1) 3763 // -- a standard conversion sequence (13.3.3.1.1) is a better 3764 // conversion sequence than a user-defined conversion sequence or 3765 // an ellipsis conversion sequence, and 3766 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3767 // conversion sequence than an ellipsis conversion sequence 3768 // (13.3.3.1.3). 3769 // 3770 // C++0x [over.best.ics]p10: 3771 // For the purpose of ranking implicit conversion sequences as 3772 // described in 13.3.3.2, the ambiguous conversion sequence is 3773 // treated as a user-defined sequence that is indistinguishable 3774 // from any other user-defined conversion sequence. 3775 3776 // String literal to 'char *' conversion has been deprecated in C++03. It has 3777 // been removed from C++11. We still accept this conversion, if it happens at 3778 // the best viable function. Otherwise, this conversion is considered worse 3779 // than ellipsis conversion. Consider this as an extension; this is not in the 3780 // standard. For example: 3781 // 3782 // int &f(...); // #1 3783 // void f(char*); // #2 3784 // void g() { int &r = f("foo"); } 3785 // 3786 // In C++03, we pick #2 as the best viable function. 3787 // In C++11, we pick #1 as the best viable function, because ellipsis 3788 // conversion is better than string-literal to char* conversion (since there 3789 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3790 // convert arguments, #2 would be the best viable function in C++11. 3791 // If the best viable function has this conversion, a warning will be issued 3792 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3793 3794 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3795 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3796 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 3797 // Ill-formedness must not differ 3798 ICS1.isBad() == ICS2.isBad()) 3799 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3800 ? ImplicitConversionSequence::Worse 3801 : ImplicitConversionSequence::Better; 3802 3803 if (ICS1.getKindRank() < ICS2.getKindRank()) 3804 return ImplicitConversionSequence::Better; 3805 if (ICS2.getKindRank() < ICS1.getKindRank()) 3806 return ImplicitConversionSequence::Worse; 3807 3808 // The following checks require both conversion sequences to be of 3809 // the same kind. 3810 if (ICS1.getKind() != ICS2.getKind()) 3811 return ImplicitConversionSequence::Indistinguishable; 3812 3813 ImplicitConversionSequence::CompareKind Result = 3814 ImplicitConversionSequence::Indistinguishable; 3815 3816 // Two implicit conversion sequences of the same form are 3817 // indistinguishable conversion sequences unless one of the 3818 // following rules apply: (C++ 13.3.3.2p3): 3819 3820 // List-initialization sequence L1 is a better conversion sequence than 3821 // list-initialization sequence L2 if: 3822 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3823 // if not that, 3824 // — L1 and L2 convert to arrays of the same element type, and either the 3825 // number of elements n_1 initialized by L1 is less than the number of 3826 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 3827 // an array of unknown bound and L1 does not, 3828 // even if one of the other rules in this paragraph would otherwise apply. 3829 if (!ICS1.isBad()) { 3830 bool StdInit1 = false, StdInit2 = false; 3831 if (ICS1.hasInitializerListContainerType()) 3832 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 3833 nullptr); 3834 if (ICS2.hasInitializerListContainerType()) 3835 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 3836 nullptr); 3837 if (StdInit1 != StdInit2) 3838 return StdInit1 ? ImplicitConversionSequence::Better 3839 : ImplicitConversionSequence::Worse; 3840 3841 if (ICS1.hasInitializerListContainerType() && 3842 ICS2.hasInitializerListContainerType()) 3843 if (auto *CAT1 = S.Context.getAsConstantArrayType( 3844 ICS1.getInitializerListContainerType())) 3845 if (auto *CAT2 = S.Context.getAsConstantArrayType( 3846 ICS2.getInitializerListContainerType())) { 3847 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 3848 CAT2->getElementType())) { 3849 // Both to arrays of the same element type 3850 if (CAT1->getSize() != CAT2->getSize()) 3851 // Different sized, the smaller wins 3852 return CAT1->getSize().ult(CAT2->getSize()) 3853 ? ImplicitConversionSequence::Better 3854 : ImplicitConversionSequence::Worse; 3855 if (ICS1.isInitializerListOfIncompleteArray() != 3856 ICS2.isInitializerListOfIncompleteArray()) 3857 // One is incomplete, it loses 3858 return ICS2.isInitializerListOfIncompleteArray() 3859 ? ImplicitConversionSequence::Better 3860 : ImplicitConversionSequence::Worse; 3861 } 3862 } 3863 } 3864 3865 if (ICS1.isStandard()) 3866 // Standard conversion sequence S1 is a better conversion sequence than 3867 // standard conversion sequence S2 if [...] 3868 Result = CompareStandardConversionSequences(S, Loc, 3869 ICS1.Standard, ICS2.Standard); 3870 else if (ICS1.isUserDefined()) { 3871 // User-defined conversion sequence U1 is a better conversion 3872 // sequence than another user-defined conversion sequence U2 if 3873 // they contain the same user-defined conversion function or 3874 // constructor and if the second standard conversion sequence of 3875 // U1 is better than the second standard conversion sequence of 3876 // U2 (C++ 13.3.3.2p3). 3877 if (ICS1.UserDefined.ConversionFunction == 3878 ICS2.UserDefined.ConversionFunction) 3879 Result = CompareStandardConversionSequences(S, Loc, 3880 ICS1.UserDefined.After, 3881 ICS2.UserDefined.After); 3882 else 3883 Result = compareConversionFunctions(S, 3884 ICS1.UserDefined.ConversionFunction, 3885 ICS2.UserDefined.ConversionFunction); 3886 } 3887 3888 return Result; 3889 } 3890 3891 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3892 // determine if one is a proper subset of the other. 3893 static ImplicitConversionSequence::CompareKind 3894 compareStandardConversionSubsets(ASTContext &Context, 3895 const StandardConversionSequence& SCS1, 3896 const StandardConversionSequence& SCS2) { 3897 ImplicitConversionSequence::CompareKind Result 3898 = ImplicitConversionSequence::Indistinguishable; 3899 3900 // the identity conversion sequence is considered to be a subsequence of 3901 // any non-identity conversion sequence 3902 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3903 return ImplicitConversionSequence::Better; 3904 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3905 return ImplicitConversionSequence::Worse; 3906 3907 if (SCS1.Second != SCS2.Second) { 3908 if (SCS1.Second == ICK_Identity) 3909 Result = ImplicitConversionSequence::Better; 3910 else if (SCS2.Second == ICK_Identity) 3911 Result = ImplicitConversionSequence::Worse; 3912 else 3913 return ImplicitConversionSequence::Indistinguishable; 3914 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3915 return ImplicitConversionSequence::Indistinguishable; 3916 3917 if (SCS1.Third == SCS2.Third) { 3918 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3919 : ImplicitConversionSequence::Indistinguishable; 3920 } 3921 3922 if (SCS1.Third == ICK_Identity) 3923 return Result == ImplicitConversionSequence::Worse 3924 ? ImplicitConversionSequence::Indistinguishable 3925 : ImplicitConversionSequence::Better; 3926 3927 if (SCS2.Third == ICK_Identity) 3928 return Result == ImplicitConversionSequence::Better 3929 ? ImplicitConversionSequence::Indistinguishable 3930 : ImplicitConversionSequence::Worse; 3931 3932 return ImplicitConversionSequence::Indistinguishable; 3933 } 3934 3935 /// Determine whether one of the given reference bindings is better 3936 /// than the other based on what kind of bindings they are. 3937 static bool 3938 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3939 const StandardConversionSequence &SCS2) { 3940 // C++0x [over.ics.rank]p3b4: 3941 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3942 // implicit object parameter of a non-static member function declared 3943 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3944 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3945 // lvalue reference to a function lvalue and S2 binds an rvalue 3946 // reference*. 3947 // 3948 // FIXME: Rvalue references. We're going rogue with the above edits, 3949 // because the semantics in the current C++0x working paper (N3225 at the 3950 // time of this writing) break the standard definition of std::forward 3951 // and std::reference_wrapper when dealing with references to functions. 3952 // Proposed wording changes submitted to CWG for consideration. 3953 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3954 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3955 return false; 3956 3957 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3958 SCS2.IsLvalueReference) || 3959 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3960 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3961 } 3962 3963 enum class FixedEnumPromotion { 3964 None, 3965 ToUnderlyingType, 3966 ToPromotedUnderlyingType 3967 }; 3968 3969 /// Returns kind of fixed enum promotion the \a SCS uses. 3970 static FixedEnumPromotion 3971 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3972 3973 if (SCS.Second != ICK_Integral_Promotion) 3974 return FixedEnumPromotion::None; 3975 3976 QualType FromType = SCS.getFromType(); 3977 if (!FromType->isEnumeralType()) 3978 return FixedEnumPromotion::None; 3979 3980 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 3981 if (!Enum->isFixed()) 3982 return FixedEnumPromotion::None; 3983 3984 QualType UnderlyingType = Enum->getIntegerType(); 3985 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3986 return FixedEnumPromotion::ToUnderlyingType; 3987 3988 return FixedEnumPromotion::ToPromotedUnderlyingType; 3989 } 3990 3991 /// CompareStandardConversionSequences - Compare two standard 3992 /// conversion sequences to determine whether one is better than the 3993 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3994 static ImplicitConversionSequence::CompareKind 3995 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3996 const StandardConversionSequence& SCS1, 3997 const StandardConversionSequence& SCS2) 3998 { 3999 // Standard conversion sequence S1 is a better conversion sequence 4000 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 4001 4002 // -- S1 is a proper subsequence of S2 (comparing the conversion 4003 // sequences in the canonical form defined by 13.3.3.1.1, 4004 // excluding any Lvalue Transformation; the identity conversion 4005 // sequence is considered to be a subsequence of any 4006 // non-identity conversion sequence) or, if not that, 4007 if (ImplicitConversionSequence::CompareKind CK 4008 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4009 return CK; 4010 4011 // -- the rank of S1 is better than the rank of S2 (by the rules 4012 // defined below), or, if not that, 4013 ImplicitConversionRank Rank1 = SCS1.getRank(); 4014 ImplicitConversionRank Rank2 = SCS2.getRank(); 4015 if (Rank1 < Rank2) 4016 return ImplicitConversionSequence::Better; 4017 else if (Rank2 < Rank1) 4018 return ImplicitConversionSequence::Worse; 4019 4020 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4021 // are indistinguishable unless one of the following rules 4022 // applies: 4023 4024 // A conversion that is not a conversion of a pointer, or 4025 // pointer to member, to bool is better than another conversion 4026 // that is such a conversion. 4027 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4028 return SCS2.isPointerConversionToBool() 4029 ? ImplicitConversionSequence::Better 4030 : ImplicitConversionSequence::Worse; 4031 4032 // C++14 [over.ics.rank]p4b2: 4033 // This is retroactively applied to C++11 by CWG 1601. 4034 // 4035 // A conversion that promotes an enumeration whose underlying type is fixed 4036 // to its underlying type is better than one that promotes to the promoted 4037 // underlying type, if the two are different. 4038 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4039 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4040 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4041 FEP1 != FEP2) 4042 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4043 ? ImplicitConversionSequence::Better 4044 : ImplicitConversionSequence::Worse; 4045 4046 // C++ [over.ics.rank]p4b2: 4047 // 4048 // If class B is derived directly or indirectly from class A, 4049 // conversion of B* to A* is better than conversion of B* to 4050 // void*, and conversion of A* to void* is better than conversion 4051 // of B* to void*. 4052 bool SCS1ConvertsToVoid 4053 = SCS1.isPointerConversionToVoidPointer(S.Context); 4054 bool SCS2ConvertsToVoid 4055 = SCS2.isPointerConversionToVoidPointer(S.Context); 4056 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4057 // Exactly one of the conversion sequences is a conversion to 4058 // a void pointer; it's the worse conversion. 4059 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4060 : ImplicitConversionSequence::Worse; 4061 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4062 // Neither conversion sequence converts to a void pointer; compare 4063 // their derived-to-base conversions. 4064 if (ImplicitConversionSequence::CompareKind DerivedCK 4065 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4066 return DerivedCK; 4067 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4068 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4069 // Both conversion sequences are conversions to void 4070 // pointers. Compare the source types to determine if there's an 4071 // inheritance relationship in their sources. 4072 QualType FromType1 = SCS1.getFromType(); 4073 QualType FromType2 = SCS2.getFromType(); 4074 4075 // Adjust the types we're converting from via the array-to-pointer 4076 // conversion, if we need to. 4077 if (SCS1.First == ICK_Array_To_Pointer) 4078 FromType1 = S.Context.getArrayDecayedType(FromType1); 4079 if (SCS2.First == ICK_Array_To_Pointer) 4080 FromType2 = S.Context.getArrayDecayedType(FromType2); 4081 4082 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4083 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4084 4085 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4086 return ImplicitConversionSequence::Better; 4087 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4088 return ImplicitConversionSequence::Worse; 4089 4090 // Objective-C++: If one interface is more specific than the 4091 // other, it is the better one. 4092 const ObjCObjectPointerType* FromObjCPtr1 4093 = FromType1->getAs<ObjCObjectPointerType>(); 4094 const ObjCObjectPointerType* FromObjCPtr2 4095 = FromType2->getAs<ObjCObjectPointerType>(); 4096 if (FromObjCPtr1 && FromObjCPtr2) { 4097 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4098 FromObjCPtr2); 4099 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4100 FromObjCPtr1); 4101 if (AssignLeft != AssignRight) { 4102 return AssignLeft? ImplicitConversionSequence::Better 4103 : ImplicitConversionSequence::Worse; 4104 } 4105 } 4106 } 4107 4108 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4109 // Check for a better reference binding based on the kind of bindings. 4110 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4111 return ImplicitConversionSequence::Better; 4112 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4113 return ImplicitConversionSequence::Worse; 4114 } 4115 4116 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4117 // bullet 3). 4118 if (ImplicitConversionSequence::CompareKind QualCK 4119 = CompareQualificationConversions(S, SCS1, SCS2)) 4120 return QualCK; 4121 4122 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4123 // C++ [over.ics.rank]p3b4: 4124 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4125 // which the references refer are the same type except for 4126 // top-level cv-qualifiers, and the type to which the reference 4127 // initialized by S2 refers is more cv-qualified than the type 4128 // to which the reference initialized by S1 refers. 4129 QualType T1 = SCS1.getToType(2); 4130 QualType T2 = SCS2.getToType(2); 4131 T1 = S.Context.getCanonicalType(T1); 4132 T2 = S.Context.getCanonicalType(T2); 4133 Qualifiers T1Quals, T2Quals; 4134 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4135 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4136 if (UnqualT1 == UnqualT2) { 4137 // Objective-C++ ARC: If the references refer to objects with different 4138 // lifetimes, prefer bindings that don't change lifetime. 4139 if (SCS1.ObjCLifetimeConversionBinding != 4140 SCS2.ObjCLifetimeConversionBinding) { 4141 return SCS1.ObjCLifetimeConversionBinding 4142 ? ImplicitConversionSequence::Worse 4143 : ImplicitConversionSequence::Better; 4144 } 4145 4146 // If the type is an array type, promote the element qualifiers to the 4147 // type for comparison. 4148 if (isa<ArrayType>(T1) && T1Quals) 4149 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4150 if (isa<ArrayType>(T2) && T2Quals) 4151 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4152 if (T2.isMoreQualifiedThan(T1)) 4153 return ImplicitConversionSequence::Better; 4154 if (T1.isMoreQualifiedThan(T2)) 4155 return ImplicitConversionSequence::Worse; 4156 } 4157 } 4158 4159 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4160 // floating-to-integral conversion if the integral conversion 4161 // is between types of the same size. 4162 // For example: 4163 // void f(float); 4164 // void f(int); 4165 // int main { 4166 // long a; 4167 // f(a); 4168 // } 4169 // Here, MSVC will call f(int) instead of generating a compile error 4170 // as clang will do in standard mode. 4171 if (S.getLangOpts().MSVCCompat && 4172 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4173 SCS1.Second == ICK_Integral_Conversion && 4174 SCS2.Second == ICK_Floating_Integral && 4175 S.Context.getTypeSize(SCS1.getFromType()) == 4176 S.Context.getTypeSize(SCS1.getToType(2))) 4177 return ImplicitConversionSequence::Better; 4178 4179 // Prefer a compatible vector conversion over a lax vector conversion 4180 // For example: 4181 // 4182 // typedef float __v4sf __attribute__((__vector_size__(16))); 4183 // void f(vector float); 4184 // void f(vector signed int); 4185 // int main() { 4186 // __v4sf a; 4187 // f(a); 4188 // } 4189 // Here, we'd like to choose f(vector float) and not 4190 // report an ambiguous call error 4191 if (SCS1.Second == ICK_Vector_Conversion && 4192 SCS2.Second == ICK_Vector_Conversion) { 4193 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4194 SCS1.getFromType(), SCS1.getToType(2)); 4195 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4196 SCS2.getFromType(), SCS2.getToType(2)); 4197 4198 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4199 return SCS1IsCompatibleVectorConversion 4200 ? ImplicitConversionSequence::Better 4201 : ImplicitConversionSequence::Worse; 4202 } 4203 4204 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4205 SCS2.Second == ICK_SVE_Vector_Conversion) { 4206 bool SCS1IsCompatibleSVEVectorConversion = 4207 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4208 bool SCS2IsCompatibleSVEVectorConversion = 4209 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4210 4211 if (SCS1IsCompatibleSVEVectorConversion != 4212 SCS2IsCompatibleSVEVectorConversion) 4213 return SCS1IsCompatibleSVEVectorConversion 4214 ? ImplicitConversionSequence::Better 4215 : ImplicitConversionSequence::Worse; 4216 } 4217 4218 return ImplicitConversionSequence::Indistinguishable; 4219 } 4220 4221 /// CompareQualificationConversions - Compares two standard conversion 4222 /// sequences to determine whether they can be ranked based on their 4223 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4224 static ImplicitConversionSequence::CompareKind 4225 CompareQualificationConversions(Sema &S, 4226 const StandardConversionSequence& SCS1, 4227 const StandardConversionSequence& SCS2) { 4228 // C++ [over.ics.rank]p3: 4229 // -- S1 and S2 differ only in their qualification conversion and 4230 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4231 // [C++98] 4232 // [...] and the cv-qualification signature of type T1 is a proper subset 4233 // of the cv-qualification signature of type T2, and S1 is not the 4234 // deprecated string literal array-to-pointer conversion (4.2). 4235 // [C++2a] 4236 // [...] where T1 can be converted to T2 by a qualification conversion. 4237 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4238 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4239 return ImplicitConversionSequence::Indistinguishable; 4240 4241 // FIXME: the example in the standard doesn't use a qualification 4242 // conversion (!) 4243 QualType T1 = SCS1.getToType(2); 4244 QualType T2 = SCS2.getToType(2); 4245 T1 = S.Context.getCanonicalType(T1); 4246 T2 = S.Context.getCanonicalType(T2); 4247 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4248 Qualifiers T1Quals, T2Quals; 4249 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4250 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4251 4252 // If the types are the same, we won't learn anything by unwrapping 4253 // them. 4254 if (UnqualT1 == UnqualT2) 4255 return ImplicitConversionSequence::Indistinguishable; 4256 4257 // Don't ever prefer a standard conversion sequence that uses the deprecated 4258 // string literal array to pointer conversion. 4259 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4260 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4261 4262 // Objective-C++ ARC: 4263 // Prefer qualification conversions not involving a change in lifetime 4264 // to qualification conversions that do change lifetime. 4265 if (SCS1.QualificationIncludesObjCLifetime && 4266 !SCS2.QualificationIncludesObjCLifetime) 4267 CanPick1 = false; 4268 if (SCS2.QualificationIncludesObjCLifetime && 4269 !SCS1.QualificationIncludesObjCLifetime) 4270 CanPick2 = false; 4271 4272 bool ObjCLifetimeConversion; 4273 if (CanPick1 && 4274 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4275 CanPick1 = false; 4276 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4277 // directions, so we can't short-cut this second check in general. 4278 if (CanPick2 && 4279 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4280 CanPick2 = false; 4281 4282 if (CanPick1 != CanPick2) 4283 return CanPick1 ? ImplicitConversionSequence::Better 4284 : ImplicitConversionSequence::Worse; 4285 return ImplicitConversionSequence::Indistinguishable; 4286 } 4287 4288 /// CompareDerivedToBaseConversions - Compares two standard conversion 4289 /// sequences to determine whether they can be ranked based on their 4290 /// various kinds of derived-to-base conversions (C++ 4291 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4292 /// conversions between Objective-C interface types. 4293 static ImplicitConversionSequence::CompareKind 4294 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4295 const StandardConversionSequence& SCS1, 4296 const StandardConversionSequence& SCS2) { 4297 QualType FromType1 = SCS1.getFromType(); 4298 QualType ToType1 = SCS1.getToType(1); 4299 QualType FromType2 = SCS2.getFromType(); 4300 QualType ToType2 = SCS2.getToType(1); 4301 4302 // Adjust the types we're converting from via the array-to-pointer 4303 // conversion, if we need to. 4304 if (SCS1.First == ICK_Array_To_Pointer) 4305 FromType1 = S.Context.getArrayDecayedType(FromType1); 4306 if (SCS2.First == ICK_Array_To_Pointer) 4307 FromType2 = S.Context.getArrayDecayedType(FromType2); 4308 4309 // Canonicalize all of the types. 4310 FromType1 = S.Context.getCanonicalType(FromType1); 4311 ToType1 = S.Context.getCanonicalType(ToType1); 4312 FromType2 = S.Context.getCanonicalType(FromType2); 4313 ToType2 = S.Context.getCanonicalType(ToType2); 4314 4315 // C++ [over.ics.rank]p4b3: 4316 // 4317 // If class B is derived directly or indirectly from class A and 4318 // class C is derived directly or indirectly from B, 4319 // 4320 // Compare based on pointer conversions. 4321 if (SCS1.Second == ICK_Pointer_Conversion && 4322 SCS2.Second == ICK_Pointer_Conversion && 4323 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4324 FromType1->isPointerType() && FromType2->isPointerType() && 4325 ToType1->isPointerType() && ToType2->isPointerType()) { 4326 QualType FromPointee1 = 4327 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4328 QualType ToPointee1 = 4329 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4330 QualType FromPointee2 = 4331 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4332 QualType ToPointee2 = 4333 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4334 4335 // -- conversion of C* to B* is better than conversion of C* to A*, 4336 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4337 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4338 return ImplicitConversionSequence::Better; 4339 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4340 return ImplicitConversionSequence::Worse; 4341 } 4342 4343 // -- conversion of B* to A* is better than conversion of C* to A*, 4344 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4345 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4346 return ImplicitConversionSequence::Better; 4347 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4348 return ImplicitConversionSequence::Worse; 4349 } 4350 } else if (SCS1.Second == ICK_Pointer_Conversion && 4351 SCS2.Second == ICK_Pointer_Conversion) { 4352 const ObjCObjectPointerType *FromPtr1 4353 = FromType1->getAs<ObjCObjectPointerType>(); 4354 const ObjCObjectPointerType *FromPtr2 4355 = FromType2->getAs<ObjCObjectPointerType>(); 4356 const ObjCObjectPointerType *ToPtr1 4357 = ToType1->getAs<ObjCObjectPointerType>(); 4358 const ObjCObjectPointerType *ToPtr2 4359 = ToType2->getAs<ObjCObjectPointerType>(); 4360 4361 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4362 // Apply the same conversion ranking rules for Objective-C pointer types 4363 // that we do for C++ pointers to class types. However, we employ the 4364 // Objective-C pseudo-subtyping relationship used for assignment of 4365 // Objective-C pointer types. 4366 bool FromAssignLeft 4367 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4368 bool FromAssignRight 4369 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4370 bool ToAssignLeft 4371 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4372 bool ToAssignRight 4373 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4374 4375 // A conversion to an a non-id object pointer type or qualified 'id' 4376 // type is better than a conversion to 'id'. 4377 if (ToPtr1->isObjCIdType() && 4378 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4379 return ImplicitConversionSequence::Worse; 4380 if (ToPtr2->isObjCIdType() && 4381 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4382 return ImplicitConversionSequence::Better; 4383 4384 // A conversion to a non-id object pointer type is better than a 4385 // conversion to a qualified 'id' type 4386 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4387 return ImplicitConversionSequence::Worse; 4388 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4389 return ImplicitConversionSequence::Better; 4390 4391 // A conversion to an a non-Class object pointer type or qualified 'Class' 4392 // type is better than a conversion to 'Class'. 4393 if (ToPtr1->isObjCClassType() && 4394 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4395 return ImplicitConversionSequence::Worse; 4396 if (ToPtr2->isObjCClassType() && 4397 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4398 return ImplicitConversionSequence::Better; 4399 4400 // A conversion to a non-Class object pointer type is better than a 4401 // conversion to a qualified 'Class' type. 4402 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4403 return ImplicitConversionSequence::Worse; 4404 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4405 return ImplicitConversionSequence::Better; 4406 4407 // -- "conversion of C* to B* is better than conversion of C* to A*," 4408 if (S.Context.hasSameType(FromType1, FromType2) && 4409 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4410 (ToAssignLeft != ToAssignRight)) { 4411 if (FromPtr1->isSpecialized()) { 4412 // "conversion of B<A> * to B * is better than conversion of B * to 4413 // C *. 4414 bool IsFirstSame = 4415 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4416 bool IsSecondSame = 4417 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4418 if (IsFirstSame) { 4419 if (!IsSecondSame) 4420 return ImplicitConversionSequence::Better; 4421 } else if (IsSecondSame) 4422 return ImplicitConversionSequence::Worse; 4423 } 4424 return ToAssignLeft? ImplicitConversionSequence::Worse 4425 : ImplicitConversionSequence::Better; 4426 } 4427 4428 // -- "conversion of B* to A* is better than conversion of C* to A*," 4429 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4430 (FromAssignLeft != FromAssignRight)) 4431 return FromAssignLeft? ImplicitConversionSequence::Better 4432 : ImplicitConversionSequence::Worse; 4433 } 4434 } 4435 4436 // Ranking of member-pointer types. 4437 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4438 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4439 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4440 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4441 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4442 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4443 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4444 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4445 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4446 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4447 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4448 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4449 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4450 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4451 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4452 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4453 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4454 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4455 return ImplicitConversionSequence::Worse; 4456 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4457 return ImplicitConversionSequence::Better; 4458 } 4459 // conversion of B::* to C::* is better than conversion of A::* to C::* 4460 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4461 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4462 return ImplicitConversionSequence::Better; 4463 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4464 return ImplicitConversionSequence::Worse; 4465 } 4466 } 4467 4468 if (SCS1.Second == ICK_Derived_To_Base) { 4469 // -- conversion of C to B is better than conversion of C to A, 4470 // -- binding of an expression of type C to a reference of type 4471 // B& is better than binding an expression of type C to a 4472 // reference of type A&, 4473 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4474 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4475 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4476 return ImplicitConversionSequence::Better; 4477 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4478 return ImplicitConversionSequence::Worse; 4479 } 4480 4481 // -- conversion of B to A is better than conversion of C to A. 4482 // -- binding of an expression of type B to a reference of type 4483 // A& is better than binding an expression of type C to a 4484 // reference of type A&, 4485 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4486 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4487 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4488 return ImplicitConversionSequence::Better; 4489 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4490 return ImplicitConversionSequence::Worse; 4491 } 4492 } 4493 4494 return ImplicitConversionSequence::Indistinguishable; 4495 } 4496 4497 /// Determine whether the given type is valid, e.g., it is not an invalid 4498 /// C++ class. 4499 static bool isTypeValid(QualType T) { 4500 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4501 return !Record->isInvalidDecl(); 4502 4503 return true; 4504 } 4505 4506 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4507 if (!T.getQualifiers().hasUnaligned()) 4508 return T; 4509 4510 Qualifiers Q; 4511 T = Ctx.getUnqualifiedArrayType(T, Q); 4512 Q.removeUnaligned(); 4513 return Ctx.getQualifiedType(T, Q); 4514 } 4515 4516 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4517 /// determine whether they are reference-compatible, 4518 /// reference-related, or incompatible, for use in C++ initialization by 4519 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4520 /// type, and the first type (T1) is the pointee type of the reference 4521 /// type being initialized. 4522 Sema::ReferenceCompareResult 4523 Sema::CompareReferenceRelationship(SourceLocation Loc, 4524 QualType OrigT1, QualType OrigT2, 4525 ReferenceConversions *ConvOut) { 4526 assert(!OrigT1->isReferenceType() && 4527 "T1 must be the pointee type of the reference type"); 4528 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4529 4530 QualType T1 = Context.getCanonicalType(OrigT1); 4531 QualType T2 = Context.getCanonicalType(OrigT2); 4532 Qualifiers T1Quals, T2Quals; 4533 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4534 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4535 4536 ReferenceConversions ConvTmp; 4537 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4538 Conv = ReferenceConversions(); 4539 4540 // C++2a [dcl.init.ref]p4: 4541 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4542 // reference-related to "cv2 T2" if T1 is similar to T2, or 4543 // T1 is a base class of T2. 4544 // "cv1 T1" is reference-compatible with "cv2 T2" if 4545 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4546 // "pointer to cv1 T1" via a standard conversion sequence. 4547 4548 // Check for standard conversions we can apply to pointers: derived-to-base 4549 // conversions, ObjC pointer conversions, and function pointer conversions. 4550 // (Qualification conversions are checked last.) 4551 QualType ConvertedT2; 4552 if (UnqualT1 == UnqualT2) { 4553 // Nothing to do. 4554 } else if (isCompleteType(Loc, OrigT2) && 4555 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4556 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4557 Conv |= ReferenceConversions::DerivedToBase; 4558 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4559 UnqualT2->isObjCObjectOrInterfaceType() && 4560 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4561 Conv |= ReferenceConversions::ObjC; 4562 else if (UnqualT2->isFunctionType() && 4563 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4564 Conv |= ReferenceConversions::Function; 4565 // No need to check qualifiers; function types don't have them. 4566 return Ref_Compatible; 4567 } 4568 bool ConvertedReferent = Conv != 0; 4569 4570 // We can have a qualification conversion. Compute whether the types are 4571 // similar at the same time. 4572 bool PreviousToQualsIncludeConst = true; 4573 bool TopLevel = true; 4574 do { 4575 if (T1 == T2) 4576 break; 4577 4578 // We will need a qualification conversion. 4579 Conv |= ReferenceConversions::Qualification; 4580 4581 // Track whether we performed a qualification conversion anywhere other 4582 // than the top level. This matters for ranking reference bindings in 4583 // overload resolution. 4584 if (!TopLevel) 4585 Conv |= ReferenceConversions::NestedQualification; 4586 4587 // MS compiler ignores __unaligned qualifier for references; do the same. 4588 T1 = withoutUnaligned(Context, T1); 4589 T2 = withoutUnaligned(Context, T2); 4590 4591 // If we find a qualifier mismatch, the types are not reference-compatible, 4592 // but are still be reference-related if they're similar. 4593 bool ObjCLifetimeConversion = false; 4594 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4595 PreviousToQualsIncludeConst, 4596 ObjCLifetimeConversion)) 4597 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4598 ? Ref_Related 4599 : Ref_Incompatible; 4600 4601 // FIXME: Should we track this for any level other than the first? 4602 if (ObjCLifetimeConversion) 4603 Conv |= ReferenceConversions::ObjCLifetime; 4604 4605 TopLevel = false; 4606 } while (Context.UnwrapSimilarTypes(T1, T2)); 4607 4608 // At this point, if the types are reference-related, we must either have the 4609 // same inner type (ignoring qualifiers), or must have already worked out how 4610 // to convert the referent. 4611 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4612 ? Ref_Compatible 4613 : Ref_Incompatible; 4614 } 4615 4616 /// Look for a user-defined conversion to a value reference-compatible 4617 /// with DeclType. Return true if something definite is found. 4618 static bool 4619 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4620 QualType DeclType, SourceLocation DeclLoc, 4621 Expr *Init, QualType T2, bool AllowRvalues, 4622 bool AllowExplicit) { 4623 assert(T2->isRecordType() && "Can only find conversions of record types."); 4624 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4625 4626 OverloadCandidateSet CandidateSet( 4627 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4628 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4629 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4630 NamedDecl *D = *I; 4631 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4632 if (isa<UsingShadowDecl>(D)) 4633 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4634 4635 FunctionTemplateDecl *ConvTemplate 4636 = dyn_cast<FunctionTemplateDecl>(D); 4637 CXXConversionDecl *Conv; 4638 if (ConvTemplate) 4639 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4640 else 4641 Conv = cast<CXXConversionDecl>(D); 4642 4643 if (AllowRvalues) { 4644 // If we are initializing an rvalue reference, don't permit conversion 4645 // functions that return lvalues. 4646 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4647 const ReferenceType *RefType 4648 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4649 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4650 continue; 4651 } 4652 4653 if (!ConvTemplate && 4654 S.CompareReferenceRelationship( 4655 DeclLoc, 4656 Conv->getConversionType() 4657 .getNonReferenceType() 4658 .getUnqualifiedType(), 4659 DeclType.getNonReferenceType().getUnqualifiedType()) == 4660 Sema::Ref_Incompatible) 4661 continue; 4662 } else { 4663 // If the conversion function doesn't return a reference type, 4664 // it can't be considered for this conversion. An rvalue reference 4665 // is only acceptable if its referencee is a function type. 4666 4667 const ReferenceType *RefType = 4668 Conv->getConversionType()->getAs<ReferenceType>(); 4669 if (!RefType || 4670 (!RefType->isLValueReferenceType() && 4671 !RefType->getPointeeType()->isFunctionType())) 4672 continue; 4673 } 4674 4675 if (ConvTemplate) 4676 S.AddTemplateConversionCandidate( 4677 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4678 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4679 else 4680 S.AddConversionCandidate( 4681 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4682 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4683 } 4684 4685 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4686 4687 OverloadCandidateSet::iterator Best; 4688 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4689 case OR_Success: 4690 // C++ [over.ics.ref]p1: 4691 // 4692 // [...] If the parameter binds directly to the result of 4693 // applying a conversion function to the argument 4694 // expression, the implicit conversion sequence is a 4695 // user-defined conversion sequence (13.3.3.1.2), with the 4696 // second standard conversion sequence either an identity 4697 // conversion or, if the conversion function returns an 4698 // entity of a type that is a derived class of the parameter 4699 // type, a derived-to-base Conversion. 4700 if (!Best->FinalConversion.DirectBinding) 4701 return false; 4702 4703 ICS.setUserDefined(); 4704 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4705 ICS.UserDefined.After = Best->FinalConversion; 4706 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4707 ICS.UserDefined.ConversionFunction = Best->Function; 4708 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4709 ICS.UserDefined.EllipsisConversion = false; 4710 assert(ICS.UserDefined.After.ReferenceBinding && 4711 ICS.UserDefined.After.DirectBinding && 4712 "Expected a direct reference binding!"); 4713 return true; 4714 4715 case OR_Ambiguous: 4716 ICS.setAmbiguous(); 4717 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4718 Cand != CandidateSet.end(); ++Cand) 4719 if (Cand->Best) 4720 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4721 return true; 4722 4723 case OR_No_Viable_Function: 4724 case OR_Deleted: 4725 // There was no suitable conversion, or we found a deleted 4726 // conversion; continue with other checks. 4727 return false; 4728 } 4729 4730 llvm_unreachable("Invalid OverloadResult!"); 4731 } 4732 4733 /// Compute an implicit conversion sequence for reference 4734 /// initialization. 4735 static ImplicitConversionSequence 4736 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4737 SourceLocation DeclLoc, 4738 bool SuppressUserConversions, 4739 bool AllowExplicit) { 4740 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4741 4742 // Most paths end in a failed conversion. 4743 ImplicitConversionSequence ICS; 4744 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4745 4746 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4747 QualType T2 = Init->getType(); 4748 4749 // If the initializer is the address of an overloaded function, try 4750 // to resolve the overloaded function. If all goes well, T2 is the 4751 // type of the resulting function. 4752 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4753 DeclAccessPair Found; 4754 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4755 false, Found)) 4756 T2 = Fn->getType(); 4757 } 4758 4759 // Compute some basic properties of the types and the initializer. 4760 bool isRValRef = DeclType->isRValueReferenceType(); 4761 Expr::Classification InitCategory = Init->Classify(S.Context); 4762 4763 Sema::ReferenceConversions RefConv; 4764 Sema::ReferenceCompareResult RefRelationship = 4765 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4766 4767 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4768 ICS.setStandard(); 4769 ICS.Standard.First = ICK_Identity; 4770 // FIXME: A reference binding can be a function conversion too. We should 4771 // consider that when ordering reference-to-function bindings. 4772 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4773 ? ICK_Derived_To_Base 4774 : (RefConv & Sema::ReferenceConversions::ObjC) 4775 ? ICK_Compatible_Conversion 4776 : ICK_Identity; 4777 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4778 // a reference binding that performs a non-top-level qualification 4779 // conversion as a qualification conversion, not as an identity conversion. 4780 ICS.Standard.Third = (RefConv & 4781 Sema::ReferenceConversions::NestedQualification) 4782 ? ICK_Qualification 4783 : ICK_Identity; 4784 ICS.Standard.setFromType(T2); 4785 ICS.Standard.setToType(0, T2); 4786 ICS.Standard.setToType(1, T1); 4787 ICS.Standard.setToType(2, T1); 4788 ICS.Standard.ReferenceBinding = true; 4789 ICS.Standard.DirectBinding = BindsDirectly; 4790 ICS.Standard.IsLvalueReference = !isRValRef; 4791 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4792 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4793 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4794 ICS.Standard.ObjCLifetimeConversionBinding = 4795 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4796 ICS.Standard.CopyConstructor = nullptr; 4797 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4798 }; 4799 4800 // C++0x [dcl.init.ref]p5: 4801 // A reference to type "cv1 T1" is initialized by an expression 4802 // of type "cv2 T2" as follows: 4803 4804 // -- If reference is an lvalue reference and the initializer expression 4805 if (!isRValRef) { 4806 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4807 // reference-compatible with "cv2 T2," or 4808 // 4809 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4810 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4811 // C++ [over.ics.ref]p1: 4812 // When a parameter of reference type binds directly (8.5.3) 4813 // to an argument expression, the implicit conversion sequence 4814 // is the identity conversion, unless the argument expression 4815 // has a type that is a derived class of the parameter type, 4816 // in which case the implicit conversion sequence is a 4817 // derived-to-base Conversion (13.3.3.1). 4818 SetAsReferenceBinding(/*BindsDirectly=*/true); 4819 4820 // Nothing more to do: the inaccessibility/ambiguity check for 4821 // derived-to-base conversions is suppressed when we're 4822 // computing the implicit conversion sequence (C++ 4823 // [over.best.ics]p2). 4824 return ICS; 4825 } 4826 4827 // -- has a class type (i.e., T2 is a class type), where T1 is 4828 // not reference-related to T2, and can be implicitly 4829 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4830 // is reference-compatible with "cv3 T3" 92) (this 4831 // conversion is selected by enumerating the applicable 4832 // conversion functions (13.3.1.6) and choosing the best 4833 // one through overload resolution (13.3)), 4834 if (!SuppressUserConversions && T2->isRecordType() && 4835 S.isCompleteType(DeclLoc, T2) && 4836 RefRelationship == Sema::Ref_Incompatible) { 4837 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4838 Init, T2, /*AllowRvalues=*/false, 4839 AllowExplicit)) 4840 return ICS; 4841 } 4842 } 4843 4844 // -- Otherwise, the reference shall be an lvalue reference to a 4845 // non-volatile const type (i.e., cv1 shall be const), or the reference 4846 // shall be an rvalue reference. 4847 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4848 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4849 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4850 return ICS; 4851 } 4852 4853 // -- If the initializer expression 4854 // 4855 // -- is an xvalue, class prvalue, array prvalue or function 4856 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4857 if (RefRelationship == Sema::Ref_Compatible && 4858 (InitCategory.isXValue() || 4859 (InitCategory.isPRValue() && 4860 (T2->isRecordType() || T2->isArrayType())) || 4861 (InitCategory.isLValue() && T2->isFunctionType()))) { 4862 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4863 // binding unless we're binding to a class prvalue. 4864 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4865 // allow the use of rvalue references in C++98/03 for the benefit of 4866 // standard library implementors; therefore, we need the xvalue check here. 4867 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4868 !(InitCategory.isPRValue() || T2->isRecordType())); 4869 return ICS; 4870 } 4871 4872 // -- has a class type (i.e., T2 is a class type), where T1 is not 4873 // reference-related to T2, and can be implicitly converted to 4874 // an xvalue, class prvalue, or function lvalue of type 4875 // "cv3 T3", where "cv1 T1" is reference-compatible with 4876 // "cv3 T3", 4877 // 4878 // then the reference is bound to the value of the initializer 4879 // expression in the first case and to the result of the conversion 4880 // in the second case (or, in either case, to an appropriate base 4881 // class subobject). 4882 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4883 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4884 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4885 Init, T2, /*AllowRvalues=*/true, 4886 AllowExplicit)) { 4887 // In the second case, if the reference is an rvalue reference 4888 // and the second standard conversion sequence of the 4889 // user-defined conversion sequence includes an lvalue-to-rvalue 4890 // conversion, the program is ill-formed. 4891 if (ICS.isUserDefined() && isRValRef && 4892 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4893 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4894 4895 return ICS; 4896 } 4897 4898 // A temporary of function type cannot be created; don't even try. 4899 if (T1->isFunctionType()) 4900 return ICS; 4901 4902 // -- Otherwise, a temporary of type "cv1 T1" is created and 4903 // initialized from the initializer expression using the 4904 // rules for a non-reference copy initialization (8.5). The 4905 // reference is then bound to the temporary. If T1 is 4906 // reference-related to T2, cv1 must be the same 4907 // cv-qualification as, or greater cv-qualification than, 4908 // cv2; otherwise, the program is ill-formed. 4909 if (RefRelationship == Sema::Ref_Related) { 4910 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4911 // we would be reference-compatible or reference-compatible with 4912 // added qualification. But that wasn't the case, so the reference 4913 // initialization fails. 4914 // 4915 // Note that we only want to check address spaces and cvr-qualifiers here. 4916 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4917 Qualifiers T1Quals = T1.getQualifiers(); 4918 Qualifiers T2Quals = T2.getQualifiers(); 4919 T1Quals.removeObjCGCAttr(); 4920 T1Quals.removeObjCLifetime(); 4921 T2Quals.removeObjCGCAttr(); 4922 T2Quals.removeObjCLifetime(); 4923 // MS compiler ignores __unaligned qualifier for references; do the same. 4924 T1Quals.removeUnaligned(); 4925 T2Quals.removeUnaligned(); 4926 if (!T1Quals.compatiblyIncludes(T2Quals)) 4927 return ICS; 4928 } 4929 4930 // If at least one of the types is a class type, the types are not 4931 // related, and we aren't allowed any user conversions, the 4932 // reference binding fails. This case is important for breaking 4933 // recursion, since TryImplicitConversion below will attempt to 4934 // create a temporary through the use of a copy constructor. 4935 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4936 (T1->isRecordType() || T2->isRecordType())) 4937 return ICS; 4938 4939 // If T1 is reference-related to T2 and the reference is an rvalue 4940 // reference, the initializer expression shall not be an lvalue. 4941 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4942 Init->Classify(S.Context).isLValue()) { 4943 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4944 return ICS; 4945 } 4946 4947 // C++ [over.ics.ref]p2: 4948 // When a parameter of reference type is not bound directly to 4949 // an argument expression, the conversion sequence is the one 4950 // required to convert the argument expression to the 4951 // underlying type of the reference according to 4952 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4953 // to copy-initializing a temporary of the underlying type with 4954 // the argument expression. Any difference in top-level 4955 // cv-qualification is subsumed by the initialization itself 4956 // and does not constitute a conversion. 4957 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4958 AllowedExplicit::None, 4959 /*InOverloadResolution=*/false, 4960 /*CStyle=*/false, 4961 /*AllowObjCWritebackConversion=*/false, 4962 /*AllowObjCConversionOnExplicit=*/false); 4963 4964 // Of course, that's still a reference binding. 4965 if (ICS.isStandard()) { 4966 ICS.Standard.ReferenceBinding = true; 4967 ICS.Standard.IsLvalueReference = !isRValRef; 4968 ICS.Standard.BindsToFunctionLvalue = false; 4969 ICS.Standard.BindsToRvalue = true; 4970 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4971 ICS.Standard.ObjCLifetimeConversionBinding = false; 4972 } else if (ICS.isUserDefined()) { 4973 const ReferenceType *LValRefType = 4974 ICS.UserDefined.ConversionFunction->getReturnType() 4975 ->getAs<LValueReferenceType>(); 4976 4977 // C++ [over.ics.ref]p3: 4978 // Except for an implicit object parameter, for which see 13.3.1, a 4979 // standard conversion sequence cannot be formed if it requires [...] 4980 // binding an rvalue reference to an lvalue other than a function 4981 // lvalue. 4982 // Note that the function case is not possible here. 4983 if (isRValRef && LValRefType) { 4984 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4985 return ICS; 4986 } 4987 4988 ICS.UserDefined.After.ReferenceBinding = true; 4989 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4990 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4991 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4992 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4993 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4994 } 4995 4996 return ICS; 4997 } 4998 4999 static ImplicitConversionSequence 5000 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5001 bool SuppressUserConversions, 5002 bool InOverloadResolution, 5003 bool AllowObjCWritebackConversion, 5004 bool AllowExplicit = false); 5005 5006 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5007 /// initializer list From. 5008 static ImplicitConversionSequence 5009 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5010 bool SuppressUserConversions, 5011 bool InOverloadResolution, 5012 bool AllowObjCWritebackConversion) { 5013 // C++11 [over.ics.list]p1: 5014 // When an argument is an initializer list, it is not an expression and 5015 // special rules apply for converting it to a parameter type. 5016 5017 ImplicitConversionSequence Result; 5018 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5019 5020 // We need a complete type for what follows. With one C++20 exception, 5021 // incomplete types can never be initialized from init lists. 5022 QualType InitTy = ToType; 5023 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5024 if (AT && S.getLangOpts().CPlusPlus20) 5025 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5026 // C++20 allows list initialization of an incomplete array type. 5027 InitTy = IAT->getElementType(); 5028 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5029 return Result; 5030 5031 // Per DR1467: 5032 // If the parameter type is a class X and the initializer list has a single 5033 // element of type cv U, where U is X or a class derived from X, the 5034 // implicit conversion sequence is the one required to convert the element 5035 // to the parameter type. 5036 // 5037 // Otherwise, if the parameter type is a character array [... ] 5038 // and the initializer list has a single element that is an 5039 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5040 // implicit conversion sequence is the identity conversion. 5041 if (From->getNumInits() == 1) { 5042 if (ToType->isRecordType()) { 5043 QualType InitType = From->getInit(0)->getType(); 5044 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5045 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5046 return TryCopyInitialization(S, From->getInit(0), ToType, 5047 SuppressUserConversions, 5048 InOverloadResolution, 5049 AllowObjCWritebackConversion); 5050 } 5051 5052 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5053 InitializedEntity Entity = 5054 InitializedEntity::InitializeParameter(S.Context, ToType, 5055 /*Consumed=*/false); 5056 if (S.CanPerformCopyInitialization(Entity, From)) { 5057 Result.setStandard(); 5058 Result.Standard.setAsIdentityConversion(); 5059 Result.Standard.setFromType(ToType); 5060 Result.Standard.setAllToTypes(ToType); 5061 return Result; 5062 } 5063 } 5064 } 5065 5066 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5067 // C++11 [over.ics.list]p2: 5068 // If the parameter type is std::initializer_list<X> or "array of X" and 5069 // all the elements can be implicitly converted to X, the implicit 5070 // conversion sequence is the worst conversion necessary to convert an 5071 // element of the list to X. 5072 // 5073 // C++14 [over.ics.list]p3: 5074 // Otherwise, if the parameter type is "array of N X", if the initializer 5075 // list has exactly N elements or if it has fewer than N elements and X is 5076 // default-constructible, and if all the elements of the initializer list 5077 // can be implicitly converted to X, the implicit conversion sequence is 5078 // the worst conversion necessary to convert an element of the list to X. 5079 if (AT || S.isStdInitializerList(ToType, &InitTy)) { 5080 unsigned e = From->getNumInits(); 5081 ImplicitConversionSequence DfltElt; 5082 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5083 QualType()); 5084 QualType ContTy = ToType; 5085 bool IsUnbounded = false; 5086 if (AT) { 5087 InitTy = AT->getElementType(); 5088 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5089 if (CT->getSize().ult(e)) { 5090 // Too many inits, fatally bad 5091 Result.setBad(BadConversionSequence::too_many_initializers, From, 5092 ToType); 5093 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5094 return Result; 5095 } 5096 if (CT->getSize().ugt(e)) { 5097 // Need an init from empty {}, is there one? 5098 InitListExpr EmptyList(S.Context, From->getEndLoc(), None, 5099 From->getEndLoc()); 5100 EmptyList.setType(S.Context.VoidTy); 5101 DfltElt = TryListConversion( 5102 S, &EmptyList, InitTy, SuppressUserConversions, 5103 InOverloadResolution, AllowObjCWritebackConversion); 5104 if (DfltElt.isBad()) { 5105 // No {} init, fatally bad 5106 Result.setBad(BadConversionSequence::too_few_initializers, From, 5107 ToType); 5108 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5109 return Result; 5110 } 5111 } 5112 } else { 5113 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5114 IsUnbounded = true; 5115 if (!e) { 5116 // Cannot convert to zero-sized. 5117 Result.setBad(BadConversionSequence::too_few_initializers, From, 5118 ToType); 5119 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5120 return Result; 5121 } 5122 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5123 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5124 ArrayType::Normal, 0); 5125 } 5126 } 5127 5128 Result.setStandard(); 5129 Result.Standard.setAsIdentityConversion(); 5130 Result.Standard.setFromType(InitTy); 5131 Result.Standard.setAllToTypes(InitTy); 5132 for (unsigned i = 0; i < e; ++i) { 5133 Expr *Init = From->getInit(i); 5134 ImplicitConversionSequence ICS = TryCopyInitialization( 5135 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5136 AllowObjCWritebackConversion); 5137 5138 // Keep the worse conversion seen so far. 5139 // FIXME: Sequences are not totally ordered, so 'worse' can be 5140 // ambiguous. CWG has been informed. 5141 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5142 Result) == 5143 ImplicitConversionSequence::Worse) { 5144 Result = ICS; 5145 // Bail as soon as we find something unconvertible. 5146 if (Result.isBad()) { 5147 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5148 return Result; 5149 } 5150 } 5151 } 5152 5153 // If we needed any implicit {} initialization, compare that now. 5154 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5155 // has been informed that this might not be the best thing. 5156 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5157 S, From->getEndLoc(), DfltElt, Result) == 5158 ImplicitConversionSequence::Worse) 5159 Result = DfltElt; 5160 // Record the type being initialized so that we may compare sequences 5161 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5162 return Result; 5163 } 5164 5165 // C++14 [over.ics.list]p4: 5166 // C++11 [over.ics.list]p3: 5167 // Otherwise, if the parameter is a non-aggregate class X and overload 5168 // resolution chooses a single best constructor [...] the implicit 5169 // conversion sequence is a user-defined conversion sequence. If multiple 5170 // constructors are viable but none is better than the others, the 5171 // implicit conversion sequence is a user-defined conversion sequence. 5172 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5173 // This function can deal with initializer lists. 5174 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5175 AllowedExplicit::None, 5176 InOverloadResolution, /*CStyle=*/false, 5177 AllowObjCWritebackConversion, 5178 /*AllowObjCConversionOnExplicit=*/false); 5179 } 5180 5181 // C++14 [over.ics.list]p5: 5182 // C++11 [over.ics.list]p4: 5183 // Otherwise, if the parameter has an aggregate type which can be 5184 // initialized from the initializer list [...] the implicit conversion 5185 // sequence is a user-defined conversion sequence. 5186 if (ToType->isAggregateType()) { 5187 // Type is an aggregate, argument is an init list. At this point it comes 5188 // down to checking whether the initialization works. 5189 // FIXME: Find out whether this parameter is consumed or not. 5190 InitializedEntity Entity = 5191 InitializedEntity::InitializeParameter(S.Context, ToType, 5192 /*Consumed=*/false); 5193 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5194 From)) { 5195 Result.setUserDefined(); 5196 Result.UserDefined.Before.setAsIdentityConversion(); 5197 // Initializer lists don't have a type. 5198 Result.UserDefined.Before.setFromType(QualType()); 5199 Result.UserDefined.Before.setAllToTypes(QualType()); 5200 5201 Result.UserDefined.After.setAsIdentityConversion(); 5202 Result.UserDefined.After.setFromType(ToType); 5203 Result.UserDefined.After.setAllToTypes(ToType); 5204 Result.UserDefined.ConversionFunction = nullptr; 5205 } 5206 return Result; 5207 } 5208 5209 // C++14 [over.ics.list]p6: 5210 // C++11 [over.ics.list]p5: 5211 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5212 if (ToType->isReferenceType()) { 5213 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5214 // mention initializer lists in any way. So we go by what list- 5215 // initialization would do and try to extrapolate from that. 5216 5217 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5218 5219 // If the initializer list has a single element that is reference-related 5220 // to the parameter type, we initialize the reference from that. 5221 if (From->getNumInits() == 1) { 5222 Expr *Init = From->getInit(0); 5223 5224 QualType T2 = Init->getType(); 5225 5226 // If the initializer is the address of an overloaded function, try 5227 // to resolve the overloaded function. If all goes well, T2 is the 5228 // type of the resulting function. 5229 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5230 DeclAccessPair Found; 5231 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5232 Init, ToType, false, Found)) 5233 T2 = Fn->getType(); 5234 } 5235 5236 // Compute some basic properties of the types and the initializer. 5237 Sema::ReferenceCompareResult RefRelationship = 5238 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5239 5240 if (RefRelationship >= Sema::Ref_Related) { 5241 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5242 SuppressUserConversions, 5243 /*AllowExplicit=*/false); 5244 } 5245 } 5246 5247 // Otherwise, we bind the reference to a temporary created from the 5248 // initializer list. 5249 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5250 InOverloadResolution, 5251 AllowObjCWritebackConversion); 5252 if (Result.isFailure()) 5253 return Result; 5254 assert(!Result.isEllipsis() && 5255 "Sub-initialization cannot result in ellipsis conversion."); 5256 5257 // Can we even bind to a temporary? 5258 if (ToType->isRValueReferenceType() || 5259 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5260 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5261 Result.UserDefined.After; 5262 SCS.ReferenceBinding = true; 5263 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5264 SCS.BindsToRvalue = true; 5265 SCS.BindsToFunctionLvalue = false; 5266 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5267 SCS.ObjCLifetimeConversionBinding = false; 5268 } else 5269 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5270 From, ToType); 5271 return Result; 5272 } 5273 5274 // C++14 [over.ics.list]p7: 5275 // C++11 [over.ics.list]p6: 5276 // Otherwise, if the parameter type is not a class: 5277 if (!ToType->isRecordType()) { 5278 // - if the initializer list has one element that is not itself an 5279 // initializer list, the implicit conversion sequence is the one 5280 // required to convert the element to the parameter type. 5281 unsigned NumInits = From->getNumInits(); 5282 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5283 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5284 SuppressUserConversions, 5285 InOverloadResolution, 5286 AllowObjCWritebackConversion); 5287 // - if the initializer list has no elements, the implicit conversion 5288 // sequence is the identity conversion. 5289 else if (NumInits == 0) { 5290 Result.setStandard(); 5291 Result.Standard.setAsIdentityConversion(); 5292 Result.Standard.setFromType(ToType); 5293 Result.Standard.setAllToTypes(ToType); 5294 } 5295 return Result; 5296 } 5297 5298 // C++14 [over.ics.list]p8: 5299 // C++11 [over.ics.list]p7: 5300 // In all cases other than those enumerated above, no conversion is possible 5301 return Result; 5302 } 5303 5304 /// TryCopyInitialization - Try to copy-initialize a value of type 5305 /// ToType from the expression From. Return the implicit conversion 5306 /// sequence required to pass this argument, which may be a bad 5307 /// conversion sequence (meaning that the argument cannot be passed to 5308 /// a parameter of this type). If @p SuppressUserConversions, then we 5309 /// do not permit any user-defined conversion sequences. 5310 static ImplicitConversionSequence 5311 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5312 bool SuppressUserConversions, 5313 bool InOverloadResolution, 5314 bool AllowObjCWritebackConversion, 5315 bool AllowExplicit) { 5316 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5317 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5318 InOverloadResolution,AllowObjCWritebackConversion); 5319 5320 if (ToType->isReferenceType()) 5321 return TryReferenceInit(S, From, ToType, 5322 /*FIXME:*/ From->getBeginLoc(), 5323 SuppressUserConversions, AllowExplicit); 5324 5325 return TryImplicitConversion(S, From, ToType, 5326 SuppressUserConversions, 5327 AllowedExplicit::None, 5328 InOverloadResolution, 5329 /*CStyle=*/false, 5330 AllowObjCWritebackConversion, 5331 /*AllowObjCConversionOnExplicit=*/false); 5332 } 5333 5334 static bool TryCopyInitialization(const CanQualType FromQTy, 5335 const CanQualType ToQTy, 5336 Sema &S, 5337 SourceLocation Loc, 5338 ExprValueKind FromVK) { 5339 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5340 ImplicitConversionSequence ICS = 5341 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5342 5343 return !ICS.isBad(); 5344 } 5345 5346 /// TryObjectArgumentInitialization - Try to initialize the object 5347 /// parameter of the given member function (@c Method) from the 5348 /// expression @p From. 5349 static ImplicitConversionSequence 5350 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5351 Expr::Classification FromClassification, 5352 CXXMethodDecl *Method, 5353 CXXRecordDecl *ActingContext) { 5354 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5355 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5356 // const volatile object. 5357 Qualifiers Quals = Method->getMethodQualifiers(); 5358 if (isa<CXXDestructorDecl>(Method)) { 5359 Quals.addConst(); 5360 Quals.addVolatile(); 5361 } 5362 5363 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5364 5365 // Set up the conversion sequence as a "bad" conversion, to allow us 5366 // to exit early. 5367 ImplicitConversionSequence ICS; 5368 5369 // We need to have an object of class type. 5370 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5371 FromType = PT->getPointeeType(); 5372 5373 // When we had a pointer, it's implicitly dereferenced, so we 5374 // better have an lvalue. 5375 assert(FromClassification.isLValue()); 5376 } 5377 5378 assert(FromType->isRecordType()); 5379 5380 // C++0x [over.match.funcs]p4: 5381 // For non-static member functions, the type of the implicit object 5382 // parameter is 5383 // 5384 // - "lvalue reference to cv X" for functions declared without a 5385 // ref-qualifier or with the & ref-qualifier 5386 // - "rvalue reference to cv X" for functions declared with the && 5387 // ref-qualifier 5388 // 5389 // where X is the class of which the function is a member and cv is the 5390 // cv-qualification on the member function declaration. 5391 // 5392 // However, when finding an implicit conversion sequence for the argument, we 5393 // are not allowed to perform user-defined conversions 5394 // (C++ [over.match.funcs]p5). We perform a simplified version of 5395 // reference binding here, that allows class rvalues to bind to 5396 // non-constant references. 5397 5398 // First check the qualifiers. 5399 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5400 if (ImplicitParamType.getCVRQualifiers() 5401 != FromTypeCanon.getLocalCVRQualifiers() && 5402 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5403 ICS.setBad(BadConversionSequence::bad_qualifiers, 5404 FromType, ImplicitParamType); 5405 return ICS; 5406 } 5407 5408 if (FromTypeCanon.hasAddressSpace()) { 5409 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5410 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5411 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5412 ICS.setBad(BadConversionSequence::bad_qualifiers, 5413 FromType, ImplicitParamType); 5414 return ICS; 5415 } 5416 } 5417 5418 // Check that we have either the same type or a derived type. It 5419 // affects the conversion rank. 5420 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5421 ImplicitConversionKind SecondKind; 5422 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5423 SecondKind = ICK_Identity; 5424 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5425 SecondKind = ICK_Derived_To_Base; 5426 else { 5427 ICS.setBad(BadConversionSequence::unrelated_class, 5428 FromType, ImplicitParamType); 5429 return ICS; 5430 } 5431 5432 // Check the ref-qualifier. 5433 switch (Method->getRefQualifier()) { 5434 case RQ_None: 5435 // Do nothing; we don't care about lvalueness or rvalueness. 5436 break; 5437 5438 case RQ_LValue: 5439 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5440 // non-const lvalue reference cannot bind to an rvalue 5441 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5442 ImplicitParamType); 5443 return ICS; 5444 } 5445 break; 5446 5447 case RQ_RValue: 5448 if (!FromClassification.isRValue()) { 5449 // rvalue reference cannot bind to an lvalue 5450 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5451 ImplicitParamType); 5452 return ICS; 5453 } 5454 break; 5455 } 5456 5457 // Success. Mark this as a reference binding. 5458 ICS.setStandard(); 5459 ICS.Standard.setAsIdentityConversion(); 5460 ICS.Standard.Second = SecondKind; 5461 ICS.Standard.setFromType(FromType); 5462 ICS.Standard.setAllToTypes(ImplicitParamType); 5463 ICS.Standard.ReferenceBinding = true; 5464 ICS.Standard.DirectBinding = true; 5465 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5466 ICS.Standard.BindsToFunctionLvalue = false; 5467 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5468 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5469 = (Method->getRefQualifier() == RQ_None); 5470 return ICS; 5471 } 5472 5473 /// PerformObjectArgumentInitialization - Perform initialization of 5474 /// the implicit object parameter for the given Method with the given 5475 /// expression. 5476 ExprResult 5477 Sema::PerformObjectArgumentInitialization(Expr *From, 5478 NestedNameSpecifier *Qualifier, 5479 NamedDecl *FoundDecl, 5480 CXXMethodDecl *Method) { 5481 QualType FromRecordType, DestType; 5482 QualType ImplicitParamRecordType = 5483 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5484 5485 Expr::Classification FromClassification; 5486 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5487 FromRecordType = PT->getPointeeType(); 5488 DestType = Method->getThisType(); 5489 FromClassification = Expr::Classification::makeSimpleLValue(); 5490 } else { 5491 FromRecordType = From->getType(); 5492 DestType = ImplicitParamRecordType; 5493 FromClassification = From->Classify(Context); 5494 5495 // When performing member access on a prvalue, materialize a temporary. 5496 if (From->isPRValue()) { 5497 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5498 Method->getRefQualifier() != 5499 RefQualifierKind::RQ_RValue); 5500 } 5501 } 5502 5503 // Note that we always use the true parent context when performing 5504 // the actual argument initialization. 5505 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5506 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5507 Method->getParent()); 5508 if (ICS.isBad()) { 5509 switch (ICS.Bad.Kind) { 5510 case BadConversionSequence::bad_qualifiers: { 5511 Qualifiers FromQs = FromRecordType.getQualifiers(); 5512 Qualifiers ToQs = DestType.getQualifiers(); 5513 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5514 if (CVR) { 5515 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5516 << Method->getDeclName() << FromRecordType << (CVR - 1) 5517 << From->getSourceRange(); 5518 Diag(Method->getLocation(), diag::note_previous_decl) 5519 << Method->getDeclName(); 5520 return ExprError(); 5521 } 5522 break; 5523 } 5524 5525 case BadConversionSequence::lvalue_ref_to_rvalue: 5526 case BadConversionSequence::rvalue_ref_to_lvalue: { 5527 bool IsRValueQualified = 5528 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5529 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5530 << Method->getDeclName() << FromClassification.isRValue() 5531 << IsRValueQualified; 5532 Diag(Method->getLocation(), diag::note_previous_decl) 5533 << Method->getDeclName(); 5534 return ExprError(); 5535 } 5536 5537 case BadConversionSequence::no_conversion: 5538 case BadConversionSequence::unrelated_class: 5539 break; 5540 5541 case BadConversionSequence::too_few_initializers: 5542 case BadConversionSequence::too_many_initializers: 5543 llvm_unreachable("Lists are not objects"); 5544 } 5545 5546 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5547 << ImplicitParamRecordType << FromRecordType 5548 << From->getSourceRange(); 5549 } 5550 5551 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5552 ExprResult FromRes = 5553 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5554 if (FromRes.isInvalid()) 5555 return ExprError(); 5556 From = FromRes.get(); 5557 } 5558 5559 if (!Context.hasSameType(From->getType(), DestType)) { 5560 CastKind CK; 5561 QualType PteeTy = DestType->getPointeeType(); 5562 LangAS DestAS = 5563 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5564 if (FromRecordType.getAddressSpace() != DestAS) 5565 CK = CK_AddressSpaceConversion; 5566 else 5567 CK = CK_NoOp; 5568 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5569 } 5570 return From; 5571 } 5572 5573 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5574 /// expression From to bool (C++0x [conv]p3). 5575 static ImplicitConversionSequence 5576 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5577 // C++ [dcl.init]/17.8: 5578 // - Otherwise, if the initialization is direct-initialization, the source 5579 // type is std::nullptr_t, and the destination type is bool, the initial 5580 // value of the object being initialized is false. 5581 if (From->getType()->isNullPtrType()) 5582 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5583 S.Context.BoolTy, 5584 From->isGLValue()); 5585 5586 // All other direct-initialization of bool is equivalent to an implicit 5587 // conversion to bool in which explicit conversions are permitted. 5588 return TryImplicitConversion(S, From, S.Context.BoolTy, 5589 /*SuppressUserConversions=*/false, 5590 AllowedExplicit::Conversions, 5591 /*InOverloadResolution=*/false, 5592 /*CStyle=*/false, 5593 /*AllowObjCWritebackConversion=*/false, 5594 /*AllowObjCConversionOnExplicit=*/false); 5595 } 5596 5597 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5598 /// of the expression From to bool (C++0x [conv]p3). 5599 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5600 if (checkPlaceholderForOverload(*this, From)) 5601 return ExprError(); 5602 5603 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5604 if (!ICS.isBad()) 5605 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5606 5607 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5608 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5609 << From->getType() << From->getSourceRange(); 5610 return ExprError(); 5611 } 5612 5613 /// Check that the specified conversion is permitted in a converted constant 5614 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5615 /// is acceptable. 5616 static bool CheckConvertedConstantConversions(Sema &S, 5617 StandardConversionSequence &SCS) { 5618 // Since we know that the target type is an integral or unscoped enumeration 5619 // type, most conversion kinds are impossible. All possible First and Third 5620 // conversions are fine. 5621 switch (SCS.Second) { 5622 case ICK_Identity: 5623 case ICK_Integral_Promotion: 5624 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5625 case ICK_Zero_Queue_Conversion: 5626 return true; 5627 5628 case ICK_Boolean_Conversion: 5629 // Conversion from an integral or unscoped enumeration type to bool is 5630 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5631 // conversion, so we allow it in a converted constant expression. 5632 // 5633 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5634 // a lot of popular code. We should at least add a warning for this 5635 // (non-conforming) extension. 5636 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5637 SCS.getToType(2)->isBooleanType(); 5638 5639 case ICK_Pointer_Conversion: 5640 case ICK_Pointer_Member: 5641 // C++1z: null pointer conversions and null member pointer conversions are 5642 // only permitted if the source type is std::nullptr_t. 5643 return SCS.getFromType()->isNullPtrType(); 5644 5645 case ICK_Floating_Promotion: 5646 case ICK_Complex_Promotion: 5647 case ICK_Floating_Conversion: 5648 case ICK_Complex_Conversion: 5649 case ICK_Floating_Integral: 5650 case ICK_Compatible_Conversion: 5651 case ICK_Derived_To_Base: 5652 case ICK_Vector_Conversion: 5653 case ICK_SVE_Vector_Conversion: 5654 case ICK_Vector_Splat: 5655 case ICK_Complex_Real: 5656 case ICK_Block_Pointer_Conversion: 5657 case ICK_TransparentUnionConversion: 5658 case ICK_Writeback_Conversion: 5659 case ICK_Zero_Event_Conversion: 5660 case ICK_C_Only_Conversion: 5661 case ICK_Incompatible_Pointer_Conversion: 5662 return false; 5663 5664 case ICK_Lvalue_To_Rvalue: 5665 case ICK_Array_To_Pointer: 5666 case ICK_Function_To_Pointer: 5667 llvm_unreachable("found a first conversion kind in Second"); 5668 5669 case ICK_Function_Conversion: 5670 case ICK_Qualification: 5671 llvm_unreachable("found a third conversion kind in Second"); 5672 5673 case ICK_Num_Conversion_Kinds: 5674 break; 5675 } 5676 5677 llvm_unreachable("unknown conversion kind"); 5678 } 5679 5680 /// CheckConvertedConstantExpression - Check that the expression From is a 5681 /// converted constant expression of type T, perform the conversion and produce 5682 /// the converted expression, per C++11 [expr.const]p3. 5683 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5684 QualType T, APValue &Value, 5685 Sema::CCEKind CCE, 5686 bool RequireInt, 5687 NamedDecl *Dest) { 5688 assert(S.getLangOpts().CPlusPlus11 && 5689 "converted constant expression outside C++11"); 5690 5691 if (checkPlaceholderForOverload(S, From)) 5692 return ExprError(); 5693 5694 // C++1z [expr.const]p3: 5695 // A converted constant expression of type T is an expression, 5696 // implicitly converted to type T, where the converted 5697 // expression is a constant expression and the implicit conversion 5698 // sequence contains only [... list of conversions ...]. 5699 ImplicitConversionSequence ICS = 5700 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 5701 ? TryContextuallyConvertToBool(S, From) 5702 : TryCopyInitialization(S, From, T, 5703 /*SuppressUserConversions=*/false, 5704 /*InOverloadResolution=*/false, 5705 /*AllowObjCWritebackConversion=*/false, 5706 /*AllowExplicit=*/false); 5707 StandardConversionSequence *SCS = nullptr; 5708 switch (ICS.getKind()) { 5709 case ImplicitConversionSequence::StandardConversion: 5710 SCS = &ICS.Standard; 5711 break; 5712 case ImplicitConversionSequence::UserDefinedConversion: 5713 if (T->isRecordType()) 5714 SCS = &ICS.UserDefined.Before; 5715 else 5716 SCS = &ICS.UserDefined.After; 5717 break; 5718 case ImplicitConversionSequence::AmbiguousConversion: 5719 case ImplicitConversionSequence::BadConversion: 5720 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5721 return S.Diag(From->getBeginLoc(), 5722 diag::err_typecheck_converted_constant_expression) 5723 << From->getType() << From->getSourceRange() << T; 5724 return ExprError(); 5725 5726 case ImplicitConversionSequence::EllipsisConversion: 5727 llvm_unreachable("ellipsis conversion in converted constant expression"); 5728 } 5729 5730 // Check that we would only use permitted conversions. 5731 if (!CheckConvertedConstantConversions(S, *SCS)) { 5732 return S.Diag(From->getBeginLoc(), 5733 diag::err_typecheck_converted_constant_expression_disallowed) 5734 << From->getType() << From->getSourceRange() << T; 5735 } 5736 // [...] and where the reference binding (if any) binds directly. 5737 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5738 return S.Diag(From->getBeginLoc(), 5739 diag::err_typecheck_converted_constant_expression_indirect) 5740 << From->getType() << From->getSourceRange() << T; 5741 } 5742 5743 // Usually we can simply apply the ImplicitConversionSequence we formed 5744 // earlier, but that's not guaranteed to work when initializing an object of 5745 // class type. 5746 ExprResult Result; 5747 if (T->isRecordType()) { 5748 assert(CCE == Sema::CCEK_TemplateArg && 5749 "unexpected class type converted constant expr"); 5750 Result = S.PerformCopyInitialization( 5751 InitializedEntity::InitializeTemplateParameter( 5752 T, cast<NonTypeTemplateParmDecl>(Dest)), 5753 SourceLocation(), From); 5754 } else { 5755 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5756 } 5757 if (Result.isInvalid()) 5758 return Result; 5759 5760 // C++2a [intro.execution]p5: 5761 // A full-expression is [...] a constant-expression [...] 5762 Result = 5763 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5764 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5765 if (Result.isInvalid()) 5766 return Result; 5767 5768 // Check for a narrowing implicit conversion. 5769 bool ReturnPreNarrowingValue = false; 5770 APValue PreNarrowingValue; 5771 QualType PreNarrowingType; 5772 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5773 PreNarrowingType)) { 5774 case NK_Dependent_Narrowing: 5775 // Implicit conversion to a narrower type, but the expression is 5776 // value-dependent so we can't tell whether it's actually narrowing. 5777 case NK_Variable_Narrowing: 5778 // Implicit conversion to a narrower type, and the value is not a constant 5779 // expression. We'll diagnose this in a moment. 5780 case NK_Not_Narrowing: 5781 break; 5782 5783 case NK_Constant_Narrowing: 5784 if (CCE == Sema::CCEK_ArrayBound && 5785 PreNarrowingType->isIntegralOrEnumerationType() && 5786 PreNarrowingValue.isInt()) { 5787 // Don't diagnose array bound narrowing here; we produce more precise 5788 // errors by allowing the un-narrowed value through. 5789 ReturnPreNarrowingValue = true; 5790 break; 5791 } 5792 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5793 << CCE << /*Constant*/ 1 5794 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5795 break; 5796 5797 case NK_Type_Narrowing: 5798 // FIXME: It would be better to diagnose that the expression is not a 5799 // constant expression. 5800 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5801 << CCE << /*Constant*/ 0 << From->getType() << T; 5802 break; 5803 } 5804 5805 if (Result.get()->isValueDependent()) { 5806 Value = APValue(); 5807 return Result; 5808 } 5809 5810 // Check the expression is a constant expression. 5811 SmallVector<PartialDiagnosticAt, 8> Notes; 5812 Expr::EvalResult Eval; 5813 Eval.Diag = &Notes; 5814 5815 ConstantExprKind Kind; 5816 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5817 Kind = ConstantExprKind::ClassTemplateArgument; 5818 else if (CCE == Sema::CCEK_TemplateArg) 5819 Kind = ConstantExprKind::NonClassTemplateArgument; 5820 else 5821 Kind = ConstantExprKind::Normal; 5822 5823 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5824 (RequireInt && !Eval.Val.isInt())) { 5825 // The expression can't be folded, so we can't keep it at this position in 5826 // the AST. 5827 Result = ExprError(); 5828 } else { 5829 Value = Eval.Val; 5830 5831 if (Notes.empty()) { 5832 // It's a constant expression. 5833 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5834 if (ReturnPreNarrowingValue) 5835 Value = std::move(PreNarrowingValue); 5836 return E; 5837 } 5838 } 5839 5840 // It's not a constant expression. Produce an appropriate diagnostic. 5841 if (Notes.size() == 1 && 5842 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5843 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5844 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5845 diag::note_constexpr_invalid_template_arg) { 5846 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5847 for (unsigned I = 0; I < Notes.size(); ++I) 5848 S.Diag(Notes[I].first, Notes[I].second); 5849 } else { 5850 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5851 << CCE << From->getSourceRange(); 5852 for (unsigned I = 0; I < Notes.size(); ++I) 5853 S.Diag(Notes[I].first, Notes[I].second); 5854 } 5855 return ExprError(); 5856 } 5857 5858 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5859 APValue &Value, CCEKind CCE, 5860 NamedDecl *Dest) { 5861 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5862 Dest); 5863 } 5864 5865 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5866 llvm::APSInt &Value, 5867 CCEKind CCE) { 5868 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5869 5870 APValue V; 5871 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5872 /*Dest=*/nullptr); 5873 if (!R.isInvalid() && !R.get()->isValueDependent()) 5874 Value = V.getInt(); 5875 return R; 5876 } 5877 5878 5879 /// dropPointerConversions - If the given standard conversion sequence 5880 /// involves any pointer conversions, remove them. This may change 5881 /// the result type of the conversion sequence. 5882 static void dropPointerConversion(StandardConversionSequence &SCS) { 5883 if (SCS.Second == ICK_Pointer_Conversion) { 5884 SCS.Second = ICK_Identity; 5885 SCS.Third = ICK_Identity; 5886 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5887 } 5888 } 5889 5890 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5891 /// convert the expression From to an Objective-C pointer type. 5892 static ImplicitConversionSequence 5893 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5894 // Do an implicit conversion to 'id'. 5895 QualType Ty = S.Context.getObjCIdType(); 5896 ImplicitConversionSequence ICS 5897 = TryImplicitConversion(S, From, Ty, 5898 // FIXME: Are these flags correct? 5899 /*SuppressUserConversions=*/false, 5900 AllowedExplicit::Conversions, 5901 /*InOverloadResolution=*/false, 5902 /*CStyle=*/false, 5903 /*AllowObjCWritebackConversion=*/false, 5904 /*AllowObjCConversionOnExplicit=*/true); 5905 5906 // Strip off any final conversions to 'id'. 5907 switch (ICS.getKind()) { 5908 case ImplicitConversionSequence::BadConversion: 5909 case ImplicitConversionSequence::AmbiguousConversion: 5910 case ImplicitConversionSequence::EllipsisConversion: 5911 break; 5912 5913 case ImplicitConversionSequence::UserDefinedConversion: 5914 dropPointerConversion(ICS.UserDefined.After); 5915 break; 5916 5917 case ImplicitConversionSequence::StandardConversion: 5918 dropPointerConversion(ICS.Standard); 5919 break; 5920 } 5921 5922 return ICS; 5923 } 5924 5925 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5926 /// conversion of the expression From to an Objective-C pointer type. 5927 /// Returns a valid but null ExprResult if no conversion sequence exists. 5928 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5929 if (checkPlaceholderForOverload(*this, From)) 5930 return ExprError(); 5931 5932 QualType Ty = Context.getObjCIdType(); 5933 ImplicitConversionSequence ICS = 5934 TryContextuallyConvertToObjCPointer(*this, From); 5935 if (!ICS.isBad()) 5936 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5937 return ExprResult(); 5938 } 5939 5940 /// Determine whether the provided type is an integral type, or an enumeration 5941 /// type of a permitted flavor. 5942 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5943 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5944 : T->isIntegralOrUnscopedEnumerationType(); 5945 } 5946 5947 static ExprResult 5948 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5949 Sema::ContextualImplicitConverter &Converter, 5950 QualType T, UnresolvedSetImpl &ViableConversions) { 5951 5952 if (Converter.Suppress) 5953 return ExprError(); 5954 5955 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5956 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5957 CXXConversionDecl *Conv = 5958 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5959 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5960 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5961 } 5962 return From; 5963 } 5964 5965 static bool 5966 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5967 Sema::ContextualImplicitConverter &Converter, 5968 QualType T, bool HadMultipleCandidates, 5969 UnresolvedSetImpl &ExplicitConversions) { 5970 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5971 DeclAccessPair Found = ExplicitConversions[0]; 5972 CXXConversionDecl *Conversion = 5973 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5974 5975 // The user probably meant to invoke the given explicit 5976 // conversion; use it. 5977 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5978 std::string TypeStr; 5979 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5980 5981 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5982 << FixItHint::CreateInsertion(From->getBeginLoc(), 5983 "static_cast<" + TypeStr + ">(") 5984 << FixItHint::CreateInsertion( 5985 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5986 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5987 5988 // If we aren't in a SFINAE context, build a call to the 5989 // explicit conversion function. 5990 if (SemaRef.isSFINAEContext()) 5991 return true; 5992 5993 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5994 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5995 HadMultipleCandidates); 5996 if (Result.isInvalid()) 5997 return true; 5998 // Record usage of conversion in an implicit cast. 5999 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6000 CK_UserDefinedConversion, Result.get(), 6001 nullptr, Result.get()->getValueKind(), 6002 SemaRef.CurFPFeatureOverrides()); 6003 } 6004 return false; 6005 } 6006 6007 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6008 Sema::ContextualImplicitConverter &Converter, 6009 QualType T, bool HadMultipleCandidates, 6010 DeclAccessPair &Found) { 6011 CXXConversionDecl *Conversion = 6012 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6013 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6014 6015 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6016 if (!Converter.SuppressConversion) { 6017 if (SemaRef.isSFINAEContext()) 6018 return true; 6019 6020 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6021 << From->getSourceRange(); 6022 } 6023 6024 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6025 HadMultipleCandidates); 6026 if (Result.isInvalid()) 6027 return true; 6028 // Record usage of conversion in an implicit cast. 6029 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6030 CK_UserDefinedConversion, Result.get(), 6031 nullptr, Result.get()->getValueKind(), 6032 SemaRef.CurFPFeatureOverrides()); 6033 return false; 6034 } 6035 6036 static ExprResult finishContextualImplicitConversion( 6037 Sema &SemaRef, SourceLocation Loc, Expr *From, 6038 Sema::ContextualImplicitConverter &Converter) { 6039 if (!Converter.match(From->getType()) && !Converter.Suppress) 6040 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6041 << From->getSourceRange(); 6042 6043 return SemaRef.DefaultLvalueConversion(From); 6044 } 6045 6046 static void 6047 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6048 UnresolvedSetImpl &ViableConversions, 6049 OverloadCandidateSet &CandidateSet) { 6050 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6051 DeclAccessPair FoundDecl = ViableConversions[I]; 6052 NamedDecl *D = FoundDecl.getDecl(); 6053 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6054 if (isa<UsingShadowDecl>(D)) 6055 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6056 6057 CXXConversionDecl *Conv; 6058 FunctionTemplateDecl *ConvTemplate; 6059 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6060 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6061 else 6062 Conv = cast<CXXConversionDecl>(D); 6063 6064 if (ConvTemplate) 6065 SemaRef.AddTemplateConversionCandidate( 6066 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6067 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6068 else 6069 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6070 ToType, CandidateSet, 6071 /*AllowObjCConversionOnExplicit=*/false, 6072 /*AllowExplicit*/ true); 6073 } 6074 } 6075 6076 /// Attempt to convert the given expression to a type which is accepted 6077 /// by the given converter. 6078 /// 6079 /// This routine will attempt to convert an expression of class type to a 6080 /// type accepted by the specified converter. In C++11 and before, the class 6081 /// must have a single non-explicit conversion function converting to a matching 6082 /// type. In C++1y, there can be multiple such conversion functions, but only 6083 /// one target type. 6084 /// 6085 /// \param Loc The source location of the construct that requires the 6086 /// conversion. 6087 /// 6088 /// \param From The expression we're converting from. 6089 /// 6090 /// \param Converter Used to control and diagnose the conversion process. 6091 /// 6092 /// \returns The expression, converted to an integral or enumeration type if 6093 /// successful. 6094 ExprResult Sema::PerformContextualImplicitConversion( 6095 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6096 // We can't perform any more checking for type-dependent expressions. 6097 if (From->isTypeDependent()) 6098 return From; 6099 6100 // Process placeholders immediately. 6101 if (From->hasPlaceholderType()) { 6102 ExprResult result = CheckPlaceholderExpr(From); 6103 if (result.isInvalid()) 6104 return result; 6105 From = result.get(); 6106 } 6107 6108 // If the expression already has a matching type, we're golden. 6109 QualType T = From->getType(); 6110 if (Converter.match(T)) 6111 return DefaultLvalueConversion(From); 6112 6113 // FIXME: Check for missing '()' if T is a function type? 6114 6115 // We can only perform contextual implicit conversions on objects of class 6116 // type. 6117 const RecordType *RecordTy = T->getAs<RecordType>(); 6118 if (!RecordTy || !getLangOpts().CPlusPlus) { 6119 if (!Converter.Suppress) 6120 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6121 return From; 6122 } 6123 6124 // We must have a complete class type. 6125 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6126 ContextualImplicitConverter &Converter; 6127 Expr *From; 6128 6129 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6130 : Converter(Converter), From(From) {} 6131 6132 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6133 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6134 } 6135 } IncompleteDiagnoser(Converter, From); 6136 6137 if (Converter.Suppress ? !isCompleteType(Loc, T) 6138 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6139 return From; 6140 6141 // Look for a conversion to an integral or enumeration type. 6142 UnresolvedSet<4> 6143 ViableConversions; // These are *potentially* viable in C++1y. 6144 UnresolvedSet<4> ExplicitConversions; 6145 const auto &Conversions = 6146 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6147 6148 bool HadMultipleCandidates = 6149 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6150 6151 // To check that there is only one target type, in C++1y: 6152 QualType ToType; 6153 bool HasUniqueTargetType = true; 6154 6155 // Collect explicit or viable (potentially in C++1y) conversions. 6156 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6157 NamedDecl *D = (*I)->getUnderlyingDecl(); 6158 CXXConversionDecl *Conversion; 6159 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6160 if (ConvTemplate) { 6161 if (getLangOpts().CPlusPlus14) 6162 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6163 else 6164 continue; // C++11 does not consider conversion operator templates(?). 6165 } else 6166 Conversion = cast<CXXConversionDecl>(D); 6167 6168 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6169 "Conversion operator templates are considered potentially " 6170 "viable in C++1y"); 6171 6172 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6173 if (Converter.match(CurToType) || ConvTemplate) { 6174 6175 if (Conversion->isExplicit()) { 6176 // FIXME: For C++1y, do we need this restriction? 6177 // cf. diagnoseNoViableConversion() 6178 if (!ConvTemplate) 6179 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6180 } else { 6181 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6182 if (ToType.isNull()) 6183 ToType = CurToType.getUnqualifiedType(); 6184 else if (HasUniqueTargetType && 6185 (CurToType.getUnqualifiedType() != ToType)) 6186 HasUniqueTargetType = false; 6187 } 6188 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6189 } 6190 } 6191 } 6192 6193 if (getLangOpts().CPlusPlus14) { 6194 // C++1y [conv]p6: 6195 // ... An expression e of class type E appearing in such a context 6196 // is said to be contextually implicitly converted to a specified 6197 // type T and is well-formed if and only if e can be implicitly 6198 // converted to a type T that is determined as follows: E is searched 6199 // for conversion functions whose return type is cv T or reference to 6200 // cv T such that T is allowed by the context. There shall be 6201 // exactly one such T. 6202 6203 // If no unique T is found: 6204 if (ToType.isNull()) { 6205 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6206 HadMultipleCandidates, 6207 ExplicitConversions)) 6208 return ExprError(); 6209 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6210 } 6211 6212 // If more than one unique Ts are found: 6213 if (!HasUniqueTargetType) 6214 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6215 ViableConversions); 6216 6217 // If one unique T is found: 6218 // First, build a candidate set from the previously recorded 6219 // potentially viable conversions. 6220 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6221 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6222 CandidateSet); 6223 6224 // Then, perform overload resolution over the candidate set. 6225 OverloadCandidateSet::iterator Best; 6226 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6227 case OR_Success: { 6228 // Apply this conversion. 6229 DeclAccessPair Found = 6230 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6231 if (recordConversion(*this, Loc, From, Converter, T, 6232 HadMultipleCandidates, Found)) 6233 return ExprError(); 6234 break; 6235 } 6236 case OR_Ambiguous: 6237 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6238 ViableConversions); 6239 case OR_No_Viable_Function: 6240 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6241 HadMultipleCandidates, 6242 ExplicitConversions)) 6243 return ExprError(); 6244 LLVM_FALLTHROUGH; 6245 case OR_Deleted: 6246 // We'll complain below about a non-integral condition type. 6247 break; 6248 } 6249 } else { 6250 switch (ViableConversions.size()) { 6251 case 0: { 6252 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6253 HadMultipleCandidates, 6254 ExplicitConversions)) 6255 return ExprError(); 6256 6257 // We'll complain below about a non-integral condition type. 6258 break; 6259 } 6260 case 1: { 6261 // Apply this conversion. 6262 DeclAccessPair Found = ViableConversions[0]; 6263 if (recordConversion(*this, Loc, From, Converter, T, 6264 HadMultipleCandidates, Found)) 6265 return ExprError(); 6266 break; 6267 } 6268 default: 6269 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6270 ViableConversions); 6271 } 6272 } 6273 6274 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6275 } 6276 6277 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6278 /// an acceptable non-member overloaded operator for a call whose 6279 /// arguments have types T1 (and, if non-empty, T2). This routine 6280 /// implements the check in C++ [over.match.oper]p3b2 concerning 6281 /// enumeration types. 6282 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6283 FunctionDecl *Fn, 6284 ArrayRef<Expr *> Args) { 6285 QualType T1 = Args[0]->getType(); 6286 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6287 6288 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6289 return true; 6290 6291 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6292 return true; 6293 6294 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6295 if (Proto->getNumParams() < 1) 6296 return false; 6297 6298 if (T1->isEnumeralType()) { 6299 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6300 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6301 return true; 6302 } 6303 6304 if (Proto->getNumParams() < 2) 6305 return false; 6306 6307 if (!T2.isNull() && T2->isEnumeralType()) { 6308 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6309 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6310 return true; 6311 } 6312 6313 return false; 6314 } 6315 6316 /// AddOverloadCandidate - Adds the given function to the set of 6317 /// candidate functions, using the given function call arguments. If 6318 /// @p SuppressUserConversions, then don't allow user-defined 6319 /// conversions via constructors or conversion operators. 6320 /// 6321 /// \param PartialOverloading true if we are performing "partial" overloading 6322 /// based on an incomplete set of function arguments. This feature is used by 6323 /// code completion. 6324 void Sema::AddOverloadCandidate( 6325 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6326 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6327 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6328 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6329 OverloadCandidateParamOrder PO) { 6330 const FunctionProtoType *Proto 6331 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6332 assert(Proto && "Functions without a prototype cannot be overloaded"); 6333 assert(!Function->getDescribedFunctionTemplate() && 6334 "Use AddTemplateOverloadCandidate for function templates"); 6335 6336 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6337 if (!isa<CXXConstructorDecl>(Method)) { 6338 // If we get here, it's because we're calling a member function 6339 // that is named without a member access expression (e.g., 6340 // "this->f") that was either written explicitly or created 6341 // implicitly. This can happen with a qualified call to a member 6342 // function, e.g., X::f(). We use an empty type for the implied 6343 // object argument (C++ [over.call.func]p3), and the acting context 6344 // is irrelevant. 6345 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6346 Expr::Classification::makeSimpleLValue(), Args, 6347 CandidateSet, SuppressUserConversions, 6348 PartialOverloading, EarlyConversions, PO); 6349 return; 6350 } 6351 // We treat a constructor like a non-member function, since its object 6352 // argument doesn't participate in overload resolution. 6353 } 6354 6355 if (!CandidateSet.isNewCandidate(Function, PO)) 6356 return; 6357 6358 // C++11 [class.copy]p11: [DR1402] 6359 // A defaulted move constructor that is defined as deleted is ignored by 6360 // overload resolution. 6361 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6362 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6363 Constructor->isMoveConstructor()) 6364 return; 6365 6366 // Overload resolution is always an unevaluated context. 6367 EnterExpressionEvaluationContext Unevaluated( 6368 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6369 6370 // C++ [over.match.oper]p3: 6371 // if no operand has a class type, only those non-member functions in the 6372 // lookup set that have a first parameter of type T1 or "reference to 6373 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6374 // is a right operand) a second parameter of type T2 or "reference to 6375 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6376 // candidate functions. 6377 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6378 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6379 return; 6380 6381 // Add this candidate 6382 OverloadCandidate &Candidate = 6383 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6384 Candidate.FoundDecl = FoundDecl; 6385 Candidate.Function = Function; 6386 Candidate.Viable = true; 6387 Candidate.RewriteKind = 6388 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6389 Candidate.IsSurrogate = false; 6390 Candidate.IsADLCandidate = IsADLCandidate; 6391 Candidate.IgnoreObjectArgument = false; 6392 Candidate.ExplicitCallArguments = Args.size(); 6393 6394 // Explicit functions are not actually candidates at all if we're not 6395 // allowing them in this context, but keep them around so we can point 6396 // to them in diagnostics. 6397 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6398 Candidate.Viable = false; 6399 Candidate.FailureKind = ovl_fail_explicit; 6400 return; 6401 } 6402 6403 // Functions with internal linkage are only viable in the same module unit. 6404 if (auto *MF = Function->getOwningModule()) { 6405 if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() && 6406 Function->getFormalLinkage() <= Linkage::InternalLinkage && 6407 !isModuleUnitOfCurrentTU(MF)) { 6408 Candidate.Viable = false; 6409 Candidate.FailureKind = ovl_fail_module_mismatched; 6410 return; 6411 } 6412 } 6413 6414 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6415 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6416 Candidate.Viable = false; 6417 Candidate.FailureKind = ovl_non_default_multiversion_function; 6418 return; 6419 } 6420 6421 if (Constructor) { 6422 // C++ [class.copy]p3: 6423 // A member function template is never instantiated to perform the copy 6424 // of a class object to an object of its class type. 6425 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6426 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6427 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6428 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6429 ClassType))) { 6430 Candidate.Viable = false; 6431 Candidate.FailureKind = ovl_fail_illegal_constructor; 6432 return; 6433 } 6434 6435 // C++ [over.match.funcs]p8: (proposed DR resolution) 6436 // A constructor inherited from class type C that has a first parameter 6437 // of type "reference to P" (including such a constructor instantiated 6438 // from a template) is excluded from the set of candidate functions when 6439 // constructing an object of type cv D if the argument list has exactly 6440 // one argument and D is reference-related to P and P is reference-related 6441 // to C. 6442 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6443 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6444 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6445 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6446 QualType C = Context.getRecordType(Constructor->getParent()); 6447 QualType D = Context.getRecordType(Shadow->getParent()); 6448 SourceLocation Loc = Args.front()->getExprLoc(); 6449 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6450 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6451 Candidate.Viable = false; 6452 Candidate.FailureKind = ovl_fail_inhctor_slice; 6453 return; 6454 } 6455 } 6456 6457 // Check that the constructor is capable of constructing an object in the 6458 // destination address space. 6459 if (!Qualifiers::isAddressSpaceSupersetOf( 6460 Constructor->getMethodQualifiers().getAddressSpace(), 6461 CandidateSet.getDestAS())) { 6462 Candidate.Viable = false; 6463 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6464 } 6465 } 6466 6467 unsigned NumParams = Proto->getNumParams(); 6468 6469 // (C++ 13.3.2p2): A candidate function having fewer than m 6470 // parameters is viable only if it has an ellipsis in its parameter 6471 // list (8.3.5). 6472 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6473 !Proto->isVariadic() && 6474 shouldEnforceArgLimit(PartialOverloading, Function)) { 6475 Candidate.Viable = false; 6476 Candidate.FailureKind = ovl_fail_too_many_arguments; 6477 return; 6478 } 6479 6480 // (C++ 13.3.2p2): A candidate function having more than m parameters 6481 // is viable only if the (m+1)st parameter has a default argument 6482 // (8.3.6). For the purposes of overload resolution, the 6483 // parameter list is truncated on the right, so that there are 6484 // exactly m parameters. 6485 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6486 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6487 // Not enough arguments. 6488 Candidate.Viable = false; 6489 Candidate.FailureKind = ovl_fail_too_few_arguments; 6490 return; 6491 } 6492 6493 // (CUDA B.1): Check for invalid calls between targets. 6494 if (getLangOpts().CUDA) 6495 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) 6496 // Skip the check for callers that are implicit members, because in this 6497 // case we may not yet know what the member's target is; the target is 6498 // inferred for the member automatically, based on the bases and fields of 6499 // the class. 6500 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6501 Candidate.Viable = false; 6502 Candidate.FailureKind = ovl_fail_bad_target; 6503 return; 6504 } 6505 6506 if (Function->getTrailingRequiresClause()) { 6507 ConstraintSatisfaction Satisfaction; 6508 if (CheckFunctionConstraints(Function, Satisfaction) || 6509 !Satisfaction.IsSatisfied) { 6510 Candidate.Viable = false; 6511 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6512 return; 6513 } 6514 } 6515 6516 // Determine the implicit conversion sequences for each of the 6517 // arguments. 6518 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6519 unsigned ConvIdx = 6520 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6521 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6522 // We already formed a conversion sequence for this parameter during 6523 // template argument deduction. 6524 } else if (ArgIdx < NumParams) { 6525 // (C++ 13.3.2p3): for F to be a viable function, there shall 6526 // exist for each argument an implicit conversion sequence 6527 // (13.3.3.1) that converts that argument to the corresponding 6528 // parameter of F. 6529 QualType ParamType = Proto->getParamType(ArgIdx); 6530 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6531 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6532 /*InOverloadResolution=*/true, 6533 /*AllowObjCWritebackConversion=*/ 6534 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6535 if (Candidate.Conversions[ConvIdx].isBad()) { 6536 Candidate.Viable = false; 6537 Candidate.FailureKind = ovl_fail_bad_conversion; 6538 return; 6539 } 6540 } else { 6541 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6542 // argument for which there is no corresponding parameter is 6543 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6544 Candidate.Conversions[ConvIdx].setEllipsis(); 6545 } 6546 } 6547 6548 if (EnableIfAttr *FailedAttr = 6549 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6550 Candidate.Viable = false; 6551 Candidate.FailureKind = ovl_fail_enable_if; 6552 Candidate.DeductionFailure.Data = FailedAttr; 6553 return; 6554 } 6555 } 6556 6557 ObjCMethodDecl * 6558 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6559 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6560 if (Methods.size() <= 1) 6561 return nullptr; 6562 6563 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6564 bool Match = true; 6565 ObjCMethodDecl *Method = Methods[b]; 6566 unsigned NumNamedArgs = Sel.getNumArgs(); 6567 // Method might have more arguments than selector indicates. This is due 6568 // to addition of c-style arguments in method. 6569 if (Method->param_size() > NumNamedArgs) 6570 NumNamedArgs = Method->param_size(); 6571 if (Args.size() < NumNamedArgs) 6572 continue; 6573 6574 for (unsigned i = 0; i < NumNamedArgs; i++) { 6575 // We can't do any type-checking on a type-dependent argument. 6576 if (Args[i]->isTypeDependent()) { 6577 Match = false; 6578 break; 6579 } 6580 6581 ParmVarDecl *param = Method->parameters()[i]; 6582 Expr *argExpr = Args[i]; 6583 assert(argExpr && "SelectBestMethod(): missing expression"); 6584 6585 // Strip the unbridged-cast placeholder expression off unless it's 6586 // a consumed argument. 6587 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6588 !param->hasAttr<CFConsumedAttr>()) 6589 argExpr = stripARCUnbridgedCast(argExpr); 6590 6591 // If the parameter is __unknown_anytype, move on to the next method. 6592 if (param->getType() == Context.UnknownAnyTy) { 6593 Match = false; 6594 break; 6595 } 6596 6597 ImplicitConversionSequence ConversionState 6598 = TryCopyInitialization(*this, argExpr, param->getType(), 6599 /*SuppressUserConversions*/false, 6600 /*InOverloadResolution=*/true, 6601 /*AllowObjCWritebackConversion=*/ 6602 getLangOpts().ObjCAutoRefCount, 6603 /*AllowExplicit*/false); 6604 // This function looks for a reasonably-exact match, so we consider 6605 // incompatible pointer conversions to be a failure here. 6606 if (ConversionState.isBad() || 6607 (ConversionState.isStandard() && 6608 ConversionState.Standard.Second == 6609 ICK_Incompatible_Pointer_Conversion)) { 6610 Match = false; 6611 break; 6612 } 6613 } 6614 // Promote additional arguments to variadic methods. 6615 if (Match && Method->isVariadic()) { 6616 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6617 if (Args[i]->isTypeDependent()) { 6618 Match = false; 6619 break; 6620 } 6621 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6622 nullptr); 6623 if (Arg.isInvalid()) { 6624 Match = false; 6625 break; 6626 } 6627 } 6628 } else { 6629 // Check for extra arguments to non-variadic methods. 6630 if (Args.size() != NumNamedArgs) 6631 Match = false; 6632 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6633 // Special case when selectors have no argument. In this case, select 6634 // one with the most general result type of 'id'. 6635 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6636 QualType ReturnT = Methods[b]->getReturnType(); 6637 if (ReturnT->isObjCIdType()) 6638 return Methods[b]; 6639 } 6640 } 6641 } 6642 6643 if (Match) 6644 return Method; 6645 } 6646 return nullptr; 6647 } 6648 6649 static bool convertArgsForAvailabilityChecks( 6650 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6651 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6652 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6653 if (ThisArg) { 6654 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6655 assert(!isa<CXXConstructorDecl>(Method) && 6656 "Shouldn't have `this` for ctors!"); 6657 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6658 ExprResult R = S.PerformObjectArgumentInitialization( 6659 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6660 if (R.isInvalid()) 6661 return false; 6662 ConvertedThis = R.get(); 6663 } else { 6664 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6665 (void)MD; 6666 assert((MissingImplicitThis || MD->isStatic() || 6667 isa<CXXConstructorDecl>(MD)) && 6668 "Expected `this` for non-ctor instance methods"); 6669 } 6670 ConvertedThis = nullptr; 6671 } 6672 6673 // Ignore any variadic arguments. Converting them is pointless, since the 6674 // user can't refer to them in the function condition. 6675 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6676 6677 // Convert the arguments. 6678 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6679 ExprResult R; 6680 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6681 S.Context, Function->getParamDecl(I)), 6682 SourceLocation(), Args[I]); 6683 6684 if (R.isInvalid()) 6685 return false; 6686 6687 ConvertedArgs.push_back(R.get()); 6688 } 6689 6690 if (Trap.hasErrorOccurred()) 6691 return false; 6692 6693 // Push default arguments if needed. 6694 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6695 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6696 ParmVarDecl *P = Function->getParamDecl(i); 6697 if (!P->hasDefaultArg()) 6698 return false; 6699 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6700 if (R.isInvalid()) 6701 return false; 6702 ConvertedArgs.push_back(R.get()); 6703 } 6704 6705 if (Trap.hasErrorOccurred()) 6706 return false; 6707 } 6708 return true; 6709 } 6710 6711 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6712 SourceLocation CallLoc, 6713 ArrayRef<Expr *> Args, 6714 bool MissingImplicitThis) { 6715 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6716 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6717 return nullptr; 6718 6719 SFINAETrap Trap(*this); 6720 SmallVector<Expr *, 16> ConvertedArgs; 6721 // FIXME: We should look into making enable_if late-parsed. 6722 Expr *DiscardedThis; 6723 if (!convertArgsForAvailabilityChecks( 6724 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6725 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6726 return *EnableIfAttrs.begin(); 6727 6728 for (auto *EIA : EnableIfAttrs) { 6729 APValue Result; 6730 // FIXME: This doesn't consider value-dependent cases, because doing so is 6731 // very difficult. Ideally, we should handle them more gracefully. 6732 if (EIA->getCond()->isValueDependent() || 6733 !EIA->getCond()->EvaluateWithSubstitution( 6734 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6735 return EIA; 6736 6737 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6738 return EIA; 6739 } 6740 return nullptr; 6741 } 6742 6743 template <typename CheckFn> 6744 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6745 bool ArgDependent, SourceLocation Loc, 6746 CheckFn &&IsSuccessful) { 6747 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6748 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6749 if (ArgDependent == DIA->getArgDependent()) 6750 Attrs.push_back(DIA); 6751 } 6752 6753 // Common case: No diagnose_if attributes, so we can quit early. 6754 if (Attrs.empty()) 6755 return false; 6756 6757 auto WarningBegin = std::stable_partition( 6758 Attrs.begin(), Attrs.end(), 6759 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6760 6761 // Note that diagnose_if attributes are late-parsed, so they appear in the 6762 // correct order (unlike enable_if attributes). 6763 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6764 IsSuccessful); 6765 if (ErrAttr != WarningBegin) { 6766 const DiagnoseIfAttr *DIA = *ErrAttr; 6767 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6768 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6769 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6770 return true; 6771 } 6772 6773 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6774 if (IsSuccessful(DIA)) { 6775 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6776 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6777 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6778 } 6779 6780 return false; 6781 } 6782 6783 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6784 const Expr *ThisArg, 6785 ArrayRef<const Expr *> Args, 6786 SourceLocation Loc) { 6787 return diagnoseDiagnoseIfAttrsWith( 6788 *this, Function, /*ArgDependent=*/true, Loc, 6789 [&](const DiagnoseIfAttr *DIA) { 6790 APValue Result; 6791 // It's sane to use the same Args for any redecl of this function, since 6792 // EvaluateWithSubstitution only cares about the position of each 6793 // argument in the arg list, not the ParmVarDecl* it maps to. 6794 if (!DIA->getCond()->EvaluateWithSubstitution( 6795 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6796 return false; 6797 return Result.isInt() && Result.getInt().getBoolValue(); 6798 }); 6799 } 6800 6801 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6802 SourceLocation Loc) { 6803 return diagnoseDiagnoseIfAttrsWith( 6804 *this, ND, /*ArgDependent=*/false, Loc, 6805 [&](const DiagnoseIfAttr *DIA) { 6806 bool Result; 6807 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6808 Result; 6809 }); 6810 } 6811 6812 /// Add all of the function declarations in the given function set to 6813 /// the overload candidate set. 6814 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6815 ArrayRef<Expr *> Args, 6816 OverloadCandidateSet &CandidateSet, 6817 TemplateArgumentListInfo *ExplicitTemplateArgs, 6818 bool SuppressUserConversions, 6819 bool PartialOverloading, 6820 bool FirstArgumentIsBase) { 6821 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6822 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6823 ArrayRef<Expr *> FunctionArgs = Args; 6824 6825 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6826 FunctionDecl *FD = 6827 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6828 6829 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6830 QualType ObjectType; 6831 Expr::Classification ObjectClassification; 6832 if (Args.size() > 0) { 6833 if (Expr *E = Args[0]) { 6834 // Use the explicit base to restrict the lookup: 6835 ObjectType = E->getType(); 6836 // Pointers in the object arguments are implicitly dereferenced, so we 6837 // always classify them as l-values. 6838 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6839 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6840 else 6841 ObjectClassification = E->Classify(Context); 6842 } // .. else there is an implicit base. 6843 FunctionArgs = Args.slice(1); 6844 } 6845 if (FunTmpl) { 6846 AddMethodTemplateCandidate( 6847 FunTmpl, F.getPair(), 6848 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6849 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6850 FunctionArgs, CandidateSet, SuppressUserConversions, 6851 PartialOverloading); 6852 } else { 6853 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6854 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6855 ObjectClassification, FunctionArgs, CandidateSet, 6856 SuppressUserConversions, PartialOverloading); 6857 } 6858 } else { 6859 // This branch handles both standalone functions and static methods. 6860 6861 // Slice the first argument (which is the base) when we access 6862 // static method as non-static. 6863 if (Args.size() > 0 && 6864 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6865 !isa<CXXConstructorDecl>(FD)))) { 6866 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6867 FunctionArgs = Args.slice(1); 6868 } 6869 if (FunTmpl) { 6870 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6871 ExplicitTemplateArgs, FunctionArgs, 6872 CandidateSet, SuppressUserConversions, 6873 PartialOverloading); 6874 } else { 6875 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6876 SuppressUserConversions, PartialOverloading); 6877 } 6878 } 6879 } 6880 } 6881 6882 /// AddMethodCandidate - Adds a named decl (which is some kind of 6883 /// method) as a method candidate to the given overload set. 6884 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6885 Expr::Classification ObjectClassification, 6886 ArrayRef<Expr *> Args, 6887 OverloadCandidateSet &CandidateSet, 6888 bool SuppressUserConversions, 6889 OverloadCandidateParamOrder PO) { 6890 NamedDecl *Decl = FoundDecl.getDecl(); 6891 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6892 6893 if (isa<UsingShadowDecl>(Decl)) 6894 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6895 6896 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6897 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6898 "Expected a member function template"); 6899 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6900 /*ExplicitArgs*/ nullptr, ObjectType, 6901 ObjectClassification, Args, CandidateSet, 6902 SuppressUserConversions, false, PO); 6903 } else { 6904 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6905 ObjectType, ObjectClassification, Args, CandidateSet, 6906 SuppressUserConversions, false, None, PO); 6907 } 6908 } 6909 6910 /// AddMethodCandidate - Adds the given C++ member function to the set 6911 /// of candidate functions, using the given function call arguments 6912 /// and the object argument (@c Object). For example, in a call 6913 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6914 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6915 /// allow user-defined conversions via constructors or conversion 6916 /// operators. 6917 void 6918 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6919 CXXRecordDecl *ActingContext, QualType ObjectType, 6920 Expr::Classification ObjectClassification, 6921 ArrayRef<Expr *> Args, 6922 OverloadCandidateSet &CandidateSet, 6923 bool SuppressUserConversions, 6924 bool PartialOverloading, 6925 ConversionSequenceList EarlyConversions, 6926 OverloadCandidateParamOrder PO) { 6927 const FunctionProtoType *Proto 6928 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6929 assert(Proto && "Methods without a prototype cannot be overloaded"); 6930 assert(!isa<CXXConstructorDecl>(Method) && 6931 "Use AddOverloadCandidate for constructors"); 6932 6933 if (!CandidateSet.isNewCandidate(Method, PO)) 6934 return; 6935 6936 // C++11 [class.copy]p23: [DR1402] 6937 // A defaulted move assignment operator that is defined as deleted is 6938 // ignored by overload resolution. 6939 if (Method->isDefaulted() && Method->isDeleted() && 6940 Method->isMoveAssignmentOperator()) 6941 return; 6942 6943 // Overload resolution is always an unevaluated context. 6944 EnterExpressionEvaluationContext Unevaluated( 6945 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6946 6947 // Add this candidate 6948 OverloadCandidate &Candidate = 6949 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6950 Candidate.FoundDecl = FoundDecl; 6951 Candidate.Function = Method; 6952 Candidate.RewriteKind = 6953 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6954 Candidate.IsSurrogate = false; 6955 Candidate.IgnoreObjectArgument = false; 6956 Candidate.ExplicitCallArguments = Args.size(); 6957 6958 unsigned NumParams = Proto->getNumParams(); 6959 6960 // (C++ 13.3.2p2): A candidate function having fewer than m 6961 // parameters is viable only if it has an ellipsis in its parameter 6962 // list (8.3.5). 6963 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6964 !Proto->isVariadic() && 6965 shouldEnforceArgLimit(PartialOverloading, Method)) { 6966 Candidate.Viable = false; 6967 Candidate.FailureKind = ovl_fail_too_many_arguments; 6968 return; 6969 } 6970 6971 // (C++ 13.3.2p2): A candidate function having more than m parameters 6972 // is viable only if the (m+1)st parameter has a default argument 6973 // (8.3.6). For the purposes of overload resolution, the 6974 // parameter list is truncated on the right, so that there are 6975 // exactly m parameters. 6976 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6977 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6978 // Not enough arguments. 6979 Candidate.Viable = false; 6980 Candidate.FailureKind = ovl_fail_too_few_arguments; 6981 return; 6982 } 6983 6984 Candidate.Viable = true; 6985 6986 if (Method->isStatic() || ObjectType.isNull()) 6987 // The implicit object argument is ignored. 6988 Candidate.IgnoreObjectArgument = true; 6989 else { 6990 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6991 // Determine the implicit conversion sequence for the object 6992 // parameter. 6993 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6994 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6995 Method, ActingContext); 6996 if (Candidate.Conversions[ConvIdx].isBad()) { 6997 Candidate.Viable = false; 6998 Candidate.FailureKind = ovl_fail_bad_conversion; 6999 return; 7000 } 7001 } 7002 7003 // (CUDA B.1): Check for invalid calls between targets. 7004 if (getLangOpts().CUDA) 7005 if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true)) 7006 if (!IsAllowedCUDACall(Caller, Method)) { 7007 Candidate.Viable = false; 7008 Candidate.FailureKind = ovl_fail_bad_target; 7009 return; 7010 } 7011 7012 if (Method->getTrailingRequiresClause()) { 7013 ConstraintSatisfaction Satisfaction; 7014 if (CheckFunctionConstraints(Method, Satisfaction) || 7015 !Satisfaction.IsSatisfied) { 7016 Candidate.Viable = false; 7017 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7018 return; 7019 } 7020 } 7021 7022 // Determine the implicit conversion sequences for each of the 7023 // arguments. 7024 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7025 unsigned ConvIdx = 7026 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7027 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7028 // We already formed a conversion sequence for this parameter during 7029 // template argument deduction. 7030 } else if (ArgIdx < NumParams) { 7031 // (C++ 13.3.2p3): for F to be a viable function, there shall 7032 // exist for each argument an implicit conversion sequence 7033 // (13.3.3.1) that converts that argument to the corresponding 7034 // parameter of F. 7035 QualType ParamType = Proto->getParamType(ArgIdx); 7036 Candidate.Conversions[ConvIdx] 7037 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7038 SuppressUserConversions, 7039 /*InOverloadResolution=*/true, 7040 /*AllowObjCWritebackConversion=*/ 7041 getLangOpts().ObjCAutoRefCount); 7042 if (Candidate.Conversions[ConvIdx].isBad()) { 7043 Candidate.Viable = false; 7044 Candidate.FailureKind = ovl_fail_bad_conversion; 7045 return; 7046 } 7047 } else { 7048 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7049 // argument for which there is no corresponding parameter is 7050 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7051 Candidate.Conversions[ConvIdx].setEllipsis(); 7052 } 7053 } 7054 7055 if (EnableIfAttr *FailedAttr = 7056 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7057 Candidate.Viable = false; 7058 Candidate.FailureKind = ovl_fail_enable_if; 7059 Candidate.DeductionFailure.Data = FailedAttr; 7060 return; 7061 } 7062 7063 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 7064 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 7065 Candidate.Viable = false; 7066 Candidate.FailureKind = ovl_non_default_multiversion_function; 7067 } 7068 } 7069 7070 /// Add a C++ member function template as a candidate to the candidate 7071 /// set, using template argument deduction to produce an appropriate member 7072 /// function template specialization. 7073 void Sema::AddMethodTemplateCandidate( 7074 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7075 CXXRecordDecl *ActingContext, 7076 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7077 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7078 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7079 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7080 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7081 return; 7082 7083 // C++ [over.match.funcs]p7: 7084 // In each case where a candidate is a function template, candidate 7085 // function template specializations are generated using template argument 7086 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7087 // candidate functions in the usual way.113) A given name can refer to one 7088 // or more function templates and also to a set of overloaded non-template 7089 // functions. In such a case, the candidate functions generated from each 7090 // function template are combined with the set of non-template candidate 7091 // functions. 7092 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7093 FunctionDecl *Specialization = nullptr; 7094 ConversionSequenceList Conversions; 7095 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7096 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7097 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7098 return CheckNonDependentConversions( 7099 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7100 SuppressUserConversions, ActingContext, ObjectType, 7101 ObjectClassification, PO); 7102 })) { 7103 OverloadCandidate &Candidate = 7104 CandidateSet.addCandidate(Conversions.size(), Conversions); 7105 Candidate.FoundDecl = FoundDecl; 7106 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7107 Candidate.Viable = false; 7108 Candidate.RewriteKind = 7109 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7110 Candidate.IsSurrogate = false; 7111 Candidate.IgnoreObjectArgument = 7112 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7113 ObjectType.isNull(); 7114 Candidate.ExplicitCallArguments = Args.size(); 7115 if (Result == TDK_NonDependentConversionFailure) 7116 Candidate.FailureKind = ovl_fail_bad_conversion; 7117 else { 7118 Candidate.FailureKind = ovl_fail_bad_deduction; 7119 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7120 Info); 7121 } 7122 return; 7123 } 7124 7125 // Add the function template specialization produced by template argument 7126 // deduction as a candidate. 7127 assert(Specialization && "Missing member function template specialization?"); 7128 assert(isa<CXXMethodDecl>(Specialization) && 7129 "Specialization is not a member function?"); 7130 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7131 ActingContext, ObjectType, ObjectClassification, Args, 7132 CandidateSet, SuppressUserConversions, PartialOverloading, 7133 Conversions, PO); 7134 } 7135 7136 /// Determine whether a given function template has a simple explicit specifier 7137 /// or a non-value-dependent explicit-specification that evaluates to true. 7138 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7139 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7140 } 7141 7142 /// Add a C++ function template specialization as a candidate 7143 /// in the candidate set, using template argument deduction to produce 7144 /// an appropriate function template specialization. 7145 void Sema::AddTemplateOverloadCandidate( 7146 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7147 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7148 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7149 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7150 OverloadCandidateParamOrder PO) { 7151 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7152 return; 7153 7154 // If the function template has a non-dependent explicit specification, 7155 // exclude it now if appropriate; we are not permitted to perform deduction 7156 // and substitution in this case. 7157 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7158 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7159 Candidate.FoundDecl = FoundDecl; 7160 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7161 Candidate.Viable = false; 7162 Candidate.FailureKind = ovl_fail_explicit; 7163 return; 7164 } 7165 7166 // C++ [over.match.funcs]p7: 7167 // In each case where a candidate is a function template, candidate 7168 // function template specializations are generated using template argument 7169 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7170 // candidate functions in the usual way.113) A given name can refer to one 7171 // or more function templates and also to a set of overloaded non-template 7172 // functions. In such a case, the candidate functions generated from each 7173 // function template are combined with the set of non-template candidate 7174 // functions. 7175 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7176 FunctionDecl *Specialization = nullptr; 7177 ConversionSequenceList Conversions; 7178 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7179 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7180 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7181 return CheckNonDependentConversions( 7182 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7183 SuppressUserConversions, nullptr, QualType(), {}, PO); 7184 })) { 7185 OverloadCandidate &Candidate = 7186 CandidateSet.addCandidate(Conversions.size(), Conversions); 7187 Candidate.FoundDecl = FoundDecl; 7188 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7189 Candidate.Viable = false; 7190 Candidate.RewriteKind = 7191 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7192 Candidate.IsSurrogate = false; 7193 Candidate.IsADLCandidate = IsADLCandidate; 7194 // Ignore the object argument if there is one, since we don't have an object 7195 // type. 7196 Candidate.IgnoreObjectArgument = 7197 isa<CXXMethodDecl>(Candidate.Function) && 7198 !isa<CXXConstructorDecl>(Candidate.Function); 7199 Candidate.ExplicitCallArguments = Args.size(); 7200 if (Result == TDK_NonDependentConversionFailure) 7201 Candidate.FailureKind = ovl_fail_bad_conversion; 7202 else { 7203 Candidate.FailureKind = ovl_fail_bad_deduction; 7204 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7205 Info); 7206 } 7207 return; 7208 } 7209 7210 // Add the function template specialization produced by template argument 7211 // deduction as a candidate. 7212 assert(Specialization && "Missing function template specialization?"); 7213 AddOverloadCandidate( 7214 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7215 PartialOverloading, AllowExplicit, 7216 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7217 } 7218 7219 /// Check that implicit conversion sequences can be formed for each argument 7220 /// whose corresponding parameter has a non-dependent type, per DR1391's 7221 /// [temp.deduct.call]p10. 7222 bool Sema::CheckNonDependentConversions( 7223 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7224 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7225 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7226 CXXRecordDecl *ActingContext, QualType ObjectType, 7227 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7228 // FIXME: The cases in which we allow explicit conversions for constructor 7229 // arguments never consider calling a constructor template. It's not clear 7230 // that is correct. 7231 const bool AllowExplicit = false; 7232 7233 auto *FD = FunctionTemplate->getTemplatedDecl(); 7234 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7235 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7236 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7237 7238 Conversions = 7239 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7240 7241 // Overload resolution is always an unevaluated context. 7242 EnterExpressionEvaluationContext Unevaluated( 7243 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7244 7245 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7246 // require that, but this check should never result in a hard error, and 7247 // overload resolution is permitted to sidestep instantiations. 7248 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7249 !ObjectType.isNull()) { 7250 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7251 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7252 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7253 Method, ActingContext); 7254 if (Conversions[ConvIdx].isBad()) 7255 return true; 7256 } 7257 7258 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7259 ++I) { 7260 QualType ParamType = ParamTypes[I]; 7261 if (!ParamType->isDependentType()) { 7262 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7263 ? 0 7264 : (ThisConversions + I); 7265 Conversions[ConvIdx] 7266 = TryCopyInitialization(*this, Args[I], ParamType, 7267 SuppressUserConversions, 7268 /*InOverloadResolution=*/true, 7269 /*AllowObjCWritebackConversion=*/ 7270 getLangOpts().ObjCAutoRefCount, 7271 AllowExplicit); 7272 if (Conversions[ConvIdx].isBad()) 7273 return true; 7274 } 7275 } 7276 7277 return false; 7278 } 7279 7280 /// Determine whether this is an allowable conversion from the result 7281 /// of an explicit conversion operator to the expected type, per C++ 7282 /// [over.match.conv]p1 and [over.match.ref]p1. 7283 /// 7284 /// \param ConvType The return type of the conversion function. 7285 /// 7286 /// \param ToType The type we are converting to. 7287 /// 7288 /// \param AllowObjCPointerConversion Allow a conversion from one 7289 /// Objective-C pointer to another. 7290 /// 7291 /// \returns true if the conversion is allowable, false otherwise. 7292 static bool isAllowableExplicitConversion(Sema &S, 7293 QualType ConvType, QualType ToType, 7294 bool AllowObjCPointerConversion) { 7295 QualType ToNonRefType = ToType.getNonReferenceType(); 7296 7297 // Easy case: the types are the same. 7298 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7299 return true; 7300 7301 // Allow qualification conversions. 7302 bool ObjCLifetimeConversion; 7303 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7304 ObjCLifetimeConversion)) 7305 return true; 7306 7307 // If we're not allowed to consider Objective-C pointer conversions, 7308 // we're done. 7309 if (!AllowObjCPointerConversion) 7310 return false; 7311 7312 // Is this an Objective-C pointer conversion? 7313 bool IncompatibleObjC = false; 7314 QualType ConvertedType; 7315 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7316 IncompatibleObjC); 7317 } 7318 7319 /// AddConversionCandidate - Add a C++ conversion function as a 7320 /// candidate in the candidate set (C++ [over.match.conv], 7321 /// C++ [over.match.copy]). From is the expression we're converting from, 7322 /// and ToType is the type that we're eventually trying to convert to 7323 /// (which may or may not be the same type as the type that the 7324 /// conversion function produces). 7325 void Sema::AddConversionCandidate( 7326 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7327 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7328 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7329 bool AllowExplicit, bool AllowResultConversion) { 7330 assert(!Conversion->getDescribedFunctionTemplate() && 7331 "Conversion function templates use AddTemplateConversionCandidate"); 7332 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7333 if (!CandidateSet.isNewCandidate(Conversion)) 7334 return; 7335 7336 // If the conversion function has an undeduced return type, trigger its 7337 // deduction now. 7338 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7339 if (DeduceReturnType(Conversion, From->getExprLoc())) 7340 return; 7341 ConvType = Conversion->getConversionType().getNonReferenceType(); 7342 } 7343 7344 // If we don't allow any conversion of the result type, ignore conversion 7345 // functions that don't convert to exactly (possibly cv-qualified) T. 7346 if (!AllowResultConversion && 7347 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7348 return; 7349 7350 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7351 // operator is only a candidate if its return type is the target type or 7352 // can be converted to the target type with a qualification conversion. 7353 // 7354 // FIXME: Include such functions in the candidate list and explain why we 7355 // can't select them. 7356 if (Conversion->isExplicit() && 7357 !isAllowableExplicitConversion(*this, ConvType, ToType, 7358 AllowObjCConversionOnExplicit)) 7359 return; 7360 7361 // Overload resolution is always an unevaluated context. 7362 EnterExpressionEvaluationContext Unevaluated( 7363 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7364 7365 // Add this candidate 7366 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7367 Candidate.FoundDecl = FoundDecl; 7368 Candidate.Function = Conversion; 7369 Candidate.IsSurrogate = false; 7370 Candidate.IgnoreObjectArgument = false; 7371 Candidate.FinalConversion.setAsIdentityConversion(); 7372 Candidate.FinalConversion.setFromType(ConvType); 7373 Candidate.FinalConversion.setAllToTypes(ToType); 7374 Candidate.Viable = true; 7375 Candidate.ExplicitCallArguments = 1; 7376 7377 // Explicit functions are not actually candidates at all if we're not 7378 // allowing them in this context, but keep them around so we can point 7379 // to them in diagnostics. 7380 if (!AllowExplicit && Conversion->isExplicit()) { 7381 Candidate.Viable = false; 7382 Candidate.FailureKind = ovl_fail_explicit; 7383 return; 7384 } 7385 7386 // C++ [over.match.funcs]p4: 7387 // For conversion functions, the function is considered to be a member of 7388 // the class of the implicit implied object argument for the purpose of 7389 // defining the type of the implicit object parameter. 7390 // 7391 // Determine the implicit conversion sequence for the implicit 7392 // object parameter. 7393 QualType ImplicitParamType = From->getType(); 7394 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7395 ImplicitParamType = FromPtrType->getPointeeType(); 7396 CXXRecordDecl *ConversionContext 7397 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7398 7399 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7400 *this, CandidateSet.getLocation(), From->getType(), 7401 From->Classify(Context), Conversion, ConversionContext); 7402 7403 if (Candidate.Conversions[0].isBad()) { 7404 Candidate.Viable = false; 7405 Candidate.FailureKind = ovl_fail_bad_conversion; 7406 return; 7407 } 7408 7409 if (Conversion->getTrailingRequiresClause()) { 7410 ConstraintSatisfaction Satisfaction; 7411 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7412 !Satisfaction.IsSatisfied) { 7413 Candidate.Viable = false; 7414 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7415 return; 7416 } 7417 } 7418 7419 // We won't go through a user-defined type conversion function to convert a 7420 // derived to base as such conversions are given Conversion Rank. They only 7421 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7422 QualType FromCanon 7423 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7424 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7425 if (FromCanon == ToCanon || 7426 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7427 Candidate.Viable = false; 7428 Candidate.FailureKind = ovl_fail_trivial_conversion; 7429 return; 7430 } 7431 7432 // To determine what the conversion from the result of calling the 7433 // conversion function to the type we're eventually trying to 7434 // convert to (ToType), we need to synthesize a call to the 7435 // conversion function and attempt copy initialization from it. This 7436 // makes sure that we get the right semantics with respect to 7437 // lvalues/rvalues and the type. Fortunately, we can allocate this 7438 // call on the stack and we don't need its arguments to be 7439 // well-formed. 7440 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7441 VK_LValue, From->getBeginLoc()); 7442 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7443 Context.getPointerType(Conversion->getType()), 7444 CK_FunctionToPointerDecay, &ConversionRef, 7445 VK_PRValue, FPOptionsOverride()); 7446 7447 QualType ConversionType = Conversion->getConversionType(); 7448 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7449 Candidate.Viable = false; 7450 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7451 return; 7452 } 7453 7454 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7455 7456 // Note that it is safe to allocate CallExpr on the stack here because 7457 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7458 // allocator). 7459 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7460 7461 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7462 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7463 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7464 7465 ImplicitConversionSequence ICS = 7466 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7467 /*SuppressUserConversions=*/true, 7468 /*InOverloadResolution=*/false, 7469 /*AllowObjCWritebackConversion=*/false); 7470 7471 switch (ICS.getKind()) { 7472 case ImplicitConversionSequence::StandardConversion: 7473 Candidate.FinalConversion = ICS.Standard; 7474 7475 // C++ [over.ics.user]p3: 7476 // If the user-defined conversion is specified by a specialization of a 7477 // conversion function template, the second standard conversion sequence 7478 // shall have exact match rank. 7479 if (Conversion->getPrimaryTemplate() && 7480 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7481 Candidate.Viable = false; 7482 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7483 return; 7484 } 7485 7486 // C++0x [dcl.init.ref]p5: 7487 // In the second case, if the reference is an rvalue reference and 7488 // the second standard conversion sequence of the user-defined 7489 // conversion sequence includes an lvalue-to-rvalue conversion, the 7490 // program is ill-formed. 7491 if (ToType->isRValueReferenceType() && 7492 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7493 Candidate.Viable = false; 7494 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7495 return; 7496 } 7497 break; 7498 7499 case ImplicitConversionSequence::BadConversion: 7500 Candidate.Viable = false; 7501 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7502 return; 7503 7504 default: 7505 llvm_unreachable( 7506 "Can only end up with a standard conversion sequence or failure"); 7507 } 7508 7509 if (EnableIfAttr *FailedAttr = 7510 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7511 Candidate.Viable = false; 7512 Candidate.FailureKind = ovl_fail_enable_if; 7513 Candidate.DeductionFailure.Data = FailedAttr; 7514 return; 7515 } 7516 7517 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7518 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7519 Candidate.Viable = false; 7520 Candidate.FailureKind = ovl_non_default_multiversion_function; 7521 } 7522 } 7523 7524 /// Adds a conversion function template specialization 7525 /// candidate to the overload set, using template argument deduction 7526 /// to deduce the template arguments of the conversion function 7527 /// template from the type that we are converting to (C++ 7528 /// [temp.deduct.conv]). 7529 void Sema::AddTemplateConversionCandidate( 7530 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7531 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7532 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7533 bool AllowExplicit, bool AllowResultConversion) { 7534 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7535 "Only conversion function templates permitted here"); 7536 7537 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7538 return; 7539 7540 // If the function template has a non-dependent explicit specification, 7541 // exclude it now if appropriate; we are not permitted to perform deduction 7542 // and substitution in this case. 7543 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7544 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7545 Candidate.FoundDecl = FoundDecl; 7546 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7547 Candidate.Viable = false; 7548 Candidate.FailureKind = ovl_fail_explicit; 7549 return; 7550 } 7551 7552 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7553 CXXConversionDecl *Specialization = nullptr; 7554 if (TemplateDeductionResult Result 7555 = DeduceTemplateArguments(FunctionTemplate, ToType, 7556 Specialization, Info)) { 7557 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7558 Candidate.FoundDecl = FoundDecl; 7559 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7560 Candidate.Viable = false; 7561 Candidate.FailureKind = ovl_fail_bad_deduction; 7562 Candidate.IsSurrogate = false; 7563 Candidate.IgnoreObjectArgument = false; 7564 Candidate.ExplicitCallArguments = 1; 7565 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7566 Info); 7567 return; 7568 } 7569 7570 // Add the conversion function template specialization produced by 7571 // template argument deduction as a candidate. 7572 assert(Specialization && "Missing function template specialization?"); 7573 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7574 CandidateSet, AllowObjCConversionOnExplicit, 7575 AllowExplicit, AllowResultConversion); 7576 } 7577 7578 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7579 /// converts the given @c Object to a function pointer via the 7580 /// conversion function @c Conversion, and then attempts to call it 7581 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7582 /// the type of function that we'll eventually be calling. 7583 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7584 DeclAccessPair FoundDecl, 7585 CXXRecordDecl *ActingContext, 7586 const FunctionProtoType *Proto, 7587 Expr *Object, 7588 ArrayRef<Expr *> Args, 7589 OverloadCandidateSet& CandidateSet) { 7590 if (!CandidateSet.isNewCandidate(Conversion)) 7591 return; 7592 7593 // Overload resolution is always an unevaluated context. 7594 EnterExpressionEvaluationContext Unevaluated( 7595 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7596 7597 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7598 Candidate.FoundDecl = FoundDecl; 7599 Candidate.Function = nullptr; 7600 Candidate.Surrogate = Conversion; 7601 Candidate.Viable = true; 7602 Candidate.IsSurrogate = true; 7603 Candidate.IgnoreObjectArgument = false; 7604 Candidate.ExplicitCallArguments = Args.size(); 7605 7606 // Determine the implicit conversion sequence for the implicit 7607 // object parameter. 7608 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7609 *this, CandidateSet.getLocation(), Object->getType(), 7610 Object->Classify(Context), Conversion, ActingContext); 7611 if (ObjectInit.isBad()) { 7612 Candidate.Viable = false; 7613 Candidate.FailureKind = ovl_fail_bad_conversion; 7614 Candidate.Conversions[0] = ObjectInit; 7615 return; 7616 } 7617 7618 // The first conversion is actually a user-defined conversion whose 7619 // first conversion is ObjectInit's standard conversion (which is 7620 // effectively a reference binding). Record it as such. 7621 Candidate.Conversions[0].setUserDefined(); 7622 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7623 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7624 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7625 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7626 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7627 Candidate.Conversions[0].UserDefined.After 7628 = Candidate.Conversions[0].UserDefined.Before; 7629 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7630 7631 // Find the 7632 unsigned NumParams = Proto->getNumParams(); 7633 7634 // (C++ 13.3.2p2): A candidate function having fewer than m 7635 // parameters is viable only if it has an ellipsis in its parameter 7636 // list (8.3.5). 7637 if (Args.size() > NumParams && !Proto->isVariadic()) { 7638 Candidate.Viable = false; 7639 Candidate.FailureKind = ovl_fail_too_many_arguments; 7640 return; 7641 } 7642 7643 // Function types don't have any default arguments, so just check if 7644 // we have enough arguments. 7645 if (Args.size() < NumParams) { 7646 // Not enough arguments. 7647 Candidate.Viable = false; 7648 Candidate.FailureKind = ovl_fail_too_few_arguments; 7649 return; 7650 } 7651 7652 // Determine the implicit conversion sequences for each of the 7653 // arguments. 7654 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7655 if (ArgIdx < NumParams) { 7656 // (C++ 13.3.2p3): for F to be a viable function, there shall 7657 // exist for each argument an implicit conversion sequence 7658 // (13.3.3.1) that converts that argument to the corresponding 7659 // parameter of F. 7660 QualType ParamType = Proto->getParamType(ArgIdx); 7661 Candidate.Conversions[ArgIdx + 1] 7662 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7663 /*SuppressUserConversions=*/false, 7664 /*InOverloadResolution=*/false, 7665 /*AllowObjCWritebackConversion=*/ 7666 getLangOpts().ObjCAutoRefCount); 7667 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7668 Candidate.Viable = false; 7669 Candidate.FailureKind = ovl_fail_bad_conversion; 7670 return; 7671 } 7672 } else { 7673 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7674 // argument for which there is no corresponding parameter is 7675 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7676 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7677 } 7678 } 7679 7680 if (EnableIfAttr *FailedAttr = 7681 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7682 Candidate.Viable = false; 7683 Candidate.FailureKind = ovl_fail_enable_if; 7684 Candidate.DeductionFailure.Data = FailedAttr; 7685 return; 7686 } 7687 } 7688 7689 /// Add all of the non-member operator function declarations in the given 7690 /// function set to the overload candidate set. 7691 void Sema::AddNonMemberOperatorCandidates( 7692 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7693 OverloadCandidateSet &CandidateSet, 7694 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7695 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7696 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7697 ArrayRef<Expr *> FunctionArgs = Args; 7698 7699 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7700 FunctionDecl *FD = 7701 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7702 7703 // Don't consider rewritten functions if we're not rewriting. 7704 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7705 continue; 7706 7707 assert(!isa<CXXMethodDecl>(FD) && 7708 "unqualified operator lookup found a member function"); 7709 7710 if (FunTmpl) { 7711 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7712 FunctionArgs, CandidateSet); 7713 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7714 AddTemplateOverloadCandidate( 7715 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7716 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7717 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7718 } else { 7719 if (ExplicitTemplateArgs) 7720 continue; 7721 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7722 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7723 AddOverloadCandidate(FD, F.getPair(), 7724 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7725 false, false, true, false, ADLCallKind::NotADL, 7726 None, OverloadCandidateParamOrder::Reversed); 7727 } 7728 } 7729 } 7730 7731 /// Add overload candidates for overloaded operators that are 7732 /// member functions. 7733 /// 7734 /// Add the overloaded operator candidates that are member functions 7735 /// for the operator Op that was used in an operator expression such 7736 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7737 /// CandidateSet will store the added overload candidates. (C++ 7738 /// [over.match.oper]). 7739 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7740 SourceLocation OpLoc, 7741 ArrayRef<Expr *> Args, 7742 OverloadCandidateSet &CandidateSet, 7743 OverloadCandidateParamOrder PO) { 7744 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7745 7746 // C++ [over.match.oper]p3: 7747 // For a unary operator @ with an operand of a type whose 7748 // cv-unqualified version is T1, and for a binary operator @ with 7749 // a left operand of a type whose cv-unqualified version is T1 and 7750 // a right operand of a type whose cv-unqualified version is T2, 7751 // three sets of candidate functions, designated member 7752 // candidates, non-member candidates and built-in candidates, are 7753 // constructed as follows: 7754 QualType T1 = Args[0]->getType(); 7755 7756 // -- If T1 is a complete class type or a class currently being 7757 // defined, the set of member candidates is the result of the 7758 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7759 // the set of member candidates is empty. 7760 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7761 // Complete the type if it can be completed. 7762 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7763 return; 7764 // If the type is neither complete nor being defined, bail out now. 7765 if (!T1Rec->getDecl()->getDefinition()) 7766 return; 7767 7768 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7769 LookupQualifiedName(Operators, T1Rec->getDecl()); 7770 Operators.suppressDiagnostics(); 7771 7772 for (LookupResult::iterator Oper = Operators.begin(), 7773 OperEnd = Operators.end(); 7774 Oper != OperEnd; 7775 ++Oper) 7776 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7777 Args[0]->Classify(Context), Args.slice(1), 7778 CandidateSet, /*SuppressUserConversion=*/false, PO); 7779 } 7780 } 7781 7782 /// AddBuiltinCandidate - Add a candidate for a built-in 7783 /// operator. ResultTy and ParamTys are the result and parameter types 7784 /// of the built-in candidate, respectively. Args and NumArgs are the 7785 /// arguments being passed to the candidate. IsAssignmentOperator 7786 /// should be true when this built-in candidate is an assignment 7787 /// operator. NumContextualBoolArguments is the number of arguments 7788 /// (at the beginning of the argument list) that will be contextually 7789 /// converted to bool. 7790 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7791 OverloadCandidateSet& CandidateSet, 7792 bool IsAssignmentOperator, 7793 unsigned NumContextualBoolArguments) { 7794 // Overload resolution is always an unevaluated context. 7795 EnterExpressionEvaluationContext Unevaluated( 7796 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7797 7798 // Add this candidate 7799 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7800 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7801 Candidate.Function = nullptr; 7802 Candidate.IsSurrogate = false; 7803 Candidate.IgnoreObjectArgument = false; 7804 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7805 7806 // Determine the implicit conversion sequences for each of the 7807 // arguments. 7808 Candidate.Viable = true; 7809 Candidate.ExplicitCallArguments = Args.size(); 7810 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7811 // C++ [over.match.oper]p4: 7812 // For the built-in assignment operators, conversions of the 7813 // left operand are restricted as follows: 7814 // -- no temporaries are introduced to hold the left operand, and 7815 // -- no user-defined conversions are applied to the left 7816 // operand to achieve a type match with the left-most 7817 // parameter of a built-in candidate. 7818 // 7819 // We block these conversions by turning off user-defined 7820 // conversions, since that is the only way that initialization of 7821 // a reference to a non-class type can occur from something that 7822 // is not of the same type. 7823 if (ArgIdx < NumContextualBoolArguments) { 7824 assert(ParamTys[ArgIdx] == Context.BoolTy && 7825 "Contextual conversion to bool requires bool type"); 7826 Candidate.Conversions[ArgIdx] 7827 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7828 } else { 7829 Candidate.Conversions[ArgIdx] 7830 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7831 ArgIdx == 0 && IsAssignmentOperator, 7832 /*InOverloadResolution=*/false, 7833 /*AllowObjCWritebackConversion=*/ 7834 getLangOpts().ObjCAutoRefCount); 7835 } 7836 if (Candidate.Conversions[ArgIdx].isBad()) { 7837 Candidate.Viable = false; 7838 Candidate.FailureKind = ovl_fail_bad_conversion; 7839 break; 7840 } 7841 } 7842 } 7843 7844 namespace { 7845 7846 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7847 /// candidate operator functions for built-in operators (C++ 7848 /// [over.built]). The types are separated into pointer types and 7849 /// enumeration types. 7850 class BuiltinCandidateTypeSet { 7851 /// TypeSet - A set of types. 7852 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7853 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7854 7855 /// PointerTypes - The set of pointer types that will be used in the 7856 /// built-in candidates. 7857 TypeSet PointerTypes; 7858 7859 /// MemberPointerTypes - The set of member pointer types that will be 7860 /// used in the built-in candidates. 7861 TypeSet MemberPointerTypes; 7862 7863 /// EnumerationTypes - The set of enumeration types that will be 7864 /// used in the built-in candidates. 7865 TypeSet EnumerationTypes; 7866 7867 /// The set of vector types that will be used in the built-in 7868 /// candidates. 7869 TypeSet VectorTypes; 7870 7871 /// The set of matrix types that will be used in the built-in 7872 /// candidates. 7873 TypeSet MatrixTypes; 7874 7875 /// A flag indicating non-record types are viable candidates 7876 bool HasNonRecordTypes; 7877 7878 /// A flag indicating whether either arithmetic or enumeration types 7879 /// were present in the candidate set. 7880 bool HasArithmeticOrEnumeralTypes; 7881 7882 /// A flag indicating whether the nullptr type was present in the 7883 /// candidate set. 7884 bool HasNullPtrType; 7885 7886 /// Sema - The semantic analysis instance where we are building the 7887 /// candidate type set. 7888 Sema &SemaRef; 7889 7890 /// Context - The AST context in which we will build the type sets. 7891 ASTContext &Context; 7892 7893 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7894 const Qualifiers &VisibleQuals); 7895 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7896 7897 public: 7898 /// iterator - Iterates through the types that are part of the set. 7899 typedef TypeSet::iterator iterator; 7900 7901 BuiltinCandidateTypeSet(Sema &SemaRef) 7902 : HasNonRecordTypes(false), 7903 HasArithmeticOrEnumeralTypes(false), 7904 HasNullPtrType(false), 7905 SemaRef(SemaRef), 7906 Context(SemaRef.Context) { } 7907 7908 void AddTypesConvertedFrom(QualType Ty, 7909 SourceLocation Loc, 7910 bool AllowUserConversions, 7911 bool AllowExplicitConversions, 7912 const Qualifiers &VisibleTypeConversionsQuals); 7913 7914 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7915 llvm::iterator_range<iterator> member_pointer_types() { 7916 return MemberPointerTypes; 7917 } 7918 llvm::iterator_range<iterator> enumeration_types() { 7919 return EnumerationTypes; 7920 } 7921 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7922 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7923 7924 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7925 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7926 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7927 bool hasNullPtrType() const { return HasNullPtrType; } 7928 }; 7929 7930 } // end anonymous namespace 7931 7932 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7933 /// the set of pointer types along with any more-qualified variants of 7934 /// that type. For example, if @p Ty is "int const *", this routine 7935 /// will add "int const *", "int const volatile *", "int const 7936 /// restrict *", and "int const volatile restrict *" to the set of 7937 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7938 /// false otherwise. 7939 /// 7940 /// FIXME: what to do about extended qualifiers? 7941 bool 7942 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7943 const Qualifiers &VisibleQuals) { 7944 7945 // Insert this type. 7946 if (!PointerTypes.insert(Ty)) 7947 return false; 7948 7949 QualType PointeeTy; 7950 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7951 bool buildObjCPtr = false; 7952 if (!PointerTy) { 7953 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7954 PointeeTy = PTy->getPointeeType(); 7955 buildObjCPtr = true; 7956 } else { 7957 PointeeTy = PointerTy->getPointeeType(); 7958 } 7959 7960 // Don't add qualified variants of arrays. For one, they're not allowed 7961 // (the qualifier would sink to the element type), and for another, the 7962 // only overload situation where it matters is subscript or pointer +- int, 7963 // and those shouldn't have qualifier variants anyway. 7964 if (PointeeTy->isArrayType()) 7965 return true; 7966 7967 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7968 bool hasVolatile = VisibleQuals.hasVolatile(); 7969 bool hasRestrict = VisibleQuals.hasRestrict(); 7970 7971 // Iterate through all strict supersets of BaseCVR. 7972 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7973 if ((CVR | BaseCVR) != CVR) continue; 7974 // Skip over volatile if no volatile found anywhere in the types. 7975 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7976 7977 // Skip over restrict if no restrict found anywhere in the types, or if 7978 // the type cannot be restrict-qualified. 7979 if ((CVR & Qualifiers::Restrict) && 7980 (!hasRestrict || 7981 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7982 continue; 7983 7984 // Build qualified pointee type. 7985 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7986 7987 // Build qualified pointer type. 7988 QualType QPointerTy; 7989 if (!buildObjCPtr) 7990 QPointerTy = Context.getPointerType(QPointeeTy); 7991 else 7992 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7993 7994 // Insert qualified pointer type. 7995 PointerTypes.insert(QPointerTy); 7996 } 7997 7998 return true; 7999 } 8000 8001 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 8002 /// to the set of pointer types along with any more-qualified variants of 8003 /// that type. For example, if @p Ty is "int const *", this routine 8004 /// will add "int const *", "int const volatile *", "int const 8005 /// restrict *", and "int const volatile restrict *" to the set of 8006 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8007 /// false otherwise. 8008 /// 8009 /// FIXME: what to do about extended qualifiers? 8010 bool 8011 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 8012 QualType Ty) { 8013 // Insert this type. 8014 if (!MemberPointerTypes.insert(Ty)) 8015 return false; 8016 8017 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8018 assert(PointerTy && "type was not a member pointer type!"); 8019 8020 QualType PointeeTy = PointerTy->getPointeeType(); 8021 // Don't add qualified variants of arrays. For one, they're not allowed 8022 // (the qualifier would sink to the element type), and for another, the 8023 // only overload situation where it matters is subscript or pointer +- int, 8024 // and those shouldn't have qualifier variants anyway. 8025 if (PointeeTy->isArrayType()) 8026 return true; 8027 const Type *ClassTy = PointerTy->getClass(); 8028 8029 // Iterate through all strict supersets of the pointee type's CVR 8030 // qualifiers. 8031 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8032 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8033 if ((CVR | BaseCVR) != CVR) continue; 8034 8035 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8036 MemberPointerTypes.insert( 8037 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8038 } 8039 8040 return true; 8041 } 8042 8043 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8044 /// Ty can be implicit converted to the given set of @p Types. We're 8045 /// primarily interested in pointer types and enumeration types. We also 8046 /// take member pointer types, for the conditional operator. 8047 /// AllowUserConversions is true if we should look at the conversion 8048 /// functions of a class type, and AllowExplicitConversions if we 8049 /// should also include the explicit conversion functions of a class 8050 /// type. 8051 void 8052 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8053 SourceLocation Loc, 8054 bool AllowUserConversions, 8055 bool AllowExplicitConversions, 8056 const Qualifiers &VisibleQuals) { 8057 // Only deal with canonical types. 8058 Ty = Context.getCanonicalType(Ty); 8059 8060 // Look through reference types; they aren't part of the type of an 8061 // expression for the purposes of conversions. 8062 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8063 Ty = RefTy->getPointeeType(); 8064 8065 // If we're dealing with an array type, decay to the pointer. 8066 if (Ty->isArrayType()) 8067 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8068 8069 // Otherwise, we don't care about qualifiers on the type. 8070 Ty = Ty.getLocalUnqualifiedType(); 8071 8072 // Flag if we ever add a non-record type. 8073 const RecordType *TyRec = Ty->getAs<RecordType>(); 8074 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8075 8076 // Flag if we encounter an arithmetic type. 8077 HasArithmeticOrEnumeralTypes = 8078 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8079 8080 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8081 PointerTypes.insert(Ty); 8082 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8083 // Insert our type, and its more-qualified variants, into the set 8084 // of types. 8085 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8086 return; 8087 } else if (Ty->isMemberPointerType()) { 8088 // Member pointers are far easier, since the pointee can't be converted. 8089 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8090 return; 8091 } else if (Ty->isEnumeralType()) { 8092 HasArithmeticOrEnumeralTypes = true; 8093 EnumerationTypes.insert(Ty); 8094 } else if (Ty->isVectorType()) { 8095 // We treat vector types as arithmetic types in many contexts as an 8096 // extension. 8097 HasArithmeticOrEnumeralTypes = true; 8098 VectorTypes.insert(Ty); 8099 } else if (Ty->isMatrixType()) { 8100 // Similar to vector types, we treat vector types as arithmetic types in 8101 // many contexts as an extension. 8102 HasArithmeticOrEnumeralTypes = true; 8103 MatrixTypes.insert(Ty); 8104 } else if (Ty->isNullPtrType()) { 8105 HasNullPtrType = true; 8106 } else if (AllowUserConversions && TyRec) { 8107 // No conversion functions in incomplete types. 8108 if (!SemaRef.isCompleteType(Loc, Ty)) 8109 return; 8110 8111 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8112 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8113 if (isa<UsingShadowDecl>(D)) 8114 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8115 8116 // Skip conversion function templates; they don't tell us anything 8117 // about which builtin types we can convert to. 8118 if (isa<FunctionTemplateDecl>(D)) 8119 continue; 8120 8121 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8122 if (AllowExplicitConversions || !Conv->isExplicit()) { 8123 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8124 VisibleQuals); 8125 } 8126 } 8127 } 8128 } 8129 /// Helper function for adjusting address spaces for the pointer or reference 8130 /// operands of builtin operators depending on the argument. 8131 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8132 Expr *Arg) { 8133 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8134 } 8135 8136 /// Helper function for AddBuiltinOperatorCandidates() that adds 8137 /// the volatile- and non-volatile-qualified assignment operators for the 8138 /// given type to the candidate set. 8139 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8140 QualType T, 8141 ArrayRef<Expr *> Args, 8142 OverloadCandidateSet &CandidateSet) { 8143 QualType ParamTypes[2]; 8144 8145 // T& operator=(T&, T) 8146 ParamTypes[0] = S.Context.getLValueReferenceType( 8147 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8148 ParamTypes[1] = T; 8149 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8150 /*IsAssignmentOperator=*/true); 8151 8152 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8153 // volatile T& operator=(volatile T&, T) 8154 ParamTypes[0] = S.Context.getLValueReferenceType( 8155 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8156 Args[0])); 8157 ParamTypes[1] = T; 8158 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8159 /*IsAssignmentOperator=*/true); 8160 } 8161 } 8162 8163 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8164 /// if any, found in visible type conversion functions found in ArgExpr's type. 8165 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8166 Qualifiers VRQuals; 8167 const RecordType *TyRec; 8168 if (const MemberPointerType *RHSMPType = 8169 ArgExpr->getType()->getAs<MemberPointerType>()) 8170 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8171 else 8172 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8173 if (!TyRec) { 8174 // Just to be safe, assume the worst case. 8175 VRQuals.addVolatile(); 8176 VRQuals.addRestrict(); 8177 return VRQuals; 8178 } 8179 8180 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8181 if (!ClassDecl->hasDefinition()) 8182 return VRQuals; 8183 8184 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8185 if (isa<UsingShadowDecl>(D)) 8186 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8187 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8188 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8189 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8190 CanTy = ResTypeRef->getPointeeType(); 8191 // Need to go down the pointer/mempointer chain and add qualifiers 8192 // as see them. 8193 bool done = false; 8194 while (!done) { 8195 if (CanTy.isRestrictQualified()) 8196 VRQuals.addRestrict(); 8197 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8198 CanTy = ResTypePtr->getPointeeType(); 8199 else if (const MemberPointerType *ResTypeMPtr = 8200 CanTy->getAs<MemberPointerType>()) 8201 CanTy = ResTypeMPtr->getPointeeType(); 8202 else 8203 done = true; 8204 if (CanTy.isVolatileQualified()) 8205 VRQuals.addVolatile(); 8206 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8207 return VRQuals; 8208 } 8209 } 8210 } 8211 return VRQuals; 8212 } 8213 8214 // Note: We're currently only handling qualifiers that are meaningful for the 8215 // LHS of compound assignment overloading. 8216 static void forAllQualifierCombinationsImpl( 8217 QualifiersAndAtomic Available, QualifiersAndAtomic Applied, 8218 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8219 // _Atomic 8220 if (Available.hasAtomic()) { 8221 Available.removeAtomic(); 8222 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); 8223 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8224 return; 8225 } 8226 8227 // volatile 8228 if (Available.hasVolatile()) { 8229 Available.removeVolatile(); 8230 assert(!Applied.hasVolatile()); 8231 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), 8232 Callback); 8233 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8234 return; 8235 } 8236 8237 Callback(Applied); 8238 } 8239 8240 static void forAllQualifierCombinations( 8241 QualifiersAndAtomic Quals, 8242 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8243 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), 8244 Callback); 8245 } 8246 8247 static QualType makeQualifiedLValueReferenceType(QualType Base, 8248 QualifiersAndAtomic Quals, 8249 Sema &S) { 8250 if (Quals.hasAtomic()) 8251 Base = S.Context.getAtomicType(Base); 8252 if (Quals.hasVolatile()) 8253 Base = S.Context.getVolatileType(Base); 8254 return S.Context.getLValueReferenceType(Base); 8255 } 8256 8257 namespace { 8258 8259 /// Helper class to manage the addition of builtin operator overload 8260 /// candidates. It provides shared state and utility methods used throughout 8261 /// the process, as well as a helper method to add each group of builtin 8262 /// operator overloads from the standard to a candidate set. 8263 class BuiltinOperatorOverloadBuilder { 8264 // Common instance state available to all overload candidate addition methods. 8265 Sema &S; 8266 ArrayRef<Expr *> Args; 8267 QualifiersAndAtomic VisibleTypeConversionsQuals; 8268 bool HasArithmeticOrEnumeralCandidateType; 8269 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8270 OverloadCandidateSet &CandidateSet; 8271 8272 static constexpr int ArithmeticTypesCap = 24; 8273 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8274 8275 // Define some indices used to iterate over the arithmetic types in 8276 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8277 // types are that preserved by promotion (C++ [over.built]p2). 8278 unsigned FirstIntegralType, 8279 LastIntegralType; 8280 unsigned FirstPromotedIntegralType, 8281 LastPromotedIntegralType; 8282 unsigned FirstPromotedArithmeticType, 8283 LastPromotedArithmeticType; 8284 unsigned NumArithmeticTypes; 8285 8286 void InitArithmeticTypes() { 8287 // Start of promoted types. 8288 FirstPromotedArithmeticType = 0; 8289 ArithmeticTypes.push_back(S.Context.FloatTy); 8290 ArithmeticTypes.push_back(S.Context.DoubleTy); 8291 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8292 if (S.Context.getTargetInfo().hasFloat128Type()) 8293 ArithmeticTypes.push_back(S.Context.Float128Ty); 8294 if (S.Context.getTargetInfo().hasIbm128Type()) 8295 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8296 8297 // Start of integral types. 8298 FirstIntegralType = ArithmeticTypes.size(); 8299 FirstPromotedIntegralType = ArithmeticTypes.size(); 8300 ArithmeticTypes.push_back(S.Context.IntTy); 8301 ArithmeticTypes.push_back(S.Context.LongTy); 8302 ArithmeticTypes.push_back(S.Context.LongLongTy); 8303 if (S.Context.getTargetInfo().hasInt128Type() || 8304 (S.Context.getAuxTargetInfo() && 8305 S.Context.getAuxTargetInfo()->hasInt128Type())) 8306 ArithmeticTypes.push_back(S.Context.Int128Ty); 8307 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8308 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8309 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8310 if (S.Context.getTargetInfo().hasInt128Type() || 8311 (S.Context.getAuxTargetInfo() && 8312 S.Context.getAuxTargetInfo()->hasInt128Type())) 8313 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8314 LastPromotedIntegralType = ArithmeticTypes.size(); 8315 LastPromotedArithmeticType = ArithmeticTypes.size(); 8316 // End of promoted types. 8317 8318 ArithmeticTypes.push_back(S.Context.BoolTy); 8319 ArithmeticTypes.push_back(S.Context.CharTy); 8320 ArithmeticTypes.push_back(S.Context.WCharTy); 8321 if (S.Context.getLangOpts().Char8) 8322 ArithmeticTypes.push_back(S.Context.Char8Ty); 8323 ArithmeticTypes.push_back(S.Context.Char16Ty); 8324 ArithmeticTypes.push_back(S.Context.Char32Ty); 8325 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8326 ArithmeticTypes.push_back(S.Context.ShortTy); 8327 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8328 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8329 LastIntegralType = ArithmeticTypes.size(); 8330 NumArithmeticTypes = ArithmeticTypes.size(); 8331 // End of integral types. 8332 // FIXME: What about complex? What about half? 8333 8334 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8335 "Enough inline storage for all arithmetic types."); 8336 } 8337 8338 /// Helper method to factor out the common pattern of adding overloads 8339 /// for '++' and '--' builtin operators. 8340 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8341 bool HasVolatile, 8342 bool HasRestrict) { 8343 QualType ParamTypes[2] = { 8344 S.Context.getLValueReferenceType(CandidateTy), 8345 S.Context.IntTy 8346 }; 8347 8348 // Non-volatile version. 8349 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8350 8351 // Use a heuristic to reduce number of builtin candidates in the set: 8352 // add volatile version only if there are conversions to a volatile type. 8353 if (HasVolatile) { 8354 ParamTypes[0] = 8355 S.Context.getLValueReferenceType( 8356 S.Context.getVolatileType(CandidateTy)); 8357 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8358 } 8359 8360 // Add restrict version only if there are conversions to a restrict type 8361 // and our candidate type is a non-restrict-qualified pointer. 8362 if (HasRestrict && CandidateTy->isAnyPointerType() && 8363 !CandidateTy.isRestrictQualified()) { 8364 ParamTypes[0] 8365 = S.Context.getLValueReferenceType( 8366 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8367 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8368 8369 if (HasVolatile) { 8370 ParamTypes[0] 8371 = S.Context.getLValueReferenceType( 8372 S.Context.getCVRQualifiedType(CandidateTy, 8373 (Qualifiers::Volatile | 8374 Qualifiers::Restrict))); 8375 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8376 } 8377 } 8378 8379 } 8380 8381 /// Helper to add an overload candidate for a binary builtin with types \p L 8382 /// and \p R. 8383 void AddCandidate(QualType L, QualType R) { 8384 QualType LandR[2] = {L, R}; 8385 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8386 } 8387 8388 public: 8389 BuiltinOperatorOverloadBuilder( 8390 Sema &S, ArrayRef<Expr *> Args, 8391 QualifiersAndAtomic VisibleTypeConversionsQuals, 8392 bool HasArithmeticOrEnumeralCandidateType, 8393 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8394 OverloadCandidateSet &CandidateSet) 8395 : S(S), Args(Args), 8396 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8397 HasArithmeticOrEnumeralCandidateType( 8398 HasArithmeticOrEnumeralCandidateType), 8399 CandidateTypes(CandidateTypes), 8400 CandidateSet(CandidateSet) { 8401 8402 InitArithmeticTypes(); 8403 } 8404 8405 // Increment is deprecated for bool since C++17. 8406 // 8407 // C++ [over.built]p3: 8408 // 8409 // For every pair (T, VQ), where T is an arithmetic type other 8410 // than bool, and VQ is either volatile or empty, there exist 8411 // candidate operator functions of the form 8412 // 8413 // VQ T& operator++(VQ T&); 8414 // T operator++(VQ T&, int); 8415 // 8416 // C++ [over.built]p4: 8417 // 8418 // For every pair (T, VQ), where T is an arithmetic type other 8419 // than bool, and VQ is either volatile or empty, there exist 8420 // candidate operator functions of the form 8421 // 8422 // VQ T& operator--(VQ T&); 8423 // T operator--(VQ T&, int); 8424 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8425 if (!HasArithmeticOrEnumeralCandidateType) 8426 return; 8427 8428 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8429 const auto TypeOfT = ArithmeticTypes[Arith]; 8430 if (TypeOfT == S.Context.BoolTy) { 8431 if (Op == OO_MinusMinus) 8432 continue; 8433 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8434 continue; 8435 } 8436 addPlusPlusMinusMinusStyleOverloads( 8437 TypeOfT, 8438 VisibleTypeConversionsQuals.hasVolatile(), 8439 VisibleTypeConversionsQuals.hasRestrict()); 8440 } 8441 } 8442 8443 // C++ [over.built]p5: 8444 // 8445 // For every pair (T, VQ), where T is a cv-qualified or 8446 // cv-unqualified object type, and VQ is either volatile or 8447 // empty, there exist candidate operator functions of the form 8448 // 8449 // T*VQ& operator++(T*VQ&); 8450 // T*VQ& operator--(T*VQ&); 8451 // T* operator++(T*VQ&, int); 8452 // T* operator--(T*VQ&, int); 8453 void addPlusPlusMinusMinusPointerOverloads() { 8454 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8455 // Skip pointer types that aren't pointers to object types. 8456 if (!PtrTy->getPointeeType()->isObjectType()) 8457 continue; 8458 8459 addPlusPlusMinusMinusStyleOverloads( 8460 PtrTy, 8461 (!PtrTy.isVolatileQualified() && 8462 VisibleTypeConversionsQuals.hasVolatile()), 8463 (!PtrTy.isRestrictQualified() && 8464 VisibleTypeConversionsQuals.hasRestrict())); 8465 } 8466 } 8467 8468 // C++ [over.built]p6: 8469 // For every cv-qualified or cv-unqualified object type T, there 8470 // exist candidate operator functions of the form 8471 // 8472 // T& operator*(T*); 8473 // 8474 // C++ [over.built]p7: 8475 // For every function type T that does not have cv-qualifiers or a 8476 // ref-qualifier, there exist candidate operator functions of the form 8477 // T& operator*(T*); 8478 void addUnaryStarPointerOverloads() { 8479 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8480 QualType PointeeTy = ParamTy->getPointeeType(); 8481 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8482 continue; 8483 8484 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8485 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8486 continue; 8487 8488 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8489 } 8490 } 8491 8492 // C++ [over.built]p9: 8493 // For every promoted arithmetic type T, there exist candidate 8494 // operator functions of the form 8495 // 8496 // T operator+(T); 8497 // T operator-(T); 8498 void addUnaryPlusOrMinusArithmeticOverloads() { 8499 if (!HasArithmeticOrEnumeralCandidateType) 8500 return; 8501 8502 for (unsigned Arith = FirstPromotedArithmeticType; 8503 Arith < LastPromotedArithmeticType; ++Arith) { 8504 QualType ArithTy = ArithmeticTypes[Arith]; 8505 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8506 } 8507 8508 // Extension: We also add these operators for vector types. 8509 for (QualType VecTy : CandidateTypes[0].vector_types()) 8510 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8511 } 8512 8513 // C++ [over.built]p8: 8514 // For every type T, there exist candidate operator functions of 8515 // the form 8516 // 8517 // T* operator+(T*); 8518 void addUnaryPlusPointerOverloads() { 8519 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8520 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8521 } 8522 8523 // C++ [over.built]p10: 8524 // For every promoted integral type T, there exist candidate 8525 // operator functions of the form 8526 // 8527 // T operator~(T); 8528 void addUnaryTildePromotedIntegralOverloads() { 8529 if (!HasArithmeticOrEnumeralCandidateType) 8530 return; 8531 8532 for (unsigned Int = FirstPromotedIntegralType; 8533 Int < LastPromotedIntegralType; ++Int) { 8534 QualType IntTy = ArithmeticTypes[Int]; 8535 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8536 } 8537 8538 // Extension: We also add this operator for vector types. 8539 for (QualType VecTy : CandidateTypes[0].vector_types()) 8540 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8541 } 8542 8543 // C++ [over.match.oper]p16: 8544 // For every pointer to member type T or type std::nullptr_t, there 8545 // exist candidate operator functions of the form 8546 // 8547 // bool operator==(T,T); 8548 // bool operator!=(T,T); 8549 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8550 /// Set of (canonical) types that we've already handled. 8551 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8552 8553 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8554 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8555 // Don't add the same builtin candidate twice. 8556 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8557 continue; 8558 8559 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8560 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8561 } 8562 8563 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8564 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8565 if (AddedTypes.insert(NullPtrTy).second) { 8566 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8567 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8568 } 8569 } 8570 } 8571 } 8572 8573 // C++ [over.built]p15: 8574 // 8575 // For every T, where T is an enumeration type or a pointer type, 8576 // there exist candidate operator functions of the form 8577 // 8578 // bool operator<(T, T); 8579 // bool operator>(T, T); 8580 // bool operator<=(T, T); 8581 // bool operator>=(T, T); 8582 // bool operator==(T, T); 8583 // bool operator!=(T, T); 8584 // R operator<=>(T, T) 8585 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 8586 // C++ [over.match.oper]p3: 8587 // [...]the built-in candidates include all of the candidate operator 8588 // functions defined in 13.6 that, compared to the given operator, [...] 8589 // do not have the same parameter-type-list as any non-template non-member 8590 // candidate. 8591 // 8592 // Note that in practice, this only affects enumeration types because there 8593 // aren't any built-in candidates of record type, and a user-defined operator 8594 // must have an operand of record or enumeration type. Also, the only other 8595 // overloaded operator with enumeration arguments, operator=, 8596 // cannot be overloaded for enumeration types, so this is the only place 8597 // where we must suppress candidates like this. 8598 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8599 UserDefinedBinaryOperators; 8600 8601 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8602 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8603 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8604 CEnd = CandidateSet.end(); 8605 C != CEnd; ++C) { 8606 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8607 continue; 8608 8609 if (C->Function->isFunctionTemplateSpecialization()) 8610 continue; 8611 8612 // We interpret "same parameter-type-list" as applying to the 8613 // "synthesized candidate, with the order of the two parameters 8614 // reversed", not to the original function. 8615 bool Reversed = C->isReversed(); 8616 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8617 ->getType() 8618 .getUnqualifiedType(); 8619 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8620 ->getType() 8621 .getUnqualifiedType(); 8622 8623 // Skip if either parameter isn't of enumeral type. 8624 if (!FirstParamType->isEnumeralType() || 8625 !SecondParamType->isEnumeralType()) 8626 continue; 8627 8628 // Add this operator to the set of known user-defined operators. 8629 UserDefinedBinaryOperators.insert( 8630 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8631 S.Context.getCanonicalType(SecondParamType))); 8632 } 8633 } 8634 } 8635 8636 /// Set of (canonical) types that we've already handled. 8637 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8638 8639 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8640 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8641 // Don't add the same builtin candidate twice. 8642 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8643 continue; 8644 if (IsSpaceship && PtrTy->isFunctionPointerType()) 8645 continue; 8646 8647 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8648 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8649 } 8650 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8651 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8652 8653 // Don't add the same builtin candidate twice, or if a user defined 8654 // candidate exists. 8655 if (!AddedTypes.insert(CanonType).second || 8656 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8657 CanonType))) 8658 continue; 8659 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8660 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8661 } 8662 } 8663 } 8664 8665 // C++ [over.built]p13: 8666 // 8667 // For every cv-qualified or cv-unqualified object type T 8668 // there exist candidate operator functions of the form 8669 // 8670 // T* operator+(T*, ptrdiff_t); 8671 // T& operator[](T*, ptrdiff_t); [BELOW] 8672 // T* operator-(T*, ptrdiff_t); 8673 // T* operator+(ptrdiff_t, T*); 8674 // T& operator[](ptrdiff_t, T*); [BELOW] 8675 // 8676 // C++ [over.built]p14: 8677 // 8678 // For every T, where T is a pointer to object type, there 8679 // exist candidate operator functions of the form 8680 // 8681 // ptrdiff_t operator-(T, T); 8682 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8683 /// Set of (canonical) types that we've already handled. 8684 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8685 8686 for (int Arg = 0; Arg < 2; ++Arg) { 8687 QualType AsymmetricParamTypes[2] = { 8688 S.Context.getPointerDiffType(), 8689 S.Context.getPointerDiffType(), 8690 }; 8691 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8692 QualType PointeeTy = PtrTy->getPointeeType(); 8693 if (!PointeeTy->isObjectType()) 8694 continue; 8695 8696 AsymmetricParamTypes[Arg] = PtrTy; 8697 if (Arg == 0 || Op == OO_Plus) { 8698 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8699 // T* operator+(ptrdiff_t, T*); 8700 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8701 } 8702 if (Op == OO_Minus) { 8703 // ptrdiff_t operator-(T, T); 8704 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8705 continue; 8706 8707 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8708 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8709 } 8710 } 8711 } 8712 } 8713 8714 // C++ [over.built]p12: 8715 // 8716 // For every pair of promoted arithmetic types L and R, there 8717 // exist candidate operator functions of the form 8718 // 8719 // LR operator*(L, R); 8720 // LR operator/(L, R); 8721 // LR operator+(L, R); 8722 // LR operator-(L, R); 8723 // bool operator<(L, R); 8724 // bool operator>(L, R); 8725 // bool operator<=(L, R); 8726 // bool operator>=(L, R); 8727 // bool operator==(L, R); 8728 // bool operator!=(L, R); 8729 // 8730 // where LR is the result of the usual arithmetic conversions 8731 // between types L and R. 8732 // 8733 // C++ [over.built]p24: 8734 // 8735 // For every pair of promoted arithmetic types L and R, there exist 8736 // candidate operator functions of the form 8737 // 8738 // LR operator?(bool, L, R); 8739 // 8740 // where LR is the result of the usual arithmetic conversions 8741 // between types L and R. 8742 // Our candidates ignore the first parameter. 8743 void addGenericBinaryArithmeticOverloads() { 8744 if (!HasArithmeticOrEnumeralCandidateType) 8745 return; 8746 8747 for (unsigned Left = FirstPromotedArithmeticType; 8748 Left < LastPromotedArithmeticType; ++Left) { 8749 for (unsigned Right = FirstPromotedArithmeticType; 8750 Right < LastPromotedArithmeticType; ++Right) { 8751 QualType LandR[2] = { ArithmeticTypes[Left], 8752 ArithmeticTypes[Right] }; 8753 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8754 } 8755 } 8756 8757 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8758 // conditional operator for vector types. 8759 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8760 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8761 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8762 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8763 } 8764 } 8765 8766 /// Add binary operator overloads for each candidate matrix type M1, M2: 8767 /// * (M1, M1) -> M1 8768 /// * (M1, M1.getElementType()) -> M1 8769 /// * (M2.getElementType(), M2) -> M2 8770 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8771 void addMatrixBinaryArithmeticOverloads() { 8772 if (!HasArithmeticOrEnumeralCandidateType) 8773 return; 8774 8775 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8776 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8777 AddCandidate(M1, M1); 8778 } 8779 8780 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8781 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8782 if (!CandidateTypes[0].containsMatrixType(M2)) 8783 AddCandidate(M2, M2); 8784 } 8785 } 8786 8787 // C++2a [over.built]p14: 8788 // 8789 // For every integral type T there exists a candidate operator function 8790 // of the form 8791 // 8792 // std::strong_ordering operator<=>(T, T) 8793 // 8794 // C++2a [over.built]p15: 8795 // 8796 // For every pair of floating-point types L and R, there exists a candidate 8797 // operator function of the form 8798 // 8799 // std::partial_ordering operator<=>(L, R); 8800 // 8801 // FIXME: The current specification for integral types doesn't play nice with 8802 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8803 // comparisons. Under the current spec this can lead to ambiguity during 8804 // overload resolution. For example: 8805 // 8806 // enum A : int {a}; 8807 // auto x = (a <=> (long)42); 8808 // 8809 // error: call is ambiguous for arguments 'A' and 'long'. 8810 // note: candidate operator<=>(int, int) 8811 // note: candidate operator<=>(long, long) 8812 // 8813 // To avoid this error, this function deviates from the specification and adds 8814 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8815 // arithmetic types (the same as the generic relational overloads). 8816 // 8817 // For now this function acts as a placeholder. 8818 void addThreeWayArithmeticOverloads() { 8819 addGenericBinaryArithmeticOverloads(); 8820 } 8821 8822 // C++ [over.built]p17: 8823 // 8824 // For every pair of promoted integral types L and R, there 8825 // exist candidate operator functions of the form 8826 // 8827 // LR operator%(L, R); 8828 // LR operator&(L, R); 8829 // LR operator^(L, R); 8830 // LR operator|(L, R); 8831 // L operator<<(L, R); 8832 // L operator>>(L, R); 8833 // 8834 // where LR is the result of the usual arithmetic conversions 8835 // between types L and R. 8836 void addBinaryBitwiseArithmeticOverloads() { 8837 if (!HasArithmeticOrEnumeralCandidateType) 8838 return; 8839 8840 for (unsigned Left = FirstPromotedIntegralType; 8841 Left < LastPromotedIntegralType; ++Left) { 8842 for (unsigned Right = FirstPromotedIntegralType; 8843 Right < LastPromotedIntegralType; ++Right) { 8844 QualType LandR[2] = { ArithmeticTypes[Left], 8845 ArithmeticTypes[Right] }; 8846 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8847 } 8848 } 8849 } 8850 8851 // C++ [over.built]p20: 8852 // 8853 // For every pair (T, VQ), where T is an enumeration or 8854 // pointer to member type and VQ is either volatile or 8855 // empty, there exist candidate operator functions of the form 8856 // 8857 // VQ T& operator=(VQ T&, T); 8858 void addAssignmentMemberPointerOrEnumeralOverloads() { 8859 /// Set of (canonical) types that we've already handled. 8860 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8861 8862 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8863 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8864 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8865 continue; 8866 8867 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8868 } 8869 8870 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8871 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8872 continue; 8873 8874 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8875 } 8876 } 8877 } 8878 8879 // C++ [over.built]p19: 8880 // 8881 // For every pair (T, VQ), where T is any type and VQ is either 8882 // volatile or empty, there exist candidate operator functions 8883 // of the form 8884 // 8885 // T*VQ& operator=(T*VQ&, T*); 8886 // 8887 // C++ [over.built]p21: 8888 // 8889 // For every pair (T, VQ), where T is a cv-qualified or 8890 // cv-unqualified object type and VQ is either volatile or 8891 // empty, there exist candidate operator functions of the form 8892 // 8893 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8894 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8895 void addAssignmentPointerOverloads(bool isEqualOp) { 8896 /// Set of (canonical) types that we've already handled. 8897 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8898 8899 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8900 // If this is operator=, keep track of the builtin candidates we added. 8901 if (isEqualOp) 8902 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8903 else if (!PtrTy->getPointeeType()->isObjectType()) 8904 continue; 8905 8906 // non-volatile version 8907 QualType ParamTypes[2] = { 8908 S.Context.getLValueReferenceType(PtrTy), 8909 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8910 }; 8911 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8912 /*IsAssignmentOperator=*/ isEqualOp); 8913 8914 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8915 VisibleTypeConversionsQuals.hasVolatile(); 8916 if (NeedVolatile) { 8917 // volatile version 8918 ParamTypes[0] = 8919 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8920 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8921 /*IsAssignmentOperator=*/isEqualOp); 8922 } 8923 8924 if (!PtrTy.isRestrictQualified() && 8925 VisibleTypeConversionsQuals.hasRestrict()) { 8926 // restrict version 8927 ParamTypes[0] = 8928 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8929 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8930 /*IsAssignmentOperator=*/isEqualOp); 8931 8932 if (NeedVolatile) { 8933 // volatile restrict version 8934 ParamTypes[0] = 8935 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8936 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8937 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8938 /*IsAssignmentOperator=*/isEqualOp); 8939 } 8940 } 8941 } 8942 8943 if (isEqualOp) { 8944 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8945 // Make sure we don't add the same candidate twice. 8946 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8947 continue; 8948 8949 QualType ParamTypes[2] = { 8950 S.Context.getLValueReferenceType(PtrTy), 8951 PtrTy, 8952 }; 8953 8954 // non-volatile version 8955 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8956 /*IsAssignmentOperator=*/true); 8957 8958 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8959 VisibleTypeConversionsQuals.hasVolatile(); 8960 if (NeedVolatile) { 8961 // volatile version 8962 ParamTypes[0] = S.Context.getLValueReferenceType( 8963 S.Context.getVolatileType(PtrTy)); 8964 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8965 /*IsAssignmentOperator=*/true); 8966 } 8967 8968 if (!PtrTy.isRestrictQualified() && 8969 VisibleTypeConversionsQuals.hasRestrict()) { 8970 // restrict version 8971 ParamTypes[0] = S.Context.getLValueReferenceType( 8972 S.Context.getRestrictType(PtrTy)); 8973 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8974 /*IsAssignmentOperator=*/true); 8975 8976 if (NeedVolatile) { 8977 // volatile restrict version 8978 ParamTypes[0] = 8979 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8980 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8981 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8982 /*IsAssignmentOperator=*/true); 8983 } 8984 } 8985 } 8986 } 8987 } 8988 8989 // C++ [over.built]p18: 8990 // 8991 // For every triple (L, VQ, R), where L is an arithmetic type, 8992 // VQ is either volatile or empty, and R is a promoted 8993 // arithmetic type, there exist candidate operator functions of 8994 // the form 8995 // 8996 // VQ L& operator=(VQ L&, R); 8997 // VQ L& operator*=(VQ L&, R); 8998 // VQ L& operator/=(VQ L&, R); 8999 // VQ L& operator+=(VQ L&, R); 9000 // VQ L& operator-=(VQ L&, R); 9001 void addAssignmentArithmeticOverloads(bool isEqualOp) { 9002 if (!HasArithmeticOrEnumeralCandidateType) 9003 return; 9004 9005 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 9006 for (unsigned Right = FirstPromotedArithmeticType; 9007 Right < LastPromotedArithmeticType; ++Right) { 9008 QualType ParamTypes[2]; 9009 ParamTypes[1] = ArithmeticTypes[Right]; 9010 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9011 S, ArithmeticTypes[Left], Args[0]); 9012 9013 forAllQualifierCombinations( 9014 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9015 ParamTypes[0] = 9016 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9017 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9018 /*IsAssignmentOperator=*/isEqualOp); 9019 }); 9020 } 9021 } 9022 9023 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 9024 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9025 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 9026 QualType ParamTypes[2]; 9027 ParamTypes[1] = Vec2Ty; 9028 // Add this built-in operator as a candidate (VQ is empty). 9029 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 9030 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9031 /*IsAssignmentOperator=*/isEqualOp); 9032 9033 // Add this built-in operator as a candidate (VQ is 'volatile'). 9034 if (VisibleTypeConversionsQuals.hasVolatile()) { 9035 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 9036 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9037 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9038 /*IsAssignmentOperator=*/isEqualOp); 9039 } 9040 } 9041 } 9042 9043 // C++ [over.built]p22: 9044 // 9045 // For every triple (L, VQ, R), where L is an integral type, VQ 9046 // is either volatile or empty, and R is a promoted integral 9047 // type, there exist candidate operator functions of the form 9048 // 9049 // VQ L& operator%=(VQ L&, R); 9050 // VQ L& operator<<=(VQ L&, R); 9051 // VQ L& operator>>=(VQ L&, R); 9052 // VQ L& operator&=(VQ L&, R); 9053 // VQ L& operator^=(VQ L&, R); 9054 // VQ L& operator|=(VQ L&, R); 9055 void addAssignmentIntegralOverloads() { 9056 if (!HasArithmeticOrEnumeralCandidateType) 9057 return; 9058 9059 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9060 for (unsigned Right = FirstPromotedIntegralType; 9061 Right < LastPromotedIntegralType; ++Right) { 9062 QualType ParamTypes[2]; 9063 ParamTypes[1] = ArithmeticTypes[Right]; 9064 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9065 S, ArithmeticTypes[Left], Args[0]); 9066 9067 forAllQualifierCombinations( 9068 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9069 ParamTypes[0] = 9070 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9071 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9072 }); 9073 } 9074 } 9075 } 9076 9077 // C++ [over.operator]p23: 9078 // 9079 // There also exist candidate operator functions of the form 9080 // 9081 // bool operator!(bool); 9082 // bool operator&&(bool, bool); 9083 // bool operator||(bool, bool); 9084 void addExclaimOverload() { 9085 QualType ParamTy = S.Context.BoolTy; 9086 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9087 /*IsAssignmentOperator=*/false, 9088 /*NumContextualBoolArguments=*/1); 9089 } 9090 void addAmpAmpOrPipePipeOverload() { 9091 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9093 /*IsAssignmentOperator=*/false, 9094 /*NumContextualBoolArguments=*/2); 9095 } 9096 9097 // C++ [over.built]p13: 9098 // 9099 // For every cv-qualified or cv-unqualified object type T there 9100 // exist candidate operator functions of the form 9101 // 9102 // T* operator+(T*, ptrdiff_t); [ABOVE] 9103 // T& operator[](T*, ptrdiff_t); 9104 // T* operator-(T*, ptrdiff_t); [ABOVE] 9105 // T* operator+(ptrdiff_t, T*); [ABOVE] 9106 // T& operator[](ptrdiff_t, T*); 9107 void addSubscriptOverloads() { 9108 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9109 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9110 QualType PointeeType = PtrTy->getPointeeType(); 9111 if (!PointeeType->isObjectType()) 9112 continue; 9113 9114 // T& operator[](T*, ptrdiff_t) 9115 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9116 } 9117 9118 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9119 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9120 QualType PointeeType = PtrTy->getPointeeType(); 9121 if (!PointeeType->isObjectType()) 9122 continue; 9123 9124 // T& operator[](ptrdiff_t, T*) 9125 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9126 } 9127 } 9128 9129 // C++ [over.built]p11: 9130 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9131 // C1 is the same type as C2 or is a derived class of C2, T is an object 9132 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9133 // there exist candidate operator functions of the form 9134 // 9135 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9136 // 9137 // where CV12 is the union of CV1 and CV2. 9138 void addArrowStarOverloads() { 9139 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9140 QualType C1Ty = PtrTy; 9141 QualType C1; 9142 QualifierCollector Q1; 9143 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9144 if (!isa<RecordType>(C1)) 9145 continue; 9146 // heuristic to reduce number of builtin candidates in the set. 9147 // Add volatile/restrict version only if there are conversions to a 9148 // volatile/restrict type. 9149 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9150 continue; 9151 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9152 continue; 9153 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9154 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9155 QualType C2 = QualType(mptr->getClass(), 0); 9156 C2 = C2.getUnqualifiedType(); 9157 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9158 break; 9159 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9160 // build CV12 T& 9161 QualType T = mptr->getPointeeType(); 9162 if (!VisibleTypeConversionsQuals.hasVolatile() && 9163 T.isVolatileQualified()) 9164 continue; 9165 if (!VisibleTypeConversionsQuals.hasRestrict() && 9166 T.isRestrictQualified()) 9167 continue; 9168 T = Q1.apply(S.Context, T); 9169 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9170 } 9171 } 9172 } 9173 9174 // Note that we don't consider the first argument, since it has been 9175 // contextually converted to bool long ago. The candidates below are 9176 // therefore added as binary. 9177 // 9178 // C++ [over.built]p25: 9179 // For every type T, where T is a pointer, pointer-to-member, or scoped 9180 // enumeration type, there exist candidate operator functions of the form 9181 // 9182 // T operator?(bool, T, T); 9183 // 9184 void addConditionalOperatorOverloads() { 9185 /// Set of (canonical) types that we've already handled. 9186 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9187 9188 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9189 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9190 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9191 continue; 9192 9193 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9194 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9195 } 9196 9197 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9198 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9199 continue; 9200 9201 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9202 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9203 } 9204 9205 if (S.getLangOpts().CPlusPlus11) { 9206 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9207 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9208 continue; 9209 9210 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9211 continue; 9212 9213 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9214 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9215 } 9216 } 9217 } 9218 } 9219 }; 9220 9221 } // end anonymous namespace 9222 9223 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9224 /// operator overloads to the candidate set (C++ [over.built]), based 9225 /// on the operator @p Op and the arguments given. For example, if the 9226 /// operator is a binary '+', this routine might add "int 9227 /// operator+(int, int)" to cover integer addition. 9228 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9229 SourceLocation OpLoc, 9230 ArrayRef<Expr *> Args, 9231 OverloadCandidateSet &CandidateSet) { 9232 // Find all of the types that the arguments can convert to, but only 9233 // if the operator we're looking at has built-in operator candidates 9234 // that make use of these types. Also record whether we encounter non-record 9235 // candidate types or either arithmetic or enumeral candidate types. 9236 QualifiersAndAtomic VisibleTypeConversionsQuals; 9237 VisibleTypeConversionsQuals.addConst(); 9238 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9239 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9240 if (Args[ArgIdx]->getType()->isAtomicType()) 9241 VisibleTypeConversionsQuals.addAtomic(); 9242 } 9243 9244 bool HasNonRecordCandidateType = false; 9245 bool HasArithmeticOrEnumeralCandidateType = false; 9246 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9247 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9248 CandidateTypes.emplace_back(*this); 9249 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9250 OpLoc, 9251 true, 9252 (Op == OO_Exclaim || 9253 Op == OO_AmpAmp || 9254 Op == OO_PipePipe), 9255 VisibleTypeConversionsQuals); 9256 HasNonRecordCandidateType = HasNonRecordCandidateType || 9257 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9258 HasArithmeticOrEnumeralCandidateType = 9259 HasArithmeticOrEnumeralCandidateType || 9260 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9261 } 9262 9263 // Exit early when no non-record types have been added to the candidate set 9264 // for any of the arguments to the operator. 9265 // 9266 // We can't exit early for !, ||, or &&, since there we have always have 9267 // 'bool' overloads. 9268 if (!HasNonRecordCandidateType && 9269 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9270 return; 9271 9272 // Setup an object to manage the common state for building overloads. 9273 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9274 VisibleTypeConversionsQuals, 9275 HasArithmeticOrEnumeralCandidateType, 9276 CandidateTypes, CandidateSet); 9277 9278 // Dispatch over the operation to add in only those overloads which apply. 9279 switch (Op) { 9280 case OO_None: 9281 case NUM_OVERLOADED_OPERATORS: 9282 llvm_unreachable("Expected an overloaded operator"); 9283 9284 case OO_New: 9285 case OO_Delete: 9286 case OO_Array_New: 9287 case OO_Array_Delete: 9288 case OO_Call: 9289 llvm_unreachable( 9290 "Special operators don't use AddBuiltinOperatorCandidates"); 9291 9292 case OO_Comma: 9293 case OO_Arrow: 9294 case OO_Coawait: 9295 // C++ [over.match.oper]p3: 9296 // -- For the operator ',', the unary operator '&', the 9297 // operator '->', or the operator 'co_await', the 9298 // built-in candidates set is empty. 9299 break; 9300 9301 case OO_Plus: // '+' is either unary or binary 9302 if (Args.size() == 1) 9303 OpBuilder.addUnaryPlusPointerOverloads(); 9304 LLVM_FALLTHROUGH; 9305 9306 case OO_Minus: // '-' is either unary or binary 9307 if (Args.size() == 1) { 9308 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9309 } else { 9310 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9311 OpBuilder.addGenericBinaryArithmeticOverloads(); 9312 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9313 } 9314 break; 9315 9316 case OO_Star: // '*' is either unary or binary 9317 if (Args.size() == 1) 9318 OpBuilder.addUnaryStarPointerOverloads(); 9319 else { 9320 OpBuilder.addGenericBinaryArithmeticOverloads(); 9321 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9322 } 9323 break; 9324 9325 case OO_Slash: 9326 OpBuilder.addGenericBinaryArithmeticOverloads(); 9327 break; 9328 9329 case OO_PlusPlus: 9330 case OO_MinusMinus: 9331 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9332 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9333 break; 9334 9335 case OO_EqualEqual: 9336 case OO_ExclaimEqual: 9337 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9338 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9339 OpBuilder.addGenericBinaryArithmeticOverloads(); 9340 break; 9341 9342 case OO_Less: 9343 case OO_Greater: 9344 case OO_LessEqual: 9345 case OO_GreaterEqual: 9346 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9347 OpBuilder.addGenericBinaryArithmeticOverloads(); 9348 break; 9349 9350 case OO_Spaceship: 9351 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9352 OpBuilder.addThreeWayArithmeticOverloads(); 9353 break; 9354 9355 case OO_Percent: 9356 case OO_Caret: 9357 case OO_Pipe: 9358 case OO_LessLess: 9359 case OO_GreaterGreater: 9360 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9361 break; 9362 9363 case OO_Amp: // '&' is either unary or binary 9364 if (Args.size() == 1) 9365 // C++ [over.match.oper]p3: 9366 // -- For the operator ',', the unary operator '&', or the 9367 // operator '->', the built-in candidates set is empty. 9368 break; 9369 9370 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9371 break; 9372 9373 case OO_Tilde: 9374 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9375 break; 9376 9377 case OO_Equal: 9378 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9379 LLVM_FALLTHROUGH; 9380 9381 case OO_PlusEqual: 9382 case OO_MinusEqual: 9383 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9384 LLVM_FALLTHROUGH; 9385 9386 case OO_StarEqual: 9387 case OO_SlashEqual: 9388 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9389 break; 9390 9391 case OO_PercentEqual: 9392 case OO_LessLessEqual: 9393 case OO_GreaterGreaterEqual: 9394 case OO_AmpEqual: 9395 case OO_CaretEqual: 9396 case OO_PipeEqual: 9397 OpBuilder.addAssignmentIntegralOverloads(); 9398 break; 9399 9400 case OO_Exclaim: 9401 OpBuilder.addExclaimOverload(); 9402 break; 9403 9404 case OO_AmpAmp: 9405 case OO_PipePipe: 9406 OpBuilder.addAmpAmpOrPipePipeOverload(); 9407 break; 9408 9409 case OO_Subscript: 9410 if (Args.size() == 2) 9411 OpBuilder.addSubscriptOverloads(); 9412 break; 9413 9414 case OO_ArrowStar: 9415 OpBuilder.addArrowStarOverloads(); 9416 break; 9417 9418 case OO_Conditional: 9419 OpBuilder.addConditionalOperatorOverloads(); 9420 OpBuilder.addGenericBinaryArithmeticOverloads(); 9421 break; 9422 } 9423 } 9424 9425 /// Add function candidates found via argument-dependent lookup 9426 /// to the set of overloading candidates. 9427 /// 9428 /// This routine performs argument-dependent name lookup based on the 9429 /// given function name (which may also be an operator name) and adds 9430 /// all of the overload candidates found by ADL to the overload 9431 /// candidate set (C++ [basic.lookup.argdep]). 9432 void 9433 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9434 SourceLocation Loc, 9435 ArrayRef<Expr *> Args, 9436 TemplateArgumentListInfo *ExplicitTemplateArgs, 9437 OverloadCandidateSet& CandidateSet, 9438 bool PartialOverloading) { 9439 ADLResult Fns; 9440 9441 // FIXME: This approach for uniquing ADL results (and removing 9442 // redundant candidates from the set) relies on pointer-equality, 9443 // which means we need to key off the canonical decl. However, 9444 // always going back to the canonical decl might not get us the 9445 // right set of default arguments. What default arguments are 9446 // we supposed to consider on ADL candidates, anyway? 9447 9448 // FIXME: Pass in the explicit template arguments? 9449 ArgumentDependentLookup(Name, Loc, Args, Fns); 9450 9451 // Erase all of the candidates we already knew about. 9452 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9453 CandEnd = CandidateSet.end(); 9454 Cand != CandEnd; ++Cand) 9455 if (Cand->Function) { 9456 Fns.erase(Cand->Function); 9457 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9458 Fns.erase(FunTmpl); 9459 } 9460 9461 // For each of the ADL candidates we found, add it to the overload 9462 // set. 9463 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9464 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9465 9466 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9467 if (ExplicitTemplateArgs) 9468 continue; 9469 9470 AddOverloadCandidate( 9471 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9472 PartialOverloading, /*AllowExplicit=*/true, 9473 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9474 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9475 AddOverloadCandidate( 9476 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9477 /*SuppressUserConversions=*/false, PartialOverloading, 9478 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9479 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9480 } 9481 } else { 9482 auto *FTD = cast<FunctionTemplateDecl>(*I); 9483 AddTemplateOverloadCandidate( 9484 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9485 /*SuppressUserConversions=*/false, PartialOverloading, 9486 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9487 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9488 Context, FTD->getTemplatedDecl())) { 9489 AddTemplateOverloadCandidate( 9490 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9491 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9492 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9493 OverloadCandidateParamOrder::Reversed); 9494 } 9495 } 9496 } 9497 } 9498 9499 namespace { 9500 enum class Comparison { Equal, Better, Worse }; 9501 } 9502 9503 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9504 /// overload resolution. 9505 /// 9506 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9507 /// Cand1's first N enable_if attributes have precisely the same conditions as 9508 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9509 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9510 /// 9511 /// Note that you can have a pair of candidates such that Cand1's enable_if 9512 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9513 /// worse than Cand1's. 9514 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9515 const FunctionDecl *Cand2) { 9516 // Common case: One (or both) decls don't have enable_if attrs. 9517 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9518 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9519 if (!Cand1Attr || !Cand2Attr) { 9520 if (Cand1Attr == Cand2Attr) 9521 return Comparison::Equal; 9522 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9523 } 9524 9525 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9526 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9527 9528 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9529 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9530 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9531 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9532 9533 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9534 // has fewer enable_if attributes than Cand2, and vice versa. 9535 if (!Cand1A) 9536 return Comparison::Worse; 9537 if (!Cand2A) 9538 return Comparison::Better; 9539 9540 Cand1ID.clear(); 9541 Cand2ID.clear(); 9542 9543 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9544 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9545 if (Cand1ID != Cand2ID) 9546 return Comparison::Worse; 9547 } 9548 9549 return Comparison::Equal; 9550 } 9551 9552 static Comparison 9553 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9554 const OverloadCandidate &Cand2) { 9555 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9556 !Cand2.Function->isMultiVersion()) 9557 return Comparison::Equal; 9558 9559 // If both are invalid, they are equal. If one of them is invalid, the other 9560 // is better. 9561 if (Cand1.Function->isInvalidDecl()) { 9562 if (Cand2.Function->isInvalidDecl()) 9563 return Comparison::Equal; 9564 return Comparison::Worse; 9565 } 9566 if (Cand2.Function->isInvalidDecl()) 9567 return Comparison::Better; 9568 9569 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9570 // cpu_dispatch, else arbitrarily based on the identifiers. 9571 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9572 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9573 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9574 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9575 9576 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9577 return Comparison::Equal; 9578 9579 if (Cand1CPUDisp && !Cand2CPUDisp) 9580 return Comparison::Better; 9581 if (Cand2CPUDisp && !Cand1CPUDisp) 9582 return Comparison::Worse; 9583 9584 if (Cand1CPUSpec && Cand2CPUSpec) { 9585 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9586 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9587 ? Comparison::Better 9588 : Comparison::Worse; 9589 9590 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9591 FirstDiff = std::mismatch( 9592 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9593 Cand2CPUSpec->cpus_begin(), 9594 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9595 return LHS->getName() == RHS->getName(); 9596 }); 9597 9598 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9599 "Two different cpu-specific versions should not have the same " 9600 "identifier list, otherwise they'd be the same decl!"); 9601 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9602 ? Comparison::Better 9603 : Comparison::Worse; 9604 } 9605 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9606 } 9607 9608 /// Compute the type of the implicit object parameter for the given function, 9609 /// if any. Returns None if there is no implicit object parameter, and a null 9610 /// QualType if there is a 'matches anything' implicit object parameter. 9611 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9612 const FunctionDecl *F) { 9613 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9614 return llvm::None; 9615 9616 auto *M = cast<CXXMethodDecl>(F); 9617 // Static member functions' object parameters match all types. 9618 if (M->isStatic()) 9619 return QualType(); 9620 9621 QualType T = M->getThisObjectType(); 9622 if (M->getRefQualifier() == RQ_RValue) 9623 return Context.getRValueReferenceType(T); 9624 return Context.getLValueReferenceType(T); 9625 } 9626 9627 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9628 const FunctionDecl *F2, unsigned NumParams) { 9629 if (declaresSameEntity(F1, F2)) 9630 return true; 9631 9632 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9633 if (First) { 9634 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9635 return *T; 9636 } 9637 assert(I < F->getNumParams()); 9638 return F->getParamDecl(I++)->getType(); 9639 }; 9640 9641 unsigned I1 = 0, I2 = 0; 9642 for (unsigned I = 0; I != NumParams; ++I) { 9643 QualType T1 = NextParam(F1, I1, I == 0); 9644 QualType T2 = NextParam(F2, I2, I == 0); 9645 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 9646 if (!Context.hasSameUnqualifiedType(T1, T2)) 9647 return false; 9648 } 9649 return true; 9650 } 9651 9652 /// We're allowed to use constraints partial ordering only if the candidates 9653 /// have the same parameter types: 9654 /// [temp.func.order]p6.2.2 [...] or if the function parameters that 9655 /// positionally correspond between the two templates are not of the same type, 9656 /// neither template is more specialized than the other. 9657 /// [over.match.best]p2.6 9658 /// F1 and F2 are non-template functions with the same parameter-type-lists, 9659 /// and F1 is more constrained than F2 [...] 9660 static bool canCompareFunctionConstraints(Sema &S, 9661 const OverloadCandidate &Cand1, 9662 const OverloadCandidate &Cand2) { 9663 // FIXME: Per P2113R0 we also need to compare the template parameter lists 9664 // when comparing template functions. 9665 if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() && 9666 Cand2.Function->hasPrototype()) { 9667 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9668 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9669 if (PT1->getNumParams() == PT2->getNumParams() && 9670 PT1->isVariadic() == PT2->isVariadic() && 9671 S.FunctionParamTypesAreEqual(PT1, PT2, nullptr, 9672 Cand1.isReversed() ^ Cand2.isReversed())) 9673 return true; 9674 } 9675 return false; 9676 } 9677 9678 /// isBetterOverloadCandidate - Determines whether the first overload 9679 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9680 bool clang::isBetterOverloadCandidate( 9681 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9682 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9683 // Define viable functions to be better candidates than non-viable 9684 // functions. 9685 if (!Cand2.Viable) 9686 return Cand1.Viable; 9687 else if (!Cand1.Viable) 9688 return false; 9689 9690 // [CUDA] A function with 'never' preference is marked not viable, therefore 9691 // is never shown up here. The worst preference shown up here is 'wrong side', 9692 // e.g. an H function called by a HD function in device compilation. This is 9693 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9694 // function which is called only by an H function. A deferred diagnostic will 9695 // be triggered if it is emitted. However a wrong-sided function is still 9696 // a viable candidate here. 9697 // 9698 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9699 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9700 // can be emitted, Cand1 is not better than Cand2. This rule should have 9701 // precedence over other rules. 9702 // 9703 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9704 // other rules should be used to determine which is better. This is because 9705 // host/device based overloading resolution is mostly for determining 9706 // viability of a function. If two functions are both viable, other factors 9707 // should take precedence in preference, e.g. the standard-defined preferences 9708 // like argument conversion ranks or enable_if partial-ordering. The 9709 // preference for pass-object-size parameters is probably most similar to a 9710 // type-based-overloading decision and so should take priority. 9711 // 9712 // If other rules cannot determine which is better, CUDA preference will be 9713 // used again to determine which is better. 9714 // 9715 // TODO: Currently IdentifyCUDAPreference does not return correct values 9716 // for functions called in global variable initializers due to missing 9717 // correct context about device/host. Therefore we can only enforce this 9718 // rule when there is a caller. We should enforce this rule for functions 9719 // in global variable initializers once proper context is added. 9720 // 9721 // TODO: We can only enable the hostness based overloading resolution when 9722 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9723 // overloading resolution diagnostics. 9724 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9725 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9726 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { 9727 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9728 bool IsCand1ImplicitHD = 9729 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9730 bool IsCand2ImplicitHD = 9731 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9732 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9733 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9734 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9735 // The implicit HD function may be a function in a system header which 9736 // is forced by pragma. In device compilation, if we prefer HD candidates 9737 // over wrong-sided candidates, overloading resolution may change, which 9738 // may result in non-deferrable diagnostics. As a workaround, we let 9739 // implicit HD candidates take equal preference as wrong-sided candidates. 9740 // This will preserve the overloading resolution. 9741 // TODO: We still need special handling of implicit HD functions since 9742 // they may incur other diagnostics to be deferred. We should make all 9743 // host/device related diagnostics deferrable and remove special handling 9744 // of implicit HD functions. 9745 auto EmitThreshold = 9746 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9747 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9748 ? Sema::CFP_Never 9749 : Sema::CFP_WrongSide; 9750 auto Cand1Emittable = P1 > EmitThreshold; 9751 auto Cand2Emittable = P2 > EmitThreshold; 9752 if (Cand1Emittable && !Cand2Emittable) 9753 return true; 9754 if (!Cand1Emittable && Cand2Emittable) 9755 return false; 9756 } 9757 } 9758 9759 // C++ [over.match.best]p1: 9760 // 9761 // -- if F is a static member function, ICS1(F) is defined such 9762 // that ICS1(F) is neither better nor worse than ICS1(G) for 9763 // any function G, and, symmetrically, ICS1(G) is neither 9764 // better nor worse than ICS1(F). 9765 unsigned StartArg = 0; 9766 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9767 StartArg = 1; 9768 9769 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9770 // We don't allow incompatible pointer conversions in C++. 9771 if (!S.getLangOpts().CPlusPlus) 9772 return ICS.isStandard() && 9773 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9774 9775 // The only ill-formed conversion we allow in C++ is the string literal to 9776 // char* conversion, which is only considered ill-formed after C++11. 9777 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9778 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9779 }; 9780 9781 // Define functions that don't require ill-formed conversions for a given 9782 // argument to be better candidates than functions that do. 9783 unsigned NumArgs = Cand1.Conversions.size(); 9784 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9785 bool HasBetterConversion = false; 9786 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9787 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9788 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9789 if (Cand1Bad != Cand2Bad) { 9790 if (Cand1Bad) 9791 return false; 9792 HasBetterConversion = true; 9793 } 9794 } 9795 9796 if (HasBetterConversion) 9797 return true; 9798 9799 // C++ [over.match.best]p1: 9800 // A viable function F1 is defined to be a better function than another 9801 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9802 // conversion sequence than ICSi(F2), and then... 9803 bool HasWorseConversion = false; 9804 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9805 switch (CompareImplicitConversionSequences(S, Loc, 9806 Cand1.Conversions[ArgIdx], 9807 Cand2.Conversions[ArgIdx])) { 9808 case ImplicitConversionSequence::Better: 9809 // Cand1 has a better conversion sequence. 9810 HasBetterConversion = true; 9811 break; 9812 9813 case ImplicitConversionSequence::Worse: 9814 if (Cand1.Function && Cand2.Function && 9815 Cand1.isReversed() != Cand2.isReversed() && 9816 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9817 NumArgs)) { 9818 // Work around large-scale breakage caused by considering reversed 9819 // forms of operator== in C++20: 9820 // 9821 // When comparing a function against a reversed function with the same 9822 // parameter types, if we have a better conversion for one argument and 9823 // a worse conversion for the other, the implicit conversion sequences 9824 // are treated as being equally good. 9825 // 9826 // This prevents a comparison function from being considered ambiguous 9827 // with a reversed form that is written in the same way. 9828 // 9829 // We diagnose this as an extension from CreateOverloadedBinOp. 9830 HasWorseConversion = true; 9831 break; 9832 } 9833 9834 // Cand1 can't be better than Cand2. 9835 return false; 9836 9837 case ImplicitConversionSequence::Indistinguishable: 9838 // Do nothing. 9839 break; 9840 } 9841 } 9842 9843 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9844 // ICSj(F2), or, if not that, 9845 if (HasBetterConversion && !HasWorseConversion) 9846 return true; 9847 9848 // -- the context is an initialization by user-defined conversion 9849 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9850 // from the return type of F1 to the destination type (i.e., 9851 // the type of the entity being initialized) is a better 9852 // conversion sequence than the standard conversion sequence 9853 // from the return type of F2 to the destination type. 9854 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9855 Cand1.Function && Cand2.Function && 9856 isa<CXXConversionDecl>(Cand1.Function) && 9857 isa<CXXConversionDecl>(Cand2.Function)) { 9858 // First check whether we prefer one of the conversion functions over the 9859 // other. This only distinguishes the results in non-standard, extension 9860 // cases such as the conversion from a lambda closure type to a function 9861 // pointer or block. 9862 ImplicitConversionSequence::CompareKind Result = 9863 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9864 if (Result == ImplicitConversionSequence::Indistinguishable) 9865 Result = CompareStandardConversionSequences(S, Loc, 9866 Cand1.FinalConversion, 9867 Cand2.FinalConversion); 9868 9869 if (Result != ImplicitConversionSequence::Indistinguishable) 9870 return Result == ImplicitConversionSequence::Better; 9871 9872 // FIXME: Compare kind of reference binding if conversion functions 9873 // convert to a reference type used in direct reference binding, per 9874 // C++14 [over.match.best]p1 section 2 bullet 3. 9875 } 9876 9877 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9878 // as combined with the resolution to CWG issue 243. 9879 // 9880 // When the context is initialization by constructor ([over.match.ctor] or 9881 // either phase of [over.match.list]), a constructor is preferred over 9882 // a conversion function. 9883 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9884 Cand1.Function && Cand2.Function && 9885 isa<CXXConstructorDecl>(Cand1.Function) != 9886 isa<CXXConstructorDecl>(Cand2.Function)) 9887 return isa<CXXConstructorDecl>(Cand1.Function); 9888 9889 // -- F1 is a non-template function and F2 is a function template 9890 // specialization, or, if not that, 9891 bool Cand1IsSpecialization = Cand1.Function && 9892 Cand1.Function->getPrimaryTemplate(); 9893 bool Cand2IsSpecialization = Cand2.Function && 9894 Cand2.Function->getPrimaryTemplate(); 9895 if (Cand1IsSpecialization != Cand2IsSpecialization) 9896 return Cand2IsSpecialization; 9897 9898 // -- F1 and F2 are function template specializations, and the function 9899 // template for F1 is more specialized than the template for F2 9900 // according to the partial ordering rules described in 14.5.5.2, or, 9901 // if not that, 9902 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9903 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9904 Cand1.Function->getPrimaryTemplate(), 9905 Cand2.Function->getPrimaryTemplate(), Loc, 9906 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9907 : TPOC_Call, 9908 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9909 Cand1.isReversed() ^ Cand2.isReversed(), 9910 canCompareFunctionConstraints(S, Cand1, Cand2))) 9911 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9912 } 9913 9914 // -— F1 and F2 are non-template functions with the same 9915 // parameter-type-lists, and F1 is more constrained than F2 [...], 9916 if (!Cand1IsSpecialization && !Cand2IsSpecialization && 9917 canCompareFunctionConstraints(S, Cand1, Cand2)) { 9918 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9919 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9920 if (RC1 && RC2) { 9921 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9922 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2}, 9923 AtLeastAsConstrained1) || 9924 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1}, 9925 AtLeastAsConstrained2)) 9926 return false; 9927 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9928 return AtLeastAsConstrained1; 9929 } else if (RC1 || RC2) { 9930 return RC1 != nullptr; 9931 } 9932 } 9933 9934 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9935 // class B of D, and for all arguments the corresponding parameters of 9936 // F1 and F2 have the same type. 9937 // FIXME: Implement the "all parameters have the same type" check. 9938 bool Cand1IsInherited = 9939 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9940 bool Cand2IsInherited = 9941 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9942 if (Cand1IsInherited != Cand2IsInherited) 9943 return Cand2IsInherited; 9944 else if (Cand1IsInherited) { 9945 assert(Cand2IsInherited); 9946 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9947 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9948 if (Cand1Class->isDerivedFrom(Cand2Class)) 9949 return true; 9950 if (Cand2Class->isDerivedFrom(Cand1Class)) 9951 return false; 9952 // Inherited from sibling base classes: still ambiguous. 9953 } 9954 9955 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9956 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9957 // with reversed order of parameters and F1 is not 9958 // 9959 // We rank reversed + different operator as worse than just reversed, but 9960 // that comparison can never happen, because we only consider reversing for 9961 // the maximally-rewritten operator (== or <=>). 9962 if (Cand1.RewriteKind != Cand2.RewriteKind) 9963 return Cand1.RewriteKind < Cand2.RewriteKind; 9964 9965 // Check C++17 tie-breakers for deduction guides. 9966 { 9967 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9968 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9969 if (Guide1 && Guide2) { 9970 // -- F1 is generated from a deduction-guide and F2 is not 9971 if (Guide1->isImplicit() != Guide2->isImplicit()) 9972 return Guide2->isImplicit(); 9973 9974 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9975 if (Guide1->isCopyDeductionCandidate()) 9976 return true; 9977 } 9978 } 9979 9980 // Check for enable_if value-based overload resolution. 9981 if (Cand1.Function && Cand2.Function) { 9982 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9983 if (Cmp != Comparison::Equal) 9984 return Cmp == Comparison::Better; 9985 } 9986 9987 bool HasPS1 = Cand1.Function != nullptr && 9988 functionHasPassObjectSizeParams(Cand1.Function); 9989 bool HasPS2 = Cand2.Function != nullptr && 9990 functionHasPassObjectSizeParams(Cand2.Function); 9991 if (HasPS1 != HasPS2 && HasPS1) 9992 return true; 9993 9994 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9995 if (MV == Comparison::Better) 9996 return true; 9997 if (MV == Comparison::Worse) 9998 return false; 9999 10000 // If other rules cannot determine which is better, CUDA preference is used 10001 // to determine which is better. 10002 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 10003 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10004 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 10005 S.IdentifyCUDAPreference(Caller, Cand2.Function); 10006 } 10007 10008 // General member function overloading is handled above, so this only handles 10009 // constructors with address spaces. 10010 // This only handles address spaces since C++ has no other 10011 // qualifier that can be used with constructors. 10012 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 10013 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 10014 if (CD1 && CD2) { 10015 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 10016 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 10017 if (AS1 != AS2) { 10018 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10019 return true; 10020 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10021 return false; 10022 } 10023 } 10024 10025 return false; 10026 } 10027 10028 /// Determine whether two declarations are "equivalent" for the purposes of 10029 /// name lookup and overload resolution. This applies when the same internal/no 10030 /// linkage entity is defined by two modules (probably by textually including 10031 /// the same header). In such a case, we don't consider the declarations to 10032 /// declare the same entity, but we also don't want lookups with both 10033 /// declarations visible to be ambiguous in some cases (this happens when using 10034 /// a modularized libstdc++). 10035 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10036 const NamedDecl *B) { 10037 auto *VA = dyn_cast_or_null<ValueDecl>(A); 10038 auto *VB = dyn_cast_or_null<ValueDecl>(B); 10039 if (!VA || !VB) 10040 return false; 10041 10042 // The declarations must be declaring the same name as an internal linkage 10043 // entity in different modules. 10044 if (!VA->getDeclContext()->getRedeclContext()->Equals( 10045 VB->getDeclContext()->getRedeclContext()) || 10046 getOwningModule(VA) == getOwningModule(VB) || 10047 VA->isExternallyVisible() || VB->isExternallyVisible()) 10048 return false; 10049 10050 // Check that the declarations appear to be equivalent. 10051 // 10052 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 10053 // For constants and functions, we should check the initializer or body is 10054 // the same. For non-constant variables, we shouldn't allow it at all. 10055 if (Context.hasSameType(VA->getType(), VB->getType())) 10056 return true; 10057 10058 // Enum constants within unnamed enumerations will have different types, but 10059 // may still be similar enough to be interchangeable for our purposes. 10060 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 10061 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 10062 // Only handle anonymous enums. If the enumerations were named and 10063 // equivalent, they would have been merged to the same type. 10064 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 10065 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 10066 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 10067 !Context.hasSameType(EnumA->getIntegerType(), 10068 EnumB->getIntegerType())) 10069 return false; 10070 // Allow this only if the value is the same for both enumerators. 10071 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 10072 } 10073 } 10074 10075 // Nothing else is sufficiently similar. 10076 return false; 10077 } 10078 10079 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10080 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10081 assert(D && "Unknown declaration"); 10082 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10083 10084 Module *M = getOwningModule(D); 10085 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10086 << !M << (M ? M->getFullModuleName() : ""); 10087 10088 for (auto *E : Equiv) { 10089 Module *M = getOwningModule(E); 10090 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10091 << !M << (M ? M->getFullModuleName() : ""); 10092 } 10093 } 10094 10095 /// Computes the best viable function (C++ 13.3.3) 10096 /// within an overload candidate set. 10097 /// 10098 /// \param Loc The location of the function name (or operator symbol) for 10099 /// which overload resolution occurs. 10100 /// 10101 /// \param Best If overload resolution was successful or found a deleted 10102 /// function, \p Best points to the candidate function found. 10103 /// 10104 /// \returns The result of overload resolution. 10105 OverloadingResult 10106 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10107 iterator &Best) { 10108 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10109 std::transform(begin(), end(), std::back_inserter(Candidates), 10110 [](OverloadCandidate &Cand) { return &Cand; }); 10111 10112 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10113 // are accepted by both clang and NVCC. However, during a particular 10114 // compilation mode only one call variant is viable. We need to 10115 // exclude non-viable overload candidates from consideration based 10116 // only on their host/device attributes. Specifically, if one 10117 // candidate call is WrongSide and the other is SameSide, we ignore 10118 // the WrongSide candidate. 10119 // We only need to remove wrong-sided candidates here if 10120 // -fgpu-exclude-wrong-side-overloads is off. When 10121 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10122 // uniformly in isBetterOverloadCandidate. 10123 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10124 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10125 bool ContainsSameSideCandidate = 10126 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10127 // Check viable function only. 10128 return Cand->Viable && Cand->Function && 10129 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10130 Sema::CFP_SameSide; 10131 }); 10132 if (ContainsSameSideCandidate) { 10133 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10134 // Check viable function only to avoid unnecessary data copying/moving. 10135 return Cand->Viable && Cand->Function && 10136 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10137 Sema::CFP_WrongSide; 10138 }; 10139 llvm::erase_if(Candidates, IsWrongSideCandidate); 10140 } 10141 } 10142 10143 // Find the best viable function. 10144 Best = end(); 10145 for (auto *Cand : Candidates) { 10146 Cand->Best = false; 10147 if (Cand->Viable) 10148 if (Best == end() || 10149 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10150 Best = Cand; 10151 } 10152 10153 // If we didn't find any viable functions, abort. 10154 if (Best == end()) 10155 return OR_No_Viable_Function; 10156 10157 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10158 10159 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10160 PendingBest.push_back(&*Best); 10161 Best->Best = true; 10162 10163 // Make sure that this function is better than every other viable 10164 // function. If not, we have an ambiguity. 10165 while (!PendingBest.empty()) { 10166 auto *Curr = PendingBest.pop_back_val(); 10167 for (auto *Cand : Candidates) { 10168 if (Cand->Viable && !Cand->Best && 10169 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10170 PendingBest.push_back(Cand); 10171 Cand->Best = true; 10172 10173 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10174 Curr->Function)) 10175 EquivalentCands.push_back(Cand->Function); 10176 else 10177 Best = end(); 10178 } 10179 } 10180 } 10181 10182 // If we found more than one best candidate, this is ambiguous. 10183 if (Best == end()) 10184 return OR_Ambiguous; 10185 10186 // Best is the best viable function. 10187 if (Best->Function && Best->Function->isDeleted()) 10188 return OR_Deleted; 10189 10190 if (!EquivalentCands.empty()) 10191 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10192 EquivalentCands); 10193 10194 return OR_Success; 10195 } 10196 10197 namespace { 10198 10199 enum OverloadCandidateKind { 10200 oc_function, 10201 oc_method, 10202 oc_reversed_binary_operator, 10203 oc_constructor, 10204 oc_implicit_default_constructor, 10205 oc_implicit_copy_constructor, 10206 oc_implicit_move_constructor, 10207 oc_implicit_copy_assignment, 10208 oc_implicit_move_assignment, 10209 oc_implicit_equality_comparison, 10210 oc_inherited_constructor 10211 }; 10212 10213 enum OverloadCandidateSelect { 10214 ocs_non_template, 10215 ocs_template, 10216 ocs_described_template, 10217 }; 10218 10219 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10220 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10221 OverloadCandidateRewriteKind CRK, 10222 std::string &Description) { 10223 10224 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10225 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10226 isTemplate = true; 10227 Description = S.getTemplateArgumentBindingsText( 10228 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10229 } 10230 10231 OverloadCandidateSelect Select = [&]() { 10232 if (!Description.empty()) 10233 return ocs_described_template; 10234 return isTemplate ? ocs_template : ocs_non_template; 10235 }(); 10236 10237 OverloadCandidateKind Kind = [&]() { 10238 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10239 return oc_implicit_equality_comparison; 10240 10241 if (CRK & CRK_Reversed) 10242 return oc_reversed_binary_operator; 10243 10244 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10245 if (!Ctor->isImplicit()) { 10246 if (isa<ConstructorUsingShadowDecl>(Found)) 10247 return oc_inherited_constructor; 10248 else 10249 return oc_constructor; 10250 } 10251 10252 if (Ctor->isDefaultConstructor()) 10253 return oc_implicit_default_constructor; 10254 10255 if (Ctor->isMoveConstructor()) 10256 return oc_implicit_move_constructor; 10257 10258 assert(Ctor->isCopyConstructor() && 10259 "unexpected sort of implicit constructor"); 10260 return oc_implicit_copy_constructor; 10261 } 10262 10263 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10264 // This actually gets spelled 'candidate function' for now, but 10265 // it doesn't hurt to split it out. 10266 if (!Meth->isImplicit()) 10267 return oc_method; 10268 10269 if (Meth->isMoveAssignmentOperator()) 10270 return oc_implicit_move_assignment; 10271 10272 if (Meth->isCopyAssignmentOperator()) 10273 return oc_implicit_copy_assignment; 10274 10275 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10276 return oc_method; 10277 } 10278 10279 return oc_function; 10280 }(); 10281 10282 return std::make_pair(Kind, Select); 10283 } 10284 10285 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10286 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10287 // set. 10288 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10289 S.Diag(FoundDecl->getLocation(), 10290 diag::note_ovl_candidate_inherited_constructor) 10291 << Shadow->getNominatedBaseClass(); 10292 } 10293 10294 } // end anonymous namespace 10295 10296 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10297 const FunctionDecl *FD) { 10298 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10299 bool AlwaysTrue; 10300 if (EnableIf->getCond()->isValueDependent() || 10301 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10302 return false; 10303 if (!AlwaysTrue) 10304 return false; 10305 } 10306 return true; 10307 } 10308 10309 /// Returns true if we can take the address of the function. 10310 /// 10311 /// \param Complain - If true, we'll emit a diagnostic 10312 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10313 /// we in overload resolution? 10314 /// \param Loc - The location of the statement we're complaining about. Ignored 10315 /// if we're not complaining, or if we're in overload resolution. 10316 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10317 bool Complain, 10318 bool InOverloadResolution, 10319 SourceLocation Loc) { 10320 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10321 if (Complain) { 10322 if (InOverloadResolution) 10323 S.Diag(FD->getBeginLoc(), 10324 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10325 else 10326 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10327 } 10328 return false; 10329 } 10330 10331 if (FD->getTrailingRequiresClause()) { 10332 ConstraintSatisfaction Satisfaction; 10333 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10334 return false; 10335 if (!Satisfaction.IsSatisfied) { 10336 if (Complain) { 10337 if (InOverloadResolution) { 10338 SmallString<128> TemplateArgString; 10339 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 10340 TemplateArgString += " "; 10341 TemplateArgString += S.getTemplateArgumentBindingsText( 10342 FunTmpl->getTemplateParameters(), 10343 *FD->getTemplateSpecializationArgs()); 10344 } 10345 10346 S.Diag(FD->getBeginLoc(), 10347 diag::note_ovl_candidate_unsatisfied_constraints) 10348 << TemplateArgString; 10349 } else 10350 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10351 << FD; 10352 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10353 } 10354 return false; 10355 } 10356 } 10357 10358 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10359 return P->hasAttr<PassObjectSizeAttr>(); 10360 }); 10361 if (I == FD->param_end()) 10362 return true; 10363 10364 if (Complain) { 10365 // Add one to ParamNo because it's user-facing 10366 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10367 if (InOverloadResolution) 10368 S.Diag(FD->getLocation(), 10369 diag::note_ovl_candidate_has_pass_object_size_params) 10370 << ParamNo; 10371 else 10372 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10373 << FD << ParamNo; 10374 } 10375 return false; 10376 } 10377 10378 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10379 const FunctionDecl *FD) { 10380 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10381 /*InOverloadResolution=*/true, 10382 /*Loc=*/SourceLocation()); 10383 } 10384 10385 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10386 bool Complain, 10387 SourceLocation Loc) { 10388 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10389 /*InOverloadResolution=*/false, 10390 Loc); 10391 } 10392 10393 // Don't print candidates other than the one that matches the calling 10394 // convention of the call operator, since that is guaranteed to exist. 10395 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10396 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10397 10398 if (!ConvD) 10399 return false; 10400 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10401 if (!RD->isLambda()) 10402 return false; 10403 10404 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10405 CallingConv CallOpCC = 10406 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10407 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10408 CallingConv ConvToCC = 10409 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10410 10411 return ConvToCC != CallOpCC; 10412 } 10413 10414 // Notes the location of an overload candidate. 10415 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10416 OverloadCandidateRewriteKind RewriteKind, 10417 QualType DestType, bool TakingAddress) { 10418 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10419 return; 10420 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10421 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10422 return; 10423 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10424 return; 10425 10426 std::string FnDesc; 10427 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10428 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10429 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10430 << (unsigned)KSPair.first << (unsigned)KSPair.second 10431 << Fn << FnDesc; 10432 10433 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10434 Diag(Fn->getLocation(), PD); 10435 MaybeEmitInheritedConstructorNote(*this, Found); 10436 } 10437 10438 static void 10439 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10440 // Perhaps the ambiguity was caused by two atomic constraints that are 10441 // 'identical' but not equivalent: 10442 // 10443 // void foo() requires (sizeof(T) > 4) { } // #1 10444 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10445 // 10446 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10447 // #2 to subsume #1, but these constraint are not considered equivalent 10448 // according to the subsumption rules because they are not the same 10449 // source-level construct. This behavior is quite confusing and we should try 10450 // to help the user figure out what happened. 10451 10452 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10453 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10454 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10455 if (!I->Function) 10456 continue; 10457 SmallVector<const Expr *, 3> AC; 10458 if (auto *Template = I->Function->getPrimaryTemplate()) 10459 Template->getAssociatedConstraints(AC); 10460 else 10461 I->Function->getAssociatedConstraints(AC); 10462 if (AC.empty()) 10463 continue; 10464 if (FirstCand == nullptr) { 10465 FirstCand = I->Function; 10466 FirstAC = AC; 10467 } else if (SecondCand == nullptr) { 10468 SecondCand = I->Function; 10469 SecondAC = AC; 10470 } else { 10471 // We have more than one pair of constrained functions - this check is 10472 // expensive and we'd rather not try to diagnose it. 10473 return; 10474 } 10475 } 10476 if (!SecondCand) 10477 return; 10478 // The diagnostic can only happen if there are associated constraints on 10479 // both sides (there needs to be some identical atomic constraint). 10480 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10481 SecondCand, SecondAC)) 10482 // Just show the user one diagnostic, they'll probably figure it out 10483 // from here. 10484 return; 10485 } 10486 10487 // Notes the location of all overload candidates designated through 10488 // OverloadedExpr 10489 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10490 bool TakingAddress) { 10491 assert(OverloadedExpr->getType() == Context.OverloadTy); 10492 10493 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10494 OverloadExpr *OvlExpr = Ovl.Expression; 10495 10496 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10497 IEnd = OvlExpr->decls_end(); 10498 I != IEnd; ++I) { 10499 if (FunctionTemplateDecl *FunTmpl = 10500 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10501 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10502 TakingAddress); 10503 } else if (FunctionDecl *Fun 10504 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10505 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10506 } 10507 } 10508 } 10509 10510 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10511 /// "lead" diagnostic; it will be given two arguments, the source and 10512 /// target types of the conversion. 10513 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10514 Sema &S, 10515 SourceLocation CaretLoc, 10516 const PartialDiagnostic &PDiag) const { 10517 S.Diag(CaretLoc, PDiag) 10518 << Ambiguous.getFromType() << Ambiguous.getToType(); 10519 unsigned CandsShown = 0; 10520 AmbiguousConversionSequence::const_iterator I, E; 10521 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10522 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10523 break; 10524 ++CandsShown; 10525 S.NoteOverloadCandidate(I->first, I->second); 10526 } 10527 S.Diags.overloadCandidatesShown(CandsShown); 10528 if (I != E) 10529 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10530 } 10531 10532 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10533 unsigned I, bool TakingCandidateAddress) { 10534 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10535 assert(Conv.isBad()); 10536 assert(Cand->Function && "for now, candidate must be a function"); 10537 FunctionDecl *Fn = Cand->Function; 10538 10539 // There's a conversion slot for the object argument if this is a 10540 // non-constructor method. Note that 'I' corresponds the 10541 // conversion-slot index. 10542 bool isObjectArgument = false; 10543 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10544 if (I == 0) 10545 isObjectArgument = true; 10546 else 10547 I--; 10548 } 10549 10550 std::string FnDesc; 10551 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10552 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10553 FnDesc); 10554 10555 Expr *FromExpr = Conv.Bad.FromExpr; 10556 QualType FromTy = Conv.Bad.getFromType(); 10557 QualType ToTy = Conv.Bad.getToType(); 10558 10559 if (FromTy == S.Context.OverloadTy) { 10560 assert(FromExpr && "overload set argument came from implicit argument?"); 10561 Expr *E = FromExpr->IgnoreParens(); 10562 if (isa<UnaryOperator>(E)) 10563 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10564 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10565 10566 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10567 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10568 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10569 << Name << I + 1; 10570 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10571 return; 10572 } 10573 10574 // Do some hand-waving analysis to see if the non-viability is due 10575 // to a qualifier mismatch. 10576 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10577 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10578 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10579 CToTy = RT->getPointeeType(); 10580 else { 10581 // TODO: detect and diagnose the full richness of const mismatches. 10582 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10583 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10584 CFromTy = FromPT->getPointeeType(); 10585 CToTy = ToPT->getPointeeType(); 10586 } 10587 } 10588 10589 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10590 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10591 Qualifiers FromQs = CFromTy.getQualifiers(); 10592 Qualifiers ToQs = CToTy.getQualifiers(); 10593 10594 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10595 if (isObjectArgument) 10596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10597 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10598 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10599 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10600 else 10601 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10602 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10603 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10604 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10605 << ToTy->isReferenceType() << I + 1; 10606 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10607 return; 10608 } 10609 10610 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10611 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10612 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10613 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10614 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10615 << (unsigned)isObjectArgument << I + 1; 10616 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10617 return; 10618 } 10619 10620 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10621 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10622 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10623 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10624 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10625 << (unsigned)isObjectArgument << I + 1; 10626 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10627 return; 10628 } 10629 10630 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10631 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10632 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10633 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10634 << FromQs.hasUnaligned() << I + 1; 10635 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10636 return; 10637 } 10638 10639 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10640 assert(CVR && "expected qualifiers mismatch"); 10641 10642 if (isObjectArgument) { 10643 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10644 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10645 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10646 << (CVR - 1); 10647 } else { 10648 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10649 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10650 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10651 << (CVR - 1) << I + 1; 10652 } 10653 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10654 return; 10655 } 10656 10657 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10658 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10660 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10661 << (unsigned)isObjectArgument << I + 1 10662 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10663 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10664 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10665 return; 10666 } 10667 10668 // Special diagnostic for failure to convert an initializer list, since 10669 // telling the user that it has type void is not useful. 10670 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10672 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10673 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10674 << ToTy << (unsigned)isObjectArgument << I + 1 10675 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 10676 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 10677 ? 2 10678 : 0); 10679 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10680 return; 10681 } 10682 10683 // Diagnose references or pointers to incomplete types differently, 10684 // since it's far from impossible that the incompleteness triggered 10685 // the failure. 10686 QualType TempFromTy = FromTy.getNonReferenceType(); 10687 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10688 TempFromTy = PTy->getPointeeType(); 10689 if (TempFromTy->isIncompleteType()) { 10690 // Emit the generic diagnostic and, optionally, add the hints to it. 10691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10692 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10693 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10694 << ToTy << (unsigned)isObjectArgument << I + 1 10695 << (unsigned)(Cand->Fix.Kind); 10696 10697 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10698 return; 10699 } 10700 10701 // Diagnose base -> derived pointer conversions. 10702 unsigned BaseToDerivedConversion = 0; 10703 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10704 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10705 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10706 FromPtrTy->getPointeeType()) && 10707 !FromPtrTy->getPointeeType()->isIncompleteType() && 10708 !ToPtrTy->getPointeeType()->isIncompleteType() && 10709 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10710 FromPtrTy->getPointeeType())) 10711 BaseToDerivedConversion = 1; 10712 } 10713 } else if (const ObjCObjectPointerType *FromPtrTy 10714 = FromTy->getAs<ObjCObjectPointerType>()) { 10715 if (const ObjCObjectPointerType *ToPtrTy 10716 = ToTy->getAs<ObjCObjectPointerType>()) 10717 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10718 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10719 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10720 FromPtrTy->getPointeeType()) && 10721 FromIface->isSuperClassOf(ToIface)) 10722 BaseToDerivedConversion = 2; 10723 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10724 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10725 !FromTy->isIncompleteType() && 10726 !ToRefTy->getPointeeType()->isIncompleteType() && 10727 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10728 BaseToDerivedConversion = 3; 10729 } 10730 } 10731 10732 if (BaseToDerivedConversion) { 10733 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10734 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10735 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10736 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10737 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10738 return; 10739 } 10740 10741 if (isa<ObjCObjectPointerType>(CFromTy) && 10742 isa<PointerType>(CToTy)) { 10743 Qualifiers FromQs = CFromTy.getQualifiers(); 10744 Qualifiers ToQs = CToTy.getQualifiers(); 10745 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10746 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10747 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10748 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10749 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10750 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10751 return; 10752 } 10753 } 10754 10755 if (TakingCandidateAddress && 10756 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10757 return; 10758 10759 // Emit the generic diagnostic and, optionally, add the hints to it. 10760 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10761 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10762 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10763 << ToTy << (unsigned)isObjectArgument << I + 1 10764 << (unsigned)(Cand->Fix.Kind); 10765 10766 // If we can fix the conversion, suggest the FixIts. 10767 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10768 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10769 FDiag << *HI; 10770 S.Diag(Fn->getLocation(), FDiag); 10771 10772 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10773 } 10774 10775 /// Additional arity mismatch diagnosis specific to a function overload 10776 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10777 /// over a candidate in any candidate set. 10778 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10779 unsigned NumArgs) { 10780 FunctionDecl *Fn = Cand->Function; 10781 unsigned MinParams = Fn->getMinRequiredArguments(); 10782 10783 // With invalid overloaded operators, it's possible that we think we 10784 // have an arity mismatch when in fact it looks like we have the 10785 // right number of arguments, because only overloaded operators have 10786 // the weird behavior of overloading member and non-member functions. 10787 // Just don't report anything. 10788 if (Fn->isInvalidDecl() && 10789 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10790 return true; 10791 10792 if (NumArgs < MinParams) { 10793 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10794 (Cand->FailureKind == ovl_fail_bad_deduction && 10795 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10796 } else { 10797 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10798 (Cand->FailureKind == ovl_fail_bad_deduction && 10799 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10800 } 10801 10802 return false; 10803 } 10804 10805 /// General arity mismatch diagnosis over a candidate in a candidate set. 10806 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10807 unsigned NumFormalArgs) { 10808 assert(isa<FunctionDecl>(D) && 10809 "The templated declaration should at least be a function" 10810 " when diagnosing bad template argument deduction due to too many" 10811 " or too few arguments"); 10812 10813 FunctionDecl *Fn = cast<FunctionDecl>(D); 10814 10815 // TODO: treat calls to a missing default constructor as a special case 10816 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10817 unsigned MinParams = Fn->getMinRequiredArguments(); 10818 10819 // at least / at most / exactly 10820 unsigned mode, modeCount; 10821 if (NumFormalArgs < MinParams) { 10822 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10823 FnTy->isTemplateVariadic()) 10824 mode = 0; // "at least" 10825 else 10826 mode = 2; // "exactly" 10827 modeCount = MinParams; 10828 } else { 10829 if (MinParams != FnTy->getNumParams()) 10830 mode = 1; // "at most" 10831 else 10832 mode = 2; // "exactly" 10833 modeCount = FnTy->getNumParams(); 10834 } 10835 10836 std::string Description; 10837 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10838 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10839 10840 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10841 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10842 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10843 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10844 else 10845 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10846 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10847 << Description << mode << modeCount << NumFormalArgs; 10848 10849 MaybeEmitInheritedConstructorNote(S, Found); 10850 } 10851 10852 /// Arity mismatch diagnosis specific to a function overload candidate. 10853 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10854 unsigned NumFormalArgs) { 10855 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10856 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10857 } 10858 10859 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10860 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10861 return TD; 10862 llvm_unreachable("Unsupported: Getting the described template declaration" 10863 " for bad deduction diagnosis"); 10864 } 10865 10866 /// Diagnose a failed template-argument deduction. 10867 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10868 DeductionFailureInfo &DeductionFailure, 10869 unsigned NumArgs, 10870 bool TakingCandidateAddress) { 10871 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10872 NamedDecl *ParamD; 10873 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10874 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10875 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10876 switch (DeductionFailure.Result) { 10877 case Sema::TDK_Success: 10878 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10879 10880 case Sema::TDK_Incomplete: { 10881 assert(ParamD && "no parameter found for incomplete deduction result"); 10882 S.Diag(Templated->getLocation(), 10883 diag::note_ovl_candidate_incomplete_deduction) 10884 << ParamD->getDeclName(); 10885 MaybeEmitInheritedConstructorNote(S, Found); 10886 return; 10887 } 10888 10889 case Sema::TDK_IncompletePack: { 10890 assert(ParamD && "no parameter found for incomplete deduction result"); 10891 S.Diag(Templated->getLocation(), 10892 diag::note_ovl_candidate_incomplete_deduction_pack) 10893 << ParamD->getDeclName() 10894 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10895 << *DeductionFailure.getFirstArg(); 10896 MaybeEmitInheritedConstructorNote(S, Found); 10897 return; 10898 } 10899 10900 case Sema::TDK_Underqualified: { 10901 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10902 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10903 10904 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10905 10906 // Param will have been canonicalized, but it should just be a 10907 // qualified version of ParamD, so move the qualifiers to that. 10908 QualifierCollector Qs; 10909 Qs.strip(Param); 10910 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10911 assert(S.Context.hasSameType(Param, NonCanonParam)); 10912 10913 // Arg has also been canonicalized, but there's nothing we can do 10914 // about that. It also doesn't matter as much, because it won't 10915 // have any template parameters in it (because deduction isn't 10916 // done on dependent types). 10917 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10918 10919 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10920 << ParamD->getDeclName() << Arg << NonCanonParam; 10921 MaybeEmitInheritedConstructorNote(S, Found); 10922 return; 10923 } 10924 10925 case Sema::TDK_Inconsistent: { 10926 assert(ParamD && "no parameter found for inconsistent deduction result"); 10927 int which = 0; 10928 if (isa<TemplateTypeParmDecl>(ParamD)) 10929 which = 0; 10930 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10931 // Deduction might have failed because we deduced arguments of two 10932 // different types for a non-type template parameter. 10933 // FIXME: Use a different TDK value for this. 10934 QualType T1 = 10935 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10936 QualType T2 = 10937 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10938 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10939 S.Diag(Templated->getLocation(), 10940 diag::note_ovl_candidate_inconsistent_deduction_types) 10941 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10942 << *DeductionFailure.getSecondArg() << T2; 10943 MaybeEmitInheritedConstructorNote(S, Found); 10944 return; 10945 } 10946 10947 which = 1; 10948 } else { 10949 which = 2; 10950 } 10951 10952 // Tweak the diagnostic if the problem is that we deduced packs of 10953 // different arities. We'll print the actual packs anyway in case that 10954 // includes additional useful information. 10955 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10956 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10957 DeductionFailure.getFirstArg()->pack_size() != 10958 DeductionFailure.getSecondArg()->pack_size()) { 10959 which = 3; 10960 } 10961 10962 S.Diag(Templated->getLocation(), 10963 diag::note_ovl_candidate_inconsistent_deduction) 10964 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10965 << *DeductionFailure.getSecondArg(); 10966 MaybeEmitInheritedConstructorNote(S, Found); 10967 return; 10968 } 10969 10970 case Sema::TDK_InvalidExplicitArguments: 10971 assert(ParamD && "no parameter found for invalid explicit arguments"); 10972 if (ParamD->getDeclName()) 10973 S.Diag(Templated->getLocation(), 10974 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10975 << ParamD->getDeclName(); 10976 else { 10977 int index = 0; 10978 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10979 index = TTP->getIndex(); 10980 else if (NonTypeTemplateParmDecl *NTTP 10981 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10982 index = NTTP->getIndex(); 10983 else 10984 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10985 S.Diag(Templated->getLocation(), 10986 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10987 << (index + 1); 10988 } 10989 MaybeEmitInheritedConstructorNote(S, Found); 10990 return; 10991 10992 case Sema::TDK_ConstraintsNotSatisfied: { 10993 // Format the template argument list into the argument string. 10994 SmallString<128> TemplateArgString; 10995 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10996 TemplateArgString = " "; 10997 TemplateArgString += S.getTemplateArgumentBindingsText( 10998 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10999 if (TemplateArgString.size() == 1) 11000 TemplateArgString.clear(); 11001 S.Diag(Templated->getLocation(), 11002 diag::note_ovl_candidate_unsatisfied_constraints) 11003 << TemplateArgString; 11004 11005 S.DiagnoseUnsatisfiedConstraint( 11006 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 11007 return; 11008 } 11009 case Sema::TDK_TooManyArguments: 11010 case Sema::TDK_TooFewArguments: 11011 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 11012 return; 11013 11014 case Sema::TDK_InstantiationDepth: 11015 S.Diag(Templated->getLocation(), 11016 diag::note_ovl_candidate_instantiation_depth); 11017 MaybeEmitInheritedConstructorNote(S, Found); 11018 return; 11019 11020 case Sema::TDK_SubstitutionFailure: { 11021 // Format the template argument list into the argument string. 11022 SmallString<128> TemplateArgString; 11023 if (TemplateArgumentList *Args = 11024 DeductionFailure.getTemplateArgumentList()) { 11025 TemplateArgString = " "; 11026 TemplateArgString += S.getTemplateArgumentBindingsText( 11027 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11028 if (TemplateArgString.size() == 1) 11029 TemplateArgString.clear(); 11030 } 11031 11032 // If this candidate was disabled by enable_if, say so. 11033 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 11034 if (PDiag && PDiag->second.getDiagID() == 11035 diag::err_typename_nested_not_found_enable_if) { 11036 // FIXME: Use the source range of the condition, and the fully-qualified 11037 // name of the enable_if template. These are both present in PDiag. 11038 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 11039 << "'enable_if'" << TemplateArgString; 11040 return; 11041 } 11042 11043 // We found a specific requirement that disabled the enable_if. 11044 if (PDiag && PDiag->second.getDiagID() == 11045 diag::err_typename_nested_not_found_requirement) { 11046 S.Diag(Templated->getLocation(), 11047 diag::note_ovl_candidate_disabled_by_requirement) 11048 << PDiag->second.getStringArg(0) << TemplateArgString; 11049 return; 11050 } 11051 11052 // Format the SFINAE diagnostic into the argument string. 11053 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 11054 // formatted message in another diagnostic. 11055 SmallString<128> SFINAEArgString; 11056 SourceRange R; 11057 if (PDiag) { 11058 SFINAEArgString = ": "; 11059 R = SourceRange(PDiag->first, PDiag->first); 11060 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 11061 } 11062 11063 S.Diag(Templated->getLocation(), 11064 diag::note_ovl_candidate_substitution_failure) 11065 << TemplateArgString << SFINAEArgString << R; 11066 MaybeEmitInheritedConstructorNote(S, Found); 11067 return; 11068 } 11069 11070 case Sema::TDK_DeducedMismatch: 11071 case Sema::TDK_DeducedMismatchNested: { 11072 // Format the template argument list into the argument string. 11073 SmallString<128> TemplateArgString; 11074 if (TemplateArgumentList *Args = 11075 DeductionFailure.getTemplateArgumentList()) { 11076 TemplateArgString = " "; 11077 TemplateArgString += S.getTemplateArgumentBindingsText( 11078 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11079 if (TemplateArgString.size() == 1) 11080 TemplateArgString.clear(); 11081 } 11082 11083 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11084 << (*DeductionFailure.getCallArgIndex() + 1) 11085 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11086 << TemplateArgString 11087 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11088 break; 11089 } 11090 11091 case Sema::TDK_NonDeducedMismatch: { 11092 // FIXME: Provide a source location to indicate what we couldn't match. 11093 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11094 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11095 if (FirstTA.getKind() == TemplateArgument::Template && 11096 SecondTA.getKind() == TemplateArgument::Template) { 11097 TemplateName FirstTN = FirstTA.getAsTemplate(); 11098 TemplateName SecondTN = SecondTA.getAsTemplate(); 11099 if (FirstTN.getKind() == TemplateName::Template && 11100 SecondTN.getKind() == TemplateName::Template) { 11101 if (FirstTN.getAsTemplateDecl()->getName() == 11102 SecondTN.getAsTemplateDecl()->getName()) { 11103 // FIXME: This fixes a bad diagnostic where both templates are named 11104 // the same. This particular case is a bit difficult since: 11105 // 1) It is passed as a string to the diagnostic printer. 11106 // 2) The diagnostic printer only attempts to find a better 11107 // name for types, not decls. 11108 // Ideally, this should folded into the diagnostic printer. 11109 S.Diag(Templated->getLocation(), 11110 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11111 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11112 return; 11113 } 11114 } 11115 } 11116 11117 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11118 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11119 return; 11120 11121 // FIXME: For generic lambda parameters, check if the function is a lambda 11122 // call operator, and if so, emit a prettier and more informative 11123 // diagnostic that mentions 'auto' and lambda in addition to 11124 // (or instead of?) the canonical template type parameters. 11125 S.Diag(Templated->getLocation(), 11126 diag::note_ovl_candidate_non_deduced_mismatch) 11127 << FirstTA << SecondTA; 11128 return; 11129 } 11130 // TODO: diagnose these individually, then kill off 11131 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11132 case Sema::TDK_MiscellaneousDeductionFailure: 11133 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11134 MaybeEmitInheritedConstructorNote(S, Found); 11135 return; 11136 case Sema::TDK_CUDATargetMismatch: 11137 S.Diag(Templated->getLocation(), 11138 diag::note_cuda_ovl_candidate_target_mismatch); 11139 return; 11140 } 11141 } 11142 11143 /// Diagnose a failed template-argument deduction, for function calls. 11144 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11145 unsigned NumArgs, 11146 bool TakingCandidateAddress) { 11147 unsigned TDK = Cand->DeductionFailure.Result; 11148 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11149 if (CheckArityMismatch(S, Cand, NumArgs)) 11150 return; 11151 } 11152 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11153 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11154 } 11155 11156 /// CUDA: diagnose an invalid call across targets. 11157 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11158 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 11159 FunctionDecl *Callee = Cand->Function; 11160 11161 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11162 CalleeTarget = S.IdentifyCUDATarget(Callee); 11163 11164 std::string FnDesc; 11165 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11166 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11167 Cand->getRewriteKind(), FnDesc); 11168 11169 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11170 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11171 << FnDesc /* Ignored */ 11172 << CalleeTarget << CallerTarget; 11173 11174 // This could be an implicit constructor for which we could not infer the 11175 // target due to a collsion. Diagnose that case. 11176 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11177 if (Meth != nullptr && Meth->isImplicit()) { 11178 CXXRecordDecl *ParentClass = Meth->getParent(); 11179 Sema::CXXSpecialMember CSM; 11180 11181 switch (FnKindPair.first) { 11182 default: 11183 return; 11184 case oc_implicit_default_constructor: 11185 CSM = Sema::CXXDefaultConstructor; 11186 break; 11187 case oc_implicit_copy_constructor: 11188 CSM = Sema::CXXCopyConstructor; 11189 break; 11190 case oc_implicit_move_constructor: 11191 CSM = Sema::CXXMoveConstructor; 11192 break; 11193 case oc_implicit_copy_assignment: 11194 CSM = Sema::CXXCopyAssignment; 11195 break; 11196 case oc_implicit_move_assignment: 11197 CSM = Sema::CXXMoveAssignment; 11198 break; 11199 }; 11200 11201 bool ConstRHS = false; 11202 if (Meth->getNumParams()) { 11203 if (const ReferenceType *RT = 11204 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11205 ConstRHS = RT->getPointeeType().isConstQualified(); 11206 } 11207 } 11208 11209 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11210 /* ConstRHS */ ConstRHS, 11211 /* Diagnose */ true); 11212 } 11213 } 11214 11215 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11216 FunctionDecl *Callee = Cand->Function; 11217 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11218 11219 S.Diag(Callee->getLocation(), 11220 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11221 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11222 } 11223 11224 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11225 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11226 assert(ES.isExplicit() && "not an explicit candidate"); 11227 11228 unsigned Kind; 11229 switch (Cand->Function->getDeclKind()) { 11230 case Decl::Kind::CXXConstructor: 11231 Kind = 0; 11232 break; 11233 case Decl::Kind::CXXConversion: 11234 Kind = 1; 11235 break; 11236 case Decl::Kind::CXXDeductionGuide: 11237 Kind = Cand->Function->isImplicit() ? 0 : 2; 11238 break; 11239 default: 11240 llvm_unreachable("invalid Decl"); 11241 } 11242 11243 // Note the location of the first (in-class) declaration; a redeclaration 11244 // (particularly an out-of-class definition) will typically lack the 11245 // 'explicit' specifier. 11246 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11247 FunctionDecl *First = Cand->Function->getFirstDecl(); 11248 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11249 First = Pattern->getFirstDecl(); 11250 11251 S.Diag(First->getLocation(), 11252 diag::note_ovl_candidate_explicit) 11253 << Kind << (ES.getExpr() ? 1 : 0) 11254 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11255 } 11256 11257 /// Generates a 'note' diagnostic for an overload candidate. We've 11258 /// already generated a primary error at the call site. 11259 /// 11260 /// It really does need to be a single diagnostic with its caret 11261 /// pointed at the candidate declaration. Yes, this creates some 11262 /// major challenges of technical writing. Yes, this makes pointing 11263 /// out problems with specific arguments quite awkward. It's still 11264 /// better than generating twenty screens of text for every failed 11265 /// overload. 11266 /// 11267 /// It would be great to be able to express per-candidate problems 11268 /// more richly for those diagnostic clients that cared, but we'd 11269 /// still have to be just as careful with the default diagnostics. 11270 /// \param CtorDestAS Addr space of object being constructed (for ctor 11271 /// candidates only). 11272 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11273 unsigned NumArgs, 11274 bool TakingCandidateAddress, 11275 LangAS CtorDestAS = LangAS::Default) { 11276 FunctionDecl *Fn = Cand->Function; 11277 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11278 return; 11279 11280 // There is no physical candidate declaration to point to for OpenCL builtins. 11281 // Except for failed conversions, the notes are identical for each candidate, 11282 // so do not generate such notes. 11283 if (S.getLangOpts().OpenCL && Fn->isImplicit() && 11284 Cand->FailureKind != ovl_fail_bad_conversion) 11285 return; 11286 11287 // Note deleted candidates, but only if they're viable. 11288 if (Cand->Viable) { 11289 if (Fn->isDeleted()) { 11290 std::string FnDesc; 11291 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11292 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11293 Cand->getRewriteKind(), FnDesc); 11294 11295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11296 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11297 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11298 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11299 return; 11300 } 11301 11302 // We don't really have anything else to say about viable candidates. 11303 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11304 return; 11305 } 11306 11307 switch (Cand->FailureKind) { 11308 case ovl_fail_too_many_arguments: 11309 case ovl_fail_too_few_arguments: 11310 return DiagnoseArityMismatch(S, Cand, NumArgs); 11311 11312 case ovl_fail_bad_deduction: 11313 return DiagnoseBadDeduction(S, Cand, NumArgs, 11314 TakingCandidateAddress); 11315 11316 case ovl_fail_illegal_constructor: { 11317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11318 << (Fn->getPrimaryTemplate() ? 1 : 0); 11319 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11320 return; 11321 } 11322 11323 case ovl_fail_object_addrspace_mismatch: { 11324 Qualifiers QualsForPrinting; 11325 QualsForPrinting.setAddressSpace(CtorDestAS); 11326 S.Diag(Fn->getLocation(), 11327 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11328 << QualsForPrinting; 11329 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11330 return; 11331 } 11332 11333 case ovl_fail_trivial_conversion: 11334 case ovl_fail_bad_final_conversion: 11335 case ovl_fail_final_conversion_not_exact: 11336 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11337 11338 case ovl_fail_bad_conversion: { 11339 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11340 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11341 if (Cand->Conversions[I].isBad()) 11342 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11343 11344 // FIXME: this currently happens when we're called from SemaInit 11345 // when user-conversion overload fails. Figure out how to handle 11346 // those conditions and diagnose them well. 11347 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11348 } 11349 11350 case ovl_fail_bad_target: 11351 return DiagnoseBadTarget(S, Cand); 11352 11353 case ovl_fail_enable_if: 11354 return DiagnoseFailedEnableIfAttr(S, Cand); 11355 11356 case ovl_fail_explicit: 11357 return DiagnoseFailedExplicitSpec(S, Cand); 11358 11359 case ovl_fail_inhctor_slice: 11360 // It's generally not interesting to note copy/move constructors here. 11361 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11362 return; 11363 S.Diag(Fn->getLocation(), 11364 diag::note_ovl_candidate_inherited_constructor_slice) 11365 << (Fn->getPrimaryTemplate() ? 1 : 0) 11366 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11367 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11368 return; 11369 11370 case ovl_fail_addr_not_available: { 11371 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11372 (void)Available; 11373 assert(!Available); 11374 break; 11375 } 11376 case ovl_non_default_multiversion_function: 11377 // Do nothing, these should simply be ignored. 11378 break; 11379 11380 case ovl_fail_constraints_not_satisfied: { 11381 std::string FnDesc; 11382 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11383 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11384 Cand->getRewriteKind(), FnDesc); 11385 11386 S.Diag(Fn->getLocation(), 11387 diag::note_ovl_candidate_constraints_not_satisfied) 11388 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11389 << FnDesc /* Ignored */; 11390 ConstraintSatisfaction Satisfaction; 11391 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11392 break; 11393 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11394 } 11395 } 11396 } 11397 11398 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11399 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11400 return; 11401 11402 // Desugar the type of the surrogate down to a function type, 11403 // retaining as many typedefs as possible while still showing 11404 // the function type (and, therefore, its parameter types). 11405 QualType FnType = Cand->Surrogate->getConversionType(); 11406 bool isLValueReference = false; 11407 bool isRValueReference = false; 11408 bool isPointer = false; 11409 if (const LValueReferenceType *FnTypeRef = 11410 FnType->getAs<LValueReferenceType>()) { 11411 FnType = FnTypeRef->getPointeeType(); 11412 isLValueReference = true; 11413 } else if (const RValueReferenceType *FnTypeRef = 11414 FnType->getAs<RValueReferenceType>()) { 11415 FnType = FnTypeRef->getPointeeType(); 11416 isRValueReference = true; 11417 } 11418 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11419 FnType = FnTypePtr->getPointeeType(); 11420 isPointer = true; 11421 } 11422 // Desugar down to a function type. 11423 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11424 // Reconstruct the pointer/reference as appropriate. 11425 if (isPointer) FnType = S.Context.getPointerType(FnType); 11426 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11427 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11428 11429 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11430 << FnType; 11431 } 11432 11433 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11434 SourceLocation OpLoc, 11435 OverloadCandidate *Cand) { 11436 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11437 std::string TypeStr("operator"); 11438 TypeStr += Opc; 11439 TypeStr += "("; 11440 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11441 if (Cand->Conversions.size() == 1) { 11442 TypeStr += ")"; 11443 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11444 } else { 11445 TypeStr += ", "; 11446 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11447 TypeStr += ")"; 11448 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11449 } 11450 } 11451 11452 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11453 OverloadCandidate *Cand) { 11454 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11455 if (ICS.isBad()) break; // all meaningless after first invalid 11456 if (!ICS.isAmbiguous()) continue; 11457 11458 ICS.DiagnoseAmbiguousConversion( 11459 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11460 } 11461 } 11462 11463 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11464 if (Cand->Function) 11465 return Cand->Function->getLocation(); 11466 if (Cand->IsSurrogate) 11467 return Cand->Surrogate->getLocation(); 11468 return SourceLocation(); 11469 } 11470 11471 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11472 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11473 case Sema::TDK_Success: 11474 case Sema::TDK_NonDependentConversionFailure: 11475 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11476 11477 case Sema::TDK_Invalid: 11478 case Sema::TDK_Incomplete: 11479 case Sema::TDK_IncompletePack: 11480 return 1; 11481 11482 case Sema::TDK_Underqualified: 11483 case Sema::TDK_Inconsistent: 11484 return 2; 11485 11486 case Sema::TDK_SubstitutionFailure: 11487 case Sema::TDK_DeducedMismatch: 11488 case Sema::TDK_ConstraintsNotSatisfied: 11489 case Sema::TDK_DeducedMismatchNested: 11490 case Sema::TDK_NonDeducedMismatch: 11491 case Sema::TDK_MiscellaneousDeductionFailure: 11492 case Sema::TDK_CUDATargetMismatch: 11493 return 3; 11494 11495 case Sema::TDK_InstantiationDepth: 11496 return 4; 11497 11498 case Sema::TDK_InvalidExplicitArguments: 11499 return 5; 11500 11501 case Sema::TDK_TooManyArguments: 11502 case Sema::TDK_TooFewArguments: 11503 return 6; 11504 } 11505 llvm_unreachable("Unhandled deduction result"); 11506 } 11507 11508 namespace { 11509 struct CompareOverloadCandidatesForDisplay { 11510 Sema &S; 11511 SourceLocation Loc; 11512 size_t NumArgs; 11513 OverloadCandidateSet::CandidateSetKind CSK; 11514 11515 CompareOverloadCandidatesForDisplay( 11516 Sema &S, SourceLocation Loc, size_t NArgs, 11517 OverloadCandidateSet::CandidateSetKind CSK) 11518 : S(S), NumArgs(NArgs), CSK(CSK) {} 11519 11520 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11521 // If there are too many or too few arguments, that's the high-order bit we 11522 // want to sort by, even if the immediate failure kind was something else. 11523 if (C->FailureKind == ovl_fail_too_many_arguments || 11524 C->FailureKind == ovl_fail_too_few_arguments) 11525 return static_cast<OverloadFailureKind>(C->FailureKind); 11526 11527 if (C->Function) { 11528 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11529 return ovl_fail_too_many_arguments; 11530 if (NumArgs < C->Function->getMinRequiredArguments()) 11531 return ovl_fail_too_few_arguments; 11532 } 11533 11534 return static_cast<OverloadFailureKind>(C->FailureKind); 11535 } 11536 11537 bool operator()(const OverloadCandidate *L, 11538 const OverloadCandidate *R) { 11539 // Fast-path this check. 11540 if (L == R) return false; 11541 11542 // Order first by viability. 11543 if (L->Viable) { 11544 if (!R->Viable) return true; 11545 11546 // TODO: introduce a tri-valued comparison for overload 11547 // candidates. Would be more worthwhile if we had a sort 11548 // that could exploit it. 11549 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11550 return true; 11551 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11552 return false; 11553 } else if (R->Viable) 11554 return false; 11555 11556 assert(L->Viable == R->Viable); 11557 11558 // Criteria by which we can sort non-viable candidates: 11559 if (!L->Viable) { 11560 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11561 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11562 11563 // 1. Arity mismatches come after other candidates. 11564 if (LFailureKind == ovl_fail_too_many_arguments || 11565 LFailureKind == ovl_fail_too_few_arguments) { 11566 if (RFailureKind == ovl_fail_too_many_arguments || 11567 RFailureKind == ovl_fail_too_few_arguments) { 11568 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11569 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11570 if (LDist == RDist) { 11571 if (LFailureKind == RFailureKind) 11572 // Sort non-surrogates before surrogates. 11573 return !L->IsSurrogate && R->IsSurrogate; 11574 // Sort candidates requiring fewer parameters than there were 11575 // arguments given after candidates requiring more parameters 11576 // than there were arguments given. 11577 return LFailureKind == ovl_fail_too_many_arguments; 11578 } 11579 return LDist < RDist; 11580 } 11581 return false; 11582 } 11583 if (RFailureKind == ovl_fail_too_many_arguments || 11584 RFailureKind == ovl_fail_too_few_arguments) 11585 return true; 11586 11587 // 2. Bad conversions come first and are ordered by the number 11588 // of bad conversions and quality of good conversions. 11589 if (LFailureKind == ovl_fail_bad_conversion) { 11590 if (RFailureKind != ovl_fail_bad_conversion) 11591 return true; 11592 11593 // The conversion that can be fixed with a smaller number of changes, 11594 // comes first. 11595 unsigned numLFixes = L->Fix.NumConversionsFixed; 11596 unsigned numRFixes = R->Fix.NumConversionsFixed; 11597 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11598 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11599 if (numLFixes != numRFixes) { 11600 return numLFixes < numRFixes; 11601 } 11602 11603 // If there's any ordering between the defined conversions... 11604 // FIXME: this might not be transitive. 11605 assert(L->Conversions.size() == R->Conversions.size()); 11606 11607 int leftBetter = 0; 11608 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11609 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11610 switch (CompareImplicitConversionSequences(S, Loc, 11611 L->Conversions[I], 11612 R->Conversions[I])) { 11613 case ImplicitConversionSequence::Better: 11614 leftBetter++; 11615 break; 11616 11617 case ImplicitConversionSequence::Worse: 11618 leftBetter--; 11619 break; 11620 11621 case ImplicitConversionSequence::Indistinguishable: 11622 break; 11623 } 11624 } 11625 if (leftBetter > 0) return true; 11626 if (leftBetter < 0) return false; 11627 11628 } else if (RFailureKind == ovl_fail_bad_conversion) 11629 return false; 11630 11631 if (LFailureKind == ovl_fail_bad_deduction) { 11632 if (RFailureKind != ovl_fail_bad_deduction) 11633 return true; 11634 11635 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11636 return RankDeductionFailure(L->DeductionFailure) 11637 < RankDeductionFailure(R->DeductionFailure); 11638 } else if (RFailureKind == ovl_fail_bad_deduction) 11639 return false; 11640 11641 // TODO: others? 11642 } 11643 11644 // Sort everything else by location. 11645 SourceLocation LLoc = GetLocationForCandidate(L); 11646 SourceLocation RLoc = GetLocationForCandidate(R); 11647 11648 // Put candidates without locations (e.g. builtins) at the end. 11649 if (LLoc.isInvalid()) return false; 11650 if (RLoc.isInvalid()) return true; 11651 11652 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11653 } 11654 }; 11655 } 11656 11657 /// CompleteNonViableCandidate - Normally, overload resolution only 11658 /// computes up to the first bad conversion. Produces the FixIt set if 11659 /// possible. 11660 static void 11661 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11662 ArrayRef<Expr *> Args, 11663 OverloadCandidateSet::CandidateSetKind CSK) { 11664 assert(!Cand->Viable); 11665 11666 // Don't do anything on failures other than bad conversion. 11667 if (Cand->FailureKind != ovl_fail_bad_conversion) 11668 return; 11669 11670 // We only want the FixIts if all the arguments can be corrected. 11671 bool Unfixable = false; 11672 // Use a implicit copy initialization to check conversion fixes. 11673 Cand->Fix.setConversionChecker(TryCopyInitialization); 11674 11675 // Attempt to fix the bad conversion. 11676 unsigned ConvCount = Cand->Conversions.size(); 11677 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11678 ++ConvIdx) { 11679 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11680 if (Cand->Conversions[ConvIdx].isInitialized() && 11681 Cand->Conversions[ConvIdx].isBad()) { 11682 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11683 break; 11684 } 11685 } 11686 11687 // FIXME: this should probably be preserved from the overload 11688 // operation somehow. 11689 bool SuppressUserConversions = false; 11690 11691 unsigned ConvIdx = 0; 11692 unsigned ArgIdx = 0; 11693 ArrayRef<QualType> ParamTypes; 11694 bool Reversed = Cand->isReversed(); 11695 11696 if (Cand->IsSurrogate) { 11697 QualType ConvType 11698 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11699 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11700 ConvType = ConvPtrType->getPointeeType(); 11701 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11702 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11703 ConvIdx = 1; 11704 } else if (Cand->Function) { 11705 ParamTypes = 11706 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11707 if (isa<CXXMethodDecl>(Cand->Function) && 11708 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11709 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11710 ConvIdx = 1; 11711 if (CSK == OverloadCandidateSet::CSK_Operator && 11712 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 11713 Cand->Function->getDeclName().getCXXOverloadedOperator() != 11714 OO_Subscript) 11715 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11716 ArgIdx = 1; 11717 } 11718 } else { 11719 // Builtin operator. 11720 assert(ConvCount <= 3); 11721 ParamTypes = Cand->BuiltinParamTypes; 11722 } 11723 11724 // Fill in the rest of the conversions. 11725 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11726 ConvIdx != ConvCount; 11727 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11728 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11729 if (Cand->Conversions[ConvIdx].isInitialized()) { 11730 // We've already checked this conversion. 11731 } else if (ParamIdx < ParamTypes.size()) { 11732 if (ParamTypes[ParamIdx]->isDependentType()) 11733 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11734 Args[ArgIdx]->getType()); 11735 else { 11736 Cand->Conversions[ConvIdx] = 11737 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11738 SuppressUserConversions, 11739 /*InOverloadResolution=*/true, 11740 /*AllowObjCWritebackConversion=*/ 11741 S.getLangOpts().ObjCAutoRefCount); 11742 // Store the FixIt in the candidate if it exists. 11743 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11744 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11745 } 11746 } else 11747 Cand->Conversions[ConvIdx].setEllipsis(); 11748 } 11749 } 11750 11751 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11752 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11753 SourceLocation OpLoc, 11754 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11755 // Sort the candidates by viability and position. Sorting directly would 11756 // be prohibitive, so we make a set of pointers and sort those. 11757 SmallVector<OverloadCandidate*, 32> Cands; 11758 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11759 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11760 if (!Filter(*Cand)) 11761 continue; 11762 switch (OCD) { 11763 case OCD_AllCandidates: 11764 if (!Cand->Viable) { 11765 if (!Cand->Function && !Cand->IsSurrogate) { 11766 // This a non-viable builtin candidate. We do not, in general, 11767 // want to list every possible builtin candidate. 11768 continue; 11769 } 11770 CompleteNonViableCandidate(S, Cand, Args, Kind); 11771 } 11772 break; 11773 11774 case OCD_ViableCandidates: 11775 if (!Cand->Viable) 11776 continue; 11777 break; 11778 11779 case OCD_AmbiguousCandidates: 11780 if (!Cand->Best) 11781 continue; 11782 break; 11783 } 11784 11785 Cands.push_back(Cand); 11786 } 11787 11788 llvm::stable_sort( 11789 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11790 11791 return Cands; 11792 } 11793 11794 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11795 SourceLocation OpLoc) { 11796 bool DeferHint = false; 11797 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11798 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11799 // host device candidates. 11800 auto WrongSidedCands = 11801 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11802 return (Cand.Viable == false && 11803 Cand.FailureKind == ovl_fail_bad_target) || 11804 (Cand.Function && 11805 Cand.Function->template hasAttr<CUDAHostAttr>() && 11806 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11807 }); 11808 DeferHint = !WrongSidedCands.empty(); 11809 } 11810 return DeferHint; 11811 } 11812 11813 /// When overload resolution fails, prints diagnostic messages containing the 11814 /// candidates in the candidate set. 11815 void OverloadCandidateSet::NoteCandidates( 11816 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11817 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11818 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11819 11820 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11821 11822 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11823 11824 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11825 11826 if (OCD == OCD_AmbiguousCandidates) 11827 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11828 } 11829 11830 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11831 ArrayRef<OverloadCandidate *> Cands, 11832 StringRef Opc, SourceLocation OpLoc) { 11833 bool ReportedAmbiguousConversions = false; 11834 11835 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11836 unsigned CandsShown = 0; 11837 auto I = Cands.begin(), E = Cands.end(); 11838 for (; I != E; ++I) { 11839 OverloadCandidate *Cand = *I; 11840 11841 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11842 ShowOverloads == Ovl_Best) { 11843 break; 11844 } 11845 ++CandsShown; 11846 11847 if (Cand->Function) 11848 NoteFunctionCandidate(S, Cand, Args.size(), 11849 /*TakingCandidateAddress=*/false, DestAS); 11850 else if (Cand->IsSurrogate) 11851 NoteSurrogateCandidate(S, Cand); 11852 else { 11853 assert(Cand->Viable && 11854 "Non-viable built-in candidates are not added to Cands."); 11855 // Generally we only see ambiguities including viable builtin 11856 // operators if overload resolution got screwed up by an 11857 // ambiguous user-defined conversion. 11858 // 11859 // FIXME: It's quite possible for different conversions to see 11860 // different ambiguities, though. 11861 if (!ReportedAmbiguousConversions) { 11862 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11863 ReportedAmbiguousConversions = true; 11864 } 11865 11866 // If this is a viable builtin, print it. 11867 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11868 } 11869 } 11870 11871 // Inform S.Diags that we've shown an overload set with N elements. This may 11872 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11873 S.Diags.overloadCandidatesShown(CandsShown); 11874 11875 if (I != E) 11876 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11877 shouldDeferDiags(S, Args, OpLoc)) 11878 << int(E - I); 11879 } 11880 11881 static SourceLocation 11882 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11883 return Cand->Specialization ? Cand->Specialization->getLocation() 11884 : SourceLocation(); 11885 } 11886 11887 namespace { 11888 struct CompareTemplateSpecCandidatesForDisplay { 11889 Sema &S; 11890 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11891 11892 bool operator()(const TemplateSpecCandidate *L, 11893 const TemplateSpecCandidate *R) { 11894 // Fast-path this check. 11895 if (L == R) 11896 return false; 11897 11898 // Assuming that both candidates are not matches... 11899 11900 // Sort by the ranking of deduction failures. 11901 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11902 return RankDeductionFailure(L->DeductionFailure) < 11903 RankDeductionFailure(R->DeductionFailure); 11904 11905 // Sort everything else by location. 11906 SourceLocation LLoc = GetLocationForCandidate(L); 11907 SourceLocation RLoc = GetLocationForCandidate(R); 11908 11909 // Put candidates without locations (e.g. builtins) at the end. 11910 if (LLoc.isInvalid()) 11911 return false; 11912 if (RLoc.isInvalid()) 11913 return true; 11914 11915 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11916 } 11917 }; 11918 } 11919 11920 /// Diagnose a template argument deduction failure. 11921 /// We are treating these failures as overload failures due to bad 11922 /// deductions. 11923 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11924 bool ForTakingAddress) { 11925 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11926 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11927 } 11928 11929 void TemplateSpecCandidateSet::destroyCandidates() { 11930 for (iterator i = begin(), e = end(); i != e; ++i) { 11931 i->DeductionFailure.Destroy(); 11932 } 11933 } 11934 11935 void TemplateSpecCandidateSet::clear() { 11936 destroyCandidates(); 11937 Candidates.clear(); 11938 } 11939 11940 /// NoteCandidates - When no template specialization match is found, prints 11941 /// diagnostic messages containing the non-matching specializations that form 11942 /// the candidate set. 11943 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11944 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11945 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11946 // Sort the candidates by position (assuming no candidate is a match). 11947 // Sorting directly would be prohibitive, so we make a set of pointers 11948 // and sort those. 11949 SmallVector<TemplateSpecCandidate *, 32> Cands; 11950 Cands.reserve(size()); 11951 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11952 if (Cand->Specialization) 11953 Cands.push_back(Cand); 11954 // Otherwise, this is a non-matching builtin candidate. We do not, 11955 // in general, want to list every possible builtin candidate. 11956 } 11957 11958 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11959 11960 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11961 // for generalization purposes (?). 11962 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11963 11964 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11965 unsigned CandsShown = 0; 11966 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11967 TemplateSpecCandidate *Cand = *I; 11968 11969 // Set an arbitrary limit on the number of candidates we'll spam 11970 // the user with. FIXME: This limit should depend on details of the 11971 // candidate list. 11972 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11973 break; 11974 ++CandsShown; 11975 11976 assert(Cand->Specialization && 11977 "Non-matching built-in candidates are not added to Cands."); 11978 Cand->NoteDeductionFailure(S, ForTakingAddress); 11979 } 11980 11981 if (I != E) 11982 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11983 } 11984 11985 // [PossiblyAFunctionType] --> [Return] 11986 // NonFunctionType --> NonFunctionType 11987 // R (A) --> R(A) 11988 // R (*)(A) --> R (A) 11989 // R (&)(A) --> R (A) 11990 // R (S::*)(A) --> R (A) 11991 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11992 QualType Ret = PossiblyAFunctionType; 11993 if (const PointerType *ToTypePtr = 11994 PossiblyAFunctionType->getAs<PointerType>()) 11995 Ret = ToTypePtr->getPointeeType(); 11996 else if (const ReferenceType *ToTypeRef = 11997 PossiblyAFunctionType->getAs<ReferenceType>()) 11998 Ret = ToTypeRef->getPointeeType(); 11999 else if (const MemberPointerType *MemTypePtr = 12000 PossiblyAFunctionType->getAs<MemberPointerType>()) 12001 Ret = MemTypePtr->getPointeeType(); 12002 Ret = 12003 Context.getCanonicalType(Ret).getUnqualifiedType(); 12004 return Ret; 12005 } 12006 12007 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 12008 bool Complain = true) { 12009 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 12010 S.DeduceReturnType(FD, Loc, Complain)) 12011 return true; 12012 12013 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 12014 if (S.getLangOpts().CPlusPlus17 && 12015 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 12016 !S.ResolveExceptionSpec(Loc, FPT)) 12017 return true; 12018 12019 return false; 12020 } 12021 12022 namespace { 12023 // A helper class to help with address of function resolution 12024 // - allows us to avoid passing around all those ugly parameters 12025 class AddressOfFunctionResolver { 12026 Sema& S; 12027 Expr* SourceExpr; 12028 const QualType& TargetType; 12029 QualType TargetFunctionType; // Extracted function type from target type 12030 12031 bool Complain; 12032 //DeclAccessPair& ResultFunctionAccessPair; 12033 ASTContext& Context; 12034 12035 bool TargetTypeIsNonStaticMemberFunction; 12036 bool FoundNonTemplateFunction; 12037 bool StaticMemberFunctionFromBoundPointer; 12038 bool HasComplained; 12039 12040 OverloadExpr::FindResult OvlExprInfo; 12041 OverloadExpr *OvlExpr; 12042 TemplateArgumentListInfo OvlExplicitTemplateArgs; 12043 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 12044 TemplateSpecCandidateSet FailedCandidates; 12045 12046 public: 12047 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 12048 const QualType &TargetType, bool Complain) 12049 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 12050 Complain(Complain), Context(S.getASTContext()), 12051 TargetTypeIsNonStaticMemberFunction( 12052 !!TargetType->getAs<MemberPointerType>()), 12053 FoundNonTemplateFunction(false), 12054 StaticMemberFunctionFromBoundPointer(false), 12055 HasComplained(false), 12056 OvlExprInfo(OverloadExpr::find(SourceExpr)), 12057 OvlExpr(OvlExprInfo.Expression), 12058 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 12059 ExtractUnqualifiedFunctionTypeFromTargetType(); 12060 12061 if (TargetFunctionType->isFunctionType()) { 12062 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 12063 if (!UME->isImplicitAccess() && 12064 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 12065 StaticMemberFunctionFromBoundPointer = true; 12066 } else if (OvlExpr->hasExplicitTemplateArgs()) { 12067 DeclAccessPair dap; 12068 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 12069 OvlExpr, false, &dap)) { 12070 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 12071 if (!Method->isStatic()) { 12072 // If the target type is a non-function type and the function found 12073 // is a non-static member function, pretend as if that was the 12074 // target, it's the only possible type to end up with. 12075 TargetTypeIsNonStaticMemberFunction = true; 12076 12077 // And skip adding the function if its not in the proper form. 12078 // We'll diagnose this due to an empty set of functions. 12079 if (!OvlExprInfo.HasFormOfMemberPointer) 12080 return; 12081 } 12082 12083 Matches.push_back(std::make_pair(dap, Fn)); 12084 } 12085 return; 12086 } 12087 12088 if (OvlExpr->hasExplicitTemplateArgs()) 12089 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 12090 12091 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 12092 // C++ [over.over]p4: 12093 // If more than one function is selected, [...] 12094 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12095 if (FoundNonTemplateFunction) 12096 EliminateAllTemplateMatches(); 12097 else 12098 EliminateAllExceptMostSpecializedTemplate(); 12099 } 12100 } 12101 12102 if (S.getLangOpts().CUDA && Matches.size() > 1) 12103 EliminateSuboptimalCudaMatches(); 12104 } 12105 12106 bool hasComplained() const { return HasComplained; } 12107 12108 private: 12109 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12110 QualType Discard; 12111 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12112 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12113 } 12114 12115 /// \return true if A is considered a better overload candidate for the 12116 /// desired type than B. 12117 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12118 // If A doesn't have exactly the correct type, we don't want to classify it 12119 // as "better" than anything else. This way, the user is required to 12120 // disambiguate for us if there are multiple candidates and no exact match. 12121 return candidateHasExactlyCorrectType(A) && 12122 (!candidateHasExactlyCorrectType(B) || 12123 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12124 } 12125 12126 /// \return true if we were able to eliminate all but one overload candidate, 12127 /// false otherwise. 12128 bool eliminiateSuboptimalOverloadCandidates() { 12129 // Same algorithm as overload resolution -- one pass to pick the "best", 12130 // another pass to be sure that nothing is better than the best. 12131 auto Best = Matches.begin(); 12132 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12133 if (isBetterCandidate(I->second, Best->second)) 12134 Best = I; 12135 12136 const FunctionDecl *BestFn = Best->second; 12137 auto IsBestOrInferiorToBest = [this, BestFn]( 12138 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12139 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12140 }; 12141 12142 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12143 // option, so we can potentially give the user a better error 12144 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12145 return false; 12146 Matches[0] = *Best; 12147 Matches.resize(1); 12148 return true; 12149 } 12150 12151 bool isTargetTypeAFunction() const { 12152 return TargetFunctionType->isFunctionType(); 12153 } 12154 12155 // [ToType] [Return] 12156 12157 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12158 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12159 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12160 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12161 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12162 } 12163 12164 // return true if any matching specializations were found 12165 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12166 const DeclAccessPair& CurAccessFunPair) { 12167 if (CXXMethodDecl *Method 12168 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12169 // Skip non-static function templates when converting to pointer, and 12170 // static when converting to member pointer. 12171 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12172 return false; 12173 } 12174 else if (TargetTypeIsNonStaticMemberFunction) 12175 return false; 12176 12177 // C++ [over.over]p2: 12178 // If the name is a function template, template argument deduction is 12179 // done (14.8.2.2), and if the argument deduction succeeds, the 12180 // resulting template argument list is used to generate a single 12181 // function template specialization, which is added to the set of 12182 // overloaded functions considered. 12183 FunctionDecl *Specialization = nullptr; 12184 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12185 if (Sema::TemplateDeductionResult Result 12186 = S.DeduceTemplateArguments(FunctionTemplate, 12187 &OvlExplicitTemplateArgs, 12188 TargetFunctionType, Specialization, 12189 Info, /*IsAddressOfFunction*/true)) { 12190 // Make a note of the failed deduction for diagnostics. 12191 FailedCandidates.addCandidate() 12192 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12193 MakeDeductionFailureInfo(Context, Result, Info)); 12194 return false; 12195 } 12196 12197 // Template argument deduction ensures that we have an exact match or 12198 // compatible pointer-to-function arguments that would be adjusted by ICS. 12199 // This function template specicalization works. 12200 assert(S.isSameOrCompatibleFunctionType( 12201 Context.getCanonicalType(Specialization->getType()), 12202 Context.getCanonicalType(TargetFunctionType))); 12203 12204 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12205 return false; 12206 12207 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12208 return true; 12209 } 12210 12211 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12212 const DeclAccessPair& CurAccessFunPair) { 12213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12214 // Skip non-static functions when converting to pointer, and static 12215 // when converting to member pointer. 12216 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12217 return false; 12218 } 12219 else if (TargetTypeIsNonStaticMemberFunction) 12220 return false; 12221 12222 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12223 if (S.getLangOpts().CUDA) 12224 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) 12225 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12226 return false; 12227 if (FunDecl->isMultiVersion()) { 12228 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12229 if (TA && !TA->isDefaultVersion()) 12230 return false; 12231 } 12232 12233 // If any candidate has a placeholder return type, trigger its deduction 12234 // now. 12235 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12236 Complain)) { 12237 HasComplained |= Complain; 12238 return false; 12239 } 12240 12241 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12242 return false; 12243 12244 // If we're in C, we need to support types that aren't exactly identical. 12245 if (!S.getLangOpts().CPlusPlus || 12246 candidateHasExactlyCorrectType(FunDecl)) { 12247 Matches.push_back(std::make_pair( 12248 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12249 FoundNonTemplateFunction = true; 12250 return true; 12251 } 12252 } 12253 12254 return false; 12255 } 12256 12257 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12258 bool Ret = false; 12259 12260 // If the overload expression doesn't have the form of a pointer to 12261 // member, don't try to convert it to a pointer-to-member type. 12262 if (IsInvalidFormOfPointerToMemberFunction()) 12263 return false; 12264 12265 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12266 E = OvlExpr->decls_end(); 12267 I != E; ++I) { 12268 // Look through any using declarations to find the underlying function. 12269 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12270 12271 // C++ [over.over]p3: 12272 // Non-member functions and static member functions match 12273 // targets of type "pointer-to-function" or "reference-to-function." 12274 // Nonstatic member functions match targets of 12275 // type "pointer-to-member-function." 12276 // Note that according to DR 247, the containing class does not matter. 12277 if (FunctionTemplateDecl *FunctionTemplate 12278 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12279 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12280 Ret = true; 12281 } 12282 // If we have explicit template arguments supplied, skip non-templates. 12283 else if (!OvlExpr->hasExplicitTemplateArgs() && 12284 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12285 Ret = true; 12286 } 12287 assert(Ret || Matches.empty()); 12288 return Ret; 12289 } 12290 12291 void EliminateAllExceptMostSpecializedTemplate() { 12292 // [...] and any given function template specialization F1 is 12293 // eliminated if the set contains a second function template 12294 // specialization whose function template is more specialized 12295 // than the function template of F1 according to the partial 12296 // ordering rules of 14.5.5.2. 12297 12298 // The algorithm specified above is quadratic. We instead use a 12299 // two-pass algorithm (similar to the one used to identify the 12300 // best viable function in an overload set) that identifies the 12301 // best function template (if it exists). 12302 12303 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12304 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12305 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12306 12307 // TODO: It looks like FailedCandidates does not serve much purpose 12308 // here, since the no_viable diagnostic has index 0. 12309 UnresolvedSetIterator Result = S.getMostSpecialized( 12310 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12311 SourceExpr->getBeginLoc(), S.PDiag(), 12312 S.PDiag(diag::err_addr_ovl_ambiguous) 12313 << Matches[0].second->getDeclName(), 12314 S.PDiag(diag::note_ovl_candidate) 12315 << (unsigned)oc_function << (unsigned)ocs_described_template, 12316 Complain, TargetFunctionType); 12317 12318 if (Result != MatchesCopy.end()) { 12319 // Make it the first and only element 12320 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12321 Matches[0].second = cast<FunctionDecl>(*Result); 12322 Matches.resize(1); 12323 } else 12324 HasComplained |= Complain; 12325 } 12326 12327 void EliminateAllTemplateMatches() { 12328 // [...] any function template specializations in the set are 12329 // eliminated if the set also contains a non-template function, [...] 12330 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12331 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12332 ++I; 12333 else { 12334 Matches[I] = Matches[--N]; 12335 Matches.resize(N); 12336 } 12337 } 12338 } 12339 12340 void EliminateSuboptimalCudaMatches() { 12341 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), 12342 Matches); 12343 } 12344 12345 public: 12346 void ComplainNoMatchesFound() const { 12347 assert(Matches.empty()); 12348 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12349 << OvlExpr->getName() << TargetFunctionType 12350 << OvlExpr->getSourceRange(); 12351 if (FailedCandidates.empty()) 12352 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12353 /*TakingAddress=*/true); 12354 else { 12355 // We have some deduction failure messages. Use them to diagnose 12356 // the function templates, and diagnose the non-template candidates 12357 // normally. 12358 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12359 IEnd = OvlExpr->decls_end(); 12360 I != IEnd; ++I) 12361 if (FunctionDecl *Fun = 12362 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12363 if (!functionHasPassObjectSizeParams(Fun)) 12364 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12365 /*TakingAddress=*/true); 12366 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12367 } 12368 } 12369 12370 bool IsInvalidFormOfPointerToMemberFunction() const { 12371 return TargetTypeIsNonStaticMemberFunction && 12372 !OvlExprInfo.HasFormOfMemberPointer; 12373 } 12374 12375 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12376 // TODO: Should we condition this on whether any functions might 12377 // have matched, or is it more appropriate to do that in callers? 12378 // TODO: a fixit wouldn't hurt. 12379 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12380 << TargetType << OvlExpr->getSourceRange(); 12381 } 12382 12383 bool IsStaticMemberFunctionFromBoundPointer() const { 12384 return StaticMemberFunctionFromBoundPointer; 12385 } 12386 12387 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12388 S.Diag(OvlExpr->getBeginLoc(), 12389 diag::err_invalid_form_pointer_member_function) 12390 << OvlExpr->getSourceRange(); 12391 } 12392 12393 void ComplainOfInvalidConversion() const { 12394 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12395 << OvlExpr->getName() << TargetType; 12396 } 12397 12398 void ComplainMultipleMatchesFound() const { 12399 assert(Matches.size() > 1); 12400 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12401 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12402 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12403 /*TakingAddress=*/true); 12404 } 12405 12406 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12407 12408 int getNumMatches() const { return Matches.size(); } 12409 12410 FunctionDecl* getMatchingFunctionDecl() const { 12411 if (Matches.size() != 1) return nullptr; 12412 return Matches[0].second; 12413 } 12414 12415 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12416 if (Matches.size() != 1) return nullptr; 12417 return &Matches[0].first; 12418 } 12419 }; 12420 } 12421 12422 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12423 /// an overloaded function (C++ [over.over]), where @p From is an 12424 /// expression with overloaded function type and @p ToType is the type 12425 /// we're trying to resolve to. For example: 12426 /// 12427 /// @code 12428 /// int f(double); 12429 /// int f(int); 12430 /// 12431 /// int (*pfd)(double) = f; // selects f(double) 12432 /// @endcode 12433 /// 12434 /// This routine returns the resulting FunctionDecl if it could be 12435 /// resolved, and NULL otherwise. When @p Complain is true, this 12436 /// routine will emit diagnostics if there is an error. 12437 FunctionDecl * 12438 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12439 QualType TargetType, 12440 bool Complain, 12441 DeclAccessPair &FoundResult, 12442 bool *pHadMultipleCandidates) { 12443 assert(AddressOfExpr->getType() == Context.OverloadTy); 12444 12445 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12446 Complain); 12447 int NumMatches = Resolver.getNumMatches(); 12448 FunctionDecl *Fn = nullptr; 12449 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12450 if (NumMatches == 0 && ShouldComplain) { 12451 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12452 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12453 else 12454 Resolver.ComplainNoMatchesFound(); 12455 } 12456 else if (NumMatches > 1 && ShouldComplain) 12457 Resolver.ComplainMultipleMatchesFound(); 12458 else if (NumMatches == 1) { 12459 Fn = Resolver.getMatchingFunctionDecl(); 12460 assert(Fn); 12461 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12462 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12463 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12464 if (Complain) { 12465 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12466 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12467 else 12468 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12469 } 12470 } 12471 12472 if (pHadMultipleCandidates) 12473 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12474 return Fn; 12475 } 12476 12477 /// Given an expression that refers to an overloaded function, try to 12478 /// resolve that function to a single function that can have its address taken. 12479 /// This will modify `Pair` iff it returns non-null. 12480 /// 12481 /// This routine can only succeed if from all of the candidates in the overload 12482 /// set for SrcExpr that can have their addresses taken, there is one candidate 12483 /// that is more constrained than the rest. 12484 FunctionDecl * 12485 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12486 OverloadExpr::FindResult R = OverloadExpr::find(E); 12487 OverloadExpr *Ovl = R.Expression; 12488 bool IsResultAmbiguous = false; 12489 FunctionDecl *Result = nullptr; 12490 DeclAccessPair DAP; 12491 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12492 12493 auto CheckMoreConstrained = 12494 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12495 SmallVector<const Expr *, 1> AC1, AC2; 12496 FD1->getAssociatedConstraints(AC1); 12497 FD2->getAssociatedConstraints(AC2); 12498 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12499 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12500 return None; 12501 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12502 return None; 12503 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12504 return None; 12505 return AtLeastAsConstrained1; 12506 }; 12507 12508 // Don't use the AddressOfResolver because we're specifically looking for 12509 // cases where we have one overload candidate that lacks 12510 // enable_if/pass_object_size/... 12511 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12512 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12513 if (!FD) 12514 return nullptr; 12515 12516 if (!checkAddressOfFunctionIsAvailable(FD)) 12517 continue; 12518 12519 // We have more than one result - see if it is more constrained than the 12520 // previous one. 12521 if (Result) { 12522 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12523 Result); 12524 if (!MoreConstrainedThanPrevious) { 12525 IsResultAmbiguous = true; 12526 AmbiguousDecls.push_back(FD); 12527 continue; 12528 } 12529 if (!*MoreConstrainedThanPrevious) 12530 continue; 12531 // FD is more constrained - replace Result with it. 12532 } 12533 IsResultAmbiguous = false; 12534 DAP = I.getPair(); 12535 Result = FD; 12536 } 12537 12538 if (IsResultAmbiguous) 12539 return nullptr; 12540 12541 if (Result) { 12542 SmallVector<const Expr *, 1> ResultAC; 12543 // We skipped over some ambiguous declarations which might be ambiguous with 12544 // the selected result. 12545 for (FunctionDecl *Skipped : AmbiguousDecls) 12546 if (!CheckMoreConstrained(Skipped, Result)) 12547 return nullptr; 12548 Pair = DAP; 12549 } 12550 return Result; 12551 } 12552 12553 /// Given an overloaded function, tries to turn it into a non-overloaded 12554 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12555 /// will perform access checks, diagnose the use of the resultant decl, and, if 12556 /// requested, potentially perform a function-to-pointer decay. 12557 /// 12558 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12559 /// Otherwise, returns true. This may emit diagnostics and return true. 12560 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12561 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12562 Expr *E = SrcExpr.get(); 12563 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12564 12565 DeclAccessPair DAP; 12566 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12567 if (!Found || Found->isCPUDispatchMultiVersion() || 12568 Found->isCPUSpecificMultiVersion()) 12569 return false; 12570 12571 // Emitting multiple diagnostics for a function that is both inaccessible and 12572 // unavailable is consistent with our behavior elsewhere. So, always check 12573 // for both. 12574 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12575 CheckAddressOfMemberAccess(E, DAP); 12576 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12577 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12578 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12579 else 12580 SrcExpr = Fixed; 12581 return true; 12582 } 12583 12584 /// Given an expression that refers to an overloaded function, try to 12585 /// resolve that overloaded function expression down to a single function. 12586 /// 12587 /// This routine can only resolve template-ids that refer to a single function 12588 /// template, where that template-id refers to a single template whose template 12589 /// arguments are either provided by the template-id or have defaults, 12590 /// as described in C++0x [temp.arg.explicit]p3. 12591 /// 12592 /// If no template-ids are found, no diagnostics are emitted and NULL is 12593 /// returned. 12594 FunctionDecl * 12595 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12596 bool Complain, 12597 DeclAccessPair *FoundResult) { 12598 // C++ [over.over]p1: 12599 // [...] [Note: any redundant set of parentheses surrounding the 12600 // overloaded function name is ignored (5.1). ] 12601 // C++ [over.over]p1: 12602 // [...] The overloaded function name can be preceded by the & 12603 // operator. 12604 12605 // If we didn't actually find any template-ids, we're done. 12606 if (!ovl->hasExplicitTemplateArgs()) 12607 return nullptr; 12608 12609 TemplateArgumentListInfo ExplicitTemplateArgs; 12610 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12611 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12612 12613 // Look through all of the overloaded functions, searching for one 12614 // whose type matches exactly. 12615 FunctionDecl *Matched = nullptr; 12616 for (UnresolvedSetIterator I = ovl->decls_begin(), 12617 E = ovl->decls_end(); I != E; ++I) { 12618 // C++0x [temp.arg.explicit]p3: 12619 // [...] In contexts where deduction is done and fails, or in contexts 12620 // where deduction is not done, if a template argument list is 12621 // specified and it, along with any default template arguments, 12622 // identifies a single function template specialization, then the 12623 // template-id is an lvalue for the function template specialization. 12624 FunctionTemplateDecl *FunctionTemplate 12625 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12626 12627 // C++ [over.over]p2: 12628 // If the name is a function template, template argument deduction is 12629 // done (14.8.2.2), and if the argument deduction succeeds, the 12630 // resulting template argument list is used to generate a single 12631 // function template specialization, which is added to the set of 12632 // overloaded functions considered. 12633 FunctionDecl *Specialization = nullptr; 12634 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12635 if (TemplateDeductionResult Result 12636 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12637 Specialization, Info, 12638 /*IsAddressOfFunction*/true)) { 12639 // Make a note of the failed deduction for diagnostics. 12640 // TODO: Actually use the failed-deduction info? 12641 FailedCandidates.addCandidate() 12642 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12643 MakeDeductionFailureInfo(Context, Result, Info)); 12644 continue; 12645 } 12646 12647 assert(Specialization && "no specialization and no error?"); 12648 12649 // Multiple matches; we can't resolve to a single declaration. 12650 if (Matched) { 12651 if (Complain) { 12652 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12653 << ovl->getName(); 12654 NoteAllOverloadCandidates(ovl); 12655 } 12656 return nullptr; 12657 } 12658 12659 Matched = Specialization; 12660 if (FoundResult) *FoundResult = I.getPair(); 12661 } 12662 12663 if (Matched && 12664 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12665 return nullptr; 12666 12667 return Matched; 12668 } 12669 12670 // Resolve and fix an overloaded expression that can be resolved 12671 // because it identifies a single function template specialization. 12672 // 12673 // Last three arguments should only be supplied if Complain = true 12674 // 12675 // Return true if it was logically possible to so resolve the 12676 // expression, regardless of whether or not it succeeded. Always 12677 // returns true if 'complain' is set. 12678 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12679 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12680 bool complain, SourceRange OpRangeForComplaining, 12681 QualType DestTypeForComplaining, 12682 unsigned DiagIDForComplaining) { 12683 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12684 12685 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12686 12687 DeclAccessPair found; 12688 ExprResult SingleFunctionExpression; 12689 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12690 ovl.Expression, /*complain*/ false, &found)) { 12691 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12692 SrcExpr = ExprError(); 12693 return true; 12694 } 12695 12696 // It is only correct to resolve to an instance method if we're 12697 // resolving a form that's permitted to be a pointer to member. 12698 // Otherwise we'll end up making a bound member expression, which 12699 // is illegal in all the contexts we resolve like this. 12700 if (!ovl.HasFormOfMemberPointer && 12701 isa<CXXMethodDecl>(fn) && 12702 cast<CXXMethodDecl>(fn)->isInstance()) { 12703 if (!complain) return false; 12704 12705 Diag(ovl.Expression->getExprLoc(), 12706 diag::err_bound_member_function) 12707 << 0 << ovl.Expression->getSourceRange(); 12708 12709 // TODO: I believe we only end up here if there's a mix of 12710 // static and non-static candidates (otherwise the expression 12711 // would have 'bound member' type, not 'overload' type). 12712 // Ideally we would note which candidate was chosen and why 12713 // the static candidates were rejected. 12714 SrcExpr = ExprError(); 12715 return true; 12716 } 12717 12718 // Fix the expression to refer to 'fn'. 12719 SingleFunctionExpression = 12720 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12721 12722 // If desired, do function-to-pointer decay. 12723 if (doFunctionPointerConverion) { 12724 SingleFunctionExpression = 12725 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12726 if (SingleFunctionExpression.isInvalid()) { 12727 SrcExpr = ExprError(); 12728 return true; 12729 } 12730 } 12731 } 12732 12733 if (!SingleFunctionExpression.isUsable()) { 12734 if (complain) { 12735 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12736 << ovl.Expression->getName() 12737 << DestTypeForComplaining 12738 << OpRangeForComplaining 12739 << ovl.Expression->getQualifierLoc().getSourceRange(); 12740 NoteAllOverloadCandidates(SrcExpr.get()); 12741 12742 SrcExpr = ExprError(); 12743 return true; 12744 } 12745 12746 return false; 12747 } 12748 12749 SrcExpr = SingleFunctionExpression; 12750 return true; 12751 } 12752 12753 /// Add a single candidate to the overload set. 12754 static void AddOverloadedCallCandidate(Sema &S, 12755 DeclAccessPair FoundDecl, 12756 TemplateArgumentListInfo *ExplicitTemplateArgs, 12757 ArrayRef<Expr *> Args, 12758 OverloadCandidateSet &CandidateSet, 12759 bool PartialOverloading, 12760 bool KnownValid) { 12761 NamedDecl *Callee = FoundDecl.getDecl(); 12762 if (isa<UsingShadowDecl>(Callee)) 12763 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12764 12765 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12766 if (ExplicitTemplateArgs) { 12767 assert(!KnownValid && "Explicit template arguments?"); 12768 return; 12769 } 12770 // Prevent ill-formed function decls to be added as overload candidates. 12771 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12772 return; 12773 12774 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12775 /*SuppressUserConversions=*/false, 12776 PartialOverloading); 12777 return; 12778 } 12779 12780 if (FunctionTemplateDecl *FuncTemplate 12781 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12782 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12783 ExplicitTemplateArgs, Args, CandidateSet, 12784 /*SuppressUserConversions=*/false, 12785 PartialOverloading); 12786 return; 12787 } 12788 12789 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12790 } 12791 12792 /// Add the overload candidates named by callee and/or found by argument 12793 /// dependent lookup to the given overload set. 12794 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12795 ArrayRef<Expr *> Args, 12796 OverloadCandidateSet &CandidateSet, 12797 bool PartialOverloading) { 12798 12799 #ifndef NDEBUG 12800 // Verify that ArgumentDependentLookup is consistent with the rules 12801 // in C++0x [basic.lookup.argdep]p3: 12802 // 12803 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12804 // and let Y be the lookup set produced by argument dependent 12805 // lookup (defined as follows). If X contains 12806 // 12807 // -- a declaration of a class member, or 12808 // 12809 // -- a block-scope function declaration that is not a 12810 // using-declaration, or 12811 // 12812 // -- a declaration that is neither a function or a function 12813 // template 12814 // 12815 // then Y is empty. 12816 12817 if (ULE->requiresADL()) { 12818 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12819 E = ULE->decls_end(); I != E; ++I) { 12820 assert(!(*I)->getDeclContext()->isRecord()); 12821 assert(isa<UsingShadowDecl>(*I) || 12822 !(*I)->getDeclContext()->isFunctionOrMethod()); 12823 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12824 } 12825 } 12826 #endif 12827 12828 // It would be nice to avoid this copy. 12829 TemplateArgumentListInfo TABuffer; 12830 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12831 if (ULE->hasExplicitTemplateArgs()) { 12832 ULE->copyTemplateArgumentsInto(TABuffer); 12833 ExplicitTemplateArgs = &TABuffer; 12834 } 12835 12836 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12837 E = ULE->decls_end(); I != E; ++I) 12838 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12839 CandidateSet, PartialOverloading, 12840 /*KnownValid*/ true); 12841 12842 if (ULE->requiresADL()) 12843 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12844 Args, ExplicitTemplateArgs, 12845 CandidateSet, PartialOverloading); 12846 } 12847 12848 /// Add the call candidates from the given set of lookup results to the given 12849 /// overload set. Non-function lookup results are ignored. 12850 void Sema::AddOverloadedCallCandidates( 12851 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12852 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12853 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12854 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12855 CandidateSet, false, /*KnownValid*/ false); 12856 } 12857 12858 /// Determine whether a declaration with the specified name could be moved into 12859 /// a different namespace. 12860 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12861 switch (Name.getCXXOverloadedOperator()) { 12862 case OO_New: case OO_Array_New: 12863 case OO_Delete: case OO_Array_Delete: 12864 return false; 12865 12866 default: 12867 return true; 12868 } 12869 } 12870 12871 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12872 /// template, where the non-dependent name was declared after the template 12873 /// was defined. This is common in code written for a compilers which do not 12874 /// correctly implement two-stage name lookup. 12875 /// 12876 /// Returns true if a viable candidate was found and a diagnostic was issued. 12877 static bool DiagnoseTwoPhaseLookup( 12878 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12879 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12880 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12881 CXXRecordDecl **FoundInClass = nullptr) { 12882 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12883 return false; 12884 12885 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12886 if (DC->isTransparentContext()) 12887 continue; 12888 12889 SemaRef.LookupQualifiedName(R, DC); 12890 12891 if (!R.empty()) { 12892 R.suppressDiagnostics(); 12893 12894 OverloadCandidateSet Candidates(FnLoc, CSK); 12895 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12896 Candidates); 12897 12898 OverloadCandidateSet::iterator Best; 12899 OverloadingResult OR = 12900 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12901 12902 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12903 // We either found non-function declarations or a best viable function 12904 // at class scope. A class-scope lookup result disables ADL. Don't 12905 // look past this, but let the caller know that we found something that 12906 // either is, or might be, usable in this class. 12907 if (FoundInClass) { 12908 *FoundInClass = RD; 12909 if (OR == OR_Success) { 12910 R.clear(); 12911 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12912 R.resolveKind(); 12913 } 12914 } 12915 return false; 12916 } 12917 12918 if (OR != OR_Success) { 12919 // There wasn't a unique best function or function template. 12920 return false; 12921 } 12922 12923 // Find the namespaces where ADL would have looked, and suggest 12924 // declaring the function there instead. 12925 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12926 Sema::AssociatedClassSet AssociatedClasses; 12927 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12928 AssociatedNamespaces, 12929 AssociatedClasses); 12930 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12931 if (canBeDeclaredInNamespace(R.getLookupName())) { 12932 DeclContext *Std = SemaRef.getStdNamespace(); 12933 for (Sema::AssociatedNamespaceSet::iterator 12934 it = AssociatedNamespaces.begin(), 12935 end = AssociatedNamespaces.end(); it != end; ++it) { 12936 // Never suggest declaring a function within namespace 'std'. 12937 if (Std && Std->Encloses(*it)) 12938 continue; 12939 12940 // Never suggest declaring a function within a namespace with a 12941 // reserved name, like __gnu_cxx. 12942 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12943 if (NS && 12944 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12945 continue; 12946 12947 SuggestedNamespaces.insert(*it); 12948 } 12949 } 12950 12951 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12952 << R.getLookupName(); 12953 if (SuggestedNamespaces.empty()) { 12954 SemaRef.Diag(Best->Function->getLocation(), 12955 diag::note_not_found_by_two_phase_lookup) 12956 << R.getLookupName() << 0; 12957 } else if (SuggestedNamespaces.size() == 1) { 12958 SemaRef.Diag(Best->Function->getLocation(), 12959 diag::note_not_found_by_two_phase_lookup) 12960 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12961 } else { 12962 // FIXME: It would be useful to list the associated namespaces here, 12963 // but the diagnostics infrastructure doesn't provide a way to produce 12964 // a localized representation of a list of items. 12965 SemaRef.Diag(Best->Function->getLocation(), 12966 diag::note_not_found_by_two_phase_lookup) 12967 << R.getLookupName() << 2; 12968 } 12969 12970 // Try to recover by calling this function. 12971 return true; 12972 } 12973 12974 R.clear(); 12975 } 12976 12977 return false; 12978 } 12979 12980 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12981 /// template, where the non-dependent operator was declared after the template 12982 /// was defined. 12983 /// 12984 /// Returns true if a viable candidate was found and a diagnostic was issued. 12985 static bool 12986 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12987 SourceLocation OpLoc, 12988 ArrayRef<Expr *> Args) { 12989 DeclarationName OpName = 12990 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12991 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12992 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12993 OverloadCandidateSet::CSK_Operator, 12994 /*ExplicitTemplateArgs=*/nullptr, Args); 12995 } 12996 12997 namespace { 12998 class BuildRecoveryCallExprRAII { 12999 Sema &SemaRef; 13000 public: 13001 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 13002 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 13003 SemaRef.IsBuildingRecoveryCallExpr = true; 13004 } 13005 13006 ~BuildRecoveryCallExprRAII() { 13007 SemaRef.IsBuildingRecoveryCallExpr = false; 13008 } 13009 }; 13010 13011 } 13012 13013 /// Attempts to recover from a call where no functions were found. 13014 /// 13015 /// This function will do one of three things: 13016 /// * Diagnose, recover, and return a recovery expression. 13017 /// * Diagnose, fail to recover, and return ExprError(). 13018 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 13019 /// expected to diagnose as appropriate. 13020 static ExprResult 13021 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13022 UnresolvedLookupExpr *ULE, 13023 SourceLocation LParenLoc, 13024 MutableArrayRef<Expr *> Args, 13025 SourceLocation RParenLoc, 13026 bool EmptyLookup, bool AllowTypoCorrection) { 13027 // Do not try to recover if it is already building a recovery call. 13028 // This stops infinite loops for template instantiations like 13029 // 13030 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 13031 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 13032 if (SemaRef.IsBuildingRecoveryCallExpr) 13033 return ExprResult(); 13034 BuildRecoveryCallExprRAII RCE(SemaRef); 13035 13036 CXXScopeSpec SS; 13037 SS.Adopt(ULE->getQualifierLoc()); 13038 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 13039 13040 TemplateArgumentListInfo TABuffer; 13041 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13042 if (ULE->hasExplicitTemplateArgs()) { 13043 ULE->copyTemplateArgumentsInto(TABuffer); 13044 ExplicitTemplateArgs = &TABuffer; 13045 } 13046 13047 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 13048 Sema::LookupOrdinaryName); 13049 CXXRecordDecl *FoundInClass = nullptr; 13050 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 13051 OverloadCandidateSet::CSK_Normal, 13052 ExplicitTemplateArgs, Args, &FoundInClass)) { 13053 // OK, diagnosed a two-phase lookup issue. 13054 } else if (EmptyLookup) { 13055 // Try to recover from an empty lookup with typo correction. 13056 R.clear(); 13057 NoTypoCorrectionCCC NoTypoValidator{}; 13058 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 13059 ExplicitTemplateArgs != nullptr, 13060 dyn_cast<MemberExpr>(Fn)); 13061 CorrectionCandidateCallback &Validator = 13062 AllowTypoCorrection 13063 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 13064 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 13065 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 13066 Args)) 13067 return ExprError(); 13068 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 13069 // We found a usable declaration of the name in a dependent base of some 13070 // enclosing class. 13071 // FIXME: We should also explain why the candidates found by name lookup 13072 // were not viable. 13073 if (SemaRef.DiagnoseDependentMemberLookup(R)) 13074 return ExprError(); 13075 } else { 13076 // We had viable candidates and couldn't recover; let the caller diagnose 13077 // this. 13078 return ExprResult(); 13079 } 13080 13081 // If we get here, we should have issued a diagnostic and formed a recovery 13082 // lookup result. 13083 assert(!R.empty() && "lookup results empty despite recovery"); 13084 13085 // If recovery created an ambiguity, just bail out. 13086 if (R.isAmbiguous()) { 13087 R.suppressDiagnostics(); 13088 return ExprError(); 13089 } 13090 13091 // Build an implicit member call if appropriate. Just drop the 13092 // casts and such from the call, we don't really care. 13093 ExprResult NewFn = ExprError(); 13094 if ((*R.begin())->isCXXClassMember()) 13095 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13096 ExplicitTemplateArgs, S); 13097 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13098 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13099 ExplicitTemplateArgs); 13100 else 13101 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13102 13103 if (NewFn.isInvalid()) 13104 return ExprError(); 13105 13106 // This shouldn't cause an infinite loop because we're giving it 13107 // an expression with viable lookup results, which should never 13108 // end up here. 13109 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13110 MultiExprArg(Args.data(), Args.size()), 13111 RParenLoc); 13112 } 13113 13114 /// Constructs and populates an OverloadedCandidateSet from 13115 /// the given function. 13116 /// \returns true when an the ExprResult output parameter has been set. 13117 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13118 UnresolvedLookupExpr *ULE, 13119 MultiExprArg Args, 13120 SourceLocation RParenLoc, 13121 OverloadCandidateSet *CandidateSet, 13122 ExprResult *Result) { 13123 #ifndef NDEBUG 13124 if (ULE->requiresADL()) { 13125 // To do ADL, we must have found an unqualified name. 13126 assert(!ULE->getQualifier() && "qualified name with ADL"); 13127 13128 // We don't perform ADL for implicit declarations of builtins. 13129 // Verify that this was correctly set up. 13130 FunctionDecl *F; 13131 if (ULE->decls_begin() != ULE->decls_end() && 13132 ULE->decls_begin() + 1 == ULE->decls_end() && 13133 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13134 F->getBuiltinID() && F->isImplicit()) 13135 llvm_unreachable("performing ADL for builtin"); 13136 13137 // We don't perform ADL in C. 13138 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13139 } 13140 #endif 13141 13142 UnbridgedCastsSet UnbridgedCasts; 13143 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13144 *Result = ExprError(); 13145 return true; 13146 } 13147 13148 // Add the functions denoted by the callee to the set of candidate 13149 // functions, including those from argument-dependent lookup. 13150 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13151 13152 if (getLangOpts().MSVCCompat && 13153 CurContext->isDependentContext() && !isSFINAEContext() && 13154 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13155 13156 OverloadCandidateSet::iterator Best; 13157 if (CandidateSet->empty() || 13158 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13159 OR_No_Viable_Function) { 13160 // In Microsoft mode, if we are inside a template class member function 13161 // then create a type dependent CallExpr. The goal is to postpone name 13162 // lookup to instantiation time to be able to search into type dependent 13163 // base classes. 13164 CallExpr *CE = 13165 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13166 RParenLoc, CurFPFeatureOverrides()); 13167 CE->markDependentForPostponedNameLookup(); 13168 *Result = CE; 13169 return true; 13170 } 13171 } 13172 13173 if (CandidateSet->empty()) 13174 return false; 13175 13176 UnbridgedCasts.restore(); 13177 return false; 13178 } 13179 13180 // Guess at what the return type for an unresolvable overload should be. 13181 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13182 OverloadCandidateSet::iterator *Best) { 13183 llvm::Optional<QualType> Result; 13184 // Adjust Type after seeing a candidate. 13185 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13186 if (!Candidate.Function) 13187 return; 13188 if (Candidate.Function->isInvalidDecl()) 13189 return; 13190 QualType T = Candidate.Function->getReturnType(); 13191 if (T.isNull()) 13192 return; 13193 if (!Result) 13194 Result = T; 13195 else if (Result != T) 13196 Result = QualType(); 13197 }; 13198 13199 // Look for an unambiguous type from a progressively larger subset. 13200 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13201 // 13202 // First, consider only the best candidate. 13203 if (Best && *Best != CS.end()) 13204 ConsiderCandidate(**Best); 13205 // Next, consider only viable candidates. 13206 if (!Result) 13207 for (const auto &C : CS) 13208 if (C.Viable) 13209 ConsiderCandidate(C); 13210 // Finally, consider all candidates. 13211 if (!Result) 13212 for (const auto &C : CS) 13213 ConsiderCandidate(C); 13214 13215 if (!Result) 13216 return QualType(); 13217 auto Value = *Result; 13218 if (Value.isNull() || Value->isUndeducedType()) 13219 return QualType(); 13220 return Value; 13221 } 13222 13223 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13224 /// the completed call expression. If overload resolution fails, emits 13225 /// diagnostics and returns ExprError() 13226 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13227 UnresolvedLookupExpr *ULE, 13228 SourceLocation LParenLoc, 13229 MultiExprArg Args, 13230 SourceLocation RParenLoc, 13231 Expr *ExecConfig, 13232 OverloadCandidateSet *CandidateSet, 13233 OverloadCandidateSet::iterator *Best, 13234 OverloadingResult OverloadResult, 13235 bool AllowTypoCorrection) { 13236 switch (OverloadResult) { 13237 case OR_Success: { 13238 FunctionDecl *FDecl = (*Best)->Function; 13239 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13240 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13241 return ExprError(); 13242 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13243 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13244 ExecConfig, /*IsExecConfig=*/false, 13245 (*Best)->IsADLCandidate); 13246 } 13247 13248 case OR_No_Viable_Function: { 13249 // Try to recover by looking for viable functions which the user might 13250 // have meant to call. 13251 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13252 Args, RParenLoc, 13253 CandidateSet->empty(), 13254 AllowTypoCorrection); 13255 if (Recovery.isInvalid() || Recovery.isUsable()) 13256 return Recovery; 13257 13258 // If the user passes in a function that we can't take the address of, we 13259 // generally end up emitting really bad error messages. Here, we attempt to 13260 // emit better ones. 13261 for (const Expr *Arg : Args) { 13262 if (!Arg->getType()->isFunctionType()) 13263 continue; 13264 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13265 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13266 if (FD && 13267 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13268 Arg->getExprLoc())) 13269 return ExprError(); 13270 } 13271 } 13272 13273 CandidateSet->NoteCandidates( 13274 PartialDiagnosticAt( 13275 Fn->getBeginLoc(), 13276 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13277 << ULE->getName() << Fn->getSourceRange()), 13278 SemaRef, OCD_AllCandidates, Args); 13279 break; 13280 } 13281 13282 case OR_Ambiguous: 13283 CandidateSet->NoteCandidates( 13284 PartialDiagnosticAt(Fn->getBeginLoc(), 13285 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13286 << ULE->getName() << Fn->getSourceRange()), 13287 SemaRef, OCD_AmbiguousCandidates, Args); 13288 break; 13289 13290 case OR_Deleted: { 13291 CandidateSet->NoteCandidates( 13292 PartialDiagnosticAt(Fn->getBeginLoc(), 13293 SemaRef.PDiag(diag::err_ovl_deleted_call) 13294 << ULE->getName() << Fn->getSourceRange()), 13295 SemaRef, OCD_AllCandidates, Args); 13296 13297 // We emitted an error for the unavailable/deleted function call but keep 13298 // the call in the AST. 13299 FunctionDecl *FDecl = (*Best)->Function; 13300 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13301 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13302 ExecConfig, /*IsExecConfig=*/false, 13303 (*Best)->IsADLCandidate); 13304 } 13305 } 13306 13307 // Overload resolution failed, try to recover. 13308 SmallVector<Expr *, 8> SubExprs = {Fn}; 13309 SubExprs.append(Args.begin(), Args.end()); 13310 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13311 chooseRecoveryType(*CandidateSet, Best)); 13312 } 13313 13314 static void markUnaddressableCandidatesUnviable(Sema &S, 13315 OverloadCandidateSet &CS) { 13316 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13317 if (I->Viable && 13318 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13319 I->Viable = false; 13320 I->FailureKind = ovl_fail_addr_not_available; 13321 } 13322 } 13323 } 13324 13325 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13326 /// (which eventually refers to the declaration Func) and the call 13327 /// arguments Args/NumArgs, attempt to resolve the function call down 13328 /// to a specific function. If overload resolution succeeds, returns 13329 /// the call expression produced by overload resolution. 13330 /// Otherwise, emits diagnostics and returns ExprError. 13331 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13332 UnresolvedLookupExpr *ULE, 13333 SourceLocation LParenLoc, 13334 MultiExprArg Args, 13335 SourceLocation RParenLoc, 13336 Expr *ExecConfig, 13337 bool AllowTypoCorrection, 13338 bool CalleesAddressIsTaken) { 13339 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13340 OverloadCandidateSet::CSK_Normal); 13341 ExprResult result; 13342 13343 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13344 &result)) 13345 return result; 13346 13347 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13348 // functions that aren't addressible are considered unviable. 13349 if (CalleesAddressIsTaken) 13350 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13351 13352 OverloadCandidateSet::iterator Best; 13353 OverloadingResult OverloadResult = 13354 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13355 13356 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13357 ExecConfig, &CandidateSet, &Best, 13358 OverloadResult, AllowTypoCorrection); 13359 } 13360 13361 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13362 return Functions.size() > 1 || 13363 (Functions.size() == 1 && 13364 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13365 } 13366 13367 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13368 NestedNameSpecifierLoc NNSLoc, 13369 DeclarationNameInfo DNI, 13370 const UnresolvedSetImpl &Fns, 13371 bool PerformADL) { 13372 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13373 PerformADL, IsOverloaded(Fns), 13374 Fns.begin(), Fns.end()); 13375 } 13376 13377 /// Create a unary operation that may resolve to an overloaded 13378 /// operator. 13379 /// 13380 /// \param OpLoc The location of the operator itself (e.g., '*'). 13381 /// 13382 /// \param Opc The UnaryOperatorKind that describes this operator. 13383 /// 13384 /// \param Fns The set of non-member functions that will be 13385 /// considered by overload resolution. The caller needs to build this 13386 /// set based on the context using, e.g., 13387 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13388 /// set should not contain any member functions; those will be added 13389 /// by CreateOverloadedUnaryOp(). 13390 /// 13391 /// \param Input The input argument. 13392 ExprResult 13393 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13394 const UnresolvedSetImpl &Fns, 13395 Expr *Input, bool PerformADL) { 13396 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13397 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13398 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13399 // TODO: provide better source location info. 13400 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13401 13402 if (checkPlaceholderForOverload(*this, Input)) 13403 return ExprError(); 13404 13405 Expr *Args[2] = { Input, nullptr }; 13406 unsigned NumArgs = 1; 13407 13408 // For post-increment and post-decrement, add the implicit '0' as 13409 // the second argument, so that we know this is a post-increment or 13410 // post-decrement. 13411 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13412 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13413 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13414 SourceLocation()); 13415 NumArgs = 2; 13416 } 13417 13418 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13419 13420 if (Input->isTypeDependent()) { 13421 if (Fns.empty()) 13422 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13423 VK_PRValue, OK_Ordinary, OpLoc, false, 13424 CurFPFeatureOverrides()); 13425 13426 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13427 ExprResult Fn = CreateUnresolvedLookupExpr( 13428 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13429 if (Fn.isInvalid()) 13430 return ExprError(); 13431 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13432 Context.DependentTy, VK_PRValue, OpLoc, 13433 CurFPFeatureOverrides()); 13434 } 13435 13436 // Build an empty overload set. 13437 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13438 13439 // Add the candidates from the given function set. 13440 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13441 13442 // Add operator candidates that are member functions. 13443 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13444 13445 // Add candidates from ADL. 13446 if (PerformADL) { 13447 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13448 /*ExplicitTemplateArgs*/nullptr, 13449 CandidateSet); 13450 } 13451 13452 // Add builtin operator candidates. 13453 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13454 13455 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13456 13457 // Perform overload resolution. 13458 OverloadCandidateSet::iterator Best; 13459 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13460 case OR_Success: { 13461 // We found a built-in operator or an overloaded operator. 13462 FunctionDecl *FnDecl = Best->Function; 13463 13464 if (FnDecl) { 13465 Expr *Base = nullptr; 13466 // We matched an overloaded operator. Build a call to that 13467 // operator. 13468 13469 // Convert the arguments. 13470 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13471 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13472 13473 ExprResult InputRes = 13474 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13475 Best->FoundDecl, Method); 13476 if (InputRes.isInvalid()) 13477 return ExprError(); 13478 Base = Input = InputRes.get(); 13479 } else { 13480 // Convert the arguments. 13481 ExprResult InputInit 13482 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13483 Context, 13484 FnDecl->getParamDecl(0)), 13485 SourceLocation(), 13486 Input); 13487 if (InputInit.isInvalid()) 13488 return ExprError(); 13489 Input = InputInit.get(); 13490 } 13491 13492 // Build the actual expression node. 13493 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13494 Base, HadMultipleCandidates, 13495 OpLoc); 13496 if (FnExpr.isInvalid()) 13497 return ExprError(); 13498 13499 // Determine the result type. 13500 QualType ResultTy = FnDecl->getReturnType(); 13501 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13502 ResultTy = ResultTy.getNonLValueExprType(Context); 13503 13504 Args[0] = Input; 13505 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13506 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13507 CurFPFeatureOverrides(), Best->IsADLCandidate); 13508 13509 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13510 return ExprError(); 13511 13512 if (CheckFunctionCall(FnDecl, TheCall, 13513 FnDecl->getType()->castAs<FunctionProtoType>())) 13514 return ExprError(); 13515 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13516 } else { 13517 // We matched a built-in operator. Convert the arguments, then 13518 // break out so that we will build the appropriate built-in 13519 // operator node. 13520 ExprResult InputRes = PerformImplicitConversion( 13521 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13522 CCK_ForBuiltinOverloadedOp); 13523 if (InputRes.isInvalid()) 13524 return ExprError(); 13525 Input = InputRes.get(); 13526 break; 13527 } 13528 } 13529 13530 case OR_No_Viable_Function: 13531 // This is an erroneous use of an operator which can be overloaded by 13532 // a non-member function. Check for non-member operators which were 13533 // defined too late to be candidates. 13534 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13535 // FIXME: Recover by calling the found function. 13536 return ExprError(); 13537 13538 // No viable function; fall through to handling this as a 13539 // built-in operator, which will produce an error message for us. 13540 break; 13541 13542 case OR_Ambiguous: 13543 CandidateSet.NoteCandidates( 13544 PartialDiagnosticAt(OpLoc, 13545 PDiag(diag::err_ovl_ambiguous_oper_unary) 13546 << UnaryOperator::getOpcodeStr(Opc) 13547 << Input->getType() << Input->getSourceRange()), 13548 *this, OCD_AmbiguousCandidates, ArgsArray, 13549 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13550 return ExprError(); 13551 13552 case OR_Deleted: 13553 CandidateSet.NoteCandidates( 13554 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13555 << UnaryOperator::getOpcodeStr(Opc) 13556 << Input->getSourceRange()), 13557 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13558 OpLoc); 13559 return ExprError(); 13560 } 13561 13562 // Either we found no viable overloaded operator or we matched a 13563 // built-in operator. In either case, fall through to trying to 13564 // build a built-in operation. 13565 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13566 } 13567 13568 /// Perform lookup for an overloaded binary operator. 13569 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13570 OverloadedOperatorKind Op, 13571 const UnresolvedSetImpl &Fns, 13572 ArrayRef<Expr *> Args, bool PerformADL) { 13573 SourceLocation OpLoc = CandidateSet.getLocation(); 13574 13575 OverloadedOperatorKind ExtraOp = 13576 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13577 ? getRewrittenOverloadedOperator(Op) 13578 : OO_None; 13579 13580 // Add the candidates from the given function set. This also adds the 13581 // rewritten candidates using these functions if necessary. 13582 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13583 13584 // Add operator candidates that are member functions. 13585 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13586 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13587 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13588 OverloadCandidateParamOrder::Reversed); 13589 13590 // In C++20, also add any rewritten member candidates. 13591 if (ExtraOp) { 13592 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13593 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13594 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13595 CandidateSet, 13596 OverloadCandidateParamOrder::Reversed); 13597 } 13598 13599 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13600 // performed for an assignment operator (nor for operator[] nor operator->, 13601 // which don't get here). 13602 if (Op != OO_Equal && PerformADL) { 13603 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13604 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13605 /*ExplicitTemplateArgs*/ nullptr, 13606 CandidateSet); 13607 if (ExtraOp) { 13608 DeclarationName ExtraOpName = 13609 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13610 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13611 /*ExplicitTemplateArgs*/ nullptr, 13612 CandidateSet); 13613 } 13614 } 13615 13616 // Add builtin operator candidates. 13617 // 13618 // FIXME: We don't add any rewritten candidates here. This is strictly 13619 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13620 // resulting in our selecting a rewritten builtin candidate. For example: 13621 // 13622 // enum class E { e }; 13623 // bool operator!=(E, E) requires false; 13624 // bool k = E::e != E::e; 13625 // 13626 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13627 // it seems unreasonable to consider rewritten builtin candidates. A core 13628 // issue has been filed proposing to removed this requirement. 13629 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13630 } 13631 13632 /// Create a binary operation that may resolve to an overloaded 13633 /// operator. 13634 /// 13635 /// \param OpLoc The location of the operator itself (e.g., '+'). 13636 /// 13637 /// \param Opc The BinaryOperatorKind that describes this operator. 13638 /// 13639 /// \param Fns The set of non-member functions that will be 13640 /// considered by overload resolution. The caller needs to build this 13641 /// set based on the context using, e.g., 13642 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13643 /// set should not contain any member functions; those will be added 13644 /// by CreateOverloadedBinOp(). 13645 /// 13646 /// \param LHS Left-hand argument. 13647 /// \param RHS Right-hand argument. 13648 /// \param PerformADL Whether to consider operator candidates found by ADL. 13649 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13650 /// C++20 operator rewrites. 13651 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13652 /// the function in question. Such a function is never a candidate in 13653 /// our overload resolution. This also enables synthesizing a three-way 13654 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13655 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13656 BinaryOperatorKind Opc, 13657 const UnresolvedSetImpl &Fns, Expr *LHS, 13658 Expr *RHS, bool PerformADL, 13659 bool AllowRewrittenCandidates, 13660 FunctionDecl *DefaultedFn) { 13661 Expr *Args[2] = { LHS, RHS }; 13662 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13663 13664 if (!getLangOpts().CPlusPlus20) 13665 AllowRewrittenCandidates = false; 13666 13667 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13668 13669 // If either side is type-dependent, create an appropriate dependent 13670 // expression. 13671 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13672 if (Fns.empty()) { 13673 // If there are no functions to store, just build a dependent 13674 // BinaryOperator or CompoundAssignment. 13675 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13676 return CompoundAssignOperator::Create( 13677 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13678 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13679 Context.DependentTy); 13680 return BinaryOperator::Create( 13681 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 13682 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13683 } 13684 13685 // FIXME: save results of ADL from here? 13686 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13687 // TODO: provide better source location info in DNLoc component. 13688 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13689 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13690 ExprResult Fn = CreateUnresolvedLookupExpr( 13691 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13692 if (Fn.isInvalid()) 13693 return ExprError(); 13694 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13695 Context.DependentTy, VK_PRValue, OpLoc, 13696 CurFPFeatureOverrides()); 13697 } 13698 13699 // Always do placeholder-like conversions on the RHS. 13700 if (checkPlaceholderForOverload(*this, Args[1])) 13701 return ExprError(); 13702 13703 // Do placeholder-like conversion on the LHS; note that we should 13704 // not get here with a PseudoObject LHS. 13705 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13706 if (checkPlaceholderForOverload(*this, Args[0])) 13707 return ExprError(); 13708 13709 // If this is the assignment operator, we only perform overload resolution 13710 // if the left-hand side is a class or enumeration type. This is actually 13711 // a hack. The standard requires that we do overload resolution between the 13712 // various built-in candidates, but as DR507 points out, this can lead to 13713 // problems. So we do it this way, which pretty much follows what GCC does. 13714 // Note that we go the traditional code path for compound assignment forms. 13715 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13716 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13717 13718 // If this is the .* operator, which is not overloadable, just 13719 // create a built-in binary operator. 13720 if (Opc == BO_PtrMemD) 13721 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13722 13723 // Build the overload set. 13724 OverloadCandidateSet CandidateSet( 13725 OpLoc, OverloadCandidateSet::CSK_Operator, 13726 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13727 if (DefaultedFn) 13728 CandidateSet.exclude(DefaultedFn); 13729 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13730 13731 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13732 13733 // Perform overload resolution. 13734 OverloadCandidateSet::iterator Best; 13735 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13736 case OR_Success: { 13737 // We found a built-in operator or an overloaded operator. 13738 FunctionDecl *FnDecl = Best->Function; 13739 13740 bool IsReversed = Best->isReversed(); 13741 if (IsReversed) 13742 std::swap(Args[0], Args[1]); 13743 13744 if (FnDecl) { 13745 Expr *Base = nullptr; 13746 // We matched an overloaded operator. Build a call to that 13747 // operator. 13748 13749 OverloadedOperatorKind ChosenOp = 13750 FnDecl->getDeclName().getCXXOverloadedOperator(); 13751 13752 // C++2a [over.match.oper]p9: 13753 // If a rewritten operator== candidate is selected by overload 13754 // resolution for an operator@, its return type shall be cv bool 13755 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13756 !FnDecl->getReturnType()->isBooleanType()) { 13757 bool IsExtension = 13758 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13759 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13760 : diag::err_ovl_rewrite_equalequal_not_bool) 13761 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13762 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13763 Diag(FnDecl->getLocation(), diag::note_declared_at); 13764 if (!IsExtension) 13765 return ExprError(); 13766 } 13767 13768 if (AllowRewrittenCandidates && !IsReversed && 13769 CandidateSet.getRewriteInfo().isReversible()) { 13770 // We could have reversed this operator, but didn't. Check if some 13771 // reversed form was a viable candidate, and if so, if it had a 13772 // better conversion for either parameter. If so, this call is 13773 // formally ambiguous, and allowing it is an extension. 13774 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13775 for (OverloadCandidate &Cand : CandidateSet) { 13776 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13777 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13778 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13779 if (CompareImplicitConversionSequences( 13780 *this, OpLoc, Cand.Conversions[ArgIdx], 13781 Best->Conversions[ArgIdx]) == 13782 ImplicitConversionSequence::Better) { 13783 AmbiguousWith.push_back(Cand.Function); 13784 break; 13785 } 13786 } 13787 } 13788 } 13789 13790 if (!AmbiguousWith.empty()) { 13791 bool AmbiguousWithSelf = 13792 AmbiguousWith.size() == 1 && 13793 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13794 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13795 << BinaryOperator::getOpcodeStr(Opc) 13796 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13797 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13798 if (AmbiguousWithSelf) { 13799 Diag(FnDecl->getLocation(), 13800 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13801 } else { 13802 Diag(FnDecl->getLocation(), 13803 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13804 for (auto *F : AmbiguousWith) 13805 Diag(F->getLocation(), 13806 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13807 } 13808 } 13809 } 13810 13811 // Convert the arguments. 13812 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13813 // Best->Access is only meaningful for class members. 13814 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13815 13816 ExprResult Arg1 = 13817 PerformCopyInitialization( 13818 InitializedEntity::InitializeParameter(Context, 13819 FnDecl->getParamDecl(0)), 13820 SourceLocation(), Args[1]); 13821 if (Arg1.isInvalid()) 13822 return ExprError(); 13823 13824 ExprResult Arg0 = 13825 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13826 Best->FoundDecl, Method); 13827 if (Arg0.isInvalid()) 13828 return ExprError(); 13829 Base = Args[0] = Arg0.getAs<Expr>(); 13830 Args[1] = RHS = Arg1.getAs<Expr>(); 13831 } else { 13832 // Convert the arguments. 13833 ExprResult Arg0 = PerformCopyInitialization( 13834 InitializedEntity::InitializeParameter(Context, 13835 FnDecl->getParamDecl(0)), 13836 SourceLocation(), Args[0]); 13837 if (Arg0.isInvalid()) 13838 return ExprError(); 13839 13840 ExprResult Arg1 = 13841 PerformCopyInitialization( 13842 InitializedEntity::InitializeParameter(Context, 13843 FnDecl->getParamDecl(1)), 13844 SourceLocation(), Args[1]); 13845 if (Arg1.isInvalid()) 13846 return ExprError(); 13847 Args[0] = LHS = Arg0.getAs<Expr>(); 13848 Args[1] = RHS = Arg1.getAs<Expr>(); 13849 } 13850 13851 // Build the actual expression node. 13852 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13853 Best->FoundDecl, Base, 13854 HadMultipleCandidates, OpLoc); 13855 if (FnExpr.isInvalid()) 13856 return ExprError(); 13857 13858 // Determine the result type. 13859 QualType ResultTy = FnDecl->getReturnType(); 13860 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13861 ResultTy = ResultTy.getNonLValueExprType(Context); 13862 13863 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13864 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13865 CurFPFeatureOverrides(), Best->IsADLCandidate); 13866 13867 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13868 FnDecl)) 13869 return ExprError(); 13870 13871 ArrayRef<const Expr *> ArgsArray(Args, 2); 13872 const Expr *ImplicitThis = nullptr; 13873 // Cut off the implicit 'this'. 13874 if (isa<CXXMethodDecl>(FnDecl)) { 13875 ImplicitThis = ArgsArray[0]; 13876 ArgsArray = ArgsArray.slice(1); 13877 } 13878 13879 // Check for a self move. 13880 if (Op == OO_Equal) 13881 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13882 13883 if (ImplicitThis) { 13884 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13885 QualType ThisTypeFromDecl = Context.getPointerType( 13886 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13887 13888 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13889 ThisTypeFromDecl); 13890 } 13891 13892 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13893 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13894 VariadicDoesNotApply); 13895 13896 ExprResult R = MaybeBindToTemporary(TheCall); 13897 if (R.isInvalid()) 13898 return ExprError(); 13899 13900 R = CheckForImmediateInvocation(R, FnDecl); 13901 if (R.isInvalid()) 13902 return ExprError(); 13903 13904 // For a rewritten candidate, we've already reversed the arguments 13905 // if needed. Perform the rest of the rewrite now. 13906 if ((Best->RewriteKind & CRK_DifferentOperator) || 13907 (Op == OO_Spaceship && IsReversed)) { 13908 if (Op == OO_ExclaimEqual) { 13909 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13910 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13911 } else { 13912 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13913 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13914 Expr *ZeroLiteral = 13915 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13916 13917 Sema::CodeSynthesisContext Ctx; 13918 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13919 Ctx.Entity = FnDecl; 13920 pushCodeSynthesisContext(Ctx); 13921 13922 R = CreateOverloadedBinOp( 13923 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13924 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13925 /*AllowRewrittenCandidates=*/false); 13926 13927 popCodeSynthesisContext(); 13928 } 13929 if (R.isInvalid()) 13930 return ExprError(); 13931 } else { 13932 assert(ChosenOp == Op && "unexpected operator name"); 13933 } 13934 13935 // Make a note in the AST if we did any rewriting. 13936 if (Best->RewriteKind != CRK_None) 13937 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13938 13939 return R; 13940 } else { 13941 // We matched a built-in operator. Convert the arguments, then 13942 // break out so that we will build the appropriate built-in 13943 // operator node. 13944 ExprResult ArgsRes0 = PerformImplicitConversion( 13945 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13946 AA_Passing, CCK_ForBuiltinOverloadedOp); 13947 if (ArgsRes0.isInvalid()) 13948 return ExprError(); 13949 Args[0] = ArgsRes0.get(); 13950 13951 ExprResult ArgsRes1 = PerformImplicitConversion( 13952 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13953 AA_Passing, CCK_ForBuiltinOverloadedOp); 13954 if (ArgsRes1.isInvalid()) 13955 return ExprError(); 13956 Args[1] = ArgsRes1.get(); 13957 break; 13958 } 13959 } 13960 13961 case OR_No_Viable_Function: { 13962 // C++ [over.match.oper]p9: 13963 // If the operator is the operator , [...] and there are no 13964 // viable functions, then the operator is assumed to be the 13965 // built-in operator and interpreted according to clause 5. 13966 if (Opc == BO_Comma) 13967 break; 13968 13969 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13970 // compare result using '==' and '<'. 13971 if (DefaultedFn && Opc == BO_Cmp) { 13972 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13973 Args[1], DefaultedFn); 13974 if (E.isInvalid() || E.isUsable()) 13975 return E; 13976 } 13977 13978 // For class as left operand for assignment or compound assignment 13979 // operator do not fall through to handling in built-in, but report that 13980 // no overloaded assignment operator found 13981 ExprResult Result = ExprError(); 13982 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13983 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13984 Args, OpLoc); 13985 DeferDiagsRAII DDR(*this, 13986 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 13987 if (Args[0]->getType()->isRecordType() && 13988 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13989 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13990 << BinaryOperator::getOpcodeStr(Opc) 13991 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13992 if (Args[0]->getType()->isIncompleteType()) { 13993 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13994 << Args[0]->getType() 13995 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13996 } 13997 } else { 13998 // This is an erroneous use of an operator which can be overloaded by 13999 // a non-member function. Check for non-member operators which were 14000 // defined too late to be candidates. 14001 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 14002 // FIXME: Recover by calling the found function. 14003 return ExprError(); 14004 14005 // No viable function; try to create a built-in operation, which will 14006 // produce an error. Then, show the non-viable candidates. 14007 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14008 } 14009 assert(Result.isInvalid() && 14010 "C++ binary operator overloading is missing candidates!"); 14011 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 14012 return Result; 14013 } 14014 14015 case OR_Ambiguous: 14016 CandidateSet.NoteCandidates( 14017 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14018 << BinaryOperator::getOpcodeStr(Opc) 14019 << Args[0]->getType() 14020 << Args[1]->getType() 14021 << Args[0]->getSourceRange() 14022 << Args[1]->getSourceRange()), 14023 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14024 OpLoc); 14025 return ExprError(); 14026 14027 case OR_Deleted: 14028 if (isImplicitlyDeleted(Best->Function)) { 14029 FunctionDecl *DeletedFD = Best->Function; 14030 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 14031 if (DFK.isSpecialMember()) { 14032 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 14033 << Args[0]->getType() << DFK.asSpecialMember(); 14034 } else { 14035 assert(DFK.isComparison()); 14036 Diag(OpLoc, diag::err_ovl_deleted_comparison) 14037 << Args[0]->getType() << DeletedFD; 14038 } 14039 14040 // The user probably meant to call this special member. Just 14041 // explain why it's deleted. 14042 NoteDeletedFunction(DeletedFD); 14043 return ExprError(); 14044 } 14045 CandidateSet.NoteCandidates( 14046 PartialDiagnosticAt( 14047 OpLoc, PDiag(diag::err_ovl_deleted_oper) 14048 << getOperatorSpelling(Best->Function->getDeclName() 14049 .getCXXOverloadedOperator()) 14050 << Args[0]->getSourceRange() 14051 << Args[1]->getSourceRange()), 14052 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14053 OpLoc); 14054 return ExprError(); 14055 } 14056 14057 // We matched a built-in operator; build it. 14058 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14059 } 14060 14061 ExprResult Sema::BuildSynthesizedThreeWayComparison( 14062 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 14063 FunctionDecl *DefaultedFn) { 14064 const ComparisonCategoryInfo *Info = 14065 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 14066 // If we're not producing a known comparison category type, we can't 14067 // synthesize a three-way comparison. Let the caller diagnose this. 14068 if (!Info) 14069 return ExprResult((Expr*)nullptr); 14070 14071 // If we ever want to perform this synthesis more generally, we will need to 14072 // apply the temporary materialization conversion to the operands. 14073 assert(LHS->isGLValue() && RHS->isGLValue() && 14074 "cannot use prvalue expressions more than once"); 14075 Expr *OrigLHS = LHS; 14076 Expr *OrigRHS = RHS; 14077 14078 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 14079 // each of them multiple times below. 14080 LHS = new (Context) 14081 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 14082 LHS->getObjectKind(), LHS); 14083 RHS = new (Context) 14084 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 14085 RHS->getObjectKind(), RHS); 14086 14087 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 14088 DefaultedFn); 14089 if (Eq.isInvalid()) 14090 return ExprError(); 14091 14092 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 14093 true, DefaultedFn); 14094 if (Less.isInvalid()) 14095 return ExprError(); 14096 14097 ExprResult Greater; 14098 if (Info->isPartial()) { 14099 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14100 DefaultedFn); 14101 if (Greater.isInvalid()) 14102 return ExprError(); 14103 } 14104 14105 // Form the list of comparisons we're going to perform. 14106 struct Comparison { 14107 ExprResult Cmp; 14108 ComparisonCategoryResult Result; 14109 } Comparisons[4] = 14110 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14111 : ComparisonCategoryResult::Equivalent}, 14112 {Less, ComparisonCategoryResult::Less}, 14113 {Greater, ComparisonCategoryResult::Greater}, 14114 {ExprResult(), ComparisonCategoryResult::Unordered}, 14115 }; 14116 14117 int I = Info->isPartial() ? 3 : 2; 14118 14119 // Combine the comparisons with suitable conditional expressions. 14120 ExprResult Result; 14121 for (; I >= 0; --I) { 14122 // Build a reference to the comparison category constant. 14123 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14124 // FIXME: Missing a constant for a comparison category. Diagnose this? 14125 if (!VI) 14126 return ExprResult((Expr*)nullptr); 14127 ExprResult ThisResult = 14128 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14129 if (ThisResult.isInvalid()) 14130 return ExprError(); 14131 14132 // Build a conditional unless this is the final case. 14133 if (Result.get()) { 14134 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14135 ThisResult.get(), Result.get()); 14136 if (Result.isInvalid()) 14137 return ExprError(); 14138 } else { 14139 Result = ThisResult; 14140 } 14141 } 14142 14143 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14144 // bind the OpaqueValueExprs before they're (repeatedly) used. 14145 Expr *SyntacticForm = BinaryOperator::Create( 14146 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14147 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14148 CurFPFeatureOverrides()); 14149 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14150 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14151 } 14152 14153 static bool PrepareArgumentsForCallToObjectOfClassType( 14154 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 14155 MultiExprArg Args, SourceLocation LParenLoc) { 14156 14157 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14158 unsigned NumParams = Proto->getNumParams(); 14159 unsigned NumArgsSlots = 14160 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 14161 // Build the full argument list for the method call (the implicit object 14162 // parameter is placed at the beginning of the list). 14163 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 14164 bool IsError = false; 14165 // Initialize the implicit object parameter. 14166 // Check the argument types. 14167 for (unsigned i = 0; i != NumParams; i++) { 14168 Expr *Arg; 14169 if (i < Args.size()) { 14170 Arg = Args[i]; 14171 ExprResult InputInit = 14172 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 14173 S.Context, Method->getParamDecl(i)), 14174 SourceLocation(), Arg); 14175 IsError |= InputInit.isInvalid(); 14176 Arg = InputInit.getAs<Expr>(); 14177 } else { 14178 ExprResult DefArg = 14179 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14180 if (DefArg.isInvalid()) { 14181 IsError = true; 14182 break; 14183 } 14184 Arg = DefArg.getAs<Expr>(); 14185 } 14186 14187 MethodArgs.push_back(Arg); 14188 } 14189 return IsError; 14190 } 14191 14192 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14193 SourceLocation RLoc, 14194 Expr *Base, 14195 MultiExprArg ArgExpr) { 14196 SmallVector<Expr *, 2> Args; 14197 Args.push_back(Base); 14198 for (auto e : ArgExpr) { 14199 Args.push_back(e); 14200 } 14201 DeclarationName OpName = 14202 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14203 14204 SourceRange Range = ArgExpr.empty() 14205 ? SourceRange{} 14206 : SourceRange(ArgExpr.front()->getBeginLoc(), 14207 ArgExpr.back()->getEndLoc()); 14208 14209 // If either side is type-dependent, create an appropriate dependent 14210 // expression. 14211 if (Expr::hasAnyTypeDependentArguments(Args)) { 14212 14213 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14214 // CHECKME: no 'operator' keyword? 14215 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14216 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14217 ExprResult Fn = CreateUnresolvedLookupExpr( 14218 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14219 if (Fn.isInvalid()) 14220 return ExprError(); 14221 // Can't add any actual overloads yet 14222 14223 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14224 Context.DependentTy, VK_PRValue, RLoc, 14225 CurFPFeatureOverrides()); 14226 } 14227 14228 // Handle placeholders 14229 UnbridgedCastsSet UnbridgedCasts; 14230 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 14231 return ExprError(); 14232 } 14233 // Build an empty overload set. 14234 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14235 14236 // Subscript can only be overloaded as a member function. 14237 14238 // Add operator candidates that are member functions. 14239 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14240 14241 // Add builtin operator candidates. 14242 if (Args.size() == 2) 14243 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14244 14245 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14246 14247 // Perform overload resolution. 14248 OverloadCandidateSet::iterator Best; 14249 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14250 case OR_Success: { 14251 // We found a built-in operator or an overloaded operator. 14252 FunctionDecl *FnDecl = Best->Function; 14253 14254 if (FnDecl) { 14255 // We matched an overloaded operator. Build a call to that 14256 // operator. 14257 14258 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 14259 14260 // Convert the arguments. 14261 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14262 SmallVector<Expr *, 2> MethodArgs; 14263 ExprResult Arg0 = PerformObjectArgumentInitialization( 14264 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14265 if (Arg0.isInvalid()) 14266 return ExprError(); 14267 14268 MethodArgs.push_back(Arg0.get()); 14269 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 14270 *this, MethodArgs, Method, ArgExpr, LLoc); 14271 if (IsError) 14272 return ExprError(); 14273 14274 // Build the actual expression node. 14275 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14276 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14277 ExprResult FnExpr = CreateFunctionRefExpr( 14278 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 14279 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 14280 if (FnExpr.isInvalid()) 14281 return ExprError(); 14282 14283 // Determine the result type 14284 QualType ResultTy = FnDecl->getReturnType(); 14285 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14286 ResultTy = ResultTy.getNonLValueExprType(Context); 14287 14288 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14289 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc, 14290 CurFPFeatureOverrides()); 14291 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14292 return ExprError(); 14293 14294 if (CheckFunctionCall(Method, TheCall, 14295 Method->getType()->castAs<FunctionProtoType>())) 14296 return ExprError(); 14297 14298 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14299 FnDecl); 14300 } else { 14301 // We matched a built-in operator. Convert the arguments, then 14302 // break out so that we will build the appropriate built-in 14303 // operator node. 14304 ExprResult ArgsRes0 = PerformImplicitConversion( 14305 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14306 AA_Passing, CCK_ForBuiltinOverloadedOp); 14307 if (ArgsRes0.isInvalid()) 14308 return ExprError(); 14309 Args[0] = ArgsRes0.get(); 14310 14311 ExprResult ArgsRes1 = PerformImplicitConversion( 14312 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14313 AA_Passing, CCK_ForBuiltinOverloadedOp); 14314 if (ArgsRes1.isInvalid()) 14315 return ExprError(); 14316 Args[1] = ArgsRes1.get(); 14317 14318 break; 14319 } 14320 } 14321 14322 case OR_No_Viable_Function: { 14323 PartialDiagnostic PD = 14324 CandidateSet.empty() 14325 ? (PDiag(diag::err_ovl_no_oper) 14326 << Args[0]->getType() << /*subscript*/ 0 14327 << Args[0]->getSourceRange() << Range) 14328 : (PDiag(diag::err_ovl_no_viable_subscript) 14329 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 14330 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14331 OCD_AllCandidates, ArgExpr, "[]", LLoc); 14332 return ExprError(); 14333 } 14334 14335 case OR_Ambiguous: 14336 if (Args.size() == 2) { 14337 CandidateSet.NoteCandidates( 14338 PartialDiagnosticAt( 14339 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14340 << "[]" << Args[0]->getType() << Args[1]->getType() 14341 << Args[0]->getSourceRange() << Range), 14342 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14343 } else { 14344 CandidateSet.NoteCandidates( 14345 PartialDiagnosticAt(LLoc, 14346 PDiag(diag::err_ovl_ambiguous_subscript_call) 14347 << Args[0]->getType() 14348 << Args[0]->getSourceRange() << Range), 14349 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14350 } 14351 return ExprError(); 14352 14353 case OR_Deleted: 14354 CandidateSet.NoteCandidates( 14355 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14356 << "[]" << Args[0]->getSourceRange() 14357 << Range), 14358 *this, OCD_AllCandidates, Args, "[]", LLoc); 14359 return ExprError(); 14360 } 14361 14362 // We matched a built-in operator; build it. 14363 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14364 } 14365 14366 /// BuildCallToMemberFunction - Build a call to a member 14367 /// function. MemExpr is the expression that refers to the member 14368 /// function (and includes the object parameter), Args/NumArgs are the 14369 /// arguments to the function call (not including the object 14370 /// parameter). The caller needs to validate that the member 14371 /// expression refers to a non-static member function or an overloaded 14372 /// member function. 14373 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14374 SourceLocation LParenLoc, 14375 MultiExprArg Args, 14376 SourceLocation RParenLoc, 14377 Expr *ExecConfig, bool IsExecConfig, 14378 bool AllowRecovery) { 14379 assert(MemExprE->getType() == Context.BoundMemberTy || 14380 MemExprE->getType() == Context.OverloadTy); 14381 14382 // Dig out the member expression. This holds both the object 14383 // argument and the member function we're referring to. 14384 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14385 14386 // Determine whether this is a call to a pointer-to-member function. 14387 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14388 assert(op->getType() == Context.BoundMemberTy); 14389 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14390 14391 QualType fnType = 14392 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14393 14394 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14395 QualType resultType = proto->getCallResultType(Context); 14396 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14397 14398 // Check that the object type isn't more qualified than the 14399 // member function we're calling. 14400 Qualifiers funcQuals = proto->getMethodQuals(); 14401 14402 QualType objectType = op->getLHS()->getType(); 14403 if (op->getOpcode() == BO_PtrMemI) 14404 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14405 Qualifiers objectQuals = objectType.getQualifiers(); 14406 14407 Qualifiers difference = objectQuals - funcQuals; 14408 difference.removeObjCGCAttr(); 14409 difference.removeAddressSpace(); 14410 if (difference) { 14411 std::string qualsString = difference.getAsString(); 14412 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14413 << fnType.getUnqualifiedType() 14414 << qualsString 14415 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14416 } 14417 14418 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14419 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14420 CurFPFeatureOverrides(), proto->getNumParams()); 14421 14422 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14423 call, nullptr)) 14424 return ExprError(); 14425 14426 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14427 return ExprError(); 14428 14429 if (CheckOtherCall(call, proto)) 14430 return ExprError(); 14431 14432 return MaybeBindToTemporary(call); 14433 } 14434 14435 // We only try to build a recovery expr at this level if we can preserve 14436 // the return type, otherwise we return ExprError() and let the caller 14437 // recover. 14438 auto BuildRecoveryExpr = [&](QualType Type) { 14439 if (!AllowRecovery) 14440 return ExprError(); 14441 std::vector<Expr *> SubExprs = {MemExprE}; 14442 llvm::append_range(SubExprs, Args); 14443 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14444 Type); 14445 }; 14446 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14447 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 14448 RParenLoc, CurFPFeatureOverrides()); 14449 14450 UnbridgedCastsSet UnbridgedCasts; 14451 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14452 return ExprError(); 14453 14454 MemberExpr *MemExpr; 14455 CXXMethodDecl *Method = nullptr; 14456 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14457 NestedNameSpecifier *Qualifier = nullptr; 14458 if (isa<MemberExpr>(NakedMemExpr)) { 14459 MemExpr = cast<MemberExpr>(NakedMemExpr); 14460 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14461 FoundDecl = MemExpr->getFoundDecl(); 14462 Qualifier = MemExpr->getQualifier(); 14463 UnbridgedCasts.restore(); 14464 } else { 14465 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14466 Qualifier = UnresExpr->getQualifier(); 14467 14468 QualType ObjectType = UnresExpr->getBaseType(); 14469 Expr::Classification ObjectClassification 14470 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14471 : UnresExpr->getBase()->Classify(Context); 14472 14473 // Add overload candidates 14474 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14475 OverloadCandidateSet::CSK_Normal); 14476 14477 // FIXME: avoid copy. 14478 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14479 if (UnresExpr->hasExplicitTemplateArgs()) { 14480 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14481 TemplateArgs = &TemplateArgsBuffer; 14482 } 14483 14484 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14485 E = UnresExpr->decls_end(); I != E; ++I) { 14486 14487 NamedDecl *Func = *I; 14488 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14489 if (isa<UsingShadowDecl>(Func)) 14490 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14491 14492 14493 // Microsoft supports direct constructor calls. 14494 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14495 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14496 CandidateSet, 14497 /*SuppressUserConversions*/ false); 14498 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14499 // If explicit template arguments were provided, we can't call a 14500 // non-template member function. 14501 if (TemplateArgs) 14502 continue; 14503 14504 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14505 ObjectClassification, Args, CandidateSet, 14506 /*SuppressUserConversions=*/false); 14507 } else { 14508 AddMethodTemplateCandidate( 14509 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14510 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14511 /*SuppressUserConversions=*/false); 14512 } 14513 } 14514 14515 DeclarationName DeclName = UnresExpr->getMemberName(); 14516 14517 UnbridgedCasts.restore(); 14518 14519 OverloadCandidateSet::iterator Best; 14520 bool Succeeded = false; 14521 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14522 Best)) { 14523 case OR_Success: 14524 Method = cast<CXXMethodDecl>(Best->Function); 14525 FoundDecl = Best->FoundDecl; 14526 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14527 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14528 break; 14529 // If FoundDecl is different from Method (such as if one is a template 14530 // and the other a specialization), make sure DiagnoseUseOfDecl is 14531 // called on both. 14532 // FIXME: This would be more comprehensively addressed by modifying 14533 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14534 // being used. 14535 if (Method != FoundDecl.getDecl() && 14536 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14537 break; 14538 Succeeded = true; 14539 break; 14540 14541 case OR_No_Viable_Function: 14542 CandidateSet.NoteCandidates( 14543 PartialDiagnosticAt( 14544 UnresExpr->getMemberLoc(), 14545 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14546 << DeclName << MemExprE->getSourceRange()), 14547 *this, OCD_AllCandidates, Args); 14548 break; 14549 case OR_Ambiguous: 14550 CandidateSet.NoteCandidates( 14551 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14552 PDiag(diag::err_ovl_ambiguous_member_call) 14553 << DeclName << MemExprE->getSourceRange()), 14554 *this, OCD_AmbiguousCandidates, Args); 14555 break; 14556 case OR_Deleted: 14557 CandidateSet.NoteCandidates( 14558 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14559 PDiag(diag::err_ovl_deleted_member_call) 14560 << DeclName << MemExprE->getSourceRange()), 14561 *this, OCD_AllCandidates, Args); 14562 break; 14563 } 14564 // Overload resolution fails, try to recover. 14565 if (!Succeeded) 14566 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14567 14568 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14569 14570 // If overload resolution picked a static member, build a 14571 // non-member call based on that function. 14572 if (Method->isStatic()) { 14573 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 14574 ExecConfig, IsExecConfig); 14575 } 14576 14577 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14578 } 14579 14580 QualType ResultType = Method->getReturnType(); 14581 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14582 ResultType = ResultType.getNonLValueExprType(Context); 14583 14584 assert(Method && "Member call to something that isn't a method?"); 14585 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14586 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14587 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14588 CurFPFeatureOverrides(), Proto->getNumParams()); 14589 14590 // Check for a valid return type. 14591 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14592 TheCall, Method)) 14593 return BuildRecoveryExpr(ResultType); 14594 14595 // Convert the object argument (for a non-static member function call). 14596 // We only need to do this if there was actually an overload; otherwise 14597 // it was done at lookup. 14598 if (!Method->isStatic()) { 14599 ExprResult ObjectArg = 14600 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14601 FoundDecl, Method); 14602 if (ObjectArg.isInvalid()) 14603 return ExprError(); 14604 MemExpr->setBase(ObjectArg.get()); 14605 } 14606 14607 // Convert the rest of the arguments 14608 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14609 RParenLoc)) 14610 return BuildRecoveryExpr(ResultType); 14611 14612 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14613 14614 if (CheckFunctionCall(Method, TheCall, Proto)) 14615 return ExprError(); 14616 14617 // In the case the method to call was not selected by the overloading 14618 // resolution process, we still need to handle the enable_if attribute. Do 14619 // that here, so it will not hide previous -- and more relevant -- errors. 14620 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14621 if (const EnableIfAttr *Attr = 14622 CheckEnableIf(Method, LParenLoc, Args, true)) { 14623 Diag(MemE->getMemberLoc(), 14624 diag::err_ovl_no_viable_member_function_in_call) 14625 << Method << Method->getSourceRange(); 14626 Diag(Method->getLocation(), 14627 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14628 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14629 return ExprError(); 14630 } 14631 } 14632 14633 if ((isa<CXXConstructorDecl>(CurContext) || 14634 isa<CXXDestructorDecl>(CurContext)) && 14635 TheCall->getMethodDecl()->isPure()) { 14636 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14637 14638 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14639 MemExpr->performsVirtualDispatch(getLangOpts())) { 14640 Diag(MemExpr->getBeginLoc(), 14641 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14642 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14643 << MD->getParent(); 14644 14645 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14646 if (getLangOpts().AppleKext) 14647 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14648 << MD->getParent() << MD->getDeclName(); 14649 } 14650 } 14651 14652 if (CXXDestructorDecl *DD = 14653 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14654 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14655 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14656 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14657 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14658 MemExpr->getMemberLoc()); 14659 } 14660 14661 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14662 TheCall->getMethodDecl()); 14663 } 14664 14665 /// BuildCallToObjectOfClassType - Build a call to an object of class 14666 /// type (C++ [over.call.object]), which can end up invoking an 14667 /// overloaded function call operator (@c operator()) or performing a 14668 /// user-defined conversion on the object argument. 14669 ExprResult 14670 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14671 SourceLocation LParenLoc, 14672 MultiExprArg Args, 14673 SourceLocation RParenLoc) { 14674 if (checkPlaceholderForOverload(*this, Obj)) 14675 return ExprError(); 14676 ExprResult Object = Obj; 14677 14678 UnbridgedCastsSet UnbridgedCasts; 14679 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14680 return ExprError(); 14681 14682 assert(Object.get()->getType()->isRecordType() && 14683 "Requires object type argument"); 14684 14685 // C++ [over.call.object]p1: 14686 // If the primary-expression E in the function call syntax 14687 // evaluates to a class object of type "cv T", then the set of 14688 // candidate functions includes at least the function call 14689 // operators of T. The function call operators of T are obtained by 14690 // ordinary lookup of the name operator() in the context of 14691 // (E).operator(). 14692 OverloadCandidateSet CandidateSet(LParenLoc, 14693 OverloadCandidateSet::CSK_Operator); 14694 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14695 14696 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14697 diag::err_incomplete_object_call, Object.get())) 14698 return true; 14699 14700 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14701 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14702 LookupQualifiedName(R, Record->getDecl()); 14703 R.suppressDiagnostics(); 14704 14705 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14706 Oper != OperEnd; ++Oper) { 14707 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14708 Object.get()->Classify(Context), Args, CandidateSet, 14709 /*SuppressUserConversion=*/false); 14710 } 14711 14712 // C++ [over.call.object]p2: 14713 // In addition, for each (non-explicit in C++0x) conversion function 14714 // declared in T of the form 14715 // 14716 // operator conversion-type-id () cv-qualifier; 14717 // 14718 // where cv-qualifier is the same cv-qualification as, or a 14719 // greater cv-qualification than, cv, and where conversion-type-id 14720 // denotes the type "pointer to function of (P1,...,Pn) returning 14721 // R", or the type "reference to pointer to function of 14722 // (P1,...,Pn) returning R", or the type "reference to function 14723 // of (P1,...,Pn) returning R", a surrogate call function [...] 14724 // is also considered as a candidate function. Similarly, 14725 // surrogate call functions are added to the set of candidate 14726 // functions for each conversion function declared in an 14727 // accessible base class provided the function is not hidden 14728 // within T by another intervening declaration. 14729 const auto &Conversions = 14730 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14731 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14732 NamedDecl *D = *I; 14733 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14734 if (isa<UsingShadowDecl>(D)) 14735 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14736 14737 // Skip over templated conversion functions; they aren't 14738 // surrogates. 14739 if (isa<FunctionTemplateDecl>(D)) 14740 continue; 14741 14742 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14743 if (!Conv->isExplicit()) { 14744 // Strip the reference type (if any) and then the pointer type (if 14745 // any) to get down to what might be a function type. 14746 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14747 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14748 ConvType = ConvPtrType->getPointeeType(); 14749 14750 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14751 { 14752 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14753 Object.get(), Args, CandidateSet); 14754 } 14755 } 14756 } 14757 14758 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14759 14760 // Perform overload resolution. 14761 OverloadCandidateSet::iterator Best; 14762 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14763 Best)) { 14764 case OR_Success: 14765 // Overload resolution succeeded; we'll build the appropriate call 14766 // below. 14767 break; 14768 14769 case OR_No_Viable_Function: { 14770 PartialDiagnostic PD = 14771 CandidateSet.empty() 14772 ? (PDiag(diag::err_ovl_no_oper) 14773 << Object.get()->getType() << /*call*/ 1 14774 << Object.get()->getSourceRange()) 14775 : (PDiag(diag::err_ovl_no_viable_object_call) 14776 << Object.get()->getType() << Object.get()->getSourceRange()); 14777 CandidateSet.NoteCandidates( 14778 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14779 OCD_AllCandidates, Args); 14780 break; 14781 } 14782 case OR_Ambiguous: 14783 CandidateSet.NoteCandidates( 14784 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14785 PDiag(diag::err_ovl_ambiguous_object_call) 14786 << Object.get()->getType() 14787 << Object.get()->getSourceRange()), 14788 *this, OCD_AmbiguousCandidates, Args); 14789 break; 14790 14791 case OR_Deleted: 14792 CandidateSet.NoteCandidates( 14793 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14794 PDiag(diag::err_ovl_deleted_object_call) 14795 << Object.get()->getType() 14796 << Object.get()->getSourceRange()), 14797 *this, OCD_AllCandidates, Args); 14798 break; 14799 } 14800 14801 if (Best == CandidateSet.end()) 14802 return true; 14803 14804 UnbridgedCasts.restore(); 14805 14806 if (Best->Function == nullptr) { 14807 // Since there is no function declaration, this is one of the 14808 // surrogate candidates. Dig out the conversion function. 14809 CXXConversionDecl *Conv 14810 = cast<CXXConversionDecl>( 14811 Best->Conversions[0].UserDefined.ConversionFunction); 14812 14813 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14814 Best->FoundDecl); 14815 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14816 return ExprError(); 14817 assert(Conv == Best->FoundDecl.getDecl() && 14818 "Found Decl & conversion-to-functionptr should be same, right?!"); 14819 // We selected one of the surrogate functions that converts the 14820 // object parameter to a function pointer. Perform the conversion 14821 // on the object argument, then let BuildCallExpr finish the job. 14822 14823 // Create an implicit member expr to refer to the conversion operator. 14824 // and then call it. 14825 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14826 Conv, HadMultipleCandidates); 14827 if (Call.isInvalid()) 14828 return ExprError(); 14829 // Record usage of conversion in an implicit cast. 14830 Call = ImplicitCastExpr::Create( 14831 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14832 nullptr, VK_PRValue, CurFPFeatureOverrides()); 14833 14834 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14835 } 14836 14837 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14838 14839 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14840 // that calls this method, using Object for the implicit object 14841 // parameter and passing along the remaining arguments. 14842 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14843 14844 // An error diagnostic has already been printed when parsing the declaration. 14845 if (Method->isInvalidDecl()) 14846 return ExprError(); 14847 14848 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14849 unsigned NumParams = Proto->getNumParams(); 14850 14851 DeclarationNameInfo OpLocInfo( 14852 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14853 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14854 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14855 Obj, HadMultipleCandidates, 14856 OpLocInfo.getLoc(), 14857 OpLocInfo.getInfo()); 14858 if (NewFn.isInvalid()) 14859 return true; 14860 14861 SmallVector<Expr *, 8> MethodArgs; 14862 MethodArgs.reserve(NumParams + 1); 14863 14864 bool IsError = false; 14865 14866 // Initialize the implicit object parameter. 14867 ExprResult ObjRes = 14868 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14869 Best->FoundDecl, Method); 14870 if (ObjRes.isInvalid()) 14871 IsError = true; 14872 else 14873 Object = ObjRes; 14874 MethodArgs.push_back(Object.get()); 14875 14876 IsError |= PrepareArgumentsForCallToObjectOfClassType( 14877 *this, MethodArgs, Method, Args, LParenLoc); 14878 14879 // If this is a variadic call, handle args passed through "...". 14880 if (Proto->isVariadic()) { 14881 // Promote the arguments (C99 6.5.2.2p7). 14882 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14883 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14884 nullptr); 14885 IsError |= Arg.isInvalid(); 14886 MethodArgs.push_back(Arg.get()); 14887 } 14888 } 14889 14890 if (IsError) 14891 return true; 14892 14893 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14894 14895 // Once we've built TheCall, all of the expressions are properly owned. 14896 QualType ResultTy = Method->getReturnType(); 14897 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14898 ResultTy = ResultTy.getNonLValueExprType(Context); 14899 14900 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14901 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14902 CurFPFeatureOverrides()); 14903 14904 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14905 return true; 14906 14907 if (CheckFunctionCall(Method, TheCall, Proto)) 14908 return true; 14909 14910 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14911 } 14912 14913 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14914 /// (if one exists), where @c Base is an expression of class type and 14915 /// @c Member is the name of the member we're trying to find. 14916 ExprResult 14917 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14918 bool *NoArrowOperatorFound) { 14919 assert(Base->getType()->isRecordType() && 14920 "left-hand side must have class type"); 14921 14922 if (checkPlaceholderForOverload(*this, Base)) 14923 return ExprError(); 14924 14925 SourceLocation Loc = Base->getExprLoc(); 14926 14927 // C++ [over.ref]p1: 14928 // 14929 // [...] An expression x->m is interpreted as (x.operator->())->m 14930 // for a class object x of type T if T::operator->() exists and if 14931 // the operator is selected as the best match function by the 14932 // overload resolution mechanism (13.3). 14933 DeclarationName OpName = 14934 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14935 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14936 14937 if (RequireCompleteType(Loc, Base->getType(), 14938 diag::err_typecheck_incomplete_tag, Base)) 14939 return ExprError(); 14940 14941 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14942 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14943 R.suppressDiagnostics(); 14944 14945 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14946 Oper != OperEnd; ++Oper) { 14947 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14948 None, CandidateSet, /*SuppressUserConversion=*/false); 14949 } 14950 14951 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14952 14953 // Perform overload resolution. 14954 OverloadCandidateSet::iterator Best; 14955 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14956 case OR_Success: 14957 // Overload resolution succeeded; we'll build the call below. 14958 break; 14959 14960 case OR_No_Viable_Function: { 14961 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14962 if (CandidateSet.empty()) { 14963 QualType BaseType = Base->getType(); 14964 if (NoArrowOperatorFound) { 14965 // Report this specific error to the caller instead of emitting a 14966 // diagnostic, as requested. 14967 *NoArrowOperatorFound = true; 14968 return ExprError(); 14969 } 14970 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14971 << BaseType << Base->getSourceRange(); 14972 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14973 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14974 << FixItHint::CreateReplacement(OpLoc, "."); 14975 } 14976 } else 14977 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14978 << "operator->" << Base->getSourceRange(); 14979 CandidateSet.NoteCandidates(*this, Base, Cands); 14980 return ExprError(); 14981 } 14982 case OR_Ambiguous: 14983 CandidateSet.NoteCandidates( 14984 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14985 << "->" << Base->getType() 14986 << Base->getSourceRange()), 14987 *this, OCD_AmbiguousCandidates, Base); 14988 return ExprError(); 14989 14990 case OR_Deleted: 14991 CandidateSet.NoteCandidates( 14992 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14993 << "->" << Base->getSourceRange()), 14994 *this, OCD_AllCandidates, Base); 14995 return ExprError(); 14996 } 14997 14998 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14999 15000 // Convert the object parameter. 15001 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15002 ExprResult BaseResult = 15003 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 15004 Best->FoundDecl, Method); 15005 if (BaseResult.isInvalid()) 15006 return ExprError(); 15007 Base = BaseResult.get(); 15008 15009 // Build the operator call. 15010 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15011 Base, HadMultipleCandidates, OpLoc); 15012 if (FnExpr.isInvalid()) 15013 return ExprError(); 15014 15015 QualType ResultTy = Method->getReturnType(); 15016 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15017 ResultTy = ResultTy.getNonLValueExprType(Context); 15018 CXXOperatorCallExpr *TheCall = 15019 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 15020 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 15021 15022 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 15023 return ExprError(); 15024 15025 if (CheckFunctionCall(Method, TheCall, 15026 Method->getType()->castAs<FunctionProtoType>())) 15027 return ExprError(); 15028 15029 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15030 } 15031 15032 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 15033 /// a literal operator described by the provided lookup results. 15034 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 15035 DeclarationNameInfo &SuffixInfo, 15036 ArrayRef<Expr*> Args, 15037 SourceLocation LitEndLoc, 15038 TemplateArgumentListInfo *TemplateArgs) { 15039 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 15040 15041 OverloadCandidateSet CandidateSet(UDSuffixLoc, 15042 OverloadCandidateSet::CSK_Normal); 15043 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 15044 TemplateArgs); 15045 15046 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15047 15048 // Perform overload resolution. This will usually be trivial, but might need 15049 // to perform substitutions for a literal operator template. 15050 OverloadCandidateSet::iterator Best; 15051 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 15052 case OR_Success: 15053 case OR_Deleted: 15054 break; 15055 15056 case OR_No_Viable_Function: 15057 CandidateSet.NoteCandidates( 15058 PartialDiagnosticAt(UDSuffixLoc, 15059 PDiag(diag::err_ovl_no_viable_function_in_call) 15060 << R.getLookupName()), 15061 *this, OCD_AllCandidates, Args); 15062 return ExprError(); 15063 15064 case OR_Ambiguous: 15065 CandidateSet.NoteCandidates( 15066 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 15067 << R.getLookupName()), 15068 *this, OCD_AmbiguousCandidates, Args); 15069 return ExprError(); 15070 } 15071 15072 FunctionDecl *FD = Best->Function; 15073 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 15074 nullptr, HadMultipleCandidates, 15075 SuffixInfo.getLoc(), 15076 SuffixInfo.getInfo()); 15077 if (Fn.isInvalid()) 15078 return true; 15079 15080 // Check the argument types. This should almost always be a no-op, except 15081 // that array-to-pointer decay is applied to string literals. 15082 Expr *ConvArgs[2]; 15083 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 15084 ExprResult InputInit = PerformCopyInitialization( 15085 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 15086 SourceLocation(), Args[ArgIdx]); 15087 if (InputInit.isInvalid()) 15088 return true; 15089 ConvArgs[ArgIdx] = InputInit.get(); 15090 } 15091 15092 QualType ResultTy = FD->getReturnType(); 15093 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15094 ResultTy = ResultTy.getNonLValueExprType(Context); 15095 15096 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 15097 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 15098 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 15099 15100 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 15101 return ExprError(); 15102 15103 if (CheckFunctionCall(FD, UDL, nullptr)) 15104 return ExprError(); 15105 15106 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 15107 } 15108 15109 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 15110 /// given LookupResult is non-empty, it is assumed to describe a member which 15111 /// will be invoked. Otherwise, the function will be found via argument 15112 /// dependent lookup. 15113 /// CallExpr is set to a valid expression and FRS_Success returned on success, 15114 /// otherwise CallExpr is set to ExprError() and some non-success value 15115 /// is returned. 15116 Sema::ForRangeStatus 15117 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 15118 SourceLocation RangeLoc, 15119 const DeclarationNameInfo &NameInfo, 15120 LookupResult &MemberLookup, 15121 OverloadCandidateSet *CandidateSet, 15122 Expr *Range, ExprResult *CallExpr) { 15123 Scope *S = nullptr; 15124 15125 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 15126 if (!MemberLookup.empty()) { 15127 ExprResult MemberRef = 15128 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 15129 /*IsPtr=*/false, CXXScopeSpec(), 15130 /*TemplateKWLoc=*/SourceLocation(), 15131 /*FirstQualifierInScope=*/nullptr, 15132 MemberLookup, 15133 /*TemplateArgs=*/nullptr, S); 15134 if (MemberRef.isInvalid()) { 15135 *CallExpr = ExprError(); 15136 return FRS_DiagnosticIssued; 15137 } 15138 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 15139 if (CallExpr->isInvalid()) { 15140 *CallExpr = ExprError(); 15141 return FRS_DiagnosticIssued; 15142 } 15143 } else { 15144 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 15145 NestedNameSpecifierLoc(), 15146 NameInfo, UnresolvedSet<0>()); 15147 if (FnR.isInvalid()) 15148 return FRS_DiagnosticIssued; 15149 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 15150 15151 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 15152 CandidateSet, CallExpr); 15153 if (CandidateSet->empty() || CandidateSetError) { 15154 *CallExpr = ExprError(); 15155 return FRS_NoViableFunction; 15156 } 15157 OverloadCandidateSet::iterator Best; 15158 OverloadingResult OverloadResult = 15159 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 15160 15161 if (OverloadResult == OR_No_Viable_Function) { 15162 *CallExpr = ExprError(); 15163 return FRS_NoViableFunction; 15164 } 15165 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 15166 Loc, nullptr, CandidateSet, &Best, 15167 OverloadResult, 15168 /*AllowTypoCorrection=*/false); 15169 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 15170 *CallExpr = ExprError(); 15171 return FRS_DiagnosticIssued; 15172 } 15173 } 15174 return FRS_Success; 15175 } 15176 15177 15178 /// FixOverloadedFunctionReference - E is an expression that refers to 15179 /// a C++ overloaded function (possibly with some parentheses and 15180 /// perhaps a '&' around it). We have resolved the overloaded function 15181 /// to the function declaration Fn, so patch up the expression E to 15182 /// refer (possibly indirectly) to Fn. Returns the new expr. 15183 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15184 FunctionDecl *Fn) { 15185 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15186 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15187 Found, Fn); 15188 if (SubExpr == PE->getSubExpr()) 15189 return PE; 15190 15191 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15192 } 15193 15194 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15195 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15196 Found, Fn); 15197 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15198 SubExpr->getType()) && 15199 "Implicit cast type cannot be determined from overload"); 15200 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15201 if (SubExpr == ICE->getSubExpr()) 15202 return ICE; 15203 15204 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15205 SubExpr, nullptr, ICE->getValueKind(), 15206 CurFPFeatureOverrides()); 15207 } 15208 15209 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15210 if (!GSE->isResultDependent()) { 15211 Expr *SubExpr = 15212 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15213 if (SubExpr == GSE->getResultExpr()) 15214 return GSE; 15215 15216 // Replace the resulting type information before rebuilding the generic 15217 // selection expression. 15218 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15219 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15220 unsigned ResultIdx = GSE->getResultIndex(); 15221 AssocExprs[ResultIdx] = SubExpr; 15222 15223 return GenericSelectionExpr::Create( 15224 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15225 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15226 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15227 ResultIdx); 15228 } 15229 // Rather than fall through to the unreachable, return the original generic 15230 // selection expression. 15231 return GSE; 15232 } 15233 15234 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15235 assert(UnOp->getOpcode() == UO_AddrOf && 15236 "Can only take the address of an overloaded function"); 15237 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15238 if (Method->isStatic()) { 15239 // Do nothing: static member functions aren't any different 15240 // from non-member functions. 15241 } else { 15242 // Fix the subexpression, which really has to be an 15243 // UnresolvedLookupExpr holding an overloaded member function 15244 // or template. 15245 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15246 Found, Fn); 15247 if (SubExpr == UnOp->getSubExpr()) 15248 return UnOp; 15249 15250 assert(isa<DeclRefExpr>(SubExpr) 15251 && "fixed to something other than a decl ref"); 15252 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15253 && "fixed to a member ref with no nested name qualifier"); 15254 15255 // We have taken the address of a pointer to member 15256 // function. Perform the computation here so that we get the 15257 // appropriate pointer to member type. 15258 QualType ClassType 15259 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15260 QualType MemPtrType 15261 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15262 // Under the MS ABI, lock down the inheritance model now. 15263 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15264 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15265 15266 return UnaryOperator::Create( 15267 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, 15268 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15269 } 15270 } 15271 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15272 Found, Fn); 15273 if (SubExpr == UnOp->getSubExpr()) 15274 return UnOp; 15275 15276 // FIXME: This can't currently fail, but in principle it could. 15277 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr) 15278 .get(); 15279 } 15280 15281 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15282 // FIXME: avoid copy. 15283 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15284 if (ULE->hasExplicitTemplateArgs()) { 15285 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15286 TemplateArgs = &TemplateArgsBuffer; 15287 } 15288 15289 QualType Type = Fn->getType(); 15290 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; 15291 15292 // FIXME: Duplicated from BuildDeclarationNameExpr. 15293 if (unsigned BID = Fn->getBuiltinID()) { 15294 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 15295 Type = Context.BuiltinFnTy; 15296 ValueKind = VK_PRValue; 15297 } 15298 } 15299 15300 DeclRefExpr *DRE = BuildDeclRefExpr( 15301 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), 15302 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); 15303 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15304 return DRE; 15305 } 15306 15307 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15308 // FIXME: avoid copy. 15309 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15310 if (MemExpr->hasExplicitTemplateArgs()) { 15311 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15312 TemplateArgs = &TemplateArgsBuffer; 15313 } 15314 15315 Expr *Base; 15316 15317 // If we're filling in a static method where we used to have an 15318 // implicit member access, rewrite to a simple decl ref. 15319 if (MemExpr->isImplicitAccess()) { 15320 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15321 DeclRefExpr *DRE = BuildDeclRefExpr( 15322 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15323 MemExpr->getQualifierLoc(), Found.getDecl(), 15324 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15325 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15326 return DRE; 15327 } else { 15328 SourceLocation Loc = MemExpr->getMemberLoc(); 15329 if (MemExpr->getQualifier()) 15330 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15331 Base = 15332 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15333 } 15334 } else 15335 Base = MemExpr->getBase(); 15336 15337 ExprValueKind valueKind; 15338 QualType type; 15339 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15340 valueKind = VK_LValue; 15341 type = Fn->getType(); 15342 } else { 15343 valueKind = VK_PRValue; 15344 type = Context.BoundMemberTy; 15345 } 15346 15347 return BuildMemberExpr( 15348 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15349 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15350 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15351 type, valueKind, OK_Ordinary, TemplateArgs); 15352 } 15353 15354 llvm_unreachable("Invalid reference to overloaded function"); 15355 } 15356 15357 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15358 DeclAccessPair Found, 15359 FunctionDecl *Fn) { 15360 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15361 } 15362 15363 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 15364 FunctionDecl *Function) { 15365 if (!PartialOverloading || !Function) 15366 return true; 15367 if (Function->isVariadic()) 15368 return false; 15369 if (const auto *Proto = 15370 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 15371 if (Proto->isTemplateVariadic()) 15372 return false; 15373 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 15374 if (const auto *Proto = 15375 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 15376 if (Proto->isTemplateVariadic()) 15377 return false; 15378 return true; 15379 } 15380