1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult 53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 54 const Expr *Base, bool HadMultipleCandidates, 55 SourceLocation Loc = SourceLocation(), 56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 58 return ExprError(); 59 // If FoundDecl is different from Fn (such as if one is a template 60 // and the other a specialization), make sure DiagnoseUseOfDecl is 61 // called on both. 62 // FIXME: This would be more comprehensively addressed by modifying 63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 64 // being used. 65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 66 return ExprError(); 67 DeclRefExpr *DRE = new (S.Context) 68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 69 if (HadMultipleCandidates) 70 DRE->setHadMultipleCandidates(true); 71 72 S.MarkDeclRefReferenced(DRE, Base); 73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 75 S.ResolveExceptionSpec(Loc, FPT); 76 DRE->setType(Fn->getType()); 77 } 78 } 79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 80 CK_FunctionToPointerDecay); 81 } 82 83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle, 87 bool AllowObjCWritebackConversion); 88 89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 90 QualType &ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle); 94 static OverloadingResult 95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 96 UserDefinedConversionSequence& User, 97 OverloadCandidateSet& Conversions, 98 AllowedExplicit AllowExplicit, 99 bool AllowObjCConversionOnExplicit); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 static ImplicitConversionSequence::CompareKind 107 CompareQualificationConversions(Sema &S, 108 const StandardConversionSequence& SCS1, 109 const StandardConversionSequence& SCS2); 110 111 static ImplicitConversionSequence::CompareKind 112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 113 const StandardConversionSequence& SCS1, 114 const StandardConversionSequence& SCS2); 115 116 /// GetConversionRank - Retrieve the implicit conversion rank 117 /// corresponding to the given implicit conversion kind. 118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 119 static const ImplicitConversionRank 120 Rank[(int)ICK_Num_Conversion_Kinds] = { 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Exact_Match, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Promotion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_OCL_Scalar_Widening, 142 ICR_Complex_Real_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Writeback_Conversion, 146 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 147 // it was omitted by the patch that added 148 // ICK_Zero_Event_Conversion 149 ICR_C_Conversion, 150 ICR_C_Conversion_Extension 151 }; 152 return Rank[(int)Kind]; 153 } 154 155 /// GetImplicitConversionName - Return the name of this kind of 156 /// implicit conversion. 157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Function pointer conversion", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "SVE Vector conversion", 179 "Vector splat", 180 "Complex-real conversion", 181 "Block Pointer conversion", 182 "Transparent Union Conversion", 183 "Writeback conversion", 184 "OpenCL Zero Event Conversion", 185 "C specific type conversion", 186 "Incompatible pointer conversion" 187 }; 188 return Name[Kind]; 189 } 190 191 /// StandardConversionSequence - Set the standard conversion 192 /// sequence to the identity conversion. 193 void StandardConversionSequence::setAsIdentityConversion() { 194 First = ICK_Identity; 195 Second = ICK_Identity; 196 Third = ICK_Identity; 197 DeprecatedStringLiteralToCharPtr = false; 198 QualificationIncludesObjCLifetime = false; 199 ReferenceBinding = false; 200 DirectBinding = false; 201 IsLvalueReference = true; 202 BindsToFunctionLvalue = false; 203 BindsToRvalue = false; 204 BindsImplicitObjectArgumentWithoutRefQualifier = false; 205 ObjCLifetimeConversionBinding = false; 206 CopyConstructor = nullptr; 207 } 208 209 /// getRank - Retrieve the rank of this standard conversion sequence 210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 211 /// implicit conversions. 212 ImplicitConversionRank StandardConversionSequence::getRank() const { 213 ImplicitConversionRank Rank = ICR_Exact_Match; 214 if (GetConversionRank(First) > Rank) 215 Rank = GetConversionRank(First); 216 if (GetConversionRank(Second) > Rank) 217 Rank = GetConversionRank(Second); 218 if (GetConversionRank(Third) > Rank) 219 Rank = GetConversionRank(Third); 220 return Rank; 221 } 222 223 /// isPointerConversionToBool - Determines whether this conversion is 224 /// a conversion of a pointer or pointer-to-member to bool. This is 225 /// used as part of the ranking of standard conversion sequences 226 /// (C++ 13.3.3.2p4). 227 bool StandardConversionSequence::isPointerConversionToBool() const { 228 // Note that FromType has not necessarily been transformed by the 229 // array-to-pointer or function-to-pointer implicit conversions, so 230 // check for their presence as well as checking whether FromType is 231 // a pointer. 232 if (getToType(1)->isBooleanType() && 233 (getFromType()->isPointerType() || 234 getFromType()->isMemberPointerType() || 235 getFromType()->isObjCObjectPointerType() || 236 getFromType()->isBlockPointerType() || 237 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 238 return true; 239 240 return false; 241 } 242 243 /// isPointerConversionToVoidPointer - Determines whether this 244 /// conversion is a conversion of a pointer to a void pointer. This is 245 /// used as part of the ranking of standard conversion sequences (C++ 246 /// 13.3.3.2p4). 247 bool 248 StandardConversionSequence:: 249 isPointerConversionToVoidPointer(ASTContext& Context) const { 250 QualType FromType = getFromType(); 251 QualType ToType = getToType(1); 252 253 // Note that FromType has not necessarily been transformed by the 254 // array-to-pointer implicit conversion, so check for its presence 255 // and redo the conversion to get a pointer. 256 if (First == ICK_Array_To_Pointer) 257 FromType = Context.getArrayDecayedType(FromType); 258 259 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 260 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 261 return ToPtrType->getPointeeType()->isVoidType(); 262 263 return false; 264 } 265 266 /// Skip any implicit casts which could be either part of a narrowing conversion 267 /// or after one in an implicit conversion. 268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 269 const Expr *Converted) { 270 // We can have cleanups wrapping the converted expression; these need to be 271 // preserved so that destructors run if necessary. 272 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 273 Expr *Inner = 274 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 275 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 276 EWC->getObjects()); 277 } 278 279 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 280 switch (ICE->getCastKind()) { 281 case CK_NoOp: 282 case CK_IntegralCast: 283 case CK_IntegralToBoolean: 284 case CK_IntegralToFloating: 285 case CK_BooleanToSignedIntegral: 286 case CK_FloatingToIntegral: 287 case CK_FloatingToBoolean: 288 case CK_FloatingCast: 289 Converted = ICE->getSubExpr(); 290 continue; 291 292 default: 293 return Converted; 294 } 295 } 296 297 return Converted; 298 } 299 300 /// Check if this standard conversion sequence represents a narrowing 301 /// conversion, according to C++11 [dcl.init.list]p7. 302 /// 303 /// \param Ctx The AST context. 304 /// \param Converted The result of applying this standard conversion sequence. 305 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 306 /// value of the expression prior to the narrowing conversion. 307 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 308 /// type of the expression prior to the narrowing conversion. 309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 310 /// from floating point types to integral types should be ignored. 311 NarrowingKind StandardConversionSequence::getNarrowingKind( 312 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 313 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 315 316 // C++11 [dcl.init.list]p7: 317 // A narrowing conversion is an implicit conversion ... 318 QualType FromType = getToType(0); 319 QualType ToType = getToType(1); 320 321 // A conversion to an enumeration type is narrowing if the conversion to 322 // the underlying type is narrowing. This only arises for expressions of 323 // the form 'Enum{init}'. 324 if (auto *ET = ToType->getAs<EnumType>()) 325 ToType = ET->getDecl()->getIntegerType(); 326 327 switch (Second) { 328 // 'bool' is an integral type; dispatch to the right place to handle it. 329 case ICK_Boolean_Conversion: 330 if (FromType->isRealFloatingType()) 331 goto FloatingIntegralConversion; 332 if (FromType->isIntegralOrUnscopedEnumerationType()) 333 goto IntegralConversion; 334 // -- from a pointer type or pointer-to-member type to bool, or 335 return NK_Type_Narrowing; 336 337 // -- from a floating-point type to an integer type, or 338 // 339 // -- from an integer type or unscoped enumeration type to a floating-point 340 // type, except where the source is a constant expression and the actual 341 // value after conversion will fit into the target type and will produce 342 // the original value when converted back to the original type, or 343 case ICK_Floating_Integral: 344 FloatingIntegralConversion: 345 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 346 return NK_Type_Narrowing; 347 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 348 ToType->isRealFloatingType()) { 349 if (IgnoreFloatToIntegralConversion) 350 return NK_Not_Narrowing; 351 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 352 assert(Initializer && "Unknown conversion expression"); 353 354 // If it's value-dependent, we can't tell whether it's narrowing. 355 if (Initializer->isValueDependent()) 356 return NK_Dependent_Narrowing; 357 358 if (Optional<llvm::APSInt> IntConstantValue = 359 Initializer->getIntegerConstantExpr(Ctx)) { 360 // Convert the integer to the floating type. 361 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 362 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 363 llvm::APFloat::rmNearestTiesToEven); 364 // And back. 365 llvm::APSInt ConvertedValue = *IntConstantValue; 366 bool ignored; 367 Result.convertToInteger(ConvertedValue, 368 llvm::APFloat::rmTowardZero, &ignored); 369 // If the resulting value is different, this was a narrowing conversion. 370 if (*IntConstantValue != ConvertedValue) { 371 ConstantValue = APValue(*IntConstantValue); 372 ConstantType = Initializer->getType(); 373 return NK_Constant_Narrowing; 374 } 375 } else { 376 // Variables are always narrowings. 377 return NK_Variable_Narrowing; 378 } 379 } 380 return NK_Not_Narrowing; 381 382 // -- from long double to double or float, or from double to float, except 383 // where the source is a constant expression and the actual value after 384 // conversion is within the range of values that can be represented (even 385 // if it cannot be represented exactly), or 386 case ICK_Floating_Conversion: 387 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 388 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 389 // FromType is larger than ToType. 390 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 391 392 // If it's value-dependent, we can't tell whether it's narrowing. 393 if (Initializer->isValueDependent()) 394 return NK_Dependent_Narrowing; 395 396 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 397 // Constant! 398 assert(ConstantValue.isFloat()); 399 llvm::APFloat FloatVal = ConstantValue.getFloat(); 400 // Convert the source value into the target type. 401 bool ignored; 402 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 403 Ctx.getFloatTypeSemantics(ToType), 404 llvm::APFloat::rmNearestTiesToEven, &ignored); 405 // If there was no overflow, the source value is within the range of 406 // values that can be represented. 407 if (ConvertStatus & llvm::APFloat::opOverflow) { 408 ConstantType = Initializer->getType(); 409 return NK_Constant_Narrowing; 410 } 411 } else { 412 return NK_Variable_Narrowing; 413 } 414 } 415 return NK_Not_Narrowing; 416 417 // -- from an integer type or unscoped enumeration type to an integer type 418 // that cannot represent all the values of the original type, except where 419 // the source is a constant expression and the actual value after 420 // conversion will fit into the target type and will produce the original 421 // value when converted back to the original type. 422 case ICK_Integral_Conversion: 423 IntegralConversion: { 424 assert(FromType->isIntegralOrUnscopedEnumerationType()); 425 assert(ToType->isIntegralOrUnscopedEnumerationType()); 426 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 427 const unsigned FromWidth = Ctx.getIntWidth(FromType); 428 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 429 const unsigned ToWidth = Ctx.getIntWidth(ToType); 430 431 if (FromWidth > ToWidth || 432 (FromWidth == ToWidth && FromSigned != ToSigned) || 433 (FromSigned && !ToSigned)) { 434 // Not all values of FromType can be represented in ToType. 435 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 436 437 // If it's value-dependent, we can't tell whether it's narrowing. 438 if (Initializer->isValueDependent()) 439 return NK_Dependent_Narrowing; 440 441 Optional<llvm::APSInt> OptInitializerValue; 442 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 443 // Such conversions on variables are always narrowing. 444 return NK_Variable_Narrowing; 445 } 446 llvm::APSInt &InitializerValue = *OptInitializerValue; 447 bool Narrowing = false; 448 if (FromWidth < ToWidth) { 449 // Negative -> unsigned is narrowing. Otherwise, more bits is never 450 // narrowing. 451 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 452 Narrowing = true; 453 } else { 454 // Add a bit to the InitializerValue so we don't have to worry about 455 // signed vs. unsigned comparisons. 456 InitializerValue = InitializerValue.extend( 457 InitializerValue.getBitWidth() + 1); 458 // Convert the initializer to and from the target width and signed-ness. 459 llvm::APSInt ConvertedValue = InitializerValue; 460 ConvertedValue = ConvertedValue.trunc(ToWidth); 461 ConvertedValue.setIsSigned(ToSigned); 462 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 463 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 464 // If the result is different, this was a narrowing conversion. 465 if (ConvertedValue != InitializerValue) 466 Narrowing = true; 467 } 468 if (Narrowing) { 469 ConstantType = Initializer->getType(); 470 ConstantValue = APValue(InitializerValue); 471 return NK_Constant_Narrowing; 472 } 473 } 474 return NK_Not_Narrowing; 475 } 476 477 default: 478 // Other kinds of conversions are not narrowings. 479 return NK_Not_Narrowing; 480 } 481 } 482 483 /// dump - Print this standard conversion sequence to standard 484 /// error. Useful for debugging overloading issues. 485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 486 raw_ostream &OS = llvm::errs(); 487 bool PrintedSomething = false; 488 if (First != ICK_Identity) { 489 OS << GetImplicitConversionName(First); 490 PrintedSomething = true; 491 } 492 493 if (Second != ICK_Identity) { 494 if (PrintedSomething) { 495 OS << " -> "; 496 } 497 OS << GetImplicitConversionName(Second); 498 499 if (CopyConstructor) { 500 OS << " (by copy constructor)"; 501 } else if (DirectBinding) { 502 OS << " (direct reference binding)"; 503 } else if (ReferenceBinding) { 504 OS << " (reference binding)"; 505 } 506 PrintedSomething = true; 507 } 508 509 if (Third != ICK_Identity) { 510 if (PrintedSomething) { 511 OS << " -> "; 512 } 513 OS << GetImplicitConversionName(Third); 514 PrintedSomething = true; 515 } 516 517 if (!PrintedSomething) { 518 OS << "No conversions required"; 519 } 520 } 521 522 /// dump - Print this user-defined conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void UserDefinedConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (Before.First || Before.Second || Before.Third) { 527 Before.dump(); 528 OS << " -> "; 529 } 530 if (ConversionFunction) 531 OS << '\'' << *ConversionFunction << '\''; 532 else 533 OS << "aggregate initialization"; 534 if (After.First || After.Second || After.Third) { 535 OS << " -> "; 536 After.dump(); 537 } 538 } 539 540 /// dump - Print this implicit conversion sequence to standard 541 /// error. Useful for debugging overloading issues. 542 void ImplicitConversionSequence::dump() const { 543 raw_ostream &OS = llvm::errs(); 544 if (hasInitializerListContainerType()) 545 OS << "Worst list element conversion: "; 546 switch (ConversionKind) { 547 case StandardConversion: 548 OS << "Standard conversion: "; 549 Standard.dump(); 550 break; 551 case UserDefinedConversion: 552 OS << "User-defined conversion: "; 553 UserDefined.dump(); 554 break; 555 case EllipsisConversion: 556 OS << "Ellipsis conversion"; 557 break; 558 case AmbiguousConversion: 559 OS << "Ambiguous conversion"; 560 break; 561 case BadConversion: 562 OS << "Bad conversion"; 563 break; 564 } 565 566 OS << "\n"; 567 } 568 569 void AmbiguousConversionSequence::construct() { 570 new (&conversions()) ConversionSet(); 571 } 572 573 void AmbiguousConversionSequence::destruct() { 574 conversions().~ConversionSet(); 575 } 576 577 void 578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 579 FromTypePtr = O.FromTypePtr; 580 ToTypePtr = O.ToTypePtr; 581 new (&conversions()) ConversionSet(O.conversions()); 582 } 583 584 namespace { 585 // Structure used by DeductionFailureInfo to store 586 // template argument information. 587 struct DFIArguments { 588 TemplateArgument FirstArg; 589 TemplateArgument SecondArg; 590 }; 591 // Structure used by DeductionFailureInfo to store 592 // template parameter and template argument information. 593 struct DFIParamWithArguments : DFIArguments { 594 TemplateParameter Param; 595 }; 596 // Structure used by DeductionFailureInfo to store template argument 597 // information and the index of the problematic call argument. 598 struct DFIDeducedMismatchArgs : DFIArguments { 599 TemplateArgumentList *TemplateArgs; 600 unsigned CallArgIndex; 601 }; 602 // Structure used by DeductionFailureInfo to store information about 603 // unsatisfied constraints. 604 struct CNSInfo { 605 TemplateArgumentList *TemplateArgs; 606 ConstraintSatisfaction Satisfaction; 607 }; 608 } 609 610 /// Convert from Sema's representation of template deduction information 611 /// to the form used in overload-candidate information. 612 DeductionFailureInfo 613 clang::MakeDeductionFailureInfo(ASTContext &Context, 614 Sema::TemplateDeductionResult TDK, 615 TemplateDeductionInfo &Info) { 616 DeductionFailureInfo Result; 617 Result.Result = static_cast<unsigned>(TDK); 618 Result.HasDiagnostic = false; 619 switch (TDK) { 620 case Sema::TDK_Invalid: 621 case Sema::TDK_InstantiationDepth: 622 case Sema::TDK_TooManyArguments: 623 case Sema::TDK_TooFewArguments: 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 case Sema::TDK_CUDATargetMismatch: 626 Result.Data = nullptr; 627 break; 628 629 case Sema::TDK_Incomplete: 630 case Sema::TDK_InvalidExplicitArguments: 631 Result.Data = Info.Param.getOpaqueValue(); 632 break; 633 634 case Sema::TDK_DeducedMismatch: 635 case Sema::TDK_DeducedMismatchNested: { 636 // FIXME: Should allocate from normal heap so that we can free this later. 637 auto *Saved = new (Context) DFIDeducedMismatchArgs; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Saved->TemplateArgs = Info.take(); 641 Saved->CallArgIndex = Info.CallArgIndex; 642 Result.Data = Saved; 643 break; 644 } 645 646 case Sema::TDK_NonDeducedMismatch: { 647 // FIXME: Should allocate from normal heap so that we can free this later. 648 DFIArguments *Saved = new (Context) DFIArguments; 649 Saved->FirstArg = Info.FirstArg; 650 Saved->SecondArg = Info.SecondArg; 651 Result.Data = Saved; 652 break; 653 } 654 655 case Sema::TDK_IncompletePack: 656 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 657 case Sema::TDK_Inconsistent: 658 case Sema::TDK_Underqualified: { 659 // FIXME: Should allocate from normal heap so that we can free this later. 660 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 661 Saved->Param = Info.Param; 662 Saved->FirstArg = Info.FirstArg; 663 Saved->SecondArg = Info.SecondArg; 664 Result.Data = Saved; 665 break; 666 } 667 668 case Sema::TDK_SubstitutionFailure: 669 Result.Data = Info.take(); 670 if (Info.hasSFINAEDiagnostic()) { 671 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 672 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 673 Info.takeSFINAEDiagnostic(*Diag); 674 Result.HasDiagnostic = true; 675 } 676 break; 677 678 case Sema::TDK_ConstraintsNotSatisfied: { 679 CNSInfo *Saved = new (Context) CNSInfo; 680 Saved->TemplateArgs = Info.take(); 681 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 682 Result.Data = Saved; 683 break; 684 } 685 686 case Sema::TDK_Success: 687 case Sema::TDK_NonDependentConversionFailure: 688 llvm_unreachable("not a deduction failure"); 689 } 690 691 return Result; 692 } 693 694 void DeductionFailureInfo::Destroy() { 695 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 696 case Sema::TDK_Success: 697 case Sema::TDK_Invalid: 698 case Sema::TDK_InstantiationDepth: 699 case Sema::TDK_Incomplete: 700 case Sema::TDK_TooManyArguments: 701 case Sema::TDK_TooFewArguments: 702 case Sema::TDK_InvalidExplicitArguments: 703 case Sema::TDK_CUDATargetMismatch: 704 case Sema::TDK_NonDependentConversionFailure: 705 break; 706 707 case Sema::TDK_IncompletePack: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_DeducedMismatch: 711 case Sema::TDK_DeducedMismatchNested: 712 case Sema::TDK_NonDeducedMismatch: 713 // FIXME: Destroy the data? 714 Data = nullptr; 715 break; 716 717 case Sema::TDK_SubstitutionFailure: 718 // FIXME: Destroy the template argument list? 719 Data = nullptr; 720 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 721 Diag->~PartialDiagnosticAt(); 722 HasDiagnostic = false; 723 } 724 break; 725 726 case Sema::TDK_ConstraintsNotSatisfied: 727 // FIXME: Destroy the template argument list? 728 Data = nullptr; 729 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 730 Diag->~PartialDiagnosticAt(); 731 HasDiagnostic = false; 732 } 733 break; 734 735 // Unhandled 736 case Sema::TDK_MiscellaneousDeductionFailure: 737 break; 738 } 739 } 740 741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 742 if (HasDiagnostic) 743 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 744 return nullptr; 745 } 746 747 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 749 case Sema::TDK_Success: 750 case Sema::TDK_Invalid: 751 case Sema::TDK_InstantiationDepth: 752 case Sema::TDK_TooManyArguments: 753 case Sema::TDK_TooFewArguments: 754 case Sema::TDK_SubstitutionFailure: 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 case Sema::TDK_NonDeducedMismatch: 758 case Sema::TDK_CUDATargetMismatch: 759 case Sema::TDK_NonDependentConversionFailure: 760 case Sema::TDK_ConstraintsNotSatisfied: 761 return TemplateParameter(); 762 763 case Sema::TDK_Incomplete: 764 case Sema::TDK_InvalidExplicitArguments: 765 return TemplateParameter::getFromOpaqueValue(Data); 766 767 case Sema::TDK_IncompletePack: 768 case Sema::TDK_Inconsistent: 769 case Sema::TDK_Underqualified: 770 return static_cast<DFIParamWithArguments*>(Data)->Param; 771 772 // Unhandled 773 case Sema::TDK_MiscellaneousDeductionFailure: 774 break; 775 } 776 777 return TemplateParameter(); 778 } 779 780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 781 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 782 case Sema::TDK_Success: 783 case Sema::TDK_Invalid: 784 case Sema::TDK_InstantiationDepth: 785 case Sema::TDK_TooManyArguments: 786 case Sema::TDK_TooFewArguments: 787 case Sema::TDK_Incomplete: 788 case Sema::TDK_IncompletePack: 789 case Sema::TDK_InvalidExplicitArguments: 790 case Sema::TDK_Inconsistent: 791 case Sema::TDK_Underqualified: 792 case Sema::TDK_NonDeducedMismatch: 793 case Sema::TDK_CUDATargetMismatch: 794 case Sema::TDK_NonDependentConversionFailure: 795 return nullptr; 796 797 case Sema::TDK_DeducedMismatch: 798 case Sema::TDK_DeducedMismatchNested: 799 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 800 801 case Sema::TDK_SubstitutionFailure: 802 return static_cast<TemplateArgumentList*>(Data); 803 804 case Sema::TDK_ConstraintsNotSatisfied: 805 return static_cast<CNSInfo*>(Data)->TemplateArgs; 806 807 // Unhandled 808 case Sema::TDK_MiscellaneousDeductionFailure: 809 break; 810 } 811 812 return nullptr; 813 } 814 815 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 816 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 817 case Sema::TDK_Success: 818 case Sema::TDK_Invalid: 819 case Sema::TDK_InstantiationDepth: 820 case Sema::TDK_Incomplete: 821 case Sema::TDK_TooManyArguments: 822 case Sema::TDK_TooFewArguments: 823 case Sema::TDK_InvalidExplicitArguments: 824 case Sema::TDK_SubstitutionFailure: 825 case Sema::TDK_CUDATargetMismatch: 826 case Sema::TDK_NonDependentConversionFailure: 827 case Sema::TDK_ConstraintsNotSatisfied: 828 return nullptr; 829 830 case Sema::TDK_IncompletePack: 831 case Sema::TDK_Inconsistent: 832 case Sema::TDK_Underqualified: 833 case Sema::TDK_DeducedMismatch: 834 case Sema::TDK_DeducedMismatchNested: 835 case Sema::TDK_NonDeducedMismatch: 836 return &static_cast<DFIArguments*>(Data)->FirstArg; 837 838 // Unhandled 839 case Sema::TDK_MiscellaneousDeductionFailure: 840 break; 841 } 842 843 return nullptr; 844 } 845 846 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 847 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 848 case Sema::TDK_Success: 849 case Sema::TDK_Invalid: 850 case Sema::TDK_InstantiationDepth: 851 case Sema::TDK_Incomplete: 852 case Sema::TDK_IncompletePack: 853 case Sema::TDK_TooManyArguments: 854 case Sema::TDK_TooFewArguments: 855 case Sema::TDK_InvalidExplicitArguments: 856 case Sema::TDK_SubstitutionFailure: 857 case Sema::TDK_CUDATargetMismatch: 858 case Sema::TDK_NonDependentConversionFailure: 859 case Sema::TDK_ConstraintsNotSatisfied: 860 return nullptr; 861 862 case Sema::TDK_Inconsistent: 863 case Sema::TDK_Underqualified: 864 case Sema::TDK_DeducedMismatch: 865 case Sema::TDK_DeducedMismatchNested: 866 case Sema::TDK_NonDeducedMismatch: 867 return &static_cast<DFIArguments*>(Data)->SecondArg; 868 869 // Unhandled 870 case Sema::TDK_MiscellaneousDeductionFailure: 871 break; 872 } 873 874 return nullptr; 875 } 876 877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 878 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 879 case Sema::TDK_DeducedMismatch: 880 case Sema::TDK_DeducedMismatchNested: 881 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 882 883 default: 884 return llvm::None; 885 } 886 } 887 888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 889 OverloadedOperatorKind Op) { 890 if (!AllowRewrittenCandidates) 891 return false; 892 return Op == OO_EqualEqual || Op == OO_Spaceship; 893 } 894 895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 896 ASTContext &Ctx, const FunctionDecl *FD) { 897 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 898 return false; 899 // Don't bother adding a reversed candidate that can never be a better 900 // match than the non-reversed version. 901 return FD->getNumParams() != 2 || 902 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 903 FD->getParamDecl(1)->getType()) || 904 FD->hasAttr<EnableIfAttr>(); 905 } 906 907 void OverloadCandidateSet::destroyCandidates() { 908 for (iterator i = begin(), e = end(); i != e; ++i) { 909 for (auto &C : i->Conversions) 910 C.~ImplicitConversionSequence(); 911 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 912 i->DeductionFailure.Destroy(); 913 } 914 } 915 916 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 917 destroyCandidates(); 918 SlabAllocator.Reset(); 919 NumInlineBytesUsed = 0; 920 Candidates.clear(); 921 Functions.clear(); 922 Kind = CSK; 923 } 924 925 namespace { 926 class UnbridgedCastsSet { 927 struct Entry { 928 Expr **Addr; 929 Expr *Saved; 930 }; 931 SmallVector<Entry, 2> Entries; 932 933 public: 934 void save(Sema &S, Expr *&E) { 935 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 936 Entry entry = { &E, E }; 937 Entries.push_back(entry); 938 E = S.stripARCUnbridgedCast(E); 939 } 940 941 void restore() { 942 for (SmallVectorImpl<Entry>::iterator 943 i = Entries.begin(), e = Entries.end(); i != e; ++i) 944 *i->Addr = i->Saved; 945 } 946 }; 947 } 948 949 /// checkPlaceholderForOverload - Do any interesting placeholder-like 950 /// preprocessing on the given expression. 951 /// 952 /// \param unbridgedCasts a collection to which to add unbridged casts; 953 /// without this, they will be immediately diagnosed as errors 954 /// 955 /// Return true on unrecoverable error. 956 static bool 957 checkPlaceholderForOverload(Sema &S, Expr *&E, 958 UnbridgedCastsSet *unbridgedCasts = nullptr) { 959 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 960 // We can't handle overloaded expressions here because overload 961 // resolution might reasonably tweak them. 962 if (placeholder->getKind() == BuiltinType::Overload) return false; 963 964 // If the context potentially accepts unbridged ARC casts, strip 965 // the unbridged cast and add it to the collection for later restoration. 966 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 967 unbridgedCasts) { 968 unbridgedCasts->save(S, E); 969 return false; 970 } 971 972 // Go ahead and check everything else. 973 ExprResult result = S.CheckPlaceholderExpr(E); 974 if (result.isInvalid()) 975 return true; 976 977 E = result.get(); 978 return false; 979 } 980 981 // Nothing to do. 982 return false; 983 } 984 985 /// checkArgPlaceholdersForOverload - Check a set of call operands for 986 /// placeholders. 987 static bool checkArgPlaceholdersForOverload(Sema &S, 988 MultiExprArg Args, 989 UnbridgedCastsSet &unbridged) { 990 for (unsigned i = 0, e = Args.size(); i != e; ++i) 991 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 992 return true; 993 994 return false; 995 } 996 997 /// Determine whether the given New declaration is an overload of the 998 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 999 /// New and Old cannot be overloaded, e.g., if New has the same signature as 1000 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 1001 /// functions (or function templates) at all. When it does return Ovl_Match or 1002 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1003 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1004 /// declaration. 1005 /// 1006 /// Example: Given the following input: 1007 /// 1008 /// void f(int, float); // #1 1009 /// void f(int, int); // #2 1010 /// int f(int, int); // #3 1011 /// 1012 /// When we process #1, there is no previous declaration of "f", so IsOverload 1013 /// will not be used. 1014 /// 1015 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1016 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1017 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1018 /// unchanged. 1019 /// 1020 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1021 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1022 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1023 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1024 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1025 /// 1026 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1027 /// by a using declaration. The rules for whether to hide shadow declarations 1028 /// ignore some properties which otherwise figure into a function template's 1029 /// signature. 1030 Sema::OverloadKind 1031 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1032 NamedDecl *&Match, bool NewIsUsingDecl) { 1033 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1034 I != E; ++I) { 1035 NamedDecl *OldD = *I; 1036 1037 bool OldIsUsingDecl = false; 1038 if (isa<UsingShadowDecl>(OldD)) { 1039 OldIsUsingDecl = true; 1040 1041 // We can always introduce two using declarations into the same 1042 // context, even if they have identical signatures. 1043 if (NewIsUsingDecl) continue; 1044 1045 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1046 } 1047 1048 // A using-declaration does not conflict with another declaration 1049 // if one of them is hidden. 1050 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1051 continue; 1052 1053 // If either declaration was introduced by a using declaration, 1054 // we'll need to use slightly different rules for matching. 1055 // Essentially, these rules are the normal rules, except that 1056 // function templates hide function templates with different 1057 // return types or template parameter lists. 1058 bool UseMemberUsingDeclRules = 1059 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1060 !New->getFriendObjectKind(); 1061 1062 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1063 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1064 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1065 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1066 continue; 1067 } 1068 1069 if (!isa<FunctionTemplateDecl>(OldD) && 1070 !shouldLinkPossiblyHiddenDecl(*I, New)) 1071 continue; 1072 1073 Match = *I; 1074 return Ovl_Match; 1075 } 1076 1077 // Builtins that have custom typechecking or have a reference should 1078 // not be overloadable or redeclarable. 1079 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1080 Match = *I; 1081 return Ovl_NonFunction; 1082 } 1083 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1084 // We can overload with these, which can show up when doing 1085 // redeclaration checks for UsingDecls. 1086 assert(Old.getLookupKind() == LookupUsingDeclName); 1087 } else if (isa<TagDecl>(OldD)) { 1088 // We can always overload with tags by hiding them. 1089 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1090 // Optimistically assume that an unresolved using decl will 1091 // overload; if it doesn't, we'll have to diagnose during 1092 // template instantiation. 1093 // 1094 // Exception: if the scope is dependent and this is not a class 1095 // member, the using declaration can only introduce an enumerator. 1096 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1097 Match = *I; 1098 return Ovl_NonFunction; 1099 } 1100 } else { 1101 // (C++ 13p1): 1102 // Only function declarations can be overloaded; object and type 1103 // declarations cannot be overloaded. 1104 Match = *I; 1105 return Ovl_NonFunction; 1106 } 1107 } 1108 1109 // C++ [temp.friend]p1: 1110 // For a friend function declaration that is not a template declaration: 1111 // -- if the name of the friend is a qualified or unqualified template-id, 1112 // [...], otherwise 1113 // -- if the name of the friend is a qualified-id and a matching 1114 // non-template function is found in the specified class or namespace, 1115 // the friend declaration refers to that function, otherwise, 1116 // -- if the name of the friend is a qualified-id and a matching function 1117 // template is found in the specified class or namespace, the friend 1118 // declaration refers to the deduced specialization of that function 1119 // template, otherwise 1120 // -- the name shall be an unqualified-id [...] 1121 // If we get here for a qualified friend declaration, we've just reached the 1122 // third bullet. If the type of the friend is dependent, skip this lookup 1123 // until instantiation. 1124 if (New->getFriendObjectKind() && New->getQualifier() && 1125 !New->getDescribedFunctionTemplate() && 1126 !New->getDependentSpecializationInfo() && 1127 !New->getType()->isDependentType()) { 1128 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1129 TemplateSpecResult.addAllDecls(Old); 1130 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1131 /*QualifiedFriend*/true)) { 1132 New->setInvalidDecl(); 1133 return Ovl_Overload; 1134 } 1135 1136 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1137 return Ovl_Match; 1138 } 1139 1140 return Ovl_Overload; 1141 } 1142 1143 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1144 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1145 bool ConsiderRequiresClauses) { 1146 // C++ [basic.start.main]p2: This function shall not be overloaded. 1147 if (New->isMain()) 1148 return false; 1149 1150 // MSVCRT user defined entry points cannot be overloaded. 1151 if (New->isMSVCRTEntryPoint()) 1152 return false; 1153 1154 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1155 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1156 1157 // C++ [temp.fct]p2: 1158 // A function template can be overloaded with other function templates 1159 // and with normal (non-template) functions. 1160 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1161 return true; 1162 1163 // Is the function New an overload of the function Old? 1164 QualType OldQType = Context.getCanonicalType(Old->getType()); 1165 QualType NewQType = Context.getCanonicalType(New->getType()); 1166 1167 // Compare the signatures (C++ 1.3.10) of the two functions to 1168 // determine whether they are overloads. If we find any mismatch 1169 // in the signature, they are overloads. 1170 1171 // If either of these functions is a K&R-style function (no 1172 // prototype), then we consider them to have matching signatures. 1173 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1174 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1175 return false; 1176 1177 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1178 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1179 1180 // The signature of a function includes the types of its 1181 // parameters (C++ 1.3.10), which includes the presence or absence 1182 // of the ellipsis; see C++ DR 357). 1183 if (OldQType != NewQType && 1184 (OldType->getNumParams() != NewType->getNumParams() || 1185 OldType->isVariadic() != NewType->isVariadic() || 1186 !FunctionParamTypesAreEqual(OldType, NewType))) 1187 return true; 1188 1189 // C++ [temp.over.link]p4: 1190 // The signature of a function template consists of its function 1191 // signature, its return type and its template parameter list. The names 1192 // of the template parameters are significant only for establishing the 1193 // relationship between the template parameters and the rest of the 1194 // signature. 1195 // 1196 // We check the return type and template parameter lists for function 1197 // templates first; the remaining checks follow. 1198 // 1199 // However, we don't consider either of these when deciding whether 1200 // a member introduced by a shadow declaration is hidden. 1201 if (!UseMemberUsingDeclRules && NewTemplate && 1202 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1203 OldTemplate->getTemplateParameters(), 1204 false, TPL_TemplateMatch) || 1205 !Context.hasSameType(Old->getDeclaredReturnType(), 1206 New->getDeclaredReturnType()))) 1207 return true; 1208 1209 // If the function is a class member, its signature includes the 1210 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1211 // 1212 // As part of this, also check whether one of the member functions 1213 // is static, in which case they are not overloads (C++ 1214 // 13.1p2). While not part of the definition of the signature, 1215 // this check is important to determine whether these functions 1216 // can be overloaded. 1217 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1218 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1219 if (OldMethod && NewMethod && 1220 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1221 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1222 if (!UseMemberUsingDeclRules && 1223 (OldMethod->getRefQualifier() == RQ_None || 1224 NewMethod->getRefQualifier() == RQ_None)) { 1225 // C++0x [over.load]p2: 1226 // - Member function declarations with the same name and the same 1227 // parameter-type-list as well as member function template 1228 // declarations with the same name, the same parameter-type-list, and 1229 // the same template parameter lists cannot be overloaded if any of 1230 // them, but not all, have a ref-qualifier (8.3.5). 1231 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1232 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1233 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1234 } 1235 return true; 1236 } 1237 1238 // We may not have applied the implicit const for a constexpr member 1239 // function yet (because we haven't yet resolved whether this is a static 1240 // or non-static member function). Add it now, on the assumption that this 1241 // is a redeclaration of OldMethod. 1242 auto OldQuals = OldMethod->getMethodQualifiers(); 1243 auto NewQuals = NewMethod->getMethodQualifiers(); 1244 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1245 !isa<CXXConstructorDecl>(NewMethod)) 1246 NewQuals.addConst(); 1247 // We do not allow overloading based off of '__restrict'. 1248 OldQuals.removeRestrict(); 1249 NewQuals.removeRestrict(); 1250 if (OldQuals != NewQuals) 1251 return true; 1252 } 1253 1254 // Though pass_object_size is placed on parameters and takes an argument, we 1255 // consider it to be a function-level modifier for the sake of function 1256 // identity. Either the function has one or more parameters with 1257 // pass_object_size or it doesn't. 1258 if (functionHasPassObjectSizeParams(New) != 1259 functionHasPassObjectSizeParams(Old)) 1260 return true; 1261 1262 // enable_if attributes are an order-sensitive part of the signature. 1263 for (specific_attr_iterator<EnableIfAttr> 1264 NewI = New->specific_attr_begin<EnableIfAttr>(), 1265 NewE = New->specific_attr_end<EnableIfAttr>(), 1266 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1267 OldE = Old->specific_attr_end<EnableIfAttr>(); 1268 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1269 if (NewI == NewE || OldI == OldE) 1270 return true; 1271 llvm::FoldingSetNodeID NewID, OldID; 1272 NewI->getCond()->Profile(NewID, Context, true); 1273 OldI->getCond()->Profile(OldID, Context, true); 1274 if (NewID != OldID) 1275 return true; 1276 } 1277 1278 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1279 // Don't allow overloading of destructors. (In theory we could, but it 1280 // would be a giant change to clang.) 1281 if (!isa<CXXDestructorDecl>(New)) { 1282 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1283 OldTarget = IdentifyCUDATarget(Old); 1284 if (NewTarget != CFT_InvalidTarget) { 1285 assert((OldTarget != CFT_InvalidTarget) && 1286 "Unexpected invalid target."); 1287 1288 // Allow overloading of functions with same signature and different CUDA 1289 // target attributes. 1290 if (NewTarget != OldTarget) 1291 return true; 1292 } 1293 } 1294 } 1295 1296 if (ConsiderRequiresClauses) { 1297 Expr *NewRC = New->getTrailingRequiresClause(), 1298 *OldRC = Old->getTrailingRequiresClause(); 1299 if ((NewRC != nullptr) != (OldRC != nullptr)) 1300 // RC are most certainly different - these are overloads. 1301 return true; 1302 1303 if (NewRC) { 1304 llvm::FoldingSetNodeID NewID, OldID; 1305 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1306 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1307 if (NewID != OldID) 1308 // RCs are not equivalent - these are overloads. 1309 return true; 1310 } 1311 } 1312 1313 // The signatures match; this is not an overload. 1314 return false; 1315 } 1316 1317 /// Tries a user-defined conversion from From to ToType. 1318 /// 1319 /// Produces an implicit conversion sequence for when a standard conversion 1320 /// is not an option. See TryImplicitConversion for more information. 1321 static ImplicitConversionSequence 1322 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1323 bool SuppressUserConversions, 1324 AllowedExplicit AllowExplicit, 1325 bool InOverloadResolution, 1326 bool CStyle, 1327 bool AllowObjCWritebackConversion, 1328 bool AllowObjCConversionOnExplicit) { 1329 ImplicitConversionSequence ICS; 1330 1331 if (SuppressUserConversions) { 1332 // We're not in the case above, so there is no conversion that 1333 // we can perform. 1334 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1335 return ICS; 1336 } 1337 1338 // Attempt user-defined conversion. 1339 OverloadCandidateSet Conversions(From->getExprLoc(), 1340 OverloadCandidateSet::CSK_Normal); 1341 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1342 Conversions, AllowExplicit, 1343 AllowObjCConversionOnExplicit)) { 1344 case OR_Success: 1345 case OR_Deleted: 1346 ICS.setUserDefined(); 1347 // C++ [over.ics.user]p4: 1348 // A conversion of an expression of class type to the same class 1349 // type is given Exact Match rank, and a conversion of an 1350 // expression of class type to a base class of that type is 1351 // given Conversion rank, in spite of the fact that a copy 1352 // constructor (i.e., a user-defined conversion function) is 1353 // called for those cases. 1354 if (CXXConstructorDecl *Constructor 1355 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1356 QualType FromCanon 1357 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1358 QualType ToCanon 1359 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1360 if (Constructor->isCopyConstructor() && 1361 (FromCanon == ToCanon || 1362 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1363 // Turn this into a "standard" conversion sequence, so that it 1364 // gets ranked with standard conversion sequences. 1365 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1366 ICS.setStandard(); 1367 ICS.Standard.setAsIdentityConversion(); 1368 ICS.Standard.setFromType(From->getType()); 1369 ICS.Standard.setAllToTypes(ToType); 1370 ICS.Standard.CopyConstructor = Constructor; 1371 ICS.Standard.FoundCopyConstructor = Found; 1372 if (ToCanon != FromCanon) 1373 ICS.Standard.Second = ICK_Derived_To_Base; 1374 } 1375 } 1376 break; 1377 1378 case OR_Ambiguous: 1379 ICS.setAmbiguous(); 1380 ICS.Ambiguous.setFromType(From->getType()); 1381 ICS.Ambiguous.setToType(ToType); 1382 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1383 Cand != Conversions.end(); ++Cand) 1384 if (Cand->Best) 1385 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1386 break; 1387 1388 // Fall through. 1389 case OR_No_Viable_Function: 1390 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1391 break; 1392 } 1393 1394 return ICS; 1395 } 1396 1397 /// TryImplicitConversion - Attempt to perform an implicit conversion 1398 /// from the given expression (Expr) to the given type (ToType). This 1399 /// function returns an implicit conversion sequence that can be used 1400 /// to perform the initialization. Given 1401 /// 1402 /// void f(float f); 1403 /// void g(int i) { f(i); } 1404 /// 1405 /// this routine would produce an implicit conversion sequence to 1406 /// describe the initialization of f from i, which will be a standard 1407 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1408 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1409 // 1410 /// Note that this routine only determines how the conversion can be 1411 /// performed; it does not actually perform the conversion. As such, 1412 /// it will not produce any diagnostics if no conversion is available, 1413 /// but will instead return an implicit conversion sequence of kind 1414 /// "BadConversion". 1415 /// 1416 /// If @p SuppressUserConversions, then user-defined conversions are 1417 /// not permitted. 1418 /// If @p AllowExplicit, then explicit user-defined conversions are 1419 /// permitted. 1420 /// 1421 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1422 /// writeback conversion, which allows __autoreleasing id* parameters to 1423 /// be initialized with __strong id* or __weak id* arguments. 1424 static ImplicitConversionSequence 1425 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1426 bool SuppressUserConversions, 1427 AllowedExplicit AllowExplicit, 1428 bool InOverloadResolution, 1429 bool CStyle, 1430 bool AllowObjCWritebackConversion, 1431 bool AllowObjCConversionOnExplicit) { 1432 ImplicitConversionSequence ICS; 1433 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1434 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1435 ICS.setStandard(); 1436 return ICS; 1437 } 1438 1439 if (!S.getLangOpts().CPlusPlus) { 1440 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1441 return ICS; 1442 } 1443 1444 // C++ [over.ics.user]p4: 1445 // A conversion of an expression of class type to the same class 1446 // type is given Exact Match rank, and a conversion of an 1447 // expression of class type to a base class of that type is 1448 // given Conversion rank, in spite of the fact that a copy/move 1449 // constructor (i.e., a user-defined conversion function) is 1450 // called for those cases. 1451 QualType FromType = From->getType(); 1452 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1453 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1454 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1455 ICS.setStandard(); 1456 ICS.Standard.setAsIdentityConversion(); 1457 ICS.Standard.setFromType(FromType); 1458 ICS.Standard.setAllToTypes(ToType); 1459 1460 // We don't actually check at this point whether there is a valid 1461 // copy/move constructor, since overloading just assumes that it 1462 // exists. When we actually perform initialization, we'll find the 1463 // appropriate constructor to copy the returned object, if needed. 1464 ICS.Standard.CopyConstructor = nullptr; 1465 1466 // Determine whether this is considered a derived-to-base conversion. 1467 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1468 ICS.Standard.Second = ICK_Derived_To_Base; 1469 1470 return ICS; 1471 } 1472 1473 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1474 AllowExplicit, InOverloadResolution, CStyle, 1475 AllowObjCWritebackConversion, 1476 AllowObjCConversionOnExplicit); 1477 } 1478 1479 ImplicitConversionSequence 1480 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1481 bool SuppressUserConversions, 1482 AllowedExplicit AllowExplicit, 1483 bool InOverloadResolution, 1484 bool CStyle, 1485 bool AllowObjCWritebackConversion) { 1486 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1487 AllowExplicit, InOverloadResolution, CStyle, 1488 AllowObjCWritebackConversion, 1489 /*AllowObjCConversionOnExplicit=*/false); 1490 } 1491 1492 /// PerformImplicitConversion - Perform an implicit conversion of the 1493 /// expression From to the type ToType. Returns the 1494 /// converted expression. Flavor is the kind of conversion we're 1495 /// performing, used in the error message. If @p AllowExplicit, 1496 /// explicit user-defined conversions are permitted. 1497 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1498 AssignmentAction Action, 1499 bool AllowExplicit) { 1500 if (checkPlaceholderForOverload(*this, From)) 1501 return ExprError(); 1502 1503 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1504 bool AllowObjCWritebackConversion 1505 = getLangOpts().ObjCAutoRefCount && 1506 (Action == AA_Passing || Action == AA_Sending); 1507 if (getLangOpts().ObjC) 1508 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1509 From->getType(), From); 1510 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1511 *this, From, ToType, 1512 /*SuppressUserConversions=*/false, 1513 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1514 /*InOverloadResolution=*/false, 1515 /*CStyle=*/false, AllowObjCWritebackConversion, 1516 /*AllowObjCConversionOnExplicit=*/false); 1517 return PerformImplicitConversion(From, ToType, ICS, Action); 1518 } 1519 1520 /// Determine whether the conversion from FromType to ToType is a valid 1521 /// conversion that strips "noexcept" or "noreturn" off the nested function 1522 /// type. 1523 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1524 QualType &ResultTy) { 1525 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1526 return false; 1527 1528 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1529 // or F(t noexcept) -> F(t) 1530 // where F adds one of the following at most once: 1531 // - a pointer 1532 // - a member pointer 1533 // - a block pointer 1534 // Changes here need matching changes in FindCompositePointerType. 1535 CanQualType CanTo = Context.getCanonicalType(ToType); 1536 CanQualType CanFrom = Context.getCanonicalType(FromType); 1537 Type::TypeClass TyClass = CanTo->getTypeClass(); 1538 if (TyClass != CanFrom->getTypeClass()) return false; 1539 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1540 if (TyClass == Type::Pointer) { 1541 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1542 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1543 } else if (TyClass == Type::BlockPointer) { 1544 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1545 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1546 } else if (TyClass == Type::MemberPointer) { 1547 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1548 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1549 // A function pointer conversion cannot change the class of the function. 1550 if (ToMPT->getClass() != FromMPT->getClass()) 1551 return false; 1552 CanTo = ToMPT->getPointeeType(); 1553 CanFrom = FromMPT->getPointeeType(); 1554 } else { 1555 return false; 1556 } 1557 1558 TyClass = CanTo->getTypeClass(); 1559 if (TyClass != CanFrom->getTypeClass()) return false; 1560 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1561 return false; 1562 } 1563 1564 const auto *FromFn = cast<FunctionType>(CanFrom); 1565 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1566 1567 const auto *ToFn = cast<FunctionType>(CanTo); 1568 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1569 1570 bool Changed = false; 1571 1572 // Drop 'noreturn' if not present in target type. 1573 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1574 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1575 Changed = true; 1576 } 1577 1578 // Drop 'noexcept' if not present in target type. 1579 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1580 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1581 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1582 FromFn = cast<FunctionType>( 1583 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1584 EST_None) 1585 .getTypePtr()); 1586 Changed = true; 1587 } 1588 1589 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1590 // only if the ExtParameterInfo lists of the two function prototypes can be 1591 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1592 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1593 bool CanUseToFPT, CanUseFromFPT; 1594 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1595 CanUseFromFPT, NewParamInfos) && 1596 CanUseToFPT && !CanUseFromFPT) { 1597 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1598 ExtInfo.ExtParameterInfos = 1599 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1600 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1601 FromFPT->getParamTypes(), ExtInfo); 1602 FromFn = QT->getAs<FunctionType>(); 1603 Changed = true; 1604 } 1605 } 1606 1607 if (!Changed) 1608 return false; 1609 1610 assert(QualType(FromFn, 0).isCanonical()); 1611 if (QualType(FromFn, 0) != CanTo) return false; 1612 1613 ResultTy = ToType; 1614 return true; 1615 } 1616 1617 /// Determine whether the conversion from FromType to ToType is a valid 1618 /// vector conversion. 1619 /// 1620 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1621 /// conversion. 1622 static bool IsVectorConversion(Sema &S, QualType FromType, 1623 QualType ToType, ImplicitConversionKind &ICK) { 1624 // We need at least one of these types to be a vector type to have a vector 1625 // conversion. 1626 if (!ToType->isVectorType() && !FromType->isVectorType()) 1627 return false; 1628 1629 // Identical types require no conversions. 1630 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1631 return false; 1632 1633 // There are no conversions between extended vector types, only identity. 1634 if (ToType->isExtVectorType()) { 1635 // There are no conversions between extended vector types other than the 1636 // identity conversion. 1637 if (FromType->isExtVectorType()) 1638 return false; 1639 1640 // Vector splat from any arithmetic type to a vector. 1641 if (FromType->isArithmeticType()) { 1642 ICK = ICK_Vector_Splat; 1643 return true; 1644 } 1645 } 1646 1647 if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) 1648 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1649 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1650 ICK = ICK_SVE_Vector_Conversion; 1651 return true; 1652 } 1653 1654 // We can perform the conversion between vector types in the following cases: 1655 // 1)vector types are equivalent AltiVec and GCC vector types 1656 // 2)lax vector conversions are permitted and the vector types are of the 1657 // same size 1658 // 3)the destination type does not have the ARM MVE strict-polymorphism 1659 // attribute, which inhibits lax vector conversion for overload resolution 1660 // only 1661 if (ToType->isVectorType() && FromType->isVectorType()) { 1662 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1663 (S.isLaxVectorConversion(FromType, ToType) && 1664 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1665 ICK = ICK_Vector_Conversion; 1666 return true; 1667 } 1668 } 1669 1670 return false; 1671 } 1672 1673 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1674 bool InOverloadResolution, 1675 StandardConversionSequence &SCS, 1676 bool CStyle); 1677 1678 /// IsStandardConversion - Determines whether there is a standard 1679 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1680 /// expression From to the type ToType. Standard conversion sequences 1681 /// only consider non-class types; for conversions that involve class 1682 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1683 /// contain the standard conversion sequence required to perform this 1684 /// conversion and this routine will return true. Otherwise, this 1685 /// routine will return false and the value of SCS is unspecified. 1686 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1687 bool InOverloadResolution, 1688 StandardConversionSequence &SCS, 1689 bool CStyle, 1690 bool AllowObjCWritebackConversion) { 1691 QualType FromType = From->getType(); 1692 1693 // Standard conversions (C++ [conv]) 1694 SCS.setAsIdentityConversion(); 1695 SCS.IncompatibleObjC = false; 1696 SCS.setFromType(FromType); 1697 SCS.CopyConstructor = nullptr; 1698 1699 // There are no standard conversions for class types in C++, so 1700 // abort early. When overloading in C, however, we do permit them. 1701 if (S.getLangOpts().CPlusPlus && 1702 (FromType->isRecordType() || ToType->isRecordType())) 1703 return false; 1704 1705 // The first conversion can be an lvalue-to-rvalue conversion, 1706 // array-to-pointer conversion, or function-to-pointer conversion 1707 // (C++ 4p1). 1708 1709 if (FromType == S.Context.OverloadTy) { 1710 DeclAccessPair AccessPair; 1711 if (FunctionDecl *Fn 1712 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1713 AccessPair)) { 1714 // We were able to resolve the address of the overloaded function, 1715 // so we can convert to the type of that function. 1716 FromType = Fn->getType(); 1717 SCS.setFromType(FromType); 1718 1719 // we can sometimes resolve &foo<int> regardless of ToType, so check 1720 // if the type matches (identity) or we are converting to bool 1721 if (!S.Context.hasSameUnqualifiedType( 1722 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1723 QualType resultTy; 1724 // if the function type matches except for [[noreturn]], it's ok 1725 if (!S.IsFunctionConversion(FromType, 1726 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1727 // otherwise, only a boolean conversion is standard 1728 if (!ToType->isBooleanType()) 1729 return false; 1730 } 1731 1732 // Check if the "from" expression is taking the address of an overloaded 1733 // function and recompute the FromType accordingly. Take advantage of the 1734 // fact that non-static member functions *must* have such an address-of 1735 // expression. 1736 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1737 if (Method && !Method->isStatic()) { 1738 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1739 "Non-unary operator on non-static member address"); 1740 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1741 == UO_AddrOf && 1742 "Non-address-of operator on non-static member address"); 1743 const Type *ClassType 1744 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1745 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1746 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1747 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1748 UO_AddrOf && 1749 "Non-address-of operator for overloaded function expression"); 1750 FromType = S.Context.getPointerType(FromType); 1751 } 1752 1753 // Check that we've computed the proper type after overload resolution. 1754 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1755 // be calling it from within an NDEBUG block. 1756 assert(S.Context.hasSameType( 1757 FromType, 1758 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1759 } else { 1760 return false; 1761 } 1762 } 1763 // Lvalue-to-rvalue conversion (C++11 4.1): 1764 // A glvalue (3.10) of a non-function, non-array type T can 1765 // be converted to a prvalue. 1766 bool argIsLValue = From->isGLValue(); 1767 if (argIsLValue && 1768 !FromType->isFunctionType() && !FromType->isArrayType() && 1769 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1770 SCS.First = ICK_Lvalue_To_Rvalue; 1771 1772 // C11 6.3.2.1p2: 1773 // ... if the lvalue has atomic type, the value has the non-atomic version 1774 // of the type of the lvalue ... 1775 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1776 FromType = Atomic->getValueType(); 1777 1778 // If T is a non-class type, the type of the rvalue is the 1779 // cv-unqualified version of T. Otherwise, the type of the rvalue 1780 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1781 // just strip the qualifiers because they don't matter. 1782 FromType = FromType.getUnqualifiedType(); 1783 } else if (FromType->isArrayType()) { 1784 // Array-to-pointer conversion (C++ 4.2) 1785 SCS.First = ICK_Array_To_Pointer; 1786 1787 // An lvalue or rvalue of type "array of N T" or "array of unknown 1788 // bound of T" can be converted to an rvalue of type "pointer to 1789 // T" (C++ 4.2p1). 1790 FromType = S.Context.getArrayDecayedType(FromType); 1791 1792 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1793 // This conversion is deprecated in C++03 (D.4) 1794 SCS.DeprecatedStringLiteralToCharPtr = true; 1795 1796 // For the purpose of ranking in overload resolution 1797 // (13.3.3.1.1), this conversion is considered an 1798 // array-to-pointer conversion followed by a qualification 1799 // conversion (4.4). (C++ 4.2p2) 1800 SCS.Second = ICK_Identity; 1801 SCS.Third = ICK_Qualification; 1802 SCS.QualificationIncludesObjCLifetime = false; 1803 SCS.setAllToTypes(FromType); 1804 return true; 1805 } 1806 } else if (FromType->isFunctionType() && argIsLValue) { 1807 // Function-to-pointer conversion (C++ 4.3). 1808 SCS.First = ICK_Function_To_Pointer; 1809 1810 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1811 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1812 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1813 return false; 1814 1815 // An lvalue of function type T can be converted to an rvalue of 1816 // type "pointer to T." The result is a pointer to the 1817 // function. (C++ 4.3p1). 1818 FromType = S.Context.getPointerType(FromType); 1819 } else { 1820 // We don't require any conversions for the first step. 1821 SCS.First = ICK_Identity; 1822 } 1823 SCS.setToType(0, FromType); 1824 1825 // The second conversion can be an integral promotion, floating 1826 // point promotion, integral conversion, floating point conversion, 1827 // floating-integral conversion, pointer conversion, 1828 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1829 // For overloading in C, this can also be a "compatible-type" 1830 // conversion. 1831 bool IncompatibleObjC = false; 1832 ImplicitConversionKind SecondICK = ICK_Identity; 1833 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1834 // The unqualified versions of the types are the same: there's no 1835 // conversion to do. 1836 SCS.Second = ICK_Identity; 1837 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1838 // Integral promotion (C++ 4.5). 1839 SCS.Second = ICK_Integral_Promotion; 1840 FromType = ToType.getUnqualifiedType(); 1841 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1842 // Floating point promotion (C++ 4.6). 1843 SCS.Second = ICK_Floating_Promotion; 1844 FromType = ToType.getUnqualifiedType(); 1845 } else if (S.IsComplexPromotion(FromType, ToType)) { 1846 // Complex promotion (Clang extension) 1847 SCS.Second = ICK_Complex_Promotion; 1848 FromType = ToType.getUnqualifiedType(); 1849 } else if (ToType->isBooleanType() && 1850 (FromType->isArithmeticType() || 1851 FromType->isAnyPointerType() || 1852 FromType->isBlockPointerType() || 1853 FromType->isMemberPointerType())) { 1854 // Boolean conversions (C++ 4.12). 1855 SCS.Second = ICK_Boolean_Conversion; 1856 FromType = S.Context.BoolTy; 1857 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1858 ToType->isIntegralType(S.Context)) { 1859 // Integral conversions (C++ 4.7). 1860 SCS.Second = ICK_Integral_Conversion; 1861 FromType = ToType.getUnqualifiedType(); 1862 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1863 // Complex conversions (C99 6.3.1.6) 1864 SCS.Second = ICK_Complex_Conversion; 1865 FromType = ToType.getUnqualifiedType(); 1866 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1867 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1868 // Complex-real conversions (C99 6.3.1.7) 1869 SCS.Second = ICK_Complex_Real; 1870 FromType = ToType.getUnqualifiedType(); 1871 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1872 // FIXME: disable conversions between long double, __ibm128 and __float128 1873 // if their representation is different until there is back end support 1874 // We of course allow this conversion if long double is really double. 1875 1876 // Conversions between bfloat and other floats are not permitted. 1877 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1878 return false; 1879 1880 // Conversions between IEEE-quad and IBM-extended semantics are not 1881 // permitted. 1882 const llvm::fltSemantics &FromSem = 1883 S.Context.getFloatTypeSemantics(FromType); 1884 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 1885 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 1886 &ToSem == &llvm::APFloat::IEEEquad()) || 1887 (&FromSem == &llvm::APFloat::IEEEquad() && 1888 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 1889 return false; 1890 1891 // Floating point conversions (C++ 4.8). 1892 SCS.Second = ICK_Floating_Conversion; 1893 FromType = ToType.getUnqualifiedType(); 1894 } else if ((FromType->isRealFloatingType() && 1895 ToType->isIntegralType(S.Context)) || 1896 (FromType->isIntegralOrUnscopedEnumerationType() && 1897 ToType->isRealFloatingType())) { 1898 // Conversions between bfloat and int are not permitted. 1899 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1900 return false; 1901 1902 // Floating-integral conversions (C++ 4.9). 1903 SCS.Second = ICK_Floating_Integral; 1904 FromType = ToType.getUnqualifiedType(); 1905 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1906 SCS.Second = ICK_Block_Pointer_Conversion; 1907 } else if (AllowObjCWritebackConversion && 1908 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1909 SCS.Second = ICK_Writeback_Conversion; 1910 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1911 FromType, IncompatibleObjC)) { 1912 // Pointer conversions (C++ 4.10). 1913 SCS.Second = ICK_Pointer_Conversion; 1914 SCS.IncompatibleObjC = IncompatibleObjC; 1915 FromType = FromType.getUnqualifiedType(); 1916 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1917 InOverloadResolution, FromType)) { 1918 // Pointer to member conversions (4.11). 1919 SCS.Second = ICK_Pointer_Member; 1920 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1921 SCS.Second = SecondICK; 1922 FromType = ToType.getUnqualifiedType(); 1923 } else if (!S.getLangOpts().CPlusPlus && 1924 S.Context.typesAreCompatible(ToType, FromType)) { 1925 // Compatible conversions (Clang extension for C function overloading) 1926 SCS.Second = ICK_Compatible_Conversion; 1927 FromType = ToType.getUnqualifiedType(); 1928 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1929 InOverloadResolution, 1930 SCS, CStyle)) { 1931 SCS.Second = ICK_TransparentUnionConversion; 1932 FromType = ToType; 1933 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1934 CStyle)) { 1935 // tryAtomicConversion has updated the standard conversion sequence 1936 // appropriately. 1937 return true; 1938 } else if (ToType->isEventT() && 1939 From->isIntegerConstantExpr(S.getASTContext()) && 1940 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1941 SCS.Second = ICK_Zero_Event_Conversion; 1942 FromType = ToType; 1943 } else if (ToType->isQueueT() && 1944 From->isIntegerConstantExpr(S.getASTContext()) && 1945 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1946 SCS.Second = ICK_Zero_Queue_Conversion; 1947 FromType = ToType; 1948 } else if (ToType->isSamplerT() && 1949 From->isIntegerConstantExpr(S.getASTContext())) { 1950 SCS.Second = ICK_Compatible_Conversion; 1951 FromType = ToType; 1952 } else { 1953 // No second conversion required. 1954 SCS.Second = ICK_Identity; 1955 } 1956 SCS.setToType(1, FromType); 1957 1958 // The third conversion can be a function pointer conversion or a 1959 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1960 bool ObjCLifetimeConversion; 1961 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1962 // Function pointer conversions (removing 'noexcept') including removal of 1963 // 'noreturn' (Clang extension). 1964 SCS.Third = ICK_Function_Conversion; 1965 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1966 ObjCLifetimeConversion)) { 1967 SCS.Third = ICK_Qualification; 1968 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1969 FromType = ToType; 1970 } else { 1971 // No conversion required 1972 SCS.Third = ICK_Identity; 1973 } 1974 1975 // C++ [over.best.ics]p6: 1976 // [...] Any difference in top-level cv-qualification is 1977 // subsumed by the initialization itself and does not constitute 1978 // a conversion. [...] 1979 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1980 QualType CanonTo = S.Context.getCanonicalType(ToType); 1981 if (CanonFrom.getLocalUnqualifiedType() 1982 == CanonTo.getLocalUnqualifiedType() && 1983 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1984 FromType = ToType; 1985 CanonFrom = CanonTo; 1986 } 1987 1988 SCS.setToType(2, FromType); 1989 1990 if (CanonFrom == CanonTo) 1991 return true; 1992 1993 // If we have not converted the argument type to the parameter type, 1994 // this is a bad conversion sequence, unless we're resolving an overload in C. 1995 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1996 return false; 1997 1998 ExprResult ER = ExprResult{From}; 1999 Sema::AssignConvertType Conv = 2000 S.CheckSingleAssignmentConstraints(ToType, ER, 2001 /*Diagnose=*/false, 2002 /*DiagnoseCFAudited=*/false, 2003 /*ConvertRHS=*/false); 2004 ImplicitConversionKind SecondConv; 2005 switch (Conv) { 2006 case Sema::Compatible: 2007 SecondConv = ICK_C_Only_Conversion; 2008 break; 2009 // For our purposes, discarding qualifiers is just as bad as using an 2010 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2011 // qualifiers, as well. 2012 case Sema::CompatiblePointerDiscardsQualifiers: 2013 case Sema::IncompatiblePointer: 2014 case Sema::IncompatiblePointerSign: 2015 SecondConv = ICK_Incompatible_Pointer_Conversion; 2016 break; 2017 default: 2018 return false; 2019 } 2020 2021 // First can only be an lvalue conversion, so we pretend that this was the 2022 // second conversion. First should already be valid from earlier in the 2023 // function. 2024 SCS.Second = SecondConv; 2025 SCS.setToType(1, ToType); 2026 2027 // Third is Identity, because Second should rank us worse than any other 2028 // conversion. This could also be ICK_Qualification, but it's simpler to just 2029 // lump everything in with the second conversion, and we don't gain anything 2030 // from making this ICK_Qualification. 2031 SCS.Third = ICK_Identity; 2032 SCS.setToType(2, ToType); 2033 return true; 2034 } 2035 2036 static bool 2037 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2038 QualType &ToType, 2039 bool InOverloadResolution, 2040 StandardConversionSequence &SCS, 2041 bool CStyle) { 2042 2043 const RecordType *UT = ToType->getAsUnionType(); 2044 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2045 return false; 2046 // The field to initialize within the transparent union. 2047 RecordDecl *UD = UT->getDecl(); 2048 // It's compatible if the expression matches any of the fields. 2049 for (const auto *it : UD->fields()) { 2050 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2051 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2052 ToType = it->getType(); 2053 return true; 2054 } 2055 } 2056 return false; 2057 } 2058 2059 /// IsIntegralPromotion - Determines whether the conversion from the 2060 /// expression From (whose potentially-adjusted type is FromType) to 2061 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2062 /// sets PromotedType to the promoted type. 2063 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2064 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2065 // All integers are built-in. 2066 if (!To) { 2067 return false; 2068 } 2069 2070 // An rvalue of type char, signed char, unsigned char, short int, or 2071 // unsigned short int can be converted to an rvalue of type int if 2072 // int can represent all the values of the source type; otherwise, 2073 // the source rvalue can be converted to an rvalue of type unsigned 2074 // int (C++ 4.5p1). 2075 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2076 !FromType->isEnumeralType()) { 2077 if (// We can promote any signed, promotable integer type to an int 2078 (FromType->isSignedIntegerType() || 2079 // We can promote any unsigned integer type whose size is 2080 // less than int to an int. 2081 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2082 return To->getKind() == BuiltinType::Int; 2083 } 2084 2085 return To->getKind() == BuiltinType::UInt; 2086 } 2087 2088 // C++11 [conv.prom]p3: 2089 // A prvalue of an unscoped enumeration type whose underlying type is not 2090 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2091 // following types that can represent all the values of the enumeration 2092 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2093 // unsigned int, long int, unsigned long int, long long int, or unsigned 2094 // long long int. If none of the types in that list can represent all the 2095 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2096 // type can be converted to an rvalue a prvalue of the extended integer type 2097 // with lowest integer conversion rank (4.13) greater than the rank of long 2098 // long in which all the values of the enumeration can be represented. If 2099 // there are two such extended types, the signed one is chosen. 2100 // C++11 [conv.prom]p4: 2101 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2102 // can be converted to a prvalue of its underlying type. Moreover, if 2103 // integral promotion can be applied to its underlying type, a prvalue of an 2104 // unscoped enumeration type whose underlying type is fixed can also be 2105 // converted to a prvalue of the promoted underlying type. 2106 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2107 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2108 // provided for a scoped enumeration. 2109 if (FromEnumType->getDecl()->isScoped()) 2110 return false; 2111 2112 // We can perform an integral promotion to the underlying type of the enum, 2113 // even if that's not the promoted type. Note that the check for promoting 2114 // the underlying type is based on the type alone, and does not consider 2115 // the bitfield-ness of the actual source expression. 2116 if (FromEnumType->getDecl()->isFixed()) { 2117 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2118 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2119 IsIntegralPromotion(nullptr, Underlying, ToType); 2120 } 2121 2122 // We have already pre-calculated the promotion type, so this is trivial. 2123 if (ToType->isIntegerType() && 2124 isCompleteType(From->getBeginLoc(), FromType)) 2125 return Context.hasSameUnqualifiedType( 2126 ToType, FromEnumType->getDecl()->getPromotionType()); 2127 2128 // C++ [conv.prom]p5: 2129 // If the bit-field has an enumerated type, it is treated as any other 2130 // value of that type for promotion purposes. 2131 // 2132 // ... so do not fall through into the bit-field checks below in C++. 2133 if (getLangOpts().CPlusPlus) 2134 return false; 2135 } 2136 2137 // C++0x [conv.prom]p2: 2138 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2139 // to an rvalue a prvalue of the first of the following types that can 2140 // represent all the values of its underlying type: int, unsigned int, 2141 // long int, unsigned long int, long long int, or unsigned long long int. 2142 // If none of the types in that list can represent all the values of its 2143 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2144 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2145 // type. 2146 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2147 ToType->isIntegerType()) { 2148 // Determine whether the type we're converting from is signed or 2149 // unsigned. 2150 bool FromIsSigned = FromType->isSignedIntegerType(); 2151 uint64_t FromSize = Context.getTypeSize(FromType); 2152 2153 // The types we'll try to promote to, in the appropriate 2154 // order. Try each of these types. 2155 QualType PromoteTypes[6] = { 2156 Context.IntTy, Context.UnsignedIntTy, 2157 Context.LongTy, Context.UnsignedLongTy , 2158 Context.LongLongTy, Context.UnsignedLongLongTy 2159 }; 2160 for (int Idx = 0; Idx < 6; ++Idx) { 2161 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2162 if (FromSize < ToSize || 2163 (FromSize == ToSize && 2164 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2165 // We found the type that we can promote to. If this is the 2166 // type we wanted, we have a promotion. Otherwise, no 2167 // promotion. 2168 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2169 } 2170 } 2171 } 2172 2173 // An rvalue for an integral bit-field (9.6) can be converted to an 2174 // rvalue of type int if int can represent all the values of the 2175 // bit-field; otherwise, it can be converted to unsigned int if 2176 // unsigned int can represent all the values of the bit-field. If 2177 // the bit-field is larger yet, no integral promotion applies to 2178 // it. If the bit-field has an enumerated type, it is treated as any 2179 // other value of that type for promotion purposes (C++ 4.5p3). 2180 // FIXME: We should delay checking of bit-fields until we actually perform the 2181 // conversion. 2182 // 2183 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2184 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2185 // bit-fields and those whose underlying type is larger than int) for GCC 2186 // compatibility. 2187 if (From) { 2188 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2189 Optional<llvm::APSInt> BitWidth; 2190 if (FromType->isIntegralType(Context) && 2191 (BitWidth = 2192 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2193 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2194 ToSize = Context.getTypeSize(ToType); 2195 2196 // Are we promoting to an int from a bitfield that fits in an int? 2197 if (*BitWidth < ToSize || 2198 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2199 return To->getKind() == BuiltinType::Int; 2200 } 2201 2202 // Are we promoting to an unsigned int from an unsigned bitfield 2203 // that fits into an unsigned int? 2204 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2205 return To->getKind() == BuiltinType::UInt; 2206 } 2207 2208 return false; 2209 } 2210 } 2211 } 2212 2213 // An rvalue of type bool can be converted to an rvalue of type int, 2214 // with false becoming zero and true becoming one (C++ 4.5p4). 2215 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2216 return true; 2217 } 2218 2219 return false; 2220 } 2221 2222 /// IsFloatingPointPromotion - Determines whether the conversion from 2223 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2224 /// returns true and sets PromotedType to the promoted type. 2225 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2226 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2227 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2228 /// An rvalue of type float can be converted to an rvalue of type 2229 /// double. (C++ 4.6p1). 2230 if (FromBuiltin->getKind() == BuiltinType::Float && 2231 ToBuiltin->getKind() == BuiltinType::Double) 2232 return true; 2233 2234 // C99 6.3.1.5p1: 2235 // When a float is promoted to double or long double, or a 2236 // double is promoted to long double [...]. 2237 if (!getLangOpts().CPlusPlus && 2238 (FromBuiltin->getKind() == BuiltinType::Float || 2239 FromBuiltin->getKind() == BuiltinType::Double) && 2240 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2241 ToBuiltin->getKind() == BuiltinType::Float128 || 2242 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2243 return true; 2244 2245 // Half can be promoted to float. 2246 if (!getLangOpts().NativeHalfType && 2247 FromBuiltin->getKind() == BuiltinType::Half && 2248 ToBuiltin->getKind() == BuiltinType::Float) 2249 return true; 2250 } 2251 2252 return false; 2253 } 2254 2255 /// Determine if a conversion is a complex promotion. 2256 /// 2257 /// A complex promotion is defined as a complex -> complex conversion 2258 /// where the conversion between the underlying real types is a 2259 /// floating-point or integral promotion. 2260 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2261 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2262 if (!FromComplex) 2263 return false; 2264 2265 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2266 if (!ToComplex) 2267 return false; 2268 2269 return IsFloatingPointPromotion(FromComplex->getElementType(), 2270 ToComplex->getElementType()) || 2271 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2272 ToComplex->getElementType()); 2273 } 2274 2275 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2276 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2277 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2278 /// if non-empty, will be a pointer to ToType that may or may not have 2279 /// the right set of qualifiers on its pointee. 2280 /// 2281 static QualType 2282 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2283 QualType ToPointee, QualType ToType, 2284 ASTContext &Context, 2285 bool StripObjCLifetime = false) { 2286 assert((FromPtr->getTypeClass() == Type::Pointer || 2287 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2288 "Invalid similarly-qualified pointer type"); 2289 2290 /// Conversions to 'id' subsume cv-qualifier conversions. 2291 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2292 return ToType.getUnqualifiedType(); 2293 2294 QualType CanonFromPointee 2295 = Context.getCanonicalType(FromPtr->getPointeeType()); 2296 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2297 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2298 2299 if (StripObjCLifetime) 2300 Quals.removeObjCLifetime(); 2301 2302 // Exact qualifier match -> return the pointer type we're converting to. 2303 if (CanonToPointee.getLocalQualifiers() == Quals) { 2304 // ToType is exactly what we need. Return it. 2305 if (!ToType.isNull()) 2306 return ToType.getUnqualifiedType(); 2307 2308 // Build a pointer to ToPointee. It has the right qualifiers 2309 // already. 2310 if (isa<ObjCObjectPointerType>(ToType)) 2311 return Context.getObjCObjectPointerType(ToPointee); 2312 return Context.getPointerType(ToPointee); 2313 } 2314 2315 // Just build a canonical type that has the right qualifiers. 2316 QualType QualifiedCanonToPointee 2317 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2318 2319 if (isa<ObjCObjectPointerType>(ToType)) 2320 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2321 return Context.getPointerType(QualifiedCanonToPointee); 2322 } 2323 2324 static bool isNullPointerConstantForConversion(Expr *Expr, 2325 bool InOverloadResolution, 2326 ASTContext &Context) { 2327 // Handle value-dependent integral null pointer constants correctly. 2328 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2329 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2330 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2331 return !InOverloadResolution; 2332 2333 return Expr->isNullPointerConstant(Context, 2334 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2335 : Expr::NPC_ValueDependentIsNull); 2336 } 2337 2338 /// IsPointerConversion - Determines whether the conversion of the 2339 /// expression From, which has the (possibly adjusted) type FromType, 2340 /// can be converted to the type ToType via a pointer conversion (C++ 2341 /// 4.10). If so, returns true and places the converted type (that 2342 /// might differ from ToType in its cv-qualifiers at some level) into 2343 /// ConvertedType. 2344 /// 2345 /// This routine also supports conversions to and from block pointers 2346 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2347 /// pointers to interfaces. FIXME: Once we've determined the 2348 /// appropriate overloading rules for Objective-C, we may want to 2349 /// split the Objective-C checks into a different routine; however, 2350 /// GCC seems to consider all of these conversions to be pointer 2351 /// conversions, so for now they live here. IncompatibleObjC will be 2352 /// set if the conversion is an allowed Objective-C conversion that 2353 /// should result in a warning. 2354 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2355 bool InOverloadResolution, 2356 QualType& ConvertedType, 2357 bool &IncompatibleObjC) { 2358 IncompatibleObjC = false; 2359 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2360 IncompatibleObjC)) 2361 return true; 2362 2363 // Conversion from a null pointer constant to any Objective-C pointer type. 2364 if (ToType->isObjCObjectPointerType() && 2365 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2366 ConvertedType = ToType; 2367 return true; 2368 } 2369 2370 // Blocks: Block pointers can be converted to void*. 2371 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2372 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2373 ConvertedType = ToType; 2374 return true; 2375 } 2376 // Blocks: A null pointer constant can be converted to a block 2377 // pointer type. 2378 if (ToType->isBlockPointerType() && 2379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2380 ConvertedType = ToType; 2381 return true; 2382 } 2383 2384 // If the left-hand-side is nullptr_t, the right side can be a null 2385 // pointer constant. 2386 if (ToType->isNullPtrType() && 2387 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2388 ConvertedType = ToType; 2389 return true; 2390 } 2391 2392 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2393 if (!ToTypePtr) 2394 return false; 2395 2396 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2397 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2398 ConvertedType = ToType; 2399 return true; 2400 } 2401 2402 // Beyond this point, both types need to be pointers 2403 // , including objective-c pointers. 2404 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2405 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2406 !getLangOpts().ObjCAutoRefCount) { 2407 ConvertedType = BuildSimilarlyQualifiedPointerType( 2408 FromType->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 argument types. Caller has already checked that 2958 /// they have same number of arguments. If the parameters are different, 2959 /// ArgPos will have the parameter index of the first different parameter. 2960 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2961 const FunctionProtoType *NewType, 2962 unsigned *ArgPos) { 2963 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2964 N = NewType->param_type_begin(), 2965 E = OldType->param_type_end(); 2966 O && (O != E); ++O, ++N) { 2967 // Ignore address spaces in pointee type. This is to disallow overloading 2968 // on __ptr32/__ptr64 address spaces. 2969 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2970 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2971 2972 if (!Context.hasSameType(Old, New)) { 2973 if (ArgPos) 2974 *ArgPos = O - OldType->param_type_begin(); 2975 return false; 2976 } 2977 } 2978 return true; 2979 } 2980 2981 /// CheckPointerConversion - Check the pointer conversion from the 2982 /// expression From to the type ToType. This routine checks for 2983 /// ambiguous or inaccessible derived-to-base pointer 2984 /// conversions for which IsPointerConversion has already returned 2985 /// true. It returns true and produces a diagnostic if there was an 2986 /// error, or returns false otherwise. 2987 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2988 CastKind &Kind, 2989 CXXCastPath& BasePath, 2990 bool IgnoreBaseAccess, 2991 bool Diagnose) { 2992 QualType FromType = From->getType(); 2993 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2994 2995 Kind = CK_BitCast; 2996 2997 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2998 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2999 Expr::NPCK_ZeroExpression) { 3000 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3001 DiagRuntimeBehavior(From->getExprLoc(), From, 3002 PDiag(diag::warn_impcast_bool_to_null_pointer) 3003 << ToType << From->getSourceRange()); 3004 else if (!isUnevaluatedContext()) 3005 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3006 << ToType << From->getSourceRange(); 3007 } 3008 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3009 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3010 QualType FromPointeeType = FromPtrType->getPointeeType(), 3011 ToPointeeType = ToPtrType->getPointeeType(); 3012 3013 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3014 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3015 // We must have a derived-to-base conversion. Check an 3016 // ambiguous or inaccessible conversion. 3017 unsigned InaccessibleID = 0; 3018 unsigned AmbiguousID = 0; 3019 if (Diagnose) { 3020 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3021 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3022 } 3023 if (CheckDerivedToBaseConversion( 3024 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3025 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3026 &BasePath, IgnoreBaseAccess)) 3027 return true; 3028 3029 // The conversion was successful. 3030 Kind = CK_DerivedToBase; 3031 } 3032 3033 if (Diagnose && !IsCStyleOrFunctionalCast && 3034 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3035 assert(getLangOpts().MSVCCompat && 3036 "this should only be possible with MSVCCompat!"); 3037 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3038 << From->getSourceRange(); 3039 } 3040 } 3041 } else if (const ObjCObjectPointerType *ToPtrType = 3042 ToType->getAs<ObjCObjectPointerType>()) { 3043 if (const ObjCObjectPointerType *FromPtrType = 3044 FromType->getAs<ObjCObjectPointerType>()) { 3045 // Objective-C++ conversions are always okay. 3046 // FIXME: We should have a different class of conversions for the 3047 // Objective-C++ implicit conversions. 3048 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3049 return false; 3050 } else if (FromType->isBlockPointerType()) { 3051 Kind = CK_BlockPointerToObjCPointerCast; 3052 } else { 3053 Kind = CK_CPointerToObjCPointerCast; 3054 } 3055 } else if (ToType->isBlockPointerType()) { 3056 if (!FromType->isBlockPointerType()) 3057 Kind = CK_AnyPointerToBlockPointerCast; 3058 } 3059 3060 // We shouldn't fall into this case unless it's valid for other 3061 // reasons. 3062 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3063 Kind = CK_NullToPointer; 3064 3065 return false; 3066 } 3067 3068 /// IsMemberPointerConversion - Determines whether the conversion of the 3069 /// expression From, which has the (possibly adjusted) type FromType, can be 3070 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3071 /// If so, returns true and places the converted type (that might differ from 3072 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3073 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3074 QualType ToType, 3075 bool InOverloadResolution, 3076 QualType &ConvertedType) { 3077 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3078 if (!ToTypePtr) 3079 return false; 3080 3081 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3082 if (From->isNullPointerConstant(Context, 3083 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3084 : Expr::NPC_ValueDependentIsNull)) { 3085 ConvertedType = ToType; 3086 return true; 3087 } 3088 3089 // Otherwise, both types have to be member pointers. 3090 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3091 if (!FromTypePtr) 3092 return false; 3093 3094 // A pointer to member of B can be converted to a pointer to member of D, 3095 // where D is derived from B (C++ 4.11p2). 3096 QualType FromClass(FromTypePtr->getClass(), 0); 3097 QualType ToClass(ToTypePtr->getClass(), 0); 3098 3099 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3100 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3101 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3102 ToClass.getTypePtr()); 3103 return true; 3104 } 3105 3106 return false; 3107 } 3108 3109 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3110 /// expression From to the type ToType. This routine checks for ambiguous or 3111 /// virtual or inaccessible base-to-derived member pointer conversions 3112 /// for which IsMemberPointerConversion has already returned true. It returns 3113 /// true and produces a diagnostic if there was an error, or returns false 3114 /// otherwise. 3115 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3116 CastKind &Kind, 3117 CXXCastPath &BasePath, 3118 bool IgnoreBaseAccess) { 3119 QualType FromType = From->getType(); 3120 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3121 if (!FromPtrType) { 3122 // This must be a null pointer to member pointer conversion 3123 assert(From->isNullPointerConstant(Context, 3124 Expr::NPC_ValueDependentIsNull) && 3125 "Expr must be null pointer constant!"); 3126 Kind = CK_NullToMemberPointer; 3127 return false; 3128 } 3129 3130 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3131 assert(ToPtrType && "No member pointer cast has a target type " 3132 "that is not a member pointer."); 3133 3134 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3135 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3136 3137 // FIXME: What about dependent types? 3138 assert(FromClass->isRecordType() && "Pointer into non-class."); 3139 assert(ToClass->isRecordType() && "Pointer into non-class."); 3140 3141 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3142 /*DetectVirtual=*/true); 3143 bool DerivationOkay = 3144 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3145 assert(DerivationOkay && 3146 "Should not have been called if derivation isn't OK."); 3147 (void)DerivationOkay; 3148 3149 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3150 getUnqualifiedType())) { 3151 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3152 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3153 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3154 return true; 3155 } 3156 3157 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3158 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3159 << FromClass << ToClass << QualType(VBase, 0) 3160 << From->getSourceRange(); 3161 return true; 3162 } 3163 3164 if (!IgnoreBaseAccess) 3165 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3166 Paths.front(), 3167 diag::err_downcast_from_inaccessible_base); 3168 3169 // Must be a base to derived member conversion. 3170 BuildBasePathArray(Paths, BasePath); 3171 Kind = CK_BaseToDerivedMemberPointer; 3172 return false; 3173 } 3174 3175 /// Determine whether the lifetime conversion between the two given 3176 /// qualifiers sets is nontrivial. 3177 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3178 Qualifiers ToQuals) { 3179 // Converting anything to const __unsafe_unretained is trivial. 3180 if (ToQuals.hasConst() && 3181 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3182 return false; 3183 3184 return true; 3185 } 3186 3187 /// Perform a single iteration of the loop for checking if a qualification 3188 /// conversion is valid. 3189 /// 3190 /// Specifically, check whether any change between the qualifiers of \p 3191 /// FromType and \p ToType is permissible, given knowledge about whether every 3192 /// outer layer is const-qualified. 3193 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3194 bool CStyle, bool IsTopLevel, 3195 bool &PreviousToQualsIncludeConst, 3196 bool &ObjCLifetimeConversion) { 3197 Qualifiers FromQuals = FromType.getQualifiers(); 3198 Qualifiers ToQuals = ToType.getQualifiers(); 3199 3200 // Ignore __unaligned qualifier if this type is void. 3201 if (ToType.getUnqualifiedType()->isVoidType()) 3202 FromQuals.removeUnaligned(); 3203 3204 // Objective-C ARC: 3205 // Check Objective-C lifetime conversions. 3206 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3207 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3208 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3209 ObjCLifetimeConversion = true; 3210 FromQuals.removeObjCLifetime(); 3211 ToQuals.removeObjCLifetime(); 3212 } else { 3213 // Qualification conversions cannot cast between different 3214 // Objective-C lifetime qualifiers. 3215 return false; 3216 } 3217 } 3218 3219 // Allow addition/removal of GC attributes but not changing GC attributes. 3220 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3221 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3222 FromQuals.removeObjCGCAttr(); 3223 ToQuals.removeObjCGCAttr(); 3224 } 3225 3226 // -- for every j > 0, if const is in cv 1,j then const is in cv 3227 // 2,j, and similarly for volatile. 3228 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3229 return false; 3230 3231 // If address spaces mismatch: 3232 // - in top level it is only valid to convert to addr space that is a 3233 // superset in all cases apart from C-style casts where we allow 3234 // conversions between overlapping address spaces. 3235 // - in non-top levels it is not a valid conversion. 3236 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3237 (!IsTopLevel || 3238 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3239 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3240 return false; 3241 3242 // -- if the cv 1,j and cv 2,j are different, then const is in 3243 // every cv for 0 < k < j. 3244 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3245 !PreviousToQualsIncludeConst) 3246 return false; 3247 3248 // The following wording is from C++20, where the result of the conversion 3249 // is T3, not T2. 3250 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3251 // "array of unknown bound of" 3252 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3253 return false; 3254 3255 // -- if the resulting P3,i is different from P1,i [...], then const is 3256 // added to every cv 3_k for 0 < k < i. 3257 if (!CStyle && FromType->isConstantArrayType() && 3258 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3259 return false; 3260 3261 // Keep track of whether all prior cv-qualifiers in the "to" type 3262 // include const. 3263 PreviousToQualsIncludeConst = 3264 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3265 return true; 3266 } 3267 3268 /// IsQualificationConversion - Determines whether the conversion from 3269 /// an rvalue of type FromType to ToType is a qualification conversion 3270 /// (C++ 4.4). 3271 /// 3272 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3273 /// when the qualification conversion involves a change in the Objective-C 3274 /// object lifetime. 3275 bool 3276 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3277 bool CStyle, bool &ObjCLifetimeConversion) { 3278 FromType = Context.getCanonicalType(FromType); 3279 ToType = Context.getCanonicalType(ToType); 3280 ObjCLifetimeConversion = false; 3281 3282 // If FromType and ToType are the same type, this is not a 3283 // qualification conversion. 3284 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3285 return false; 3286 3287 // (C++ 4.4p4): 3288 // A conversion can add cv-qualifiers at levels other than the first 3289 // in multi-level pointers, subject to the following rules: [...] 3290 bool PreviousToQualsIncludeConst = true; 3291 bool UnwrappedAnyPointer = false; 3292 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3293 if (!isQualificationConversionStep( 3294 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3295 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3296 return false; 3297 UnwrappedAnyPointer = true; 3298 } 3299 3300 // We are left with FromType and ToType being the pointee types 3301 // after unwrapping the original FromType and ToType the same number 3302 // of times. If we unwrapped any pointers, and if FromType and 3303 // ToType have the same unqualified type (since we checked 3304 // qualifiers above), then this is a qualification conversion. 3305 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3306 } 3307 3308 /// - Determine whether this is a conversion from a scalar type to an 3309 /// atomic type. 3310 /// 3311 /// If successful, updates \c SCS's second and third steps in the conversion 3312 /// sequence to finish the conversion. 3313 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3314 bool InOverloadResolution, 3315 StandardConversionSequence &SCS, 3316 bool CStyle) { 3317 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3318 if (!ToAtomic) 3319 return false; 3320 3321 StandardConversionSequence InnerSCS; 3322 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3323 InOverloadResolution, InnerSCS, 3324 CStyle, /*AllowObjCWritebackConversion=*/false)) 3325 return false; 3326 3327 SCS.Second = InnerSCS.Second; 3328 SCS.setToType(1, InnerSCS.getToType(1)); 3329 SCS.Third = InnerSCS.Third; 3330 SCS.QualificationIncludesObjCLifetime 3331 = InnerSCS.QualificationIncludesObjCLifetime; 3332 SCS.setToType(2, InnerSCS.getToType(2)); 3333 return true; 3334 } 3335 3336 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3337 CXXConstructorDecl *Constructor, 3338 QualType Type) { 3339 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3340 if (CtorType->getNumParams() > 0) { 3341 QualType FirstArg = CtorType->getParamType(0); 3342 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3343 return true; 3344 } 3345 return false; 3346 } 3347 3348 static OverloadingResult 3349 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3350 CXXRecordDecl *To, 3351 UserDefinedConversionSequence &User, 3352 OverloadCandidateSet &CandidateSet, 3353 bool AllowExplicit) { 3354 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3355 for (auto *D : S.LookupConstructors(To)) { 3356 auto Info = getConstructorInfo(D); 3357 if (!Info) 3358 continue; 3359 3360 bool Usable = !Info.Constructor->isInvalidDecl() && 3361 S.isInitListConstructor(Info.Constructor); 3362 if (Usable) { 3363 bool SuppressUserConversions = false; 3364 if (Info.ConstructorTmpl) 3365 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3366 /*ExplicitArgs*/ nullptr, From, 3367 CandidateSet, SuppressUserConversions, 3368 /*PartialOverloading*/ false, 3369 AllowExplicit); 3370 else 3371 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3372 CandidateSet, SuppressUserConversions, 3373 /*PartialOverloading*/ false, AllowExplicit); 3374 } 3375 } 3376 3377 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3378 3379 OverloadCandidateSet::iterator Best; 3380 switch (auto Result = 3381 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3382 case OR_Deleted: 3383 case OR_Success: { 3384 // Record the standard conversion we used and the conversion function. 3385 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3386 QualType ThisType = Constructor->getThisType(); 3387 // Initializer lists don't have conversions as such. 3388 User.Before.setAsIdentityConversion(); 3389 User.HadMultipleCandidates = HadMultipleCandidates; 3390 User.ConversionFunction = Constructor; 3391 User.FoundConversionFunction = Best->FoundDecl; 3392 User.After.setAsIdentityConversion(); 3393 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3394 User.After.setAllToTypes(ToType); 3395 return Result; 3396 } 3397 3398 case OR_No_Viable_Function: 3399 return OR_No_Viable_Function; 3400 case OR_Ambiguous: 3401 return OR_Ambiguous; 3402 } 3403 3404 llvm_unreachable("Invalid OverloadResult!"); 3405 } 3406 3407 /// Determines whether there is a user-defined conversion sequence 3408 /// (C++ [over.ics.user]) that converts expression From to the type 3409 /// ToType. If such a conversion exists, User will contain the 3410 /// user-defined conversion sequence that performs such a conversion 3411 /// and this routine will return true. Otherwise, this routine returns 3412 /// false and User is unspecified. 3413 /// 3414 /// \param AllowExplicit true if the conversion should consider C++0x 3415 /// "explicit" conversion functions as well as non-explicit conversion 3416 /// functions (C++0x [class.conv.fct]p2). 3417 /// 3418 /// \param AllowObjCConversionOnExplicit true if the conversion should 3419 /// allow an extra Objective-C pointer conversion on uses of explicit 3420 /// constructors. Requires \c AllowExplicit to also be set. 3421 static OverloadingResult 3422 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3423 UserDefinedConversionSequence &User, 3424 OverloadCandidateSet &CandidateSet, 3425 AllowedExplicit AllowExplicit, 3426 bool AllowObjCConversionOnExplicit) { 3427 assert(AllowExplicit != AllowedExplicit::None || 3428 !AllowObjCConversionOnExplicit); 3429 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3430 3431 // Whether we will only visit constructors. 3432 bool ConstructorsOnly = false; 3433 3434 // If the type we are conversion to is a class type, enumerate its 3435 // constructors. 3436 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3437 // C++ [over.match.ctor]p1: 3438 // When objects of class type are direct-initialized (8.5), or 3439 // copy-initialized from an expression of the same or a 3440 // derived class type (8.5), overload resolution selects the 3441 // constructor. [...] For copy-initialization, the candidate 3442 // functions are all the converting constructors (12.3.1) of 3443 // that class. The argument list is the expression-list within 3444 // the parentheses of the initializer. 3445 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3446 (From->getType()->getAs<RecordType>() && 3447 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3448 ConstructorsOnly = true; 3449 3450 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3451 // We're not going to find any constructors. 3452 } else if (CXXRecordDecl *ToRecordDecl 3453 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3454 3455 Expr **Args = &From; 3456 unsigned NumArgs = 1; 3457 bool ListInitializing = false; 3458 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3459 // But first, see if there is an init-list-constructor that will work. 3460 OverloadingResult Result = IsInitializerListConstructorConversion( 3461 S, From, ToType, ToRecordDecl, User, CandidateSet, 3462 AllowExplicit == AllowedExplicit::All); 3463 if (Result != OR_No_Viable_Function) 3464 return Result; 3465 // Never mind. 3466 CandidateSet.clear( 3467 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3468 3469 // If we're list-initializing, we pass the individual elements as 3470 // arguments, not the entire list. 3471 Args = InitList->getInits(); 3472 NumArgs = InitList->getNumInits(); 3473 ListInitializing = true; 3474 } 3475 3476 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3477 auto Info = getConstructorInfo(D); 3478 if (!Info) 3479 continue; 3480 3481 bool Usable = !Info.Constructor->isInvalidDecl(); 3482 if (!ListInitializing) 3483 Usable = Usable && Info.Constructor->isConvertingConstructor( 3484 /*AllowExplicit*/ true); 3485 if (Usable) { 3486 bool SuppressUserConversions = !ConstructorsOnly; 3487 // C++20 [over.best.ics.general]/4.5: 3488 // if the target is the first parameter of a constructor [of class 3489 // X] and the constructor [...] is a candidate by [...] the second 3490 // phase of [over.match.list] when the initializer list has exactly 3491 // one element that is itself an initializer list, [...] and the 3492 // conversion is to X or reference to cv X, user-defined conversion 3493 // sequences are not cnosidered. 3494 if (SuppressUserConversions && ListInitializing) { 3495 SuppressUserConversions = 3496 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3497 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3498 ToType); 3499 } 3500 if (Info.ConstructorTmpl) 3501 S.AddTemplateOverloadCandidate( 3502 Info.ConstructorTmpl, Info.FoundDecl, 3503 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3504 CandidateSet, SuppressUserConversions, 3505 /*PartialOverloading*/ false, 3506 AllowExplicit == AllowedExplicit::All); 3507 else 3508 // Allow one user-defined conversion when user specifies a 3509 // From->ToType conversion via an static cast (c-style, etc). 3510 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3511 llvm::makeArrayRef(Args, NumArgs), 3512 CandidateSet, SuppressUserConversions, 3513 /*PartialOverloading*/ false, 3514 AllowExplicit == AllowedExplicit::All); 3515 } 3516 } 3517 } 3518 } 3519 3520 // Enumerate conversion functions, if we're allowed to. 3521 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3522 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3523 // No conversion functions from incomplete types. 3524 } else if (const RecordType *FromRecordType = 3525 From->getType()->getAs<RecordType>()) { 3526 if (CXXRecordDecl *FromRecordDecl 3527 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3528 // Add all of the conversion functions as candidates. 3529 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3530 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3531 DeclAccessPair FoundDecl = I.getPair(); 3532 NamedDecl *D = FoundDecl.getDecl(); 3533 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3534 if (isa<UsingShadowDecl>(D)) 3535 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3536 3537 CXXConversionDecl *Conv; 3538 FunctionTemplateDecl *ConvTemplate; 3539 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3540 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3541 else 3542 Conv = cast<CXXConversionDecl>(D); 3543 3544 if (ConvTemplate) 3545 S.AddTemplateConversionCandidate( 3546 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3547 CandidateSet, AllowObjCConversionOnExplicit, 3548 AllowExplicit != AllowedExplicit::None); 3549 else 3550 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3551 CandidateSet, AllowObjCConversionOnExplicit, 3552 AllowExplicit != AllowedExplicit::None); 3553 } 3554 } 3555 } 3556 3557 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3558 3559 OverloadCandidateSet::iterator Best; 3560 switch (auto Result = 3561 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3562 case OR_Success: 3563 case OR_Deleted: 3564 // Record the standard conversion we used and the conversion function. 3565 if (CXXConstructorDecl *Constructor 3566 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3567 // C++ [over.ics.user]p1: 3568 // If the user-defined conversion is specified by a 3569 // constructor (12.3.1), the initial standard conversion 3570 // sequence converts the source type to the type required by 3571 // the argument of the constructor. 3572 // 3573 QualType ThisType = Constructor->getThisType(); 3574 if (isa<InitListExpr>(From)) { 3575 // Initializer lists don't have conversions as such. 3576 User.Before.setAsIdentityConversion(); 3577 } else { 3578 if (Best->Conversions[0].isEllipsis()) 3579 User.EllipsisConversion = true; 3580 else { 3581 User.Before = Best->Conversions[0].Standard; 3582 User.EllipsisConversion = false; 3583 } 3584 } 3585 User.HadMultipleCandidates = HadMultipleCandidates; 3586 User.ConversionFunction = Constructor; 3587 User.FoundConversionFunction = Best->FoundDecl; 3588 User.After.setAsIdentityConversion(); 3589 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3590 User.After.setAllToTypes(ToType); 3591 return Result; 3592 } 3593 if (CXXConversionDecl *Conversion 3594 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3595 // C++ [over.ics.user]p1: 3596 // 3597 // [...] If the user-defined conversion is specified by a 3598 // conversion function (12.3.2), the initial standard 3599 // conversion sequence converts the source type to the 3600 // implicit object parameter of the conversion function. 3601 User.Before = Best->Conversions[0].Standard; 3602 User.HadMultipleCandidates = HadMultipleCandidates; 3603 User.ConversionFunction = Conversion; 3604 User.FoundConversionFunction = Best->FoundDecl; 3605 User.EllipsisConversion = false; 3606 3607 // C++ [over.ics.user]p2: 3608 // The second standard conversion sequence converts the 3609 // result of the user-defined conversion to the target type 3610 // for the sequence. Since an implicit conversion sequence 3611 // is an initialization, the special rules for 3612 // initialization by user-defined conversion apply when 3613 // selecting the best user-defined conversion for a 3614 // user-defined conversion sequence (see 13.3.3 and 3615 // 13.3.3.1). 3616 User.After = Best->FinalConversion; 3617 return Result; 3618 } 3619 llvm_unreachable("Not a constructor or conversion function?"); 3620 3621 case OR_No_Viable_Function: 3622 return OR_No_Viable_Function; 3623 3624 case OR_Ambiguous: 3625 return OR_Ambiguous; 3626 } 3627 3628 llvm_unreachable("Invalid OverloadResult!"); 3629 } 3630 3631 bool 3632 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3633 ImplicitConversionSequence ICS; 3634 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3635 OverloadCandidateSet::CSK_Normal); 3636 OverloadingResult OvResult = 3637 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3638 CandidateSet, AllowedExplicit::None, false); 3639 3640 if (!(OvResult == OR_Ambiguous || 3641 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3642 return false; 3643 3644 auto Cands = CandidateSet.CompleteCandidates( 3645 *this, 3646 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3647 From); 3648 if (OvResult == OR_Ambiguous) 3649 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3650 << From->getType() << ToType << From->getSourceRange(); 3651 else { // OR_No_Viable_Function && !CandidateSet.empty() 3652 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3653 diag::err_typecheck_nonviable_condition_incomplete, 3654 From->getType(), From->getSourceRange())) 3655 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3656 << false << From->getType() << From->getSourceRange() << ToType; 3657 } 3658 3659 CandidateSet.NoteCandidates( 3660 *this, From, Cands); 3661 return true; 3662 } 3663 3664 // Helper for compareConversionFunctions that gets the FunctionType that the 3665 // conversion-operator return value 'points' to, or nullptr. 3666 static const FunctionType * 3667 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3668 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3669 const PointerType *RetPtrTy = 3670 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3671 3672 if (!RetPtrTy) 3673 return nullptr; 3674 3675 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3676 } 3677 3678 /// Compare the user-defined conversion functions or constructors 3679 /// of two user-defined conversion sequences to determine whether any ordering 3680 /// is possible. 3681 static ImplicitConversionSequence::CompareKind 3682 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3683 FunctionDecl *Function2) { 3684 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3685 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3686 if (!Conv1 || !Conv2) 3687 return ImplicitConversionSequence::Indistinguishable; 3688 3689 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3690 return ImplicitConversionSequence::Indistinguishable; 3691 3692 // Objective-C++: 3693 // If both conversion functions are implicitly-declared conversions from 3694 // a lambda closure type to a function pointer and a block pointer, 3695 // respectively, always prefer the conversion to a function pointer, 3696 // because the function pointer is more lightweight and is more likely 3697 // to keep code working. 3698 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3699 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3700 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3701 if (Block1 != Block2) 3702 return Block1 ? ImplicitConversionSequence::Worse 3703 : ImplicitConversionSequence::Better; 3704 } 3705 3706 // In order to support multiple calling conventions for the lambda conversion 3707 // operator (such as when the free and member function calling convention is 3708 // different), prefer the 'free' mechanism, followed by the calling-convention 3709 // of operator(). The latter is in place to support the MSVC-like solution of 3710 // defining ALL of the possible conversions in regards to calling-convention. 3711 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3712 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3713 3714 if (Conv1FuncRet && Conv2FuncRet && 3715 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3716 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3717 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3718 3719 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 3720 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 3721 3722 CallingConv CallOpCC = 3723 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 3724 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 3725 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 3726 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 3727 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 3728 3729 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 3730 for (CallingConv CC : PrefOrder) { 3731 if (Conv1CC == CC) 3732 return ImplicitConversionSequence::Better; 3733 if (Conv2CC == CC) 3734 return ImplicitConversionSequence::Worse; 3735 } 3736 } 3737 3738 return ImplicitConversionSequence::Indistinguishable; 3739 } 3740 3741 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3742 const ImplicitConversionSequence &ICS) { 3743 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3744 (ICS.isUserDefined() && 3745 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3746 } 3747 3748 /// CompareImplicitConversionSequences - Compare two implicit 3749 /// conversion sequences to determine whether one is better than the 3750 /// other or if they are indistinguishable (C++ 13.3.3.2). 3751 static ImplicitConversionSequence::CompareKind 3752 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3753 const ImplicitConversionSequence& ICS1, 3754 const ImplicitConversionSequence& ICS2) 3755 { 3756 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3757 // conversion sequences (as defined in 13.3.3.1) 3758 // -- a standard conversion sequence (13.3.3.1.1) is a better 3759 // conversion sequence than a user-defined conversion sequence or 3760 // an ellipsis conversion sequence, and 3761 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3762 // conversion sequence than an ellipsis conversion sequence 3763 // (13.3.3.1.3). 3764 // 3765 // C++0x [over.best.ics]p10: 3766 // For the purpose of ranking implicit conversion sequences as 3767 // described in 13.3.3.2, the ambiguous conversion sequence is 3768 // treated as a user-defined sequence that is indistinguishable 3769 // from any other user-defined conversion sequence. 3770 3771 // String literal to 'char *' conversion has been deprecated in C++03. It has 3772 // been removed from C++11. We still accept this conversion, if it happens at 3773 // the best viable function. Otherwise, this conversion is considered worse 3774 // than ellipsis conversion. Consider this as an extension; this is not in the 3775 // standard. For example: 3776 // 3777 // int &f(...); // #1 3778 // void f(char*); // #2 3779 // void g() { int &r = f("foo"); } 3780 // 3781 // In C++03, we pick #2 as the best viable function. 3782 // In C++11, we pick #1 as the best viable function, because ellipsis 3783 // conversion is better than string-literal to char* conversion (since there 3784 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3785 // convert arguments, #2 would be the best viable function in C++11. 3786 // If the best viable function has this conversion, a warning will be issued 3787 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3788 3789 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3790 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3791 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 3792 // Ill-formedness must not differ 3793 ICS1.isBad() == ICS2.isBad()) 3794 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3795 ? ImplicitConversionSequence::Worse 3796 : ImplicitConversionSequence::Better; 3797 3798 if (ICS1.getKindRank() < ICS2.getKindRank()) 3799 return ImplicitConversionSequence::Better; 3800 if (ICS2.getKindRank() < ICS1.getKindRank()) 3801 return ImplicitConversionSequence::Worse; 3802 3803 // The following checks require both conversion sequences to be of 3804 // the same kind. 3805 if (ICS1.getKind() != ICS2.getKind()) 3806 return ImplicitConversionSequence::Indistinguishable; 3807 3808 ImplicitConversionSequence::CompareKind Result = 3809 ImplicitConversionSequence::Indistinguishable; 3810 3811 // Two implicit conversion sequences of the same form are 3812 // indistinguishable conversion sequences unless one of the 3813 // following rules apply: (C++ 13.3.3.2p3): 3814 3815 // List-initialization sequence L1 is a better conversion sequence than 3816 // list-initialization sequence L2 if: 3817 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3818 // if not that, 3819 // — L1 and L2 convert to arrays of the same element type, and either the 3820 // number of elements n_1 initialized by L1 is less than the number of 3821 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 3822 // an array of unknown bound and L1 does not, 3823 // even if one of the other rules in this paragraph would otherwise apply. 3824 if (!ICS1.isBad()) { 3825 bool StdInit1 = false, StdInit2 = false; 3826 if (ICS1.hasInitializerListContainerType()) 3827 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 3828 nullptr); 3829 if (ICS2.hasInitializerListContainerType()) 3830 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 3831 nullptr); 3832 if (StdInit1 != StdInit2) 3833 return StdInit1 ? ImplicitConversionSequence::Better 3834 : ImplicitConversionSequence::Worse; 3835 3836 if (ICS1.hasInitializerListContainerType() && 3837 ICS2.hasInitializerListContainerType()) 3838 if (auto *CAT1 = S.Context.getAsConstantArrayType( 3839 ICS1.getInitializerListContainerType())) 3840 if (auto *CAT2 = S.Context.getAsConstantArrayType( 3841 ICS2.getInitializerListContainerType())) { 3842 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 3843 CAT2->getElementType())) { 3844 // Both to arrays of the same element type 3845 if (CAT1->getSize() != CAT2->getSize()) 3846 // Different sized, the smaller wins 3847 return CAT1->getSize().ult(CAT2->getSize()) 3848 ? ImplicitConversionSequence::Better 3849 : ImplicitConversionSequence::Worse; 3850 if (ICS1.isInitializerListOfIncompleteArray() != 3851 ICS2.isInitializerListOfIncompleteArray()) 3852 // One is incomplete, it loses 3853 return ICS2.isInitializerListOfIncompleteArray() 3854 ? ImplicitConversionSequence::Better 3855 : ImplicitConversionSequence::Worse; 3856 } 3857 } 3858 } 3859 3860 if (ICS1.isStandard()) 3861 // Standard conversion sequence S1 is a better conversion sequence than 3862 // standard conversion sequence S2 if [...] 3863 Result = CompareStandardConversionSequences(S, Loc, 3864 ICS1.Standard, ICS2.Standard); 3865 else if (ICS1.isUserDefined()) { 3866 // User-defined conversion sequence U1 is a better conversion 3867 // sequence than another user-defined conversion sequence U2 if 3868 // they contain the same user-defined conversion function or 3869 // constructor and if the second standard conversion sequence of 3870 // U1 is better than the second standard conversion sequence of 3871 // U2 (C++ 13.3.3.2p3). 3872 if (ICS1.UserDefined.ConversionFunction == 3873 ICS2.UserDefined.ConversionFunction) 3874 Result = CompareStandardConversionSequences(S, Loc, 3875 ICS1.UserDefined.After, 3876 ICS2.UserDefined.After); 3877 else 3878 Result = compareConversionFunctions(S, 3879 ICS1.UserDefined.ConversionFunction, 3880 ICS2.UserDefined.ConversionFunction); 3881 } 3882 3883 return Result; 3884 } 3885 3886 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3887 // determine if one is a proper subset of the other. 3888 static ImplicitConversionSequence::CompareKind 3889 compareStandardConversionSubsets(ASTContext &Context, 3890 const StandardConversionSequence& SCS1, 3891 const StandardConversionSequence& SCS2) { 3892 ImplicitConversionSequence::CompareKind Result 3893 = ImplicitConversionSequence::Indistinguishable; 3894 3895 // the identity conversion sequence is considered to be a subsequence of 3896 // any non-identity conversion sequence 3897 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3898 return ImplicitConversionSequence::Better; 3899 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3900 return ImplicitConversionSequence::Worse; 3901 3902 if (SCS1.Second != SCS2.Second) { 3903 if (SCS1.Second == ICK_Identity) 3904 Result = ImplicitConversionSequence::Better; 3905 else if (SCS2.Second == ICK_Identity) 3906 Result = ImplicitConversionSequence::Worse; 3907 else 3908 return ImplicitConversionSequence::Indistinguishable; 3909 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3910 return ImplicitConversionSequence::Indistinguishable; 3911 3912 if (SCS1.Third == SCS2.Third) { 3913 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3914 : ImplicitConversionSequence::Indistinguishable; 3915 } 3916 3917 if (SCS1.Third == ICK_Identity) 3918 return Result == ImplicitConversionSequence::Worse 3919 ? ImplicitConversionSequence::Indistinguishable 3920 : ImplicitConversionSequence::Better; 3921 3922 if (SCS2.Third == ICK_Identity) 3923 return Result == ImplicitConversionSequence::Better 3924 ? ImplicitConversionSequence::Indistinguishable 3925 : ImplicitConversionSequence::Worse; 3926 3927 return ImplicitConversionSequence::Indistinguishable; 3928 } 3929 3930 /// Determine whether one of the given reference bindings is better 3931 /// than the other based on what kind of bindings they are. 3932 static bool 3933 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3934 const StandardConversionSequence &SCS2) { 3935 // C++0x [over.ics.rank]p3b4: 3936 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3937 // implicit object parameter of a non-static member function declared 3938 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3939 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3940 // lvalue reference to a function lvalue and S2 binds an rvalue 3941 // reference*. 3942 // 3943 // FIXME: Rvalue references. We're going rogue with the above edits, 3944 // because the semantics in the current C++0x working paper (N3225 at the 3945 // time of this writing) break the standard definition of std::forward 3946 // and std::reference_wrapper when dealing with references to functions. 3947 // Proposed wording changes submitted to CWG for consideration. 3948 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3949 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3950 return false; 3951 3952 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3953 SCS2.IsLvalueReference) || 3954 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3955 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3956 } 3957 3958 enum class FixedEnumPromotion { 3959 None, 3960 ToUnderlyingType, 3961 ToPromotedUnderlyingType 3962 }; 3963 3964 /// Returns kind of fixed enum promotion the \a SCS uses. 3965 static FixedEnumPromotion 3966 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3967 3968 if (SCS.Second != ICK_Integral_Promotion) 3969 return FixedEnumPromotion::None; 3970 3971 QualType FromType = SCS.getFromType(); 3972 if (!FromType->isEnumeralType()) 3973 return FixedEnumPromotion::None; 3974 3975 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 3976 if (!Enum->isFixed()) 3977 return FixedEnumPromotion::None; 3978 3979 QualType UnderlyingType = Enum->getIntegerType(); 3980 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3981 return FixedEnumPromotion::ToUnderlyingType; 3982 3983 return FixedEnumPromotion::ToPromotedUnderlyingType; 3984 } 3985 3986 /// CompareStandardConversionSequences - Compare two standard 3987 /// conversion sequences to determine whether one is better than the 3988 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3989 static ImplicitConversionSequence::CompareKind 3990 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3991 const StandardConversionSequence& SCS1, 3992 const StandardConversionSequence& SCS2) 3993 { 3994 // Standard conversion sequence S1 is a better conversion sequence 3995 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3996 3997 // -- S1 is a proper subsequence of S2 (comparing the conversion 3998 // sequences in the canonical form defined by 13.3.3.1.1, 3999 // excluding any Lvalue Transformation; the identity conversion 4000 // sequence is considered to be a subsequence of any 4001 // non-identity conversion sequence) or, if not that, 4002 if (ImplicitConversionSequence::CompareKind CK 4003 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4004 return CK; 4005 4006 // -- the rank of S1 is better than the rank of S2 (by the rules 4007 // defined below), or, if not that, 4008 ImplicitConversionRank Rank1 = SCS1.getRank(); 4009 ImplicitConversionRank Rank2 = SCS2.getRank(); 4010 if (Rank1 < Rank2) 4011 return ImplicitConversionSequence::Better; 4012 else if (Rank2 < Rank1) 4013 return ImplicitConversionSequence::Worse; 4014 4015 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4016 // are indistinguishable unless one of the following rules 4017 // applies: 4018 4019 // A conversion that is not a conversion of a pointer, or 4020 // pointer to member, to bool is better than another conversion 4021 // that is such a conversion. 4022 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4023 return SCS2.isPointerConversionToBool() 4024 ? ImplicitConversionSequence::Better 4025 : ImplicitConversionSequence::Worse; 4026 4027 // C++14 [over.ics.rank]p4b2: 4028 // This is retroactively applied to C++11 by CWG 1601. 4029 // 4030 // A conversion that promotes an enumeration whose underlying type is fixed 4031 // to its underlying type is better than one that promotes to the promoted 4032 // underlying type, if the two are different. 4033 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4034 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4035 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4036 FEP1 != FEP2) 4037 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4038 ? ImplicitConversionSequence::Better 4039 : ImplicitConversionSequence::Worse; 4040 4041 // C++ [over.ics.rank]p4b2: 4042 // 4043 // If class B is derived directly or indirectly from class A, 4044 // conversion of B* to A* is better than conversion of B* to 4045 // void*, and conversion of A* to void* is better than conversion 4046 // of B* to void*. 4047 bool SCS1ConvertsToVoid 4048 = SCS1.isPointerConversionToVoidPointer(S.Context); 4049 bool SCS2ConvertsToVoid 4050 = SCS2.isPointerConversionToVoidPointer(S.Context); 4051 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4052 // Exactly one of the conversion sequences is a conversion to 4053 // a void pointer; it's the worse conversion. 4054 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4055 : ImplicitConversionSequence::Worse; 4056 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4057 // Neither conversion sequence converts to a void pointer; compare 4058 // their derived-to-base conversions. 4059 if (ImplicitConversionSequence::CompareKind DerivedCK 4060 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4061 return DerivedCK; 4062 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4063 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4064 // Both conversion sequences are conversions to void 4065 // pointers. Compare the source types to determine if there's an 4066 // inheritance relationship in their sources. 4067 QualType FromType1 = SCS1.getFromType(); 4068 QualType FromType2 = SCS2.getFromType(); 4069 4070 // Adjust the types we're converting from via the array-to-pointer 4071 // conversion, if we need to. 4072 if (SCS1.First == ICK_Array_To_Pointer) 4073 FromType1 = S.Context.getArrayDecayedType(FromType1); 4074 if (SCS2.First == ICK_Array_To_Pointer) 4075 FromType2 = S.Context.getArrayDecayedType(FromType2); 4076 4077 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4078 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4079 4080 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4081 return ImplicitConversionSequence::Better; 4082 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4083 return ImplicitConversionSequence::Worse; 4084 4085 // Objective-C++: If one interface is more specific than the 4086 // other, it is the better one. 4087 const ObjCObjectPointerType* FromObjCPtr1 4088 = FromType1->getAs<ObjCObjectPointerType>(); 4089 const ObjCObjectPointerType* FromObjCPtr2 4090 = FromType2->getAs<ObjCObjectPointerType>(); 4091 if (FromObjCPtr1 && FromObjCPtr2) { 4092 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4093 FromObjCPtr2); 4094 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4095 FromObjCPtr1); 4096 if (AssignLeft != AssignRight) { 4097 return AssignLeft? ImplicitConversionSequence::Better 4098 : ImplicitConversionSequence::Worse; 4099 } 4100 } 4101 } 4102 4103 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4104 // Check for a better reference binding based on the kind of bindings. 4105 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4106 return ImplicitConversionSequence::Better; 4107 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4108 return ImplicitConversionSequence::Worse; 4109 } 4110 4111 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4112 // bullet 3). 4113 if (ImplicitConversionSequence::CompareKind QualCK 4114 = CompareQualificationConversions(S, SCS1, SCS2)) 4115 return QualCK; 4116 4117 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4118 // C++ [over.ics.rank]p3b4: 4119 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4120 // which the references refer are the same type except for 4121 // top-level cv-qualifiers, and the type to which the reference 4122 // initialized by S2 refers is more cv-qualified than the type 4123 // to which the reference initialized by S1 refers. 4124 QualType T1 = SCS1.getToType(2); 4125 QualType T2 = SCS2.getToType(2); 4126 T1 = S.Context.getCanonicalType(T1); 4127 T2 = S.Context.getCanonicalType(T2); 4128 Qualifiers T1Quals, T2Quals; 4129 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4130 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4131 if (UnqualT1 == UnqualT2) { 4132 // Objective-C++ ARC: If the references refer to objects with different 4133 // lifetimes, prefer bindings that don't change lifetime. 4134 if (SCS1.ObjCLifetimeConversionBinding != 4135 SCS2.ObjCLifetimeConversionBinding) { 4136 return SCS1.ObjCLifetimeConversionBinding 4137 ? ImplicitConversionSequence::Worse 4138 : ImplicitConversionSequence::Better; 4139 } 4140 4141 // If the type is an array type, promote the element qualifiers to the 4142 // type for comparison. 4143 if (isa<ArrayType>(T1) && T1Quals) 4144 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4145 if (isa<ArrayType>(T2) && T2Quals) 4146 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4147 if (T2.isMoreQualifiedThan(T1)) 4148 return ImplicitConversionSequence::Better; 4149 if (T1.isMoreQualifiedThan(T2)) 4150 return ImplicitConversionSequence::Worse; 4151 } 4152 } 4153 4154 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4155 // floating-to-integral conversion if the integral conversion 4156 // is between types of the same size. 4157 // For example: 4158 // void f(float); 4159 // void f(int); 4160 // int main { 4161 // long a; 4162 // f(a); 4163 // } 4164 // Here, MSVC will call f(int) instead of generating a compile error 4165 // as clang will do in standard mode. 4166 if (S.getLangOpts().MSVCCompat && 4167 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4168 SCS1.Second == ICK_Integral_Conversion && 4169 SCS2.Second == ICK_Floating_Integral && 4170 S.Context.getTypeSize(SCS1.getFromType()) == 4171 S.Context.getTypeSize(SCS1.getToType(2))) 4172 return ImplicitConversionSequence::Better; 4173 4174 // Prefer a compatible vector conversion over a lax vector conversion 4175 // For example: 4176 // 4177 // typedef float __v4sf __attribute__((__vector_size__(16))); 4178 // void f(vector float); 4179 // void f(vector signed int); 4180 // int main() { 4181 // __v4sf a; 4182 // f(a); 4183 // } 4184 // Here, we'd like to choose f(vector float) and not 4185 // report an ambiguous call error 4186 if (SCS1.Second == ICK_Vector_Conversion && 4187 SCS2.Second == ICK_Vector_Conversion) { 4188 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4189 SCS1.getFromType(), SCS1.getToType(2)); 4190 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4191 SCS2.getFromType(), SCS2.getToType(2)); 4192 4193 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4194 return SCS1IsCompatibleVectorConversion 4195 ? ImplicitConversionSequence::Better 4196 : ImplicitConversionSequence::Worse; 4197 } 4198 4199 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4200 SCS2.Second == ICK_SVE_Vector_Conversion) { 4201 bool SCS1IsCompatibleSVEVectorConversion = 4202 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4203 bool SCS2IsCompatibleSVEVectorConversion = 4204 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4205 4206 if (SCS1IsCompatibleSVEVectorConversion != 4207 SCS2IsCompatibleSVEVectorConversion) 4208 return SCS1IsCompatibleSVEVectorConversion 4209 ? ImplicitConversionSequence::Better 4210 : ImplicitConversionSequence::Worse; 4211 } 4212 4213 return ImplicitConversionSequence::Indistinguishable; 4214 } 4215 4216 /// CompareQualificationConversions - Compares two standard conversion 4217 /// sequences to determine whether they can be ranked based on their 4218 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4219 static ImplicitConversionSequence::CompareKind 4220 CompareQualificationConversions(Sema &S, 4221 const StandardConversionSequence& SCS1, 4222 const StandardConversionSequence& SCS2) { 4223 // C++ [over.ics.rank]p3: 4224 // -- S1 and S2 differ only in their qualification conversion and 4225 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4226 // [C++98] 4227 // [...] and the cv-qualification signature of type T1 is a proper subset 4228 // of the cv-qualification signature of type T2, and S1 is not the 4229 // deprecated string literal array-to-pointer conversion (4.2). 4230 // [C++2a] 4231 // [...] where T1 can be converted to T2 by a qualification conversion. 4232 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4233 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4234 return ImplicitConversionSequence::Indistinguishable; 4235 4236 // FIXME: the example in the standard doesn't use a qualification 4237 // conversion (!) 4238 QualType T1 = SCS1.getToType(2); 4239 QualType T2 = SCS2.getToType(2); 4240 T1 = S.Context.getCanonicalType(T1); 4241 T2 = S.Context.getCanonicalType(T2); 4242 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4243 Qualifiers T1Quals, T2Quals; 4244 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4245 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4246 4247 // If the types are the same, we won't learn anything by unwrapping 4248 // them. 4249 if (UnqualT1 == UnqualT2) 4250 return ImplicitConversionSequence::Indistinguishable; 4251 4252 // Don't ever prefer a standard conversion sequence that uses the deprecated 4253 // string literal array to pointer conversion. 4254 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4255 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4256 4257 // Objective-C++ ARC: 4258 // Prefer qualification conversions not involving a change in lifetime 4259 // to qualification conversions that do change lifetime. 4260 if (SCS1.QualificationIncludesObjCLifetime && 4261 !SCS2.QualificationIncludesObjCLifetime) 4262 CanPick1 = false; 4263 if (SCS2.QualificationIncludesObjCLifetime && 4264 !SCS1.QualificationIncludesObjCLifetime) 4265 CanPick2 = false; 4266 4267 bool ObjCLifetimeConversion; 4268 if (CanPick1 && 4269 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4270 CanPick1 = false; 4271 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4272 // directions, so we can't short-cut this second check in general. 4273 if (CanPick2 && 4274 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4275 CanPick2 = false; 4276 4277 if (CanPick1 != CanPick2) 4278 return CanPick1 ? ImplicitConversionSequence::Better 4279 : ImplicitConversionSequence::Worse; 4280 return ImplicitConversionSequence::Indistinguishable; 4281 } 4282 4283 /// CompareDerivedToBaseConversions - Compares two standard conversion 4284 /// sequences to determine whether they can be ranked based on their 4285 /// various kinds of derived-to-base conversions (C++ 4286 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4287 /// conversions between Objective-C interface types. 4288 static ImplicitConversionSequence::CompareKind 4289 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4290 const StandardConversionSequence& SCS1, 4291 const StandardConversionSequence& SCS2) { 4292 QualType FromType1 = SCS1.getFromType(); 4293 QualType ToType1 = SCS1.getToType(1); 4294 QualType FromType2 = SCS2.getFromType(); 4295 QualType ToType2 = SCS2.getToType(1); 4296 4297 // Adjust the types we're converting from via the array-to-pointer 4298 // conversion, if we need to. 4299 if (SCS1.First == ICK_Array_To_Pointer) 4300 FromType1 = S.Context.getArrayDecayedType(FromType1); 4301 if (SCS2.First == ICK_Array_To_Pointer) 4302 FromType2 = S.Context.getArrayDecayedType(FromType2); 4303 4304 // Canonicalize all of the types. 4305 FromType1 = S.Context.getCanonicalType(FromType1); 4306 ToType1 = S.Context.getCanonicalType(ToType1); 4307 FromType2 = S.Context.getCanonicalType(FromType2); 4308 ToType2 = S.Context.getCanonicalType(ToType2); 4309 4310 // C++ [over.ics.rank]p4b3: 4311 // 4312 // If class B is derived directly or indirectly from class A and 4313 // class C is derived directly or indirectly from B, 4314 // 4315 // Compare based on pointer conversions. 4316 if (SCS1.Second == ICK_Pointer_Conversion && 4317 SCS2.Second == ICK_Pointer_Conversion && 4318 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4319 FromType1->isPointerType() && FromType2->isPointerType() && 4320 ToType1->isPointerType() && ToType2->isPointerType()) { 4321 QualType FromPointee1 = 4322 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4323 QualType ToPointee1 = 4324 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4325 QualType FromPointee2 = 4326 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4327 QualType ToPointee2 = 4328 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4329 4330 // -- conversion of C* to B* is better than conversion of C* to A*, 4331 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4332 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4333 return ImplicitConversionSequence::Better; 4334 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4335 return ImplicitConversionSequence::Worse; 4336 } 4337 4338 // -- conversion of B* to A* is better than conversion of C* to A*, 4339 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4340 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4341 return ImplicitConversionSequence::Better; 4342 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4343 return ImplicitConversionSequence::Worse; 4344 } 4345 } else if (SCS1.Second == ICK_Pointer_Conversion && 4346 SCS2.Second == ICK_Pointer_Conversion) { 4347 const ObjCObjectPointerType *FromPtr1 4348 = FromType1->getAs<ObjCObjectPointerType>(); 4349 const ObjCObjectPointerType *FromPtr2 4350 = FromType2->getAs<ObjCObjectPointerType>(); 4351 const ObjCObjectPointerType *ToPtr1 4352 = ToType1->getAs<ObjCObjectPointerType>(); 4353 const ObjCObjectPointerType *ToPtr2 4354 = ToType2->getAs<ObjCObjectPointerType>(); 4355 4356 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4357 // Apply the same conversion ranking rules for Objective-C pointer types 4358 // that we do for C++ pointers to class types. However, we employ the 4359 // Objective-C pseudo-subtyping relationship used for assignment of 4360 // Objective-C pointer types. 4361 bool FromAssignLeft 4362 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4363 bool FromAssignRight 4364 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4365 bool ToAssignLeft 4366 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4367 bool ToAssignRight 4368 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4369 4370 // A conversion to an a non-id object pointer type or qualified 'id' 4371 // type is better than a conversion to 'id'. 4372 if (ToPtr1->isObjCIdType() && 4373 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4374 return ImplicitConversionSequence::Worse; 4375 if (ToPtr2->isObjCIdType() && 4376 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4377 return ImplicitConversionSequence::Better; 4378 4379 // A conversion to a non-id object pointer type is better than a 4380 // conversion to a qualified 'id' type 4381 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4382 return ImplicitConversionSequence::Worse; 4383 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4384 return ImplicitConversionSequence::Better; 4385 4386 // A conversion to an a non-Class object pointer type or qualified 'Class' 4387 // type is better than a conversion to 'Class'. 4388 if (ToPtr1->isObjCClassType() && 4389 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4390 return ImplicitConversionSequence::Worse; 4391 if (ToPtr2->isObjCClassType() && 4392 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4393 return ImplicitConversionSequence::Better; 4394 4395 // A conversion to a non-Class object pointer type is better than a 4396 // conversion to a qualified 'Class' type. 4397 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4398 return ImplicitConversionSequence::Worse; 4399 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4400 return ImplicitConversionSequence::Better; 4401 4402 // -- "conversion of C* to B* is better than conversion of C* to A*," 4403 if (S.Context.hasSameType(FromType1, FromType2) && 4404 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4405 (ToAssignLeft != ToAssignRight)) { 4406 if (FromPtr1->isSpecialized()) { 4407 // "conversion of B<A> * to B * is better than conversion of B * to 4408 // C *. 4409 bool IsFirstSame = 4410 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4411 bool IsSecondSame = 4412 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4413 if (IsFirstSame) { 4414 if (!IsSecondSame) 4415 return ImplicitConversionSequence::Better; 4416 } else if (IsSecondSame) 4417 return ImplicitConversionSequence::Worse; 4418 } 4419 return ToAssignLeft? ImplicitConversionSequence::Worse 4420 : ImplicitConversionSequence::Better; 4421 } 4422 4423 // -- "conversion of B* to A* is better than conversion of C* to A*," 4424 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4425 (FromAssignLeft != FromAssignRight)) 4426 return FromAssignLeft? ImplicitConversionSequence::Better 4427 : ImplicitConversionSequence::Worse; 4428 } 4429 } 4430 4431 // Ranking of member-pointer types. 4432 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4433 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4434 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4435 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4436 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4437 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4438 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4439 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4440 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4441 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4442 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4443 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4444 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4445 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4446 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4447 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4448 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4449 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4450 return ImplicitConversionSequence::Worse; 4451 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4452 return ImplicitConversionSequence::Better; 4453 } 4454 // conversion of B::* to C::* is better than conversion of A::* to C::* 4455 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4456 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4457 return ImplicitConversionSequence::Better; 4458 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4459 return ImplicitConversionSequence::Worse; 4460 } 4461 } 4462 4463 if (SCS1.Second == ICK_Derived_To_Base) { 4464 // -- conversion of C to B is better than conversion of C to A, 4465 // -- binding of an expression of type C to a reference of type 4466 // B& is better than binding an expression of type C to a 4467 // reference of type A&, 4468 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4469 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4470 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4471 return ImplicitConversionSequence::Better; 4472 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4473 return ImplicitConversionSequence::Worse; 4474 } 4475 4476 // -- conversion of B to A is better than conversion of C to A. 4477 // -- binding of an expression of type B to a reference of type 4478 // A& is better than binding an expression of type C to a 4479 // reference of type A&, 4480 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4481 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4482 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4483 return ImplicitConversionSequence::Better; 4484 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4485 return ImplicitConversionSequence::Worse; 4486 } 4487 } 4488 4489 return ImplicitConversionSequence::Indistinguishable; 4490 } 4491 4492 /// Determine whether the given type is valid, e.g., it is not an invalid 4493 /// C++ class. 4494 static bool isTypeValid(QualType T) { 4495 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4496 return !Record->isInvalidDecl(); 4497 4498 return true; 4499 } 4500 4501 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4502 if (!T.getQualifiers().hasUnaligned()) 4503 return T; 4504 4505 Qualifiers Q; 4506 T = Ctx.getUnqualifiedArrayType(T, Q); 4507 Q.removeUnaligned(); 4508 return Ctx.getQualifiedType(T, Q); 4509 } 4510 4511 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4512 /// determine whether they are reference-compatible, 4513 /// reference-related, or incompatible, for use in C++ initialization by 4514 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4515 /// type, and the first type (T1) is the pointee type of the reference 4516 /// type being initialized. 4517 Sema::ReferenceCompareResult 4518 Sema::CompareReferenceRelationship(SourceLocation Loc, 4519 QualType OrigT1, QualType OrigT2, 4520 ReferenceConversions *ConvOut) { 4521 assert(!OrigT1->isReferenceType() && 4522 "T1 must be the pointee type of the reference type"); 4523 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4524 4525 QualType T1 = Context.getCanonicalType(OrigT1); 4526 QualType T2 = Context.getCanonicalType(OrigT2); 4527 Qualifiers T1Quals, T2Quals; 4528 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4529 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4530 4531 ReferenceConversions ConvTmp; 4532 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4533 Conv = ReferenceConversions(); 4534 4535 // C++2a [dcl.init.ref]p4: 4536 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4537 // reference-related to "cv2 T2" if T1 is similar to T2, or 4538 // T1 is a base class of T2. 4539 // "cv1 T1" is reference-compatible with "cv2 T2" if 4540 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4541 // "pointer to cv1 T1" via a standard conversion sequence. 4542 4543 // Check for standard conversions we can apply to pointers: derived-to-base 4544 // conversions, ObjC pointer conversions, and function pointer conversions. 4545 // (Qualification conversions are checked last.) 4546 QualType ConvertedT2; 4547 if (UnqualT1 == UnqualT2) { 4548 // Nothing to do. 4549 } else if (isCompleteType(Loc, OrigT2) && 4550 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4551 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4552 Conv |= ReferenceConversions::DerivedToBase; 4553 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4554 UnqualT2->isObjCObjectOrInterfaceType() && 4555 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4556 Conv |= ReferenceConversions::ObjC; 4557 else if (UnqualT2->isFunctionType() && 4558 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4559 Conv |= ReferenceConversions::Function; 4560 // No need to check qualifiers; function types don't have them. 4561 return Ref_Compatible; 4562 } 4563 bool ConvertedReferent = Conv != 0; 4564 4565 // We can have a qualification conversion. Compute whether the types are 4566 // similar at the same time. 4567 bool PreviousToQualsIncludeConst = true; 4568 bool TopLevel = true; 4569 do { 4570 if (T1 == T2) 4571 break; 4572 4573 // We will need a qualification conversion. 4574 Conv |= ReferenceConversions::Qualification; 4575 4576 // Track whether we performed a qualification conversion anywhere other 4577 // than the top level. This matters for ranking reference bindings in 4578 // overload resolution. 4579 if (!TopLevel) 4580 Conv |= ReferenceConversions::NestedQualification; 4581 4582 // MS compiler ignores __unaligned qualifier for references; do the same. 4583 T1 = withoutUnaligned(Context, T1); 4584 T2 = withoutUnaligned(Context, T2); 4585 4586 // If we find a qualifier mismatch, the types are not reference-compatible, 4587 // but are still be reference-related if they're similar. 4588 bool ObjCLifetimeConversion = false; 4589 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4590 PreviousToQualsIncludeConst, 4591 ObjCLifetimeConversion)) 4592 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4593 ? Ref_Related 4594 : Ref_Incompatible; 4595 4596 // FIXME: Should we track this for any level other than the first? 4597 if (ObjCLifetimeConversion) 4598 Conv |= ReferenceConversions::ObjCLifetime; 4599 4600 TopLevel = false; 4601 } while (Context.UnwrapSimilarTypes(T1, T2)); 4602 4603 // At this point, if the types are reference-related, we must either have the 4604 // same inner type (ignoring qualifiers), or must have already worked out how 4605 // to convert the referent. 4606 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4607 ? Ref_Compatible 4608 : Ref_Incompatible; 4609 } 4610 4611 /// Look for a user-defined conversion to a value reference-compatible 4612 /// with DeclType. Return true if something definite is found. 4613 static bool 4614 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4615 QualType DeclType, SourceLocation DeclLoc, 4616 Expr *Init, QualType T2, bool AllowRvalues, 4617 bool AllowExplicit) { 4618 assert(T2->isRecordType() && "Can only find conversions of record types."); 4619 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4620 4621 OverloadCandidateSet CandidateSet( 4622 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4623 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4624 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4625 NamedDecl *D = *I; 4626 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4627 if (isa<UsingShadowDecl>(D)) 4628 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4629 4630 FunctionTemplateDecl *ConvTemplate 4631 = dyn_cast<FunctionTemplateDecl>(D); 4632 CXXConversionDecl *Conv; 4633 if (ConvTemplate) 4634 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4635 else 4636 Conv = cast<CXXConversionDecl>(D); 4637 4638 if (AllowRvalues) { 4639 // If we are initializing an rvalue reference, don't permit conversion 4640 // functions that return lvalues. 4641 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4642 const ReferenceType *RefType 4643 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4644 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4645 continue; 4646 } 4647 4648 if (!ConvTemplate && 4649 S.CompareReferenceRelationship( 4650 DeclLoc, 4651 Conv->getConversionType() 4652 .getNonReferenceType() 4653 .getUnqualifiedType(), 4654 DeclType.getNonReferenceType().getUnqualifiedType()) == 4655 Sema::Ref_Incompatible) 4656 continue; 4657 } else { 4658 // If the conversion function doesn't return a reference type, 4659 // it can't be considered for this conversion. An rvalue reference 4660 // is only acceptable if its referencee is a function type. 4661 4662 const ReferenceType *RefType = 4663 Conv->getConversionType()->getAs<ReferenceType>(); 4664 if (!RefType || 4665 (!RefType->isLValueReferenceType() && 4666 !RefType->getPointeeType()->isFunctionType())) 4667 continue; 4668 } 4669 4670 if (ConvTemplate) 4671 S.AddTemplateConversionCandidate( 4672 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4673 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4674 else 4675 S.AddConversionCandidate( 4676 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4677 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4678 } 4679 4680 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4681 4682 OverloadCandidateSet::iterator Best; 4683 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4684 case OR_Success: 4685 // C++ [over.ics.ref]p1: 4686 // 4687 // [...] If the parameter binds directly to the result of 4688 // applying a conversion function to the argument 4689 // expression, the implicit conversion sequence is a 4690 // user-defined conversion sequence (13.3.3.1.2), with the 4691 // second standard conversion sequence either an identity 4692 // conversion or, if the conversion function returns an 4693 // entity of a type that is a derived class of the parameter 4694 // type, a derived-to-base Conversion. 4695 if (!Best->FinalConversion.DirectBinding) 4696 return false; 4697 4698 ICS.setUserDefined(); 4699 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4700 ICS.UserDefined.After = Best->FinalConversion; 4701 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4702 ICS.UserDefined.ConversionFunction = Best->Function; 4703 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4704 ICS.UserDefined.EllipsisConversion = false; 4705 assert(ICS.UserDefined.After.ReferenceBinding && 4706 ICS.UserDefined.After.DirectBinding && 4707 "Expected a direct reference binding!"); 4708 return true; 4709 4710 case OR_Ambiguous: 4711 ICS.setAmbiguous(); 4712 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4713 Cand != CandidateSet.end(); ++Cand) 4714 if (Cand->Best) 4715 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4716 return true; 4717 4718 case OR_No_Viable_Function: 4719 case OR_Deleted: 4720 // There was no suitable conversion, or we found a deleted 4721 // conversion; continue with other checks. 4722 return false; 4723 } 4724 4725 llvm_unreachable("Invalid OverloadResult!"); 4726 } 4727 4728 /// Compute an implicit conversion sequence for reference 4729 /// initialization. 4730 static ImplicitConversionSequence 4731 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4732 SourceLocation DeclLoc, 4733 bool SuppressUserConversions, 4734 bool AllowExplicit) { 4735 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4736 4737 // Most paths end in a failed conversion. 4738 ImplicitConversionSequence ICS; 4739 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4740 4741 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4742 QualType T2 = Init->getType(); 4743 4744 // If the initializer is the address of an overloaded function, try 4745 // to resolve the overloaded function. If all goes well, T2 is the 4746 // type of the resulting function. 4747 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4748 DeclAccessPair Found; 4749 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4750 false, Found)) 4751 T2 = Fn->getType(); 4752 } 4753 4754 // Compute some basic properties of the types and the initializer. 4755 bool isRValRef = DeclType->isRValueReferenceType(); 4756 Expr::Classification InitCategory = Init->Classify(S.Context); 4757 4758 Sema::ReferenceConversions RefConv; 4759 Sema::ReferenceCompareResult RefRelationship = 4760 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4761 4762 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4763 ICS.setStandard(); 4764 ICS.Standard.First = ICK_Identity; 4765 // FIXME: A reference binding can be a function conversion too. We should 4766 // consider that when ordering reference-to-function bindings. 4767 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4768 ? ICK_Derived_To_Base 4769 : (RefConv & Sema::ReferenceConversions::ObjC) 4770 ? ICK_Compatible_Conversion 4771 : ICK_Identity; 4772 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4773 // a reference binding that performs a non-top-level qualification 4774 // conversion as a qualification conversion, not as an identity conversion. 4775 ICS.Standard.Third = (RefConv & 4776 Sema::ReferenceConversions::NestedQualification) 4777 ? ICK_Qualification 4778 : ICK_Identity; 4779 ICS.Standard.setFromType(T2); 4780 ICS.Standard.setToType(0, T2); 4781 ICS.Standard.setToType(1, T1); 4782 ICS.Standard.setToType(2, T1); 4783 ICS.Standard.ReferenceBinding = true; 4784 ICS.Standard.DirectBinding = BindsDirectly; 4785 ICS.Standard.IsLvalueReference = !isRValRef; 4786 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4787 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4788 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4789 ICS.Standard.ObjCLifetimeConversionBinding = 4790 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4791 ICS.Standard.CopyConstructor = nullptr; 4792 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4793 }; 4794 4795 // C++0x [dcl.init.ref]p5: 4796 // A reference to type "cv1 T1" is initialized by an expression 4797 // of type "cv2 T2" as follows: 4798 4799 // -- If reference is an lvalue reference and the initializer expression 4800 if (!isRValRef) { 4801 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4802 // reference-compatible with "cv2 T2," or 4803 // 4804 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4805 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4806 // C++ [over.ics.ref]p1: 4807 // When a parameter of reference type binds directly (8.5.3) 4808 // to an argument expression, the implicit conversion sequence 4809 // is the identity conversion, unless the argument expression 4810 // has a type that is a derived class of the parameter type, 4811 // in which case the implicit conversion sequence is a 4812 // derived-to-base Conversion (13.3.3.1). 4813 SetAsReferenceBinding(/*BindsDirectly=*/true); 4814 4815 // Nothing more to do: the inaccessibility/ambiguity check for 4816 // derived-to-base conversions is suppressed when we're 4817 // computing the implicit conversion sequence (C++ 4818 // [over.best.ics]p2). 4819 return ICS; 4820 } 4821 4822 // -- has a class type (i.e., T2 is a class type), where T1 is 4823 // not reference-related to T2, and can be implicitly 4824 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4825 // is reference-compatible with "cv3 T3" 92) (this 4826 // conversion is selected by enumerating the applicable 4827 // conversion functions (13.3.1.6) and choosing the best 4828 // one through overload resolution (13.3)), 4829 if (!SuppressUserConversions && T2->isRecordType() && 4830 S.isCompleteType(DeclLoc, T2) && 4831 RefRelationship == Sema::Ref_Incompatible) { 4832 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4833 Init, T2, /*AllowRvalues=*/false, 4834 AllowExplicit)) 4835 return ICS; 4836 } 4837 } 4838 4839 // -- Otherwise, the reference shall be an lvalue reference to a 4840 // non-volatile const type (i.e., cv1 shall be const), or the reference 4841 // shall be an rvalue reference. 4842 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 4843 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 4844 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4845 return ICS; 4846 } 4847 4848 // -- If the initializer expression 4849 // 4850 // -- is an xvalue, class prvalue, array prvalue or function 4851 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4852 if (RefRelationship == Sema::Ref_Compatible && 4853 (InitCategory.isXValue() || 4854 (InitCategory.isPRValue() && 4855 (T2->isRecordType() || T2->isArrayType())) || 4856 (InitCategory.isLValue() && T2->isFunctionType()))) { 4857 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4858 // binding unless we're binding to a class prvalue. 4859 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4860 // allow the use of rvalue references in C++98/03 for the benefit of 4861 // standard library implementors; therefore, we need the xvalue check here. 4862 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4863 !(InitCategory.isPRValue() || T2->isRecordType())); 4864 return ICS; 4865 } 4866 4867 // -- has a class type (i.e., T2 is a class type), where T1 is not 4868 // reference-related to T2, and can be implicitly converted to 4869 // an xvalue, class prvalue, or function lvalue of type 4870 // "cv3 T3", where "cv1 T1" is reference-compatible with 4871 // "cv3 T3", 4872 // 4873 // then the reference is bound to the value of the initializer 4874 // expression in the first case and to the result of the conversion 4875 // in the second case (or, in either case, to an appropriate base 4876 // class subobject). 4877 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4878 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4879 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4880 Init, T2, /*AllowRvalues=*/true, 4881 AllowExplicit)) { 4882 // In the second case, if the reference is an rvalue reference 4883 // and the second standard conversion sequence of the 4884 // user-defined conversion sequence includes an lvalue-to-rvalue 4885 // conversion, the program is ill-formed. 4886 if (ICS.isUserDefined() && isRValRef && 4887 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4888 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4889 4890 return ICS; 4891 } 4892 4893 // A temporary of function type cannot be created; don't even try. 4894 if (T1->isFunctionType()) 4895 return ICS; 4896 4897 // -- Otherwise, a temporary of type "cv1 T1" is created and 4898 // initialized from the initializer expression using the 4899 // rules for a non-reference copy initialization (8.5). The 4900 // reference is then bound to the temporary. If T1 is 4901 // reference-related to T2, cv1 must be the same 4902 // cv-qualification as, or greater cv-qualification than, 4903 // cv2; otherwise, the program is ill-formed. 4904 if (RefRelationship == Sema::Ref_Related) { 4905 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4906 // we would be reference-compatible or reference-compatible with 4907 // added qualification. But that wasn't the case, so the reference 4908 // initialization fails. 4909 // 4910 // Note that we only want to check address spaces and cvr-qualifiers here. 4911 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4912 Qualifiers T1Quals = T1.getQualifiers(); 4913 Qualifiers T2Quals = T2.getQualifiers(); 4914 T1Quals.removeObjCGCAttr(); 4915 T1Quals.removeObjCLifetime(); 4916 T2Quals.removeObjCGCAttr(); 4917 T2Quals.removeObjCLifetime(); 4918 // MS compiler ignores __unaligned qualifier for references; do the same. 4919 T1Quals.removeUnaligned(); 4920 T2Quals.removeUnaligned(); 4921 if (!T1Quals.compatiblyIncludes(T2Quals)) 4922 return ICS; 4923 } 4924 4925 // If at least one of the types is a class type, the types are not 4926 // related, and we aren't allowed any user conversions, the 4927 // reference binding fails. This case is important for breaking 4928 // recursion, since TryImplicitConversion below will attempt to 4929 // create a temporary through the use of a copy constructor. 4930 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4931 (T1->isRecordType() || T2->isRecordType())) 4932 return ICS; 4933 4934 // If T1 is reference-related to T2 and the reference is an rvalue 4935 // reference, the initializer expression shall not be an lvalue. 4936 if (RefRelationship >= Sema::Ref_Related && isRValRef && 4937 Init->Classify(S.Context).isLValue()) { 4938 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 4939 return ICS; 4940 } 4941 4942 // C++ [over.ics.ref]p2: 4943 // When a parameter of reference type is not bound directly to 4944 // an argument expression, the conversion sequence is the one 4945 // required to convert the argument expression to the 4946 // underlying type of the reference according to 4947 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4948 // to copy-initializing a temporary of the underlying type with 4949 // the argument expression. Any difference in top-level 4950 // cv-qualification is subsumed by the initialization itself 4951 // and does not constitute a conversion. 4952 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4953 AllowedExplicit::None, 4954 /*InOverloadResolution=*/false, 4955 /*CStyle=*/false, 4956 /*AllowObjCWritebackConversion=*/false, 4957 /*AllowObjCConversionOnExplicit=*/false); 4958 4959 // Of course, that's still a reference binding. 4960 if (ICS.isStandard()) { 4961 ICS.Standard.ReferenceBinding = true; 4962 ICS.Standard.IsLvalueReference = !isRValRef; 4963 ICS.Standard.BindsToFunctionLvalue = false; 4964 ICS.Standard.BindsToRvalue = true; 4965 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4966 ICS.Standard.ObjCLifetimeConversionBinding = false; 4967 } else if (ICS.isUserDefined()) { 4968 const ReferenceType *LValRefType = 4969 ICS.UserDefined.ConversionFunction->getReturnType() 4970 ->getAs<LValueReferenceType>(); 4971 4972 // C++ [over.ics.ref]p3: 4973 // Except for an implicit object parameter, for which see 13.3.1, a 4974 // standard conversion sequence cannot be formed if it requires [...] 4975 // binding an rvalue reference to an lvalue other than a function 4976 // lvalue. 4977 // Note that the function case is not possible here. 4978 if (isRValRef && LValRefType) { 4979 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4980 return ICS; 4981 } 4982 4983 ICS.UserDefined.After.ReferenceBinding = true; 4984 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4985 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4986 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4987 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4988 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4989 } 4990 4991 return ICS; 4992 } 4993 4994 static ImplicitConversionSequence 4995 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4996 bool SuppressUserConversions, 4997 bool InOverloadResolution, 4998 bool AllowObjCWritebackConversion, 4999 bool AllowExplicit = false); 5000 5001 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5002 /// initializer list From. 5003 static ImplicitConversionSequence 5004 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5005 bool SuppressUserConversions, 5006 bool InOverloadResolution, 5007 bool AllowObjCWritebackConversion) { 5008 // C++11 [over.ics.list]p1: 5009 // When an argument is an initializer list, it is not an expression and 5010 // special rules apply for converting it to a parameter type. 5011 5012 ImplicitConversionSequence Result; 5013 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5014 5015 // We need a complete type for what follows. With one C++20 exception, 5016 // incomplete types can never be initialized from init lists. 5017 QualType InitTy = ToType; 5018 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5019 if (AT && S.getLangOpts().CPlusPlus20) 5020 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5021 // C++20 allows list initialization of an incomplete array type. 5022 InitTy = IAT->getElementType(); 5023 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5024 return Result; 5025 5026 // Per DR1467: 5027 // If the parameter type is a class X and the initializer list has a single 5028 // element of type cv U, where U is X or a class derived from X, the 5029 // implicit conversion sequence is the one required to convert the element 5030 // to the parameter type. 5031 // 5032 // Otherwise, if the parameter type is a character array [... ] 5033 // and the initializer list has a single element that is an 5034 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5035 // implicit conversion sequence is the identity conversion. 5036 if (From->getNumInits() == 1) { 5037 if (ToType->isRecordType()) { 5038 QualType InitType = From->getInit(0)->getType(); 5039 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5040 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5041 return TryCopyInitialization(S, From->getInit(0), ToType, 5042 SuppressUserConversions, 5043 InOverloadResolution, 5044 AllowObjCWritebackConversion); 5045 } 5046 5047 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5048 InitializedEntity Entity = 5049 InitializedEntity::InitializeParameter(S.Context, ToType, 5050 /*Consumed=*/false); 5051 if (S.CanPerformCopyInitialization(Entity, From)) { 5052 Result.setStandard(); 5053 Result.Standard.setAsIdentityConversion(); 5054 Result.Standard.setFromType(ToType); 5055 Result.Standard.setAllToTypes(ToType); 5056 return Result; 5057 } 5058 } 5059 } 5060 5061 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5062 // C++11 [over.ics.list]p2: 5063 // If the parameter type is std::initializer_list<X> or "array of X" and 5064 // all the elements can be implicitly converted to X, the implicit 5065 // conversion sequence is the worst conversion necessary to convert an 5066 // element of the list to X. 5067 // 5068 // C++14 [over.ics.list]p3: 5069 // Otherwise, if the parameter type is "array of N X", if the initializer 5070 // list has exactly N elements or if it has fewer than N elements and X is 5071 // default-constructible, and if all the elements of the initializer list 5072 // can be implicitly converted to X, the implicit conversion sequence is 5073 // the worst conversion necessary to convert an element of the list to X. 5074 if (AT || S.isStdInitializerList(ToType, &InitTy)) { 5075 unsigned e = From->getNumInits(); 5076 ImplicitConversionSequence DfltElt; 5077 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5078 QualType()); 5079 QualType ContTy = ToType; 5080 bool IsUnbounded = false; 5081 if (AT) { 5082 InitTy = AT->getElementType(); 5083 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5084 if (CT->getSize().ult(e)) { 5085 // Too many inits, fatally bad 5086 Result.setBad(BadConversionSequence::too_many_initializers, From, 5087 ToType); 5088 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5089 return Result; 5090 } 5091 if (CT->getSize().ugt(e)) { 5092 // Need an init from empty {}, is there one? 5093 InitListExpr EmptyList(S.Context, From->getEndLoc(), None, 5094 From->getEndLoc()); 5095 EmptyList.setType(S.Context.VoidTy); 5096 DfltElt = TryListConversion( 5097 S, &EmptyList, InitTy, SuppressUserConversions, 5098 InOverloadResolution, AllowObjCWritebackConversion); 5099 if (DfltElt.isBad()) { 5100 // No {} init, fatally bad 5101 Result.setBad(BadConversionSequence::too_few_initializers, From, 5102 ToType); 5103 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5104 return Result; 5105 } 5106 } 5107 } else { 5108 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5109 IsUnbounded = true; 5110 if (!e) { 5111 // Cannot convert to zero-sized. 5112 Result.setBad(BadConversionSequence::too_few_initializers, From, 5113 ToType); 5114 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5115 return Result; 5116 } 5117 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5118 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5119 ArrayType::Normal, 0); 5120 } 5121 } 5122 5123 Result.setStandard(); 5124 Result.Standard.setAsIdentityConversion(); 5125 Result.Standard.setFromType(InitTy); 5126 Result.Standard.setAllToTypes(InitTy); 5127 for (unsigned i = 0; i < e; ++i) { 5128 Expr *Init = From->getInit(i); 5129 ImplicitConversionSequence ICS = TryCopyInitialization( 5130 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5131 AllowObjCWritebackConversion); 5132 5133 // Keep the worse conversion seen so far. 5134 // FIXME: Sequences are not totally ordered, so 'worse' can be 5135 // ambiguous. CWG has been informed. 5136 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5137 Result) == 5138 ImplicitConversionSequence::Worse) { 5139 Result = ICS; 5140 // Bail as soon as we find something unconvertible. 5141 if (Result.isBad()) { 5142 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5143 return Result; 5144 } 5145 } 5146 } 5147 5148 // If we needed any implicit {} initialization, compare that now. 5149 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5150 // has been informed that this might not be the best thing. 5151 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5152 S, From->getEndLoc(), DfltElt, Result) == 5153 ImplicitConversionSequence::Worse) 5154 Result = DfltElt; 5155 // Record the type being initialized so that we may compare sequences 5156 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5157 return Result; 5158 } 5159 5160 // C++14 [over.ics.list]p4: 5161 // C++11 [over.ics.list]p3: 5162 // Otherwise, if the parameter is a non-aggregate class X and overload 5163 // resolution chooses a single best constructor [...] the implicit 5164 // conversion sequence is a user-defined conversion sequence. If multiple 5165 // constructors are viable but none is better than the others, the 5166 // implicit conversion sequence is a user-defined conversion sequence. 5167 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5168 // This function can deal with initializer lists. 5169 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5170 AllowedExplicit::None, 5171 InOverloadResolution, /*CStyle=*/false, 5172 AllowObjCWritebackConversion, 5173 /*AllowObjCConversionOnExplicit=*/false); 5174 } 5175 5176 // C++14 [over.ics.list]p5: 5177 // C++11 [over.ics.list]p4: 5178 // Otherwise, if the parameter has an aggregate type which can be 5179 // initialized from the initializer list [...] the implicit conversion 5180 // sequence is a user-defined conversion sequence. 5181 if (ToType->isAggregateType()) { 5182 // Type is an aggregate, argument is an init list. At this point it comes 5183 // down to checking whether the initialization works. 5184 // FIXME: Find out whether this parameter is consumed or not. 5185 InitializedEntity Entity = 5186 InitializedEntity::InitializeParameter(S.Context, ToType, 5187 /*Consumed=*/false); 5188 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5189 From)) { 5190 Result.setUserDefined(); 5191 Result.UserDefined.Before.setAsIdentityConversion(); 5192 // Initializer lists don't have a type. 5193 Result.UserDefined.Before.setFromType(QualType()); 5194 Result.UserDefined.Before.setAllToTypes(QualType()); 5195 5196 Result.UserDefined.After.setAsIdentityConversion(); 5197 Result.UserDefined.After.setFromType(ToType); 5198 Result.UserDefined.After.setAllToTypes(ToType); 5199 Result.UserDefined.ConversionFunction = nullptr; 5200 } 5201 return Result; 5202 } 5203 5204 // C++14 [over.ics.list]p6: 5205 // C++11 [over.ics.list]p5: 5206 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5207 if (ToType->isReferenceType()) { 5208 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5209 // mention initializer lists in any way. So we go by what list- 5210 // initialization would do and try to extrapolate from that. 5211 5212 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5213 5214 // If the initializer list has a single element that is reference-related 5215 // to the parameter type, we initialize the reference from that. 5216 if (From->getNumInits() == 1) { 5217 Expr *Init = From->getInit(0); 5218 5219 QualType T2 = Init->getType(); 5220 5221 // If the initializer is the address of an overloaded function, try 5222 // to resolve the overloaded function. If all goes well, T2 is the 5223 // type of the resulting function. 5224 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5225 DeclAccessPair Found; 5226 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5227 Init, ToType, false, Found)) 5228 T2 = Fn->getType(); 5229 } 5230 5231 // Compute some basic properties of the types and the initializer. 5232 Sema::ReferenceCompareResult RefRelationship = 5233 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5234 5235 if (RefRelationship >= Sema::Ref_Related) { 5236 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5237 SuppressUserConversions, 5238 /*AllowExplicit=*/false); 5239 } 5240 } 5241 5242 // Otherwise, we bind the reference to a temporary created from the 5243 // initializer list. 5244 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5245 InOverloadResolution, 5246 AllowObjCWritebackConversion); 5247 if (Result.isFailure()) 5248 return Result; 5249 assert(!Result.isEllipsis() && 5250 "Sub-initialization cannot result in ellipsis conversion."); 5251 5252 // Can we even bind to a temporary? 5253 if (ToType->isRValueReferenceType() || 5254 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5255 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5256 Result.UserDefined.After; 5257 SCS.ReferenceBinding = true; 5258 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5259 SCS.BindsToRvalue = true; 5260 SCS.BindsToFunctionLvalue = false; 5261 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5262 SCS.ObjCLifetimeConversionBinding = false; 5263 } else 5264 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5265 From, ToType); 5266 return Result; 5267 } 5268 5269 // C++14 [over.ics.list]p7: 5270 // C++11 [over.ics.list]p6: 5271 // Otherwise, if the parameter type is not a class: 5272 if (!ToType->isRecordType()) { 5273 // - if the initializer list has one element that is not itself an 5274 // initializer list, the implicit conversion sequence is the one 5275 // required to convert the element to the parameter type. 5276 unsigned NumInits = From->getNumInits(); 5277 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5278 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5279 SuppressUserConversions, 5280 InOverloadResolution, 5281 AllowObjCWritebackConversion); 5282 // - if the initializer list has no elements, the implicit conversion 5283 // sequence is the identity conversion. 5284 else if (NumInits == 0) { 5285 Result.setStandard(); 5286 Result.Standard.setAsIdentityConversion(); 5287 Result.Standard.setFromType(ToType); 5288 Result.Standard.setAllToTypes(ToType); 5289 } 5290 return Result; 5291 } 5292 5293 // C++14 [over.ics.list]p8: 5294 // C++11 [over.ics.list]p7: 5295 // In all cases other than those enumerated above, no conversion is possible 5296 return Result; 5297 } 5298 5299 /// TryCopyInitialization - Try to copy-initialize a value of type 5300 /// ToType from the expression From. Return the implicit conversion 5301 /// sequence required to pass this argument, which may be a bad 5302 /// conversion sequence (meaning that the argument cannot be passed to 5303 /// a parameter of this type). If @p SuppressUserConversions, then we 5304 /// do not permit any user-defined conversion sequences. 5305 static ImplicitConversionSequence 5306 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5307 bool SuppressUserConversions, 5308 bool InOverloadResolution, 5309 bool AllowObjCWritebackConversion, 5310 bool AllowExplicit) { 5311 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5312 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5313 InOverloadResolution,AllowObjCWritebackConversion); 5314 5315 if (ToType->isReferenceType()) 5316 return TryReferenceInit(S, From, ToType, 5317 /*FIXME:*/ From->getBeginLoc(), 5318 SuppressUserConversions, AllowExplicit); 5319 5320 return TryImplicitConversion(S, From, ToType, 5321 SuppressUserConversions, 5322 AllowedExplicit::None, 5323 InOverloadResolution, 5324 /*CStyle=*/false, 5325 AllowObjCWritebackConversion, 5326 /*AllowObjCConversionOnExplicit=*/false); 5327 } 5328 5329 static bool TryCopyInitialization(const CanQualType FromQTy, 5330 const CanQualType ToQTy, 5331 Sema &S, 5332 SourceLocation Loc, 5333 ExprValueKind FromVK) { 5334 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5335 ImplicitConversionSequence ICS = 5336 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5337 5338 return !ICS.isBad(); 5339 } 5340 5341 /// TryObjectArgumentInitialization - Try to initialize the object 5342 /// parameter of the given member function (@c Method) from the 5343 /// expression @p From. 5344 static ImplicitConversionSequence 5345 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5346 Expr::Classification FromClassification, 5347 CXXMethodDecl *Method, 5348 CXXRecordDecl *ActingContext) { 5349 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5350 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5351 // const volatile object. 5352 Qualifiers Quals = Method->getMethodQualifiers(); 5353 if (isa<CXXDestructorDecl>(Method)) { 5354 Quals.addConst(); 5355 Quals.addVolatile(); 5356 } 5357 5358 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5359 5360 // Set up the conversion sequence as a "bad" conversion, to allow us 5361 // to exit early. 5362 ImplicitConversionSequence ICS; 5363 5364 // We need to have an object of class type. 5365 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5366 FromType = PT->getPointeeType(); 5367 5368 // When we had a pointer, it's implicitly dereferenced, so we 5369 // better have an lvalue. 5370 assert(FromClassification.isLValue()); 5371 } 5372 5373 assert(FromType->isRecordType()); 5374 5375 // C++0x [over.match.funcs]p4: 5376 // For non-static member functions, the type of the implicit object 5377 // parameter is 5378 // 5379 // - "lvalue reference to cv X" for functions declared without a 5380 // ref-qualifier or with the & ref-qualifier 5381 // - "rvalue reference to cv X" for functions declared with the && 5382 // ref-qualifier 5383 // 5384 // where X is the class of which the function is a member and cv is the 5385 // cv-qualification on the member function declaration. 5386 // 5387 // However, when finding an implicit conversion sequence for the argument, we 5388 // are not allowed to perform user-defined conversions 5389 // (C++ [over.match.funcs]p5). We perform a simplified version of 5390 // reference binding here, that allows class rvalues to bind to 5391 // non-constant references. 5392 5393 // First check the qualifiers. 5394 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5395 if (ImplicitParamType.getCVRQualifiers() 5396 != FromTypeCanon.getLocalCVRQualifiers() && 5397 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5398 ICS.setBad(BadConversionSequence::bad_qualifiers, 5399 FromType, ImplicitParamType); 5400 return ICS; 5401 } 5402 5403 if (FromTypeCanon.hasAddressSpace()) { 5404 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5405 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5406 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5407 ICS.setBad(BadConversionSequence::bad_qualifiers, 5408 FromType, ImplicitParamType); 5409 return ICS; 5410 } 5411 } 5412 5413 // Check that we have either the same type or a derived type. It 5414 // affects the conversion rank. 5415 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5416 ImplicitConversionKind SecondKind; 5417 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5418 SecondKind = ICK_Identity; 5419 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5420 SecondKind = ICK_Derived_To_Base; 5421 else { 5422 ICS.setBad(BadConversionSequence::unrelated_class, 5423 FromType, ImplicitParamType); 5424 return ICS; 5425 } 5426 5427 // Check the ref-qualifier. 5428 switch (Method->getRefQualifier()) { 5429 case RQ_None: 5430 // Do nothing; we don't care about lvalueness or rvalueness. 5431 break; 5432 5433 case RQ_LValue: 5434 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5435 // non-const lvalue reference cannot bind to an rvalue 5436 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5437 ImplicitParamType); 5438 return ICS; 5439 } 5440 break; 5441 5442 case RQ_RValue: 5443 if (!FromClassification.isRValue()) { 5444 // rvalue reference cannot bind to an lvalue 5445 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5446 ImplicitParamType); 5447 return ICS; 5448 } 5449 break; 5450 } 5451 5452 // Success. Mark this as a reference binding. 5453 ICS.setStandard(); 5454 ICS.Standard.setAsIdentityConversion(); 5455 ICS.Standard.Second = SecondKind; 5456 ICS.Standard.setFromType(FromType); 5457 ICS.Standard.setAllToTypes(ImplicitParamType); 5458 ICS.Standard.ReferenceBinding = true; 5459 ICS.Standard.DirectBinding = true; 5460 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5461 ICS.Standard.BindsToFunctionLvalue = false; 5462 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5463 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5464 = (Method->getRefQualifier() == RQ_None); 5465 return ICS; 5466 } 5467 5468 /// PerformObjectArgumentInitialization - Perform initialization of 5469 /// the implicit object parameter for the given Method with the given 5470 /// expression. 5471 ExprResult 5472 Sema::PerformObjectArgumentInitialization(Expr *From, 5473 NestedNameSpecifier *Qualifier, 5474 NamedDecl *FoundDecl, 5475 CXXMethodDecl *Method) { 5476 QualType FromRecordType, DestType; 5477 QualType ImplicitParamRecordType = 5478 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5479 5480 Expr::Classification FromClassification; 5481 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5482 FromRecordType = PT->getPointeeType(); 5483 DestType = Method->getThisType(); 5484 FromClassification = Expr::Classification::makeSimpleLValue(); 5485 } else { 5486 FromRecordType = From->getType(); 5487 DestType = ImplicitParamRecordType; 5488 FromClassification = From->Classify(Context); 5489 5490 // When performing member access on a prvalue, materialize a temporary. 5491 if (From->isPRValue()) { 5492 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5493 Method->getRefQualifier() != 5494 RefQualifierKind::RQ_RValue); 5495 } 5496 } 5497 5498 // Note that we always use the true parent context when performing 5499 // the actual argument initialization. 5500 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5501 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5502 Method->getParent()); 5503 if (ICS.isBad()) { 5504 switch (ICS.Bad.Kind) { 5505 case BadConversionSequence::bad_qualifiers: { 5506 Qualifiers FromQs = FromRecordType.getQualifiers(); 5507 Qualifiers ToQs = DestType.getQualifiers(); 5508 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5509 if (CVR) { 5510 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5511 << Method->getDeclName() << FromRecordType << (CVR - 1) 5512 << From->getSourceRange(); 5513 Diag(Method->getLocation(), diag::note_previous_decl) 5514 << Method->getDeclName(); 5515 return ExprError(); 5516 } 5517 break; 5518 } 5519 5520 case BadConversionSequence::lvalue_ref_to_rvalue: 5521 case BadConversionSequence::rvalue_ref_to_lvalue: { 5522 bool IsRValueQualified = 5523 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5524 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5525 << Method->getDeclName() << FromClassification.isRValue() 5526 << IsRValueQualified; 5527 Diag(Method->getLocation(), diag::note_previous_decl) 5528 << Method->getDeclName(); 5529 return ExprError(); 5530 } 5531 5532 case BadConversionSequence::no_conversion: 5533 case BadConversionSequence::unrelated_class: 5534 break; 5535 5536 case BadConversionSequence::too_few_initializers: 5537 case BadConversionSequence::too_many_initializers: 5538 llvm_unreachable("Lists are not objects"); 5539 } 5540 5541 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5542 << ImplicitParamRecordType << FromRecordType 5543 << From->getSourceRange(); 5544 } 5545 5546 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5547 ExprResult FromRes = 5548 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5549 if (FromRes.isInvalid()) 5550 return ExprError(); 5551 From = FromRes.get(); 5552 } 5553 5554 if (!Context.hasSameType(From->getType(), DestType)) { 5555 CastKind CK; 5556 QualType PteeTy = DestType->getPointeeType(); 5557 LangAS DestAS = 5558 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5559 if (FromRecordType.getAddressSpace() != DestAS) 5560 CK = CK_AddressSpaceConversion; 5561 else 5562 CK = CK_NoOp; 5563 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5564 } 5565 return From; 5566 } 5567 5568 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5569 /// expression From to bool (C++0x [conv]p3). 5570 static ImplicitConversionSequence 5571 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5572 // C++ [dcl.init]/17.8: 5573 // - Otherwise, if the initialization is direct-initialization, the source 5574 // type is std::nullptr_t, and the destination type is bool, the initial 5575 // value of the object being initialized is false. 5576 if (From->getType()->isNullPtrType()) 5577 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5578 S.Context.BoolTy, 5579 From->isGLValue()); 5580 5581 // All other direct-initialization of bool is equivalent to an implicit 5582 // conversion to bool in which explicit conversions are permitted. 5583 return TryImplicitConversion(S, From, S.Context.BoolTy, 5584 /*SuppressUserConversions=*/false, 5585 AllowedExplicit::Conversions, 5586 /*InOverloadResolution=*/false, 5587 /*CStyle=*/false, 5588 /*AllowObjCWritebackConversion=*/false, 5589 /*AllowObjCConversionOnExplicit=*/false); 5590 } 5591 5592 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5593 /// of the expression From to bool (C++0x [conv]p3). 5594 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5595 if (checkPlaceholderForOverload(*this, From)) 5596 return ExprError(); 5597 5598 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5599 if (!ICS.isBad()) 5600 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5601 5602 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5603 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5604 << From->getType() << From->getSourceRange(); 5605 return ExprError(); 5606 } 5607 5608 /// Check that the specified conversion is permitted in a converted constant 5609 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5610 /// is acceptable. 5611 static bool CheckConvertedConstantConversions(Sema &S, 5612 StandardConversionSequence &SCS) { 5613 // Since we know that the target type is an integral or unscoped enumeration 5614 // type, most conversion kinds are impossible. All possible First and Third 5615 // conversions are fine. 5616 switch (SCS.Second) { 5617 case ICK_Identity: 5618 case ICK_Integral_Promotion: 5619 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5620 case ICK_Zero_Queue_Conversion: 5621 return true; 5622 5623 case ICK_Boolean_Conversion: 5624 // Conversion from an integral or unscoped enumeration type to bool is 5625 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5626 // conversion, so we allow it in a converted constant expression. 5627 // 5628 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5629 // a lot of popular code. We should at least add a warning for this 5630 // (non-conforming) extension. 5631 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5632 SCS.getToType(2)->isBooleanType(); 5633 5634 case ICK_Pointer_Conversion: 5635 case ICK_Pointer_Member: 5636 // C++1z: null pointer conversions and null member pointer conversions are 5637 // only permitted if the source type is std::nullptr_t. 5638 return SCS.getFromType()->isNullPtrType(); 5639 5640 case ICK_Floating_Promotion: 5641 case ICK_Complex_Promotion: 5642 case ICK_Floating_Conversion: 5643 case ICK_Complex_Conversion: 5644 case ICK_Floating_Integral: 5645 case ICK_Compatible_Conversion: 5646 case ICK_Derived_To_Base: 5647 case ICK_Vector_Conversion: 5648 case ICK_SVE_Vector_Conversion: 5649 case ICK_Vector_Splat: 5650 case ICK_Complex_Real: 5651 case ICK_Block_Pointer_Conversion: 5652 case ICK_TransparentUnionConversion: 5653 case ICK_Writeback_Conversion: 5654 case ICK_Zero_Event_Conversion: 5655 case ICK_C_Only_Conversion: 5656 case ICK_Incompatible_Pointer_Conversion: 5657 return false; 5658 5659 case ICK_Lvalue_To_Rvalue: 5660 case ICK_Array_To_Pointer: 5661 case ICK_Function_To_Pointer: 5662 llvm_unreachable("found a first conversion kind in Second"); 5663 5664 case ICK_Function_Conversion: 5665 case ICK_Qualification: 5666 llvm_unreachable("found a third conversion kind in Second"); 5667 5668 case ICK_Num_Conversion_Kinds: 5669 break; 5670 } 5671 5672 llvm_unreachable("unknown conversion kind"); 5673 } 5674 5675 /// CheckConvertedConstantExpression - Check that the expression From is a 5676 /// converted constant expression of type T, perform the conversion and produce 5677 /// the converted expression, per C++11 [expr.const]p3. 5678 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5679 QualType T, APValue &Value, 5680 Sema::CCEKind CCE, 5681 bool RequireInt, 5682 NamedDecl *Dest) { 5683 assert(S.getLangOpts().CPlusPlus11 && 5684 "converted constant expression outside C++11"); 5685 5686 if (checkPlaceholderForOverload(S, From)) 5687 return ExprError(); 5688 5689 // C++1z [expr.const]p3: 5690 // A converted constant expression of type T is an expression, 5691 // implicitly converted to type T, where the converted 5692 // expression is a constant expression and the implicit conversion 5693 // sequence contains only [... list of conversions ...]. 5694 ImplicitConversionSequence ICS = 5695 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 5696 ? TryContextuallyConvertToBool(S, From) 5697 : TryCopyInitialization(S, From, T, 5698 /*SuppressUserConversions=*/false, 5699 /*InOverloadResolution=*/false, 5700 /*AllowObjCWritebackConversion=*/false, 5701 /*AllowExplicit=*/false); 5702 StandardConversionSequence *SCS = nullptr; 5703 switch (ICS.getKind()) { 5704 case ImplicitConversionSequence::StandardConversion: 5705 SCS = &ICS.Standard; 5706 break; 5707 case ImplicitConversionSequence::UserDefinedConversion: 5708 if (T->isRecordType()) 5709 SCS = &ICS.UserDefined.Before; 5710 else 5711 SCS = &ICS.UserDefined.After; 5712 break; 5713 case ImplicitConversionSequence::AmbiguousConversion: 5714 case ImplicitConversionSequence::BadConversion: 5715 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5716 return S.Diag(From->getBeginLoc(), 5717 diag::err_typecheck_converted_constant_expression) 5718 << From->getType() << From->getSourceRange() << T; 5719 return ExprError(); 5720 5721 case ImplicitConversionSequence::EllipsisConversion: 5722 llvm_unreachable("ellipsis conversion in converted constant expression"); 5723 } 5724 5725 // Check that we would only use permitted conversions. 5726 if (!CheckConvertedConstantConversions(S, *SCS)) { 5727 return S.Diag(From->getBeginLoc(), 5728 diag::err_typecheck_converted_constant_expression_disallowed) 5729 << From->getType() << From->getSourceRange() << T; 5730 } 5731 // [...] and where the reference binding (if any) binds directly. 5732 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5733 return S.Diag(From->getBeginLoc(), 5734 diag::err_typecheck_converted_constant_expression_indirect) 5735 << From->getType() << From->getSourceRange() << T; 5736 } 5737 5738 // Usually we can simply apply the ImplicitConversionSequence we formed 5739 // earlier, but that's not guaranteed to work when initializing an object of 5740 // class type. 5741 ExprResult Result; 5742 if (T->isRecordType()) { 5743 assert(CCE == Sema::CCEK_TemplateArg && 5744 "unexpected class type converted constant expr"); 5745 Result = S.PerformCopyInitialization( 5746 InitializedEntity::InitializeTemplateParameter( 5747 T, cast<NonTypeTemplateParmDecl>(Dest)), 5748 SourceLocation(), From); 5749 } else { 5750 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5751 } 5752 if (Result.isInvalid()) 5753 return Result; 5754 5755 // C++2a [intro.execution]p5: 5756 // A full-expression is [...] a constant-expression [...] 5757 Result = 5758 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5759 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5760 if (Result.isInvalid()) 5761 return Result; 5762 5763 // Check for a narrowing implicit conversion. 5764 bool ReturnPreNarrowingValue = false; 5765 APValue PreNarrowingValue; 5766 QualType PreNarrowingType; 5767 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5768 PreNarrowingType)) { 5769 case NK_Dependent_Narrowing: 5770 // Implicit conversion to a narrower type, but the expression is 5771 // value-dependent so we can't tell whether it's actually narrowing. 5772 case NK_Variable_Narrowing: 5773 // Implicit conversion to a narrower type, and the value is not a constant 5774 // expression. We'll diagnose this in a moment. 5775 case NK_Not_Narrowing: 5776 break; 5777 5778 case NK_Constant_Narrowing: 5779 if (CCE == Sema::CCEK_ArrayBound && 5780 PreNarrowingType->isIntegralOrEnumerationType() && 5781 PreNarrowingValue.isInt()) { 5782 // Don't diagnose array bound narrowing here; we produce more precise 5783 // errors by allowing the un-narrowed value through. 5784 ReturnPreNarrowingValue = true; 5785 break; 5786 } 5787 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5788 << CCE << /*Constant*/ 1 5789 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5790 break; 5791 5792 case NK_Type_Narrowing: 5793 // FIXME: It would be better to diagnose that the expression is not a 5794 // constant expression. 5795 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5796 << CCE << /*Constant*/ 0 << From->getType() << T; 5797 break; 5798 } 5799 5800 if (Result.get()->isValueDependent()) { 5801 Value = APValue(); 5802 return Result; 5803 } 5804 5805 // Check the expression is a constant expression. 5806 SmallVector<PartialDiagnosticAt, 8> Notes; 5807 Expr::EvalResult Eval; 5808 Eval.Diag = &Notes; 5809 5810 ConstantExprKind Kind; 5811 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 5812 Kind = ConstantExprKind::ClassTemplateArgument; 5813 else if (CCE == Sema::CCEK_TemplateArg) 5814 Kind = ConstantExprKind::NonClassTemplateArgument; 5815 else 5816 Kind = ConstantExprKind::Normal; 5817 5818 if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) || 5819 (RequireInt && !Eval.Val.isInt())) { 5820 // The expression can't be folded, so we can't keep it at this position in 5821 // the AST. 5822 Result = ExprError(); 5823 } else { 5824 Value = Eval.Val; 5825 5826 if (Notes.empty()) { 5827 // It's a constant expression. 5828 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5829 if (ReturnPreNarrowingValue) 5830 Value = std::move(PreNarrowingValue); 5831 return E; 5832 } 5833 } 5834 5835 // It's not a constant expression. Produce an appropriate diagnostic. 5836 if (Notes.size() == 1 && 5837 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 5838 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5839 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 5840 diag::note_constexpr_invalid_template_arg) { 5841 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 5842 for (unsigned I = 0; I < Notes.size(); ++I) 5843 S.Diag(Notes[I].first, Notes[I].second); 5844 } else { 5845 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5846 << CCE << From->getSourceRange(); 5847 for (unsigned I = 0; I < Notes.size(); ++I) 5848 S.Diag(Notes[I].first, Notes[I].second); 5849 } 5850 return ExprError(); 5851 } 5852 5853 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5854 APValue &Value, CCEKind CCE, 5855 NamedDecl *Dest) { 5856 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 5857 Dest); 5858 } 5859 5860 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5861 llvm::APSInt &Value, 5862 CCEKind CCE) { 5863 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5864 5865 APValue V; 5866 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 5867 /*Dest=*/nullptr); 5868 if (!R.isInvalid() && !R.get()->isValueDependent()) 5869 Value = V.getInt(); 5870 return R; 5871 } 5872 5873 5874 /// dropPointerConversions - If the given standard conversion sequence 5875 /// involves any pointer conversions, remove them. This may change 5876 /// the result type of the conversion sequence. 5877 static void dropPointerConversion(StandardConversionSequence &SCS) { 5878 if (SCS.Second == ICK_Pointer_Conversion) { 5879 SCS.Second = ICK_Identity; 5880 SCS.Third = ICK_Identity; 5881 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5882 } 5883 } 5884 5885 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5886 /// convert the expression From to an Objective-C pointer type. 5887 static ImplicitConversionSequence 5888 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5889 // Do an implicit conversion to 'id'. 5890 QualType Ty = S.Context.getObjCIdType(); 5891 ImplicitConversionSequence ICS 5892 = TryImplicitConversion(S, From, Ty, 5893 // FIXME: Are these flags correct? 5894 /*SuppressUserConversions=*/false, 5895 AllowedExplicit::Conversions, 5896 /*InOverloadResolution=*/false, 5897 /*CStyle=*/false, 5898 /*AllowObjCWritebackConversion=*/false, 5899 /*AllowObjCConversionOnExplicit=*/true); 5900 5901 // Strip off any final conversions to 'id'. 5902 switch (ICS.getKind()) { 5903 case ImplicitConversionSequence::BadConversion: 5904 case ImplicitConversionSequence::AmbiguousConversion: 5905 case ImplicitConversionSequence::EllipsisConversion: 5906 break; 5907 5908 case ImplicitConversionSequence::UserDefinedConversion: 5909 dropPointerConversion(ICS.UserDefined.After); 5910 break; 5911 5912 case ImplicitConversionSequence::StandardConversion: 5913 dropPointerConversion(ICS.Standard); 5914 break; 5915 } 5916 5917 return ICS; 5918 } 5919 5920 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5921 /// conversion of the expression From to an Objective-C pointer type. 5922 /// Returns a valid but null ExprResult if no conversion sequence exists. 5923 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5924 if (checkPlaceholderForOverload(*this, From)) 5925 return ExprError(); 5926 5927 QualType Ty = Context.getObjCIdType(); 5928 ImplicitConversionSequence ICS = 5929 TryContextuallyConvertToObjCPointer(*this, From); 5930 if (!ICS.isBad()) 5931 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5932 return ExprResult(); 5933 } 5934 5935 /// Determine whether the provided type is an integral type, or an enumeration 5936 /// type of a permitted flavor. 5937 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5938 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5939 : T->isIntegralOrUnscopedEnumerationType(); 5940 } 5941 5942 static ExprResult 5943 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5944 Sema::ContextualImplicitConverter &Converter, 5945 QualType T, UnresolvedSetImpl &ViableConversions) { 5946 5947 if (Converter.Suppress) 5948 return ExprError(); 5949 5950 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5951 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5952 CXXConversionDecl *Conv = 5953 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5954 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5955 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5956 } 5957 return From; 5958 } 5959 5960 static bool 5961 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5962 Sema::ContextualImplicitConverter &Converter, 5963 QualType T, bool HadMultipleCandidates, 5964 UnresolvedSetImpl &ExplicitConversions) { 5965 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5966 DeclAccessPair Found = ExplicitConversions[0]; 5967 CXXConversionDecl *Conversion = 5968 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5969 5970 // The user probably meant to invoke the given explicit 5971 // conversion; use it. 5972 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5973 std::string TypeStr; 5974 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5975 5976 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5977 << FixItHint::CreateInsertion(From->getBeginLoc(), 5978 "static_cast<" + TypeStr + ">(") 5979 << FixItHint::CreateInsertion( 5980 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5981 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5982 5983 // If we aren't in a SFINAE context, build a call to the 5984 // explicit conversion function. 5985 if (SemaRef.isSFINAEContext()) 5986 return true; 5987 5988 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5989 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5990 HadMultipleCandidates); 5991 if (Result.isInvalid()) 5992 return true; 5993 // Record usage of conversion in an implicit cast. 5994 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5995 CK_UserDefinedConversion, Result.get(), 5996 nullptr, Result.get()->getValueKind(), 5997 SemaRef.CurFPFeatureOverrides()); 5998 } 5999 return false; 6000 } 6001 6002 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6003 Sema::ContextualImplicitConverter &Converter, 6004 QualType T, bool HadMultipleCandidates, 6005 DeclAccessPair &Found) { 6006 CXXConversionDecl *Conversion = 6007 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6008 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6009 6010 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6011 if (!Converter.SuppressConversion) { 6012 if (SemaRef.isSFINAEContext()) 6013 return true; 6014 6015 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6016 << From->getSourceRange(); 6017 } 6018 6019 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6020 HadMultipleCandidates); 6021 if (Result.isInvalid()) 6022 return true; 6023 // Record usage of conversion in an implicit cast. 6024 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6025 CK_UserDefinedConversion, Result.get(), 6026 nullptr, Result.get()->getValueKind(), 6027 SemaRef.CurFPFeatureOverrides()); 6028 return false; 6029 } 6030 6031 static ExprResult finishContextualImplicitConversion( 6032 Sema &SemaRef, SourceLocation Loc, Expr *From, 6033 Sema::ContextualImplicitConverter &Converter) { 6034 if (!Converter.match(From->getType()) && !Converter.Suppress) 6035 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6036 << From->getSourceRange(); 6037 6038 return SemaRef.DefaultLvalueConversion(From); 6039 } 6040 6041 static void 6042 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6043 UnresolvedSetImpl &ViableConversions, 6044 OverloadCandidateSet &CandidateSet) { 6045 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6046 DeclAccessPair FoundDecl = ViableConversions[I]; 6047 NamedDecl *D = FoundDecl.getDecl(); 6048 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6049 if (isa<UsingShadowDecl>(D)) 6050 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6051 6052 CXXConversionDecl *Conv; 6053 FunctionTemplateDecl *ConvTemplate; 6054 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6055 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6056 else 6057 Conv = cast<CXXConversionDecl>(D); 6058 6059 if (ConvTemplate) 6060 SemaRef.AddTemplateConversionCandidate( 6061 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6062 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6063 else 6064 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6065 ToType, CandidateSet, 6066 /*AllowObjCConversionOnExplicit=*/false, 6067 /*AllowExplicit*/ true); 6068 } 6069 } 6070 6071 /// Attempt to convert the given expression to a type which is accepted 6072 /// by the given converter. 6073 /// 6074 /// This routine will attempt to convert an expression of class type to a 6075 /// type accepted by the specified converter. In C++11 and before, the class 6076 /// must have a single non-explicit conversion function converting to a matching 6077 /// type. In C++1y, there can be multiple such conversion functions, but only 6078 /// one target type. 6079 /// 6080 /// \param Loc The source location of the construct that requires the 6081 /// conversion. 6082 /// 6083 /// \param From The expression we're converting from. 6084 /// 6085 /// \param Converter Used to control and diagnose the conversion process. 6086 /// 6087 /// \returns The expression, converted to an integral or enumeration type if 6088 /// successful. 6089 ExprResult Sema::PerformContextualImplicitConversion( 6090 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6091 // We can't perform any more checking for type-dependent expressions. 6092 if (From->isTypeDependent()) 6093 return From; 6094 6095 // Process placeholders immediately. 6096 if (From->hasPlaceholderType()) { 6097 ExprResult result = CheckPlaceholderExpr(From); 6098 if (result.isInvalid()) 6099 return result; 6100 From = result.get(); 6101 } 6102 6103 // If the expression already has a matching type, we're golden. 6104 QualType T = From->getType(); 6105 if (Converter.match(T)) 6106 return DefaultLvalueConversion(From); 6107 6108 // FIXME: Check for missing '()' if T is a function type? 6109 6110 // We can only perform contextual implicit conversions on objects of class 6111 // type. 6112 const RecordType *RecordTy = T->getAs<RecordType>(); 6113 if (!RecordTy || !getLangOpts().CPlusPlus) { 6114 if (!Converter.Suppress) 6115 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6116 return From; 6117 } 6118 6119 // We must have a complete class type. 6120 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6121 ContextualImplicitConverter &Converter; 6122 Expr *From; 6123 6124 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6125 : Converter(Converter), From(From) {} 6126 6127 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6128 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6129 } 6130 } IncompleteDiagnoser(Converter, From); 6131 6132 if (Converter.Suppress ? !isCompleteType(Loc, T) 6133 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6134 return From; 6135 6136 // Look for a conversion to an integral or enumeration type. 6137 UnresolvedSet<4> 6138 ViableConversions; // These are *potentially* viable in C++1y. 6139 UnresolvedSet<4> ExplicitConversions; 6140 const auto &Conversions = 6141 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6142 6143 bool HadMultipleCandidates = 6144 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6145 6146 // To check that there is only one target type, in C++1y: 6147 QualType ToType; 6148 bool HasUniqueTargetType = true; 6149 6150 // Collect explicit or viable (potentially in C++1y) conversions. 6151 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6152 NamedDecl *D = (*I)->getUnderlyingDecl(); 6153 CXXConversionDecl *Conversion; 6154 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6155 if (ConvTemplate) { 6156 if (getLangOpts().CPlusPlus14) 6157 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6158 else 6159 continue; // C++11 does not consider conversion operator templates(?). 6160 } else 6161 Conversion = cast<CXXConversionDecl>(D); 6162 6163 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6164 "Conversion operator templates are considered potentially " 6165 "viable in C++1y"); 6166 6167 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6168 if (Converter.match(CurToType) || ConvTemplate) { 6169 6170 if (Conversion->isExplicit()) { 6171 // FIXME: For C++1y, do we need this restriction? 6172 // cf. diagnoseNoViableConversion() 6173 if (!ConvTemplate) 6174 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6175 } else { 6176 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6177 if (ToType.isNull()) 6178 ToType = CurToType.getUnqualifiedType(); 6179 else if (HasUniqueTargetType && 6180 (CurToType.getUnqualifiedType() != ToType)) 6181 HasUniqueTargetType = false; 6182 } 6183 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6184 } 6185 } 6186 } 6187 6188 if (getLangOpts().CPlusPlus14) { 6189 // C++1y [conv]p6: 6190 // ... An expression e of class type E appearing in such a context 6191 // is said to be contextually implicitly converted to a specified 6192 // type T and is well-formed if and only if e can be implicitly 6193 // converted to a type T that is determined as follows: E is searched 6194 // for conversion functions whose return type is cv T or reference to 6195 // cv T such that T is allowed by the context. There shall be 6196 // exactly one such T. 6197 6198 // If no unique T is found: 6199 if (ToType.isNull()) { 6200 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6201 HadMultipleCandidates, 6202 ExplicitConversions)) 6203 return ExprError(); 6204 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6205 } 6206 6207 // If more than one unique Ts are found: 6208 if (!HasUniqueTargetType) 6209 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6210 ViableConversions); 6211 6212 // If one unique T is found: 6213 // First, build a candidate set from the previously recorded 6214 // potentially viable conversions. 6215 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6216 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6217 CandidateSet); 6218 6219 // Then, perform overload resolution over the candidate set. 6220 OverloadCandidateSet::iterator Best; 6221 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6222 case OR_Success: { 6223 // Apply this conversion. 6224 DeclAccessPair Found = 6225 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6226 if (recordConversion(*this, Loc, From, Converter, T, 6227 HadMultipleCandidates, Found)) 6228 return ExprError(); 6229 break; 6230 } 6231 case OR_Ambiguous: 6232 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6233 ViableConversions); 6234 case OR_No_Viable_Function: 6235 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6236 HadMultipleCandidates, 6237 ExplicitConversions)) 6238 return ExprError(); 6239 LLVM_FALLTHROUGH; 6240 case OR_Deleted: 6241 // We'll complain below about a non-integral condition type. 6242 break; 6243 } 6244 } else { 6245 switch (ViableConversions.size()) { 6246 case 0: { 6247 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6248 HadMultipleCandidates, 6249 ExplicitConversions)) 6250 return ExprError(); 6251 6252 // We'll complain below about a non-integral condition type. 6253 break; 6254 } 6255 case 1: { 6256 // Apply this conversion. 6257 DeclAccessPair Found = ViableConversions[0]; 6258 if (recordConversion(*this, Loc, From, Converter, T, 6259 HadMultipleCandidates, Found)) 6260 return ExprError(); 6261 break; 6262 } 6263 default: 6264 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6265 ViableConversions); 6266 } 6267 } 6268 6269 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6270 } 6271 6272 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6273 /// an acceptable non-member overloaded operator for a call whose 6274 /// arguments have types T1 (and, if non-empty, T2). This routine 6275 /// implements the check in C++ [over.match.oper]p3b2 concerning 6276 /// enumeration types. 6277 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6278 FunctionDecl *Fn, 6279 ArrayRef<Expr *> Args) { 6280 QualType T1 = Args[0]->getType(); 6281 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6282 6283 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6284 return true; 6285 6286 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6287 return true; 6288 6289 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6290 if (Proto->getNumParams() < 1) 6291 return false; 6292 6293 if (T1->isEnumeralType()) { 6294 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6295 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6296 return true; 6297 } 6298 6299 if (Proto->getNumParams() < 2) 6300 return false; 6301 6302 if (!T2.isNull() && T2->isEnumeralType()) { 6303 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6304 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6305 return true; 6306 } 6307 6308 return false; 6309 } 6310 6311 /// AddOverloadCandidate - Adds the given function to the set of 6312 /// candidate functions, using the given function call arguments. If 6313 /// @p SuppressUserConversions, then don't allow user-defined 6314 /// conversions via constructors or conversion operators. 6315 /// 6316 /// \param PartialOverloading true if we are performing "partial" overloading 6317 /// based on an incomplete set of function arguments. This feature is used by 6318 /// code completion. 6319 void Sema::AddOverloadCandidate( 6320 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6321 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6322 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6323 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6324 OverloadCandidateParamOrder PO) { 6325 const FunctionProtoType *Proto 6326 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6327 assert(Proto && "Functions without a prototype cannot be overloaded"); 6328 assert(!Function->getDescribedFunctionTemplate() && 6329 "Use AddTemplateOverloadCandidate for function templates"); 6330 6331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6332 if (!isa<CXXConstructorDecl>(Method)) { 6333 // If we get here, it's because we're calling a member function 6334 // that is named without a member access expression (e.g., 6335 // "this->f") that was either written explicitly or created 6336 // implicitly. This can happen with a qualified call to a member 6337 // function, e.g., X::f(). We use an empty type for the implied 6338 // object argument (C++ [over.call.func]p3), and the acting context 6339 // is irrelevant. 6340 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6341 Expr::Classification::makeSimpleLValue(), Args, 6342 CandidateSet, SuppressUserConversions, 6343 PartialOverloading, EarlyConversions, PO); 6344 return; 6345 } 6346 // We treat a constructor like a non-member function, since its object 6347 // argument doesn't participate in overload resolution. 6348 } 6349 6350 if (!CandidateSet.isNewCandidate(Function, PO)) 6351 return; 6352 6353 // C++11 [class.copy]p11: [DR1402] 6354 // A defaulted move constructor that is defined as deleted is ignored by 6355 // overload resolution. 6356 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6357 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6358 Constructor->isMoveConstructor()) 6359 return; 6360 6361 // Overload resolution is always an unevaluated context. 6362 EnterExpressionEvaluationContext Unevaluated( 6363 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6364 6365 // C++ [over.match.oper]p3: 6366 // if no operand has a class type, only those non-member functions in the 6367 // lookup set that have a first parameter of type T1 or "reference to 6368 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6369 // is a right operand) a second parameter of type T2 or "reference to 6370 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6371 // candidate functions. 6372 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6373 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6374 return; 6375 6376 // Add this candidate 6377 OverloadCandidate &Candidate = 6378 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6379 Candidate.FoundDecl = FoundDecl; 6380 Candidate.Function = Function; 6381 Candidate.Viable = true; 6382 Candidate.RewriteKind = 6383 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6384 Candidate.IsSurrogate = false; 6385 Candidate.IsADLCandidate = IsADLCandidate; 6386 Candidate.IgnoreObjectArgument = false; 6387 Candidate.ExplicitCallArguments = Args.size(); 6388 6389 // Explicit functions are not actually candidates at all if we're not 6390 // allowing them in this context, but keep them around so we can point 6391 // to them in diagnostics. 6392 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6393 Candidate.Viable = false; 6394 Candidate.FailureKind = ovl_fail_explicit; 6395 return; 6396 } 6397 6398 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6399 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6400 Candidate.Viable = false; 6401 Candidate.FailureKind = ovl_non_default_multiversion_function; 6402 return; 6403 } 6404 6405 if (Constructor) { 6406 // C++ [class.copy]p3: 6407 // A member function template is never instantiated to perform the copy 6408 // of a class object to an object of its class type. 6409 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6410 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6411 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6412 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6413 ClassType))) { 6414 Candidate.Viable = false; 6415 Candidate.FailureKind = ovl_fail_illegal_constructor; 6416 return; 6417 } 6418 6419 // C++ [over.match.funcs]p8: (proposed DR resolution) 6420 // A constructor inherited from class type C that has a first parameter 6421 // of type "reference to P" (including such a constructor instantiated 6422 // from a template) is excluded from the set of candidate functions when 6423 // constructing an object of type cv D if the argument list has exactly 6424 // one argument and D is reference-related to P and P is reference-related 6425 // to C. 6426 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6427 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6428 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6429 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6430 QualType C = Context.getRecordType(Constructor->getParent()); 6431 QualType D = Context.getRecordType(Shadow->getParent()); 6432 SourceLocation Loc = Args.front()->getExprLoc(); 6433 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6434 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6435 Candidate.Viable = false; 6436 Candidate.FailureKind = ovl_fail_inhctor_slice; 6437 return; 6438 } 6439 } 6440 6441 // Check that the constructor is capable of constructing an object in the 6442 // destination address space. 6443 if (!Qualifiers::isAddressSpaceSupersetOf( 6444 Constructor->getMethodQualifiers().getAddressSpace(), 6445 CandidateSet.getDestAS())) { 6446 Candidate.Viable = false; 6447 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6448 } 6449 } 6450 6451 unsigned NumParams = Proto->getNumParams(); 6452 6453 // (C++ 13.3.2p2): A candidate function having fewer than m 6454 // parameters is viable only if it has an ellipsis in its parameter 6455 // list (8.3.5). 6456 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6457 !Proto->isVariadic() && 6458 shouldEnforceArgLimit(PartialOverloading, Function)) { 6459 Candidate.Viable = false; 6460 Candidate.FailureKind = ovl_fail_too_many_arguments; 6461 return; 6462 } 6463 6464 // (C++ 13.3.2p2): A candidate function having more than m parameters 6465 // is viable only if the (m+1)st parameter has a default argument 6466 // (8.3.6). For the purposes of overload resolution, the 6467 // parameter list is truncated on the right, so that there are 6468 // exactly m parameters. 6469 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6470 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6471 // Not enough arguments. 6472 Candidate.Viable = false; 6473 Candidate.FailureKind = ovl_fail_too_few_arguments; 6474 return; 6475 } 6476 6477 // (CUDA B.1): Check for invalid calls between targets. 6478 if (getLangOpts().CUDA) 6479 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6480 // Skip the check for callers that are implicit members, because in this 6481 // case we may not yet know what the member's target is; the target is 6482 // inferred for the member automatically, based on the bases and fields of 6483 // the class. 6484 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6485 Candidate.Viable = false; 6486 Candidate.FailureKind = ovl_fail_bad_target; 6487 return; 6488 } 6489 6490 if (Function->getTrailingRequiresClause()) { 6491 ConstraintSatisfaction Satisfaction; 6492 if (CheckFunctionConstraints(Function, Satisfaction) || 6493 !Satisfaction.IsSatisfied) { 6494 Candidate.Viable = false; 6495 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6496 return; 6497 } 6498 } 6499 6500 // Determine the implicit conversion sequences for each of the 6501 // arguments. 6502 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6503 unsigned ConvIdx = 6504 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6505 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6506 // We already formed a conversion sequence for this parameter during 6507 // template argument deduction. 6508 } else if (ArgIdx < NumParams) { 6509 // (C++ 13.3.2p3): for F to be a viable function, there shall 6510 // exist for each argument an implicit conversion sequence 6511 // (13.3.3.1) that converts that argument to the corresponding 6512 // parameter of F. 6513 QualType ParamType = Proto->getParamType(ArgIdx); 6514 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6515 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6516 /*InOverloadResolution=*/true, 6517 /*AllowObjCWritebackConversion=*/ 6518 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6519 if (Candidate.Conversions[ConvIdx].isBad()) { 6520 Candidate.Viable = false; 6521 Candidate.FailureKind = ovl_fail_bad_conversion; 6522 return; 6523 } 6524 } else { 6525 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6526 // argument for which there is no corresponding parameter is 6527 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6528 Candidate.Conversions[ConvIdx].setEllipsis(); 6529 } 6530 } 6531 6532 if (EnableIfAttr *FailedAttr = 6533 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6534 Candidate.Viable = false; 6535 Candidate.FailureKind = ovl_fail_enable_if; 6536 Candidate.DeductionFailure.Data = FailedAttr; 6537 return; 6538 } 6539 } 6540 6541 ObjCMethodDecl * 6542 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6543 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6544 if (Methods.size() <= 1) 6545 return nullptr; 6546 6547 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6548 bool Match = true; 6549 ObjCMethodDecl *Method = Methods[b]; 6550 unsigned NumNamedArgs = Sel.getNumArgs(); 6551 // Method might have more arguments than selector indicates. This is due 6552 // to addition of c-style arguments in method. 6553 if (Method->param_size() > NumNamedArgs) 6554 NumNamedArgs = Method->param_size(); 6555 if (Args.size() < NumNamedArgs) 6556 continue; 6557 6558 for (unsigned i = 0; i < NumNamedArgs; i++) { 6559 // We can't do any type-checking on a type-dependent argument. 6560 if (Args[i]->isTypeDependent()) { 6561 Match = false; 6562 break; 6563 } 6564 6565 ParmVarDecl *param = Method->parameters()[i]; 6566 Expr *argExpr = Args[i]; 6567 assert(argExpr && "SelectBestMethod(): missing expression"); 6568 6569 // Strip the unbridged-cast placeholder expression off unless it's 6570 // a consumed argument. 6571 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6572 !param->hasAttr<CFConsumedAttr>()) 6573 argExpr = stripARCUnbridgedCast(argExpr); 6574 6575 // If the parameter is __unknown_anytype, move on to the next method. 6576 if (param->getType() == Context.UnknownAnyTy) { 6577 Match = false; 6578 break; 6579 } 6580 6581 ImplicitConversionSequence ConversionState 6582 = TryCopyInitialization(*this, argExpr, param->getType(), 6583 /*SuppressUserConversions*/false, 6584 /*InOverloadResolution=*/true, 6585 /*AllowObjCWritebackConversion=*/ 6586 getLangOpts().ObjCAutoRefCount, 6587 /*AllowExplicit*/false); 6588 // This function looks for a reasonably-exact match, so we consider 6589 // incompatible pointer conversions to be a failure here. 6590 if (ConversionState.isBad() || 6591 (ConversionState.isStandard() && 6592 ConversionState.Standard.Second == 6593 ICK_Incompatible_Pointer_Conversion)) { 6594 Match = false; 6595 break; 6596 } 6597 } 6598 // Promote additional arguments to variadic methods. 6599 if (Match && Method->isVariadic()) { 6600 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6601 if (Args[i]->isTypeDependent()) { 6602 Match = false; 6603 break; 6604 } 6605 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6606 nullptr); 6607 if (Arg.isInvalid()) { 6608 Match = false; 6609 break; 6610 } 6611 } 6612 } else { 6613 // Check for extra arguments to non-variadic methods. 6614 if (Args.size() != NumNamedArgs) 6615 Match = false; 6616 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6617 // Special case when selectors have no argument. In this case, select 6618 // one with the most general result type of 'id'. 6619 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6620 QualType ReturnT = Methods[b]->getReturnType(); 6621 if (ReturnT->isObjCIdType()) 6622 return Methods[b]; 6623 } 6624 } 6625 } 6626 6627 if (Match) 6628 return Method; 6629 } 6630 return nullptr; 6631 } 6632 6633 static bool convertArgsForAvailabilityChecks( 6634 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6635 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6636 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6637 if (ThisArg) { 6638 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6639 assert(!isa<CXXConstructorDecl>(Method) && 6640 "Shouldn't have `this` for ctors!"); 6641 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6642 ExprResult R = S.PerformObjectArgumentInitialization( 6643 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6644 if (R.isInvalid()) 6645 return false; 6646 ConvertedThis = R.get(); 6647 } else { 6648 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6649 (void)MD; 6650 assert((MissingImplicitThis || MD->isStatic() || 6651 isa<CXXConstructorDecl>(MD)) && 6652 "Expected `this` for non-ctor instance methods"); 6653 } 6654 ConvertedThis = nullptr; 6655 } 6656 6657 // Ignore any variadic arguments. Converting them is pointless, since the 6658 // user can't refer to them in the function condition. 6659 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6660 6661 // Convert the arguments. 6662 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6663 ExprResult R; 6664 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6665 S.Context, Function->getParamDecl(I)), 6666 SourceLocation(), Args[I]); 6667 6668 if (R.isInvalid()) 6669 return false; 6670 6671 ConvertedArgs.push_back(R.get()); 6672 } 6673 6674 if (Trap.hasErrorOccurred()) 6675 return false; 6676 6677 // Push default arguments if needed. 6678 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6679 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6680 ParmVarDecl *P = Function->getParamDecl(i); 6681 if (!P->hasDefaultArg()) 6682 return false; 6683 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6684 if (R.isInvalid()) 6685 return false; 6686 ConvertedArgs.push_back(R.get()); 6687 } 6688 6689 if (Trap.hasErrorOccurred()) 6690 return false; 6691 } 6692 return true; 6693 } 6694 6695 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6696 SourceLocation CallLoc, 6697 ArrayRef<Expr *> Args, 6698 bool MissingImplicitThis) { 6699 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6700 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6701 return nullptr; 6702 6703 SFINAETrap Trap(*this); 6704 SmallVector<Expr *, 16> ConvertedArgs; 6705 // FIXME: We should look into making enable_if late-parsed. 6706 Expr *DiscardedThis; 6707 if (!convertArgsForAvailabilityChecks( 6708 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6709 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6710 return *EnableIfAttrs.begin(); 6711 6712 for (auto *EIA : EnableIfAttrs) { 6713 APValue Result; 6714 // FIXME: This doesn't consider value-dependent cases, because doing so is 6715 // very difficult. Ideally, we should handle them more gracefully. 6716 if (EIA->getCond()->isValueDependent() || 6717 !EIA->getCond()->EvaluateWithSubstitution( 6718 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6719 return EIA; 6720 6721 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6722 return EIA; 6723 } 6724 return nullptr; 6725 } 6726 6727 template <typename CheckFn> 6728 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6729 bool ArgDependent, SourceLocation Loc, 6730 CheckFn &&IsSuccessful) { 6731 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6732 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6733 if (ArgDependent == DIA->getArgDependent()) 6734 Attrs.push_back(DIA); 6735 } 6736 6737 // Common case: No diagnose_if attributes, so we can quit early. 6738 if (Attrs.empty()) 6739 return false; 6740 6741 auto WarningBegin = std::stable_partition( 6742 Attrs.begin(), Attrs.end(), 6743 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6744 6745 // Note that diagnose_if attributes are late-parsed, so they appear in the 6746 // correct order (unlike enable_if attributes). 6747 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6748 IsSuccessful); 6749 if (ErrAttr != WarningBegin) { 6750 const DiagnoseIfAttr *DIA = *ErrAttr; 6751 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6752 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6753 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6754 return true; 6755 } 6756 6757 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6758 if (IsSuccessful(DIA)) { 6759 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6760 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6761 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6762 } 6763 6764 return false; 6765 } 6766 6767 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6768 const Expr *ThisArg, 6769 ArrayRef<const Expr *> Args, 6770 SourceLocation Loc) { 6771 return diagnoseDiagnoseIfAttrsWith( 6772 *this, Function, /*ArgDependent=*/true, Loc, 6773 [&](const DiagnoseIfAttr *DIA) { 6774 APValue Result; 6775 // It's sane to use the same Args for any redecl of this function, since 6776 // EvaluateWithSubstitution only cares about the position of each 6777 // argument in the arg list, not the ParmVarDecl* it maps to. 6778 if (!DIA->getCond()->EvaluateWithSubstitution( 6779 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6780 return false; 6781 return Result.isInt() && Result.getInt().getBoolValue(); 6782 }); 6783 } 6784 6785 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6786 SourceLocation Loc) { 6787 return diagnoseDiagnoseIfAttrsWith( 6788 *this, ND, /*ArgDependent=*/false, Loc, 6789 [&](const DiagnoseIfAttr *DIA) { 6790 bool Result; 6791 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6792 Result; 6793 }); 6794 } 6795 6796 /// Add all of the function declarations in the given function set to 6797 /// the overload candidate set. 6798 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6799 ArrayRef<Expr *> Args, 6800 OverloadCandidateSet &CandidateSet, 6801 TemplateArgumentListInfo *ExplicitTemplateArgs, 6802 bool SuppressUserConversions, 6803 bool PartialOverloading, 6804 bool FirstArgumentIsBase) { 6805 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6806 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6807 ArrayRef<Expr *> FunctionArgs = Args; 6808 6809 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6810 FunctionDecl *FD = 6811 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6812 6813 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6814 QualType ObjectType; 6815 Expr::Classification ObjectClassification; 6816 if (Args.size() > 0) { 6817 if (Expr *E = Args[0]) { 6818 // Use the explicit base to restrict the lookup: 6819 ObjectType = E->getType(); 6820 // Pointers in the object arguments are implicitly dereferenced, so we 6821 // always classify them as l-values. 6822 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6823 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6824 else 6825 ObjectClassification = E->Classify(Context); 6826 } // .. else there is an implicit base. 6827 FunctionArgs = Args.slice(1); 6828 } 6829 if (FunTmpl) { 6830 AddMethodTemplateCandidate( 6831 FunTmpl, F.getPair(), 6832 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6833 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6834 FunctionArgs, CandidateSet, SuppressUserConversions, 6835 PartialOverloading); 6836 } else { 6837 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6838 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6839 ObjectClassification, FunctionArgs, CandidateSet, 6840 SuppressUserConversions, PartialOverloading); 6841 } 6842 } else { 6843 // This branch handles both standalone functions and static methods. 6844 6845 // Slice the first argument (which is the base) when we access 6846 // static method as non-static. 6847 if (Args.size() > 0 && 6848 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6849 !isa<CXXConstructorDecl>(FD)))) { 6850 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6851 FunctionArgs = Args.slice(1); 6852 } 6853 if (FunTmpl) { 6854 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6855 ExplicitTemplateArgs, FunctionArgs, 6856 CandidateSet, SuppressUserConversions, 6857 PartialOverloading); 6858 } else { 6859 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6860 SuppressUserConversions, PartialOverloading); 6861 } 6862 } 6863 } 6864 } 6865 6866 /// AddMethodCandidate - Adds a named decl (which is some kind of 6867 /// method) as a method candidate to the given overload set. 6868 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6869 Expr::Classification ObjectClassification, 6870 ArrayRef<Expr *> Args, 6871 OverloadCandidateSet &CandidateSet, 6872 bool SuppressUserConversions, 6873 OverloadCandidateParamOrder PO) { 6874 NamedDecl *Decl = FoundDecl.getDecl(); 6875 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6876 6877 if (isa<UsingShadowDecl>(Decl)) 6878 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6879 6880 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6881 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6882 "Expected a member function template"); 6883 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6884 /*ExplicitArgs*/ nullptr, ObjectType, 6885 ObjectClassification, Args, CandidateSet, 6886 SuppressUserConversions, false, PO); 6887 } else { 6888 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6889 ObjectType, ObjectClassification, Args, CandidateSet, 6890 SuppressUserConversions, false, None, PO); 6891 } 6892 } 6893 6894 /// AddMethodCandidate - Adds the given C++ member function to the set 6895 /// of candidate functions, using the given function call arguments 6896 /// and the object argument (@c Object). For example, in a call 6897 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6898 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6899 /// allow user-defined conversions via constructors or conversion 6900 /// operators. 6901 void 6902 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6903 CXXRecordDecl *ActingContext, QualType ObjectType, 6904 Expr::Classification ObjectClassification, 6905 ArrayRef<Expr *> Args, 6906 OverloadCandidateSet &CandidateSet, 6907 bool SuppressUserConversions, 6908 bool PartialOverloading, 6909 ConversionSequenceList EarlyConversions, 6910 OverloadCandidateParamOrder PO) { 6911 const FunctionProtoType *Proto 6912 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6913 assert(Proto && "Methods without a prototype cannot be overloaded"); 6914 assert(!isa<CXXConstructorDecl>(Method) && 6915 "Use AddOverloadCandidate for constructors"); 6916 6917 if (!CandidateSet.isNewCandidate(Method, PO)) 6918 return; 6919 6920 // C++11 [class.copy]p23: [DR1402] 6921 // A defaulted move assignment operator that is defined as deleted is 6922 // ignored by overload resolution. 6923 if (Method->isDefaulted() && Method->isDeleted() && 6924 Method->isMoveAssignmentOperator()) 6925 return; 6926 6927 // Overload resolution is always an unevaluated context. 6928 EnterExpressionEvaluationContext Unevaluated( 6929 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6930 6931 // Add this candidate 6932 OverloadCandidate &Candidate = 6933 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6934 Candidate.FoundDecl = FoundDecl; 6935 Candidate.Function = Method; 6936 Candidate.RewriteKind = 6937 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6938 Candidate.IsSurrogate = false; 6939 Candidate.IgnoreObjectArgument = false; 6940 Candidate.ExplicitCallArguments = Args.size(); 6941 6942 unsigned NumParams = Proto->getNumParams(); 6943 6944 // (C++ 13.3.2p2): A candidate function having fewer than m 6945 // parameters is viable only if it has an ellipsis in its parameter 6946 // list (8.3.5). 6947 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6948 !Proto->isVariadic() && 6949 shouldEnforceArgLimit(PartialOverloading, Method)) { 6950 Candidate.Viable = false; 6951 Candidate.FailureKind = ovl_fail_too_many_arguments; 6952 return; 6953 } 6954 6955 // (C++ 13.3.2p2): A candidate function having more than m parameters 6956 // is viable only if the (m+1)st parameter has a default argument 6957 // (8.3.6). For the purposes of overload resolution, the 6958 // parameter list is truncated on the right, so that there are 6959 // exactly m parameters. 6960 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6961 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6962 // Not enough arguments. 6963 Candidate.Viable = false; 6964 Candidate.FailureKind = ovl_fail_too_few_arguments; 6965 return; 6966 } 6967 6968 Candidate.Viable = true; 6969 6970 if (Method->isStatic() || ObjectType.isNull()) 6971 // The implicit object argument is ignored. 6972 Candidate.IgnoreObjectArgument = true; 6973 else { 6974 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6975 // Determine the implicit conversion sequence for the object 6976 // parameter. 6977 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6978 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6979 Method, ActingContext); 6980 if (Candidate.Conversions[ConvIdx].isBad()) { 6981 Candidate.Viable = false; 6982 Candidate.FailureKind = ovl_fail_bad_conversion; 6983 return; 6984 } 6985 } 6986 6987 // (CUDA B.1): Check for invalid calls between targets. 6988 if (getLangOpts().CUDA) 6989 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6990 if (!IsAllowedCUDACall(Caller, Method)) { 6991 Candidate.Viable = false; 6992 Candidate.FailureKind = ovl_fail_bad_target; 6993 return; 6994 } 6995 6996 if (Method->getTrailingRequiresClause()) { 6997 ConstraintSatisfaction Satisfaction; 6998 if (CheckFunctionConstraints(Method, Satisfaction) || 6999 !Satisfaction.IsSatisfied) { 7000 Candidate.Viable = false; 7001 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7002 return; 7003 } 7004 } 7005 7006 // Determine the implicit conversion sequences for each of the 7007 // arguments. 7008 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7009 unsigned ConvIdx = 7010 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7011 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7012 // We already formed a conversion sequence for this parameter during 7013 // template argument deduction. 7014 } else if (ArgIdx < NumParams) { 7015 // (C++ 13.3.2p3): for F to be a viable function, there shall 7016 // exist for each argument an implicit conversion sequence 7017 // (13.3.3.1) that converts that argument to the corresponding 7018 // parameter of F. 7019 QualType ParamType = Proto->getParamType(ArgIdx); 7020 Candidate.Conversions[ConvIdx] 7021 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7022 SuppressUserConversions, 7023 /*InOverloadResolution=*/true, 7024 /*AllowObjCWritebackConversion=*/ 7025 getLangOpts().ObjCAutoRefCount); 7026 if (Candidate.Conversions[ConvIdx].isBad()) { 7027 Candidate.Viable = false; 7028 Candidate.FailureKind = ovl_fail_bad_conversion; 7029 return; 7030 } 7031 } else { 7032 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7033 // argument for which there is no corresponding parameter is 7034 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7035 Candidate.Conversions[ConvIdx].setEllipsis(); 7036 } 7037 } 7038 7039 if (EnableIfAttr *FailedAttr = 7040 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7041 Candidate.Viable = false; 7042 Candidate.FailureKind = ovl_fail_enable_if; 7043 Candidate.DeductionFailure.Data = FailedAttr; 7044 return; 7045 } 7046 7047 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 7048 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 7049 Candidate.Viable = false; 7050 Candidate.FailureKind = ovl_non_default_multiversion_function; 7051 } 7052 } 7053 7054 /// Add a C++ member function template as a candidate to the candidate 7055 /// set, using template argument deduction to produce an appropriate member 7056 /// function template specialization. 7057 void Sema::AddMethodTemplateCandidate( 7058 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7059 CXXRecordDecl *ActingContext, 7060 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7061 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7062 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7063 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7064 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7065 return; 7066 7067 // C++ [over.match.funcs]p7: 7068 // In each case where a candidate is a function template, candidate 7069 // function template specializations are generated using template argument 7070 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7071 // candidate functions in the usual way.113) A given name can refer to one 7072 // or more function templates and also to a set of overloaded non-template 7073 // functions. In such a case, the candidate functions generated from each 7074 // function template are combined with the set of non-template candidate 7075 // functions. 7076 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7077 FunctionDecl *Specialization = nullptr; 7078 ConversionSequenceList Conversions; 7079 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7080 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7081 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7082 return CheckNonDependentConversions( 7083 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7084 SuppressUserConversions, ActingContext, ObjectType, 7085 ObjectClassification, PO); 7086 })) { 7087 OverloadCandidate &Candidate = 7088 CandidateSet.addCandidate(Conversions.size(), Conversions); 7089 Candidate.FoundDecl = FoundDecl; 7090 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7091 Candidate.Viable = false; 7092 Candidate.RewriteKind = 7093 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7094 Candidate.IsSurrogate = false; 7095 Candidate.IgnoreObjectArgument = 7096 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7097 ObjectType.isNull(); 7098 Candidate.ExplicitCallArguments = Args.size(); 7099 if (Result == TDK_NonDependentConversionFailure) 7100 Candidate.FailureKind = ovl_fail_bad_conversion; 7101 else { 7102 Candidate.FailureKind = ovl_fail_bad_deduction; 7103 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7104 Info); 7105 } 7106 return; 7107 } 7108 7109 // Add the function template specialization produced by template argument 7110 // deduction as a candidate. 7111 assert(Specialization && "Missing member function template specialization?"); 7112 assert(isa<CXXMethodDecl>(Specialization) && 7113 "Specialization is not a member function?"); 7114 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7115 ActingContext, ObjectType, ObjectClassification, Args, 7116 CandidateSet, SuppressUserConversions, PartialOverloading, 7117 Conversions, PO); 7118 } 7119 7120 /// Determine whether a given function template has a simple explicit specifier 7121 /// or a non-value-dependent explicit-specification that evaluates to true. 7122 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7123 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7124 } 7125 7126 /// Add a C++ function template specialization as a candidate 7127 /// in the candidate set, using template argument deduction to produce 7128 /// an appropriate function template specialization. 7129 void Sema::AddTemplateOverloadCandidate( 7130 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7131 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7132 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7133 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7134 OverloadCandidateParamOrder PO) { 7135 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7136 return; 7137 7138 // If the function template has a non-dependent explicit specification, 7139 // exclude it now if appropriate; we are not permitted to perform deduction 7140 // and substitution in this case. 7141 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7142 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7143 Candidate.FoundDecl = FoundDecl; 7144 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7145 Candidate.Viable = false; 7146 Candidate.FailureKind = ovl_fail_explicit; 7147 return; 7148 } 7149 7150 // C++ [over.match.funcs]p7: 7151 // In each case where a candidate is a function template, candidate 7152 // function template specializations are generated using template argument 7153 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7154 // candidate functions in the usual way.113) A given name can refer to one 7155 // or more function templates and also to a set of overloaded non-template 7156 // functions. In such a case, the candidate functions generated from each 7157 // function template are combined with the set of non-template candidate 7158 // functions. 7159 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7160 FunctionDecl *Specialization = nullptr; 7161 ConversionSequenceList Conversions; 7162 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7163 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7164 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7165 return CheckNonDependentConversions( 7166 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7167 SuppressUserConversions, nullptr, QualType(), {}, PO); 7168 })) { 7169 OverloadCandidate &Candidate = 7170 CandidateSet.addCandidate(Conversions.size(), Conversions); 7171 Candidate.FoundDecl = FoundDecl; 7172 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7173 Candidate.Viable = false; 7174 Candidate.RewriteKind = 7175 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7176 Candidate.IsSurrogate = false; 7177 Candidate.IsADLCandidate = IsADLCandidate; 7178 // Ignore the object argument if there is one, since we don't have an object 7179 // type. 7180 Candidate.IgnoreObjectArgument = 7181 isa<CXXMethodDecl>(Candidate.Function) && 7182 !isa<CXXConstructorDecl>(Candidate.Function); 7183 Candidate.ExplicitCallArguments = Args.size(); 7184 if (Result == TDK_NonDependentConversionFailure) 7185 Candidate.FailureKind = ovl_fail_bad_conversion; 7186 else { 7187 Candidate.FailureKind = ovl_fail_bad_deduction; 7188 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7189 Info); 7190 } 7191 return; 7192 } 7193 7194 // Add the function template specialization produced by template argument 7195 // deduction as a candidate. 7196 assert(Specialization && "Missing function template specialization?"); 7197 AddOverloadCandidate( 7198 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7199 PartialOverloading, AllowExplicit, 7200 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7201 } 7202 7203 /// Check that implicit conversion sequences can be formed for each argument 7204 /// whose corresponding parameter has a non-dependent type, per DR1391's 7205 /// [temp.deduct.call]p10. 7206 bool Sema::CheckNonDependentConversions( 7207 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7208 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7209 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7210 CXXRecordDecl *ActingContext, QualType ObjectType, 7211 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7212 // FIXME: The cases in which we allow explicit conversions for constructor 7213 // arguments never consider calling a constructor template. It's not clear 7214 // that is correct. 7215 const bool AllowExplicit = false; 7216 7217 auto *FD = FunctionTemplate->getTemplatedDecl(); 7218 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7219 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7220 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7221 7222 Conversions = 7223 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7224 7225 // Overload resolution is always an unevaluated context. 7226 EnterExpressionEvaluationContext Unevaluated( 7227 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7228 7229 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7230 // require that, but this check should never result in a hard error, and 7231 // overload resolution is permitted to sidestep instantiations. 7232 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7233 !ObjectType.isNull()) { 7234 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7235 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7236 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7237 Method, ActingContext); 7238 if (Conversions[ConvIdx].isBad()) 7239 return true; 7240 } 7241 7242 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7243 ++I) { 7244 QualType ParamType = ParamTypes[I]; 7245 if (!ParamType->isDependentType()) { 7246 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7247 ? 0 7248 : (ThisConversions + I); 7249 Conversions[ConvIdx] 7250 = TryCopyInitialization(*this, Args[I], ParamType, 7251 SuppressUserConversions, 7252 /*InOverloadResolution=*/true, 7253 /*AllowObjCWritebackConversion=*/ 7254 getLangOpts().ObjCAutoRefCount, 7255 AllowExplicit); 7256 if (Conversions[ConvIdx].isBad()) 7257 return true; 7258 } 7259 } 7260 7261 return false; 7262 } 7263 7264 /// Determine whether this is an allowable conversion from the result 7265 /// of an explicit conversion operator to the expected type, per C++ 7266 /// [over.match.conv]p1 and [over.match.ref]p1. 7267 /// 7268 /// \param ConvType The return type of the conversion function. 7269 /// 7270 /// \param ToType The type we are converting to. 7271 /// 7272 /// \param AllowObjCPointerConversion Allow a conversion from one 7273 /// Objective-C pointer to another. 7274 /// 7275 /// \returns true if the conversion is allowable, false otherwise. 7276 static bool isAllowableExplicitConversion(Sema &S, 7277 QualType ConvType, QualType ToType, 7278 bool AllowObjCPointerConversion) { 7279 QualType ToNonRefType = ToType.getNonReferenceType(); 7280 7281 // Easy case: the types are the same. 7282 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7283 return true; 7284 7285 // Allow qualification conversions. 7286 bool ObjCLifetimeConversion; 7287 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7288 ObjCLifetimeConversion)) 7289 return true; 7290 7291 // If we're not allowed to consider Objective-C pointer conversions, 7292 // we're done. 7293 if (!AllowObjCPointerConversion) 7294 return false; 7295 7296 // Is this an Objective-C pointer conversion? 7297 bool IncompatibleObjC = false; 7298 QualType ConvertedType; 7299 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7300 IncompatibleObjC); 7301 } 7302 7303 /// AddConversionCandidate - Add a C++ conversion function as a 7304 /// candidate in the candidate set (C++ [over.match.conv], 7305 /// C++ [over.match.copy]). From is the expression we're converting from, 7306 /// and ToType is the type that we're eventually trying to convert to 7307 /// (which may or may not be the same type as the type that the 7308 /// conversion function produces). 7309 void Sema::AddConversionCandidate( 7310 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7311 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7312 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7313 bool AllowExplicit, bool AllowResultConversion) { 7314 assert(!Conversion->getDescribedFunctionTemplate() && 7315 "Conversion function templates use AddTemplateConversionCandidate"); 7316 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7317 if (!CandidateSet.isNewCandidate(Conversion)) 7318 return; 7319 7320 // If the conversion function has an undeduced return type, trigger its 7321 // deduction now. 7322 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7323 if (DeduceReturnType(Conversion, From->getExprLoc())) 7324 return; 7325 ConvType = Conversion->getConversionType().getNonReferenceType(); 7326 } 7327 7328 // If we don't allow any conversion of the result type, ignore conversion 7329 // functions that don't convert to exactly (possibly cv-qualified) T. 7330 if (!AllowResultConversion && 7331 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7332 return; 7333 7334 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7335 // operator is only a candidate if its return type is the target type or 7336 // can be converted to the target type with a qualification conversion. 7337 // 7338 // FIXME: Include such functions in the candidate list and explain why we 7339 // can't select them. 7340 if (Conversion->isExplicit() && 7341 !isAllowableExplicitConversion(*this, ConvType, ToType, 7342 AllowObjCConversionOnExplicit)) 7343 return; 7344 7345 // Overload resolution is always an unevaluated context. 7346 EnterExpressionEvaluationContext Unevaluated( 7347 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7348 7349 // Add this candidate 7350 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7351 Candidate.FoundDecl = FoundDecl; 7352 Candidate.Function = Conversion; 7353 Candidate.IsSurrogate = false; 7354 Candidate.IgnoreObjectArgument = false; 7355 Candidate.FinalConversion.setAsIdentityConversion(); 7356 Candidate.FinalConversion.setFromType(ConvType); 7357 Candidate.FinalConversion.setAllToTypes(ToType); 7358 Candidate.Viable = true; 7359 Candidate.ExplicitCallArguments = 1; 7360 7361 // Explicit functions are not actually candidates at all if we're not 7362 // allowing them in this context, but keep them around so we can point 7363 // to them in diagnostics. 7364 if (!AllowExplicit && Conversion->isExplicit()) { 7365 Candidate.Viable = false; 7366 Candidate.FailureKind = ovl_fail_explicit; 7367 return; 7368 } 7369 7370 // C++ [over.match.funcs]p4: 7371 // For conversion functions, the function is considered to be a member of 7372 // the class of the implicit implied object argument for the purpose of 7373 // defining the type of the implicit object parameter. 7374 // 7375 // Determine the implicit conversion sequence for the implicit 7376 // object parameter. 7377 QualType ImplicitParamType = From->getType(); 7378 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7379 ImplicitParamType = FromPtrType->getPointeeType(); 7380 CXXRecordDecl *ConversionContext 7381 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7382 7383 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7384 *this, CandidateSet.getLocation(), From->getType(), 7385 From->Classify(Context), Conversion, ConversionContext); 7386 7387 if (Candidate.Conversions[0].isBad()) { 7388 Candidate.Viable = false; 7389 Candidate.FailureKind = ovl_fail_bad_conversion; 7390 return; 7391 } 7392 7393 if (Conversion->getTrailingRequiresClause()) { 7394 ConstraintSatisfaction Satisfaction; 7395 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7396 !Satisfaction.IsSatisfied) { 7397 Candidate.Viable = false; 7398 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7399 return; 7400 } 7401 } 7402 7403 // We won't go through a user-defined type conversion function to convert a 7404 // derived to base as such conversions are given Conversion Rank. They only 7405 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7406 QualType FromCanon 7407 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7408 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7409 if (FromCanon == ToCanon || 7410 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7411 Candidate.Viable = false; 7412 Candidate.FailureKind = ovl_fail_trivial_conversion; 7413 return; 7414 } 7415 7416 // To determine what the conversion from the result of calling the 7417 // conversion function to the type we're eventually trying to 7418 // convert to (ToType), we need to synthesize a call to the 7419 // conversion function and attempt copy initialization from it. This 7420 // makes sure that we get the right semantics with respect to 7421 // lvalues/rvalues and the type. Fortunately, we can allocate this 7422 // call on the stack and we don't need its arguments to be 7423 // well-formed. 7424 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7425 VK_LValue, From->getBeginLoc()); 7426 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7427 Context.getPointerType(Conversion->getType()), 7428 CK_FunctionToPointerDecay, &ConversionRef, 7429 VK_PRValue, FPOptionsOverride()); 7430 7431 QualType ConversionType = Conversion->getConversionType(); 7432 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7433 Candidate.Viable = false; 7434 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7435 return; 7436 } 7437 7438 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7439 7440 // Note that it is safe to allocate CallExpr on the stack here because 7441 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7442 // allocator). 7443 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7444 7445 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7446 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7447 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7448 7449 ImplicitConversionSequence ICS = 7450 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7451 /*SuppressUserConversions=*/true, 7452 /*InOverloadResolution=*/false, 7453 /*AllowObjCWritebackConversion=*/false); 7454 7455 switch (ICS.getKind()) { 7456 case ImplicitConversionSequence::StandardConversion: 7457 Candidate.FinalConversion = ICS.Standard; 7458 7459 // C++ [over.ics.user]p3: 7460 // If the user-defined conversion is specified by a specialization of a 7461 // conversion function template, the second standard conversion sequence 7462 // shall have exact match rank. 7463 if (Conversion->getPrimaryTemplate() && 7464 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7465 Candidate.Viable = false; 7466 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7467 return; 7468 } 7469 7470 // C++0x [dcl.init.ref]p5: 7471 // In the second case, if the reference is an rvalue reference and 7472 // the second standard conversion sequence of the user-defined 7473 // conversion sequence includes an lvalue-to-rvalue conversion, the 7474 // program is ill-formed. 7475 if (ToType->isRValueReferenceType() && 7476 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7477 Candidate.Viable = false; 7478 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7479 return; 7480 } 7481 break; 7482 7483 case ImplicitConversionSequence::BadConversion: 7484 Candidate.Viable = false; 7485 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7486 return; 7487 7488 default: 7489 llvm_unreachable( 7490 "Can only end up with a standard conversion sequence or failure"); 7491 } 7492 7493 if (EnableIfAttr *FailedAttr = 7494 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7495 Candidate.Viable = false; 7496 Candidate.FailureKind = ovl_fail_enable_if; 7497 Candidate.DeductionFailure.Data = FailedAttr; 7498 return; 7499 } 7500 7501 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7502 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7503 Candidate.Viable = false; 7504 Candidate.FailureKind = ovl_non_default_multiversion_function; 7505 } 7506 } 7507 7508 /// Adds a conversion function template specialization 7509 /// candidate to the overload set, using template argument deduction 7510 /// to deduce the template arguments of the conversion function 7511 /// template from the type that we are converting to (C++ 7512 /// [temp.deduct.conv]). 7513 void Sema::AddTemplateConversionCandidate( 7514 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7515 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7516 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7517 bool AllowExplicit, bool AllowResultConversion) { 7518 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7519 "Only conversion function templates permitted here"); 7520 7521 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7522 return; 7523 7524 // If the function template has a non-dependent explicit specification, 7525 // exclude it now if appropriate; we are not permitted to perform deduction 7526 // and substitution in this case. 7527 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7528 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7529 Candidate.FoundDecl = FoundDecl; 7530 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7531 Candidate.Viable = false; 7532 Candidate.FailureKind = ovl_fail_explicit; 7533 return; 7534 } 7535 7536 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7537 CXXConversionDecl *Specialization = nullptr; 7538 if (TemplateDeductionResult Result 7539 = DeduceTemplateArguments(FunctionTemplate, ToType, 7540 Specialization, Info)) { 7541 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7542 Candidate.FoundDecl = FoundDecl; 7543 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7544 Candidate.Viable = false; 7545 Candidate.FailureKind = ovl_fail_bad_deduction; 7546 Candidate.IsSurrogate = false; 7547 Candidate.IgnoreObjectArgument = false; 7548 Candidate.ExplicitCallArguments = 1; 7549 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7550 Info); 7551 return; 7552 } 7553 7554 // Add the conversion function template specialization produced by 7555 // template argument deduction as a candidate. 7556 assert(Specialization && "Missing function template specialization?"); 7557 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7558 CandidateSet, AllowObjCConversionOnExplicit, 7559 AllowExplicit, AllowResultConversion); 7560 } 7561 7562 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7563 /// converts the given @c Object to a function pointer via the 7564 /// conversion function @c Conversion, and then attempts to call it 7565 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7566 /// the type of function that we'll eventually be calling. 7567 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7568 DeclAccessPair FoundDecl, 7569 CXXRecordDecl *ActingContext, 7570 const FunctionProtoType *Proto, 7571 Expr *Object, 7572 ArrayRef<Expr *> Args, 7573 OverloadCandidateSet& CandidateSet) { 7574 if (!CandidateSet.isNewCandidate(Conversion)) 7575 return; 7576 7577 // Overload resolution is always an unevaluated context. 7578 EnterExpressionEvaluationContext Unevaluated( 7579 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7580 7581 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7582 Candidate.FoundDecl = FoundDecl; 7583 Candidate.Function = nullptr; 7584 Candidate.Surrogate = Conversion; 7585 Candidate.Viable = true; 7586 Candidate.IsSurrogate = true; 7587 Candidate.IgnoreObjectArgument = false; 7588 Candidate.ExplicitCallArguments = Args.size(); 7589 7590 // Determine the implicit conversion sequence for the implicit 7591 // object parameter. 7592 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7593 *this, CandidateSet.getLocation(), Object->getType(), 7594 Object->Classify(Context), Conversion, ActingContext); 7595 if (ObjectInit.isBad()) { 7596 Candidate.Viable = false; 7597 Candidate.FailureKind = ovl_fail_bad_conversion; 7598 Candidate.Conversions[0] = ObjectInit; 7599 return; 7600 } 7601 7602 // The first conversion is actually a user-defined conversion whose 7603 // first conversion is ObjectInit's standard conversion (which is 7604 // effectively a reference binding). Record it as such. 7605 Candidate.Conversions[0].setUserDefined(); 7606 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7607 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7608 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7609 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7610 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7611 Candidate.Conversions[0].UserDefined.After 7612 = Candidate.Conversions[0].UserDefined.Before; 7613 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7614 7615 // Find the 7616 unsigned NumParams = Proto->getNumParams(); 7617 7618 // (C++ 13.3.2p2): A candidate function having fewer than m 7619 // parameters is viable only if it has an ellipsis in its parameter 7620 // list (8.3.5). 7621 if (Args.size() > NumParams && !Proto->isVariadic()) { 7622 Candidate.Viable = false; 7623 Candidate.FailureKind = ovl_fail_too_many_arguments; 7624 return; 7625 } 7626 7627 // Function types don't have any default arguments, so just check if 7628 // we have enough arguments. 7629 if (Args.size() < NumParams) { 7630 // Not enough arguments. 7631 Candidate.Viable = false; 7632 Candidate.FailureKind = ovl_fail_too_few_arguments; 7633 return; 7634 } 7635 7636 // Determine the implicit conversion sequences for each of the 7637 // arguments. 7638 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7639 if (ArgIdx < NumParams) { 7640 // (C++ 13.3.2p3): for F to be a viable function, there shall 7641 // exist for each argument an implicit conversion sequence 7642 // (13.3.3.1) that converts that argument to the corresponding 7643 // parameter of F. 7644 QualType ParamType = Proto->getParamType(ArgIdx); 7645 Candidate.Conversions[ArgIdx + 1] 7646 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7647 /*SuppressUserConversions=*/false, 7648 /*InOverloadResolution=*/false, 7649 /*AllowObjCWritebackConversion=*/ 7650 getLangOpts().ObjCAutoRefCount); 7651 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7652 Candidate.Viable = false; 7653 Candidate.FailureKind = ovl_fail_bad_conversion; 7654 return; 7655 } 7656 } else { 7657 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7658 // argument for which there is no corresponding parameter is 7659 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7660 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7661 } 7662 } 7663 7664 if (EnableIfAttr *FailedAttr = 7665 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7666 Candidate.Viable = false; 7667 Candidate.FailureKind = ovl_fail_enable_if; 7668 Candidate.DeductionFailure.Data = FailedAttr; 7669 return; 7670 } 7671 } 7672 7673 /// Add all of the non-member operator function declarations in the given 7674 /// function set to the overload candidate set. 7675 void Sema::AddNonMemberOperatorCandidates( 7676 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7677 OverloadCandidateSet &CandidateSet, 7678 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7679 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7680 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7681 ArrayRef<Expr *> FunctionArgs = Args; 7682 7683 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7684 FunctionDecl *FD = 7685 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7686 7687 // Don't consider rewritten functions if we're not rewriting. 7688 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7689 continue; 7690 7691 assert(!isa<CXXMethodDecl>(FD) && 7692 "unqualified operator lookup found a member function"); 7693 7694 if (FunTmpl) { 7695 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7696 FunctionArgs, CandidateSet); 7697 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7698 AddTemplateOverloadCandidate( 7699 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7700 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7701 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7702 } else { 7703 if (ExplicitTemplateArgs) 7704 continue; 7705 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7706 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7707 AddOverloadCandidate(FD, F.getPair(), 7708 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7709 false, false, true, false, ADLCallKind::NotADL, 7710 None, OverloadCandidateParamOrder::Reversed); 7711 } 7712 } 7713 } 7714 7715 /// Add overload candidates for overloaded operators that are 7716 /// member functions. 7717 /// 7718 /// Add the overloaded operator candidates that are member functions 7719 /// for the operator Op that was used in an operator expression such 7720 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7721 /// CandidateSet will store the added overload candidates. (C++ 7722 /// [over.match.oper]). 7723 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7724 SourceLocation OpLoc, 7725 ArrayRef<Expr *> Args, 7726 OverloadCandidateSet &CandidateSet, 7727 OverloadCandidateParamOrder PO) { 7728 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7729 7730 // C++ [over.match.oper]p3: 7731 // For a unary operator @ with an operand of a type whose 7732 // cv-unqualified version is T1, and for a binary operator @ with 7733 // a left operand of a type whose cv-unqualified version is T1 and 7734 // a right operand of a type whose cv-unqualified version is T2, 7735 // three sets of candidate functions, designated member 7736 // candidates, non-member candidates and built-in candidates, are 7737 // constructed as follows: 7738 QualType T1 = Args[0]->getType(); 7739 7740 // -- If T1 is a complete class type or a class currently being 7741 // defined, the set of member candidates is the result of the 7742 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7743 // the set of member candidates is empty. 7744 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7745 // Complete the type if it can be completed. 7746 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7747 return; 7748 // If the type is neither complete nor being defined, bail out now. 7749 if (!T1Rec->getDecl()->getDefinition()) 7750 return; 7751 7752 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7753 LookupQualifiedName(Operators, T1Rec->getDecl()); 7754 Operators.suppressDiagnostics(); 7755 7756 for (LookupResult::iterator Oper = Operators.begin(), 7757 OperEnd = Operators.end(); 7758 Oper != OperEnd; 7759 ++Oper) 7760 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7761 Args[0]->Classify(Context), Args.slice(1), 7762 CandidateSet, /*SuppressUserConversion=*/false, PO); 7763 } 7764 } 7765 7766 /// AddBuiltinCandidate - Add a candidate for a built-in 7767 /// operator. ResultTy and ParamTys are the result and parameter types 7768 /// of the built-in candidate, respectively. Args and NumArgs are the 7769 /// arguments being passed to the candidate. IsAssignmentOperator 7770 /// should be true when this built-in candidate is an assignment 7771 /// operator. NumContextualBoolArguments is the number of arguments 7772 /// (at the beginning of the argument list) that will be contextually 7773 /// converted to bool. 7774 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7775 OverloadCandidateSet& CandidateSet, 7776 bool IsAssignmentOperator, 7777 unsigned NumContextualBoolArguments) { 7778 // Overload resolution is always an unevaluated context. 7779 EnterExpressionEvaluationContext Unevaluated( 7780 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7781 7782 // Add this candidate 7783 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7784 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7785 Candidate.Function = nullptr; 7786 Candidate.IsSurrogate = false; 7787 Candidate.IgnoreObjectArgument = false; 7788 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7789 7790 // Determine the implicit conversion sequences for each of the 7791 // arguments. 7792 Candidate.Viable = true; 7793 Candidate.ExplicitCallArguments = Args.size(); 7794 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7795 // C++ [over.match.oper]p4: 7796 // For the built-in assignment operators, conversions of the 7797 // left operand are restricted as follows: 7798 // -- no temporaries are introduced to hold the left operand, and 7799 // -- no user-defined conversions are applied to the left 7800 // operand to achieve a type match with the left-most 7801 // parameter of a built-in candidate. 7802 // 7803 // We block these conversions by turning off user-defined 7804 // conversions, since that is the only way that initialization of 7805 // a reference to a non-class type can occur from something that 7806 // is not of the same type. 7807 if (ArgIdx < NumContextualBoolArguments) { 7808 assert(ParamTys[ArgIdx] == Context.BoolTy && 7809 "Contextual conversion to bool requires bool type"); 7810 Candidate.Conversions[ArgIdx] 7811 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7812 } else { 7813 Candidate.Conversions[ArgIdx] 7814 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7815 ArgIdx == 0 && IsAssignmentOperator, 7816 /*InOverloadResolution=*/false, 7817 /*AllowObjCWritebackConversion=*/ 7818 getLangOpts().ObjCAutoRefCount); 7819 } 7820 if (Candidate.Conversions[ArgIdx].isBad()) { 7821 Candidate.Viable = false; 7822 Candidate.FailureKind = ovl_fail_bad_conversion; 7823 break; 7824 } 7825 } 7826 } 7827 7828 namespace { 7829 7830 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7831 /// candidate operator functions for built-in operators (C++ 7832 /// [over.built]). The types are separated into pointer types and 7833 /// enumeration types. 7834 class BuiltinCandidateTypeSet { 7835 /// TypeSet - A set of types. 7836 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7837 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7838 7839 /// PointerTypes - The set of pointer types that will be used in the 7840 /// built-in candidates. 7841 TypeSet PointerTypes; 7842 7843 /// MemberPointerTypes - The set of member pointer types that will be 7844 /// used in the built-in candidates. 7845 TypeSet MemberPointerTypes; 7846 7847 /// EnumerationTypes - The set of enumeration types that will be 7848 /// used in the built-in candidates. 7849 TypeSet EnumerationTypes; 7850 7851 /// The set of vector types that will be used in the built-in 7852 /// candidates. 7853 TypeSet VectorTypes; 7854 7855 /// The set of matrix types that will be used in the built-in 7856 /// candidates. 7857 TypeSet MatrixTypes; 7858 7859 /// A flag indicating non-record types are viable candidates 7860 bool HasNonRecordTypes; 7861 7862 /// A flag indicating whether either arithmetic or enumeration types 7863 /// were present in the candidate set. 7864 bool HasArithmeticOrEnumeralTypes; 7865 7866 /// A flag indicating whether the nullptr type was present in the 7867 /// candidate set. 7868 bool HasNullPtrType; 7869 7870 /// Sema - The semantic analysis instance where we are building the 7871 /// candidate type set. 7872 Sema &SemaRef; 7873 7874 /// Context - The AST context in which we will build the type sets. 7875 ASTContext &Context; 7876 7877 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7878 const Qualifiers &VisibleQuals); 7879 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7880 7881 public: 7882 /// iterator - Iterates through the types that are part of the set. 7883 typedef TypeSet::iterator iterator; 7884 7885 BuiltinCandidateTypeSet(Sema &SemaRef) 7886 : HasNonRecordTypes(false), 7887 HasArithmeticOrEnumeralTypes(false), 7888 HasNullPtrType(false), 7889 SemaRef(SemaRef), 7890 Context(SemaRef.Context) { } 7891 7892 void AddTypesConvertedFrom(QualType Ty, 7893 SourceLocation Loc, 7894 bool AllowUserConversions, 7895 bool AllowExplicitConversions, 7896 const Qualifiers &VisibleTypeConversionsQuals); 7897 7898 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 7899 llvm::iterator_range<iterator> member_pointer_types() { 7900 return MemberPointerTypes; 7901 } 7902 llvm::iterator_range<iterator> enumeration_types() { 7903 return EnumerationTypes; 7904 } 7905 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7906 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7907 7908 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7909 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7910 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7911 bool hasNullPtrType() const { return HasNullPtrType; } 7912 }; 7913 7914 } // end anonymous namespace 7915 7916 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7917 /// the set of pointer types along with any more-qualified variants of 7918 /// that type. For example, if @p Ty is "int const *", this routine 7919 /// will add "int const *", "int const volatile *", "int const 7920 /// restrict *", and "int const volatile restrict *" to the set of 7921 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7922 /// false otherwise. 7923 /// 7924 /// FIXME: what to do about extended qualifiers? 7925 bool 7926 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7927 const Qualifiers &VisibleQuals) { 7928 7929 // Insert this type. 7930 if (!PointerTypes.insert(Ty)) 7931 return false; 7932 7933 QualType PointeeTy; 7934 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7935 bool buildObjCPtr = false; 7936 if (!PointerTy) { 7937 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7938 PointeeTy = PTy->getPointeeType(); 7939 buildObjCPtr = true; 7940 } else { 7941 PointeeTy = PointerTy->getPointeeType(); 7942 } 7943 7944 // Don't add qualified variants of arrays. For one, they're not allowed 7945 // (the qualifier would sink to the element type), and for another, the 7946 // only overload situation where it matters is subscript or pointer +- int, 7947 // and those shouldn't have qualifier variants anyway. 7948 if (PointeeTy->isArrayType()) 7949 return true; 7950 7951 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7952 bool hasVolatile = VisibleQuals.hasVolatile(); 7953 bool hasRestrict = VisibleQuals.hasRestrict(); 7954 7955 // Iterate through all strict supersets of BaseCVR. 7956 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7957 if ((CVR | BaseCVR) != CVR) continue; 7958 // Skip over volatile if no volatile found anywhere in the types. 7959 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7960 7961 // Skip over restrict if no restrict found anywhere in the types, or if 7962 // the type cannot be restrict-qualified. 7963 if ((CVR & Qualifiers::Restrict) && 7964 (!hasRestrict || 7965 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7966 continue; 7967 7968 // Build qualified pointee type. 7969 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7970 7971 // Build qualified pointer type. 7972 QualType QPointerTy; 7973 if (!buildObjCPtr) 7974 QPointerTy = Context.getPointerType(QPointeeTy); 7975 else 7976 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7977 7978 // Insert qualified pointer type. 7979 PointerTypes.insert(QPointerTy); 7980 } 7981 7982 return true; 7983 } 7984 7985 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7986 /// to the set of pointer types along with any more-qualified variants of 7987 /// that type. For example, if @p Ty is "int const *", this routine 7988 /// will add "int const *", "int const volatile *", "int const 7989 /// restrict *", and "int const volatile restrict *" to the set of 7990 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7991 /// false otherwise. 7992 /// 7993 /// FIXME: what to do about extended qualifiers? 7994 bool 7995 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7996 QualType Ty) { 7997 // Insert this type. 7998 if (!MemberPointerTypes.insert(Ty)) 7999 return false; 8000 8001 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8002 assert(PointerTy && "type was not a member pointer type!"); 8003 8004 QualType PointeeTy = PointerTy->getPointeeType(); 8005 // Don't add qualified variants of arrays. For one, they're not allowed 8006 // (the qualifier would sink to the element type), and for another, the 8007 // only overload situation where it matters is subscript or pointer +- int, 8008 // and those shouldn't have qualifier variants anyway. 8009 if (PointeeTy->isArrayType()) 8010 return true; 8011 const Type *ClassTy = PointerTy->getClass(); 8012 8013 // Iterate through all strict supersets of the pointee type's CVR 8014 // qualifiers. 8015 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8016 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8017 if ((CVR | BaseCVR) != CVR) continue; 8018 8019 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8020 MemberPointerTypes.insert( 8021 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8022 } 8023 8024 return true; 8025 } 8026 8027 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8028 /// Ty can be implicit converted to the given set of @p Types. We're 8029 /// primarily interested in pointer types and enumeration types. We also 8030 /// take member pointer types, for the conditional operator. 8031 /// AllowUserConversions is true if we should look at the conversion 8032 /// functions of a class type, and AllowExplicitConversions if we 8033 /// should also include the explicit conversion functions of a class 8034 /// type. 8035 void 8036 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8037 SourceLocation Loc, 8038 bool AllowUserConversions, 8039 bool AllowExplicitConversions, 8040 const Qualifiers &VisibleQuals) { 8041 // Only deal with canonical types. 8042 Ty = Context.getCanonicalType(Ty); 8043 8044 // Look through reference types; they aren't part of the type of an 8045 // expression for the purposes of conversions. 8046 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8047 Ty = RefTy->getPointeeType(); 8048 8049 // If we're dealing with an array type, decay to the pointer. 8050 if (Ty->isArrayType()) 8051 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8052 8053 // Otherwise, we don't care about qualifiers on the type. 8054 Ty = Ty.getLocalUnqualifiedType(); 8055 8056 // Flag if we ever add a non-record type. 8057 const RecordType *TyRec = Ty->getAs<RecordType>(); 8058 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8059 8060 // Flag if we encounter an arithmetic type. 8061 HasArithmeticOrEnumeralTypes = 8062 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8063 8064 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8065 PointerTypes.insert(Ty); 8066 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8067 // Insert our type, and its more-qualified variants, into the set 8068 // of types. 8069 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8070 return; 8071 } else if (Ty->isMemberPointerType()) { 8072 // Member pointers are far easier, since the pointee can't be converted. 8073 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8074 return; 8075 } else if (Ty->isEnumeralType()) { 8076 HasArithmeticOrEnumeralTypes = true; 8077 EnumerationTypes.insert(Ty); 8078 } else if (Ty->isVectorType()) { 8079 // We treat vector types as arithmetic types in many contexts as an 8080 // extension. 8081 HasArithmeticOrEnumeralTypes = true; 8082 VectorTypes.insert(Ty); 8083 } else if (Ty->isMatrixType()) { 8084 // Similar to vector types, we treat vector types as arithmetic types in 8085 // many contexts as an extension. 8086 HasArithmeticOrEnumeralTypes = true; 8087 MatrixTypes.insert(Ty); 8088 } else if (Ty->isNullPtrType()) { 8089 HasNullPtrType = true; 8090 } else if (AllowUserConversions && TyRec) { 8091 // No conversion functions in incomplete types. 8092 if (!SemaRef.isCompleteType(Loc, Ty)) 8093 return; 8094 8095 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8096 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8097 if (isa<UsingShadowDecl>(D)) 8098 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8099 8100 // Skip conversion function templates; they don't tell us anything 8101 // about which builtin types we can convert to. 8102 if (isa<FunctionTemplateDecl>(D)) 8103 continue; 8104 8105 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8106 if (AllowExplicitConversions || !Conv->isExplicit()) { 8107 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8108 VisibleQuals); 8109 } 8110 } 8111 } 8112 } 8113 /// Helper function for adjusting address spaces for the pointer or reference 8114 /// operands of builtin operators depending on the argument. 8115 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8116 Expr *Arg) { 8117 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8118 } 8119 8120 /// Helper function for AddBuiltinOperatorCandidates() that adds 8121 /// the volatile- and non-volatile-qualified assignment operators for the 8122 /// given type to the candidate set. 8123 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8124 QualType T, 8125 ArrayRef<Expr *> Args, 8126 OverloadCandidateSet &CandidateSet) { 8127 QualType ParamTypes[2]; 8128 8129 // T& operator=(T&, T) 8130 ParamTypes[0] = S.Context.getLValueReferenceType( 8131 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8132 ParamTypes[1] = T; 8133 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8134 /*IsAssignmentOperator=*/true); 8135 8136 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8137 // volatile T& operator=(volatile T&, T) 8138 ParamTypes[0] = S.Context.getLValueReferenceType( 8139 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8140 Args[0])); 8141 ParamTypes[1] = T; 8142 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8143 /*IsAssignmentOperator=*/true); 8144 } 8145 } 8146 8147 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8148 /// if any, found in visible type conversion functions found in ArgExpr's type. 8149 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8150 Qualifiers VRQuals; 8151 const RecordType *TyRec; 8152 if (const MemberPointerType *RHSMPType = 8153 ArgExpr->getType()->getAs<MemberPointerType>()) 8154 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8155 else 8156 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8157 if (!TyRec) { 8158 // Just to be safe, assume the worst case. 8159 VRQuals.addVolatile(); 8160 VRQuals.addRestrict(); 8161 return VRQuals; 8162 } 8163 8164 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8165 if (!ClassDecl->hasDefinition()) 8166 return VRQuals; 8167 8168 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8169 if (isa<UsingShadowDecl>(D)) 8170 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8171 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8172 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8173 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8174 CanTy = ResTypeRef->getPointeeType(); 8175 // Need to go down the pointer/mempointer chain and add qualifiers 8176 // as see them. 8177 bool done = false; 8178 while (!done) { 8179 if (CanTy.isRestrictQualified()) 8180 VRQuals.addRestrict(); 8181 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8182 CanTy = ResTypePtr->getPointeeType(); 8183 else if (const MemberPointerType *ResTypeMPtr = 8184 CanTy->getAs<MemberPointerType>()) 8185 CanTy = ResTypeMPtr->getPointeeType(); 8186 else 8187 done = true; 8188 if (CanTy.isVolatileQualified()) 8189 VRQuals.addVolatile(); 8190 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8191 return VRQuals; 8192 } 8193 } 8194 } 8195 return VRQuals; 8196 } 8197 8198 namespace { 8199 8200 /// Helper class to manage the addition of builtin operator overload 8201 /// candidates. It provides shared state and utility methods used throughout 8202 /// the process, as well as a helper method to add each group of builtin 8203 /// operator overloads from the standard to a candidate set. 8204 class BuiltinOperatorOverloadBuilder { 8205 // Common instance state available to all overload candidate addition methods. 8206 Sema &S; 8207 ArrayRef<Expr *> Args; 8208 Qualifiers VisibleTypeConversionsQuals; 8209 bool HasArithmeticOrEnumeralCandidateType; 8210 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8211 OverloadCandidateSet &CandidateSet; 8212 8213 static constexpr int ArithmeticTypesCap = 24; 8214 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8215 8216 // Define some indices used to iterate over the arithmetic types in 8217 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8218 // types are that preserved by promotion (C++ [over.built]p2). 8219 unsigned FirstIntegralType, 8220 LastIntegralType; 8221 unsigned FirstPromotedIntegralType, 8222 LastPromotedIntegralType; 8223 unsigned FirstPromotedArithmeticType, 8224 LastPromotedArithmeticType; 8225 unsigned NumArithmeticTypes; 8226 8227 void InitArithmeticTypes() { 8228 // Start of promoted types. 8229 FirstPromotedArithmeticType = 0; 8230 ArithmeticTypes.push_back(S.Context.FloatTy); 8231 ArithmeticTypes.push_back(S.Context.DoubleTy); 8232 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8233 if (S.Context.getTargetInfo().hasFloat128Type()) 8234 ArithmeticTypes.push_back(S.Context.Float128Ty); 8235 if (S.Context.getTargetInfo().hasIbm128Type()) 8236 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8237 8238 // Start of integral types. 8239 FirstIntegralType = ArithmeticTypes.size(); 8240 FirstPromotedIntegralType = ArithmeticTypes.size(); 8241 ArithmeticTypes.push_back(S.Context.IntTy); 8242 ArithmeticTypes.push_back(S.Context.LongTy); 8243 ArithmeticTypes.push_back(S.Context.LongLongTy); 8244 if (S.Context.getTargetInfo().hasInt128Type() || 8245 (S.Context.getAuxTargetInfo() && 8246 S.Context.getAuxTargetInfo()->hasInt128Type())) 8247 ArithmeticTypes.push_back(S.Context.Int128Ty); 8248 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8249 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8250 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8251 if (S.Context.getTargetInfo().hasInt128Type() || 8252 (S.Context.getAuxTargetInfo() && 8253 S.Context.getAuxTargetInfo()->hasInt128Type())) 8254 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8255 LastPromotedIntegralType = ArithmeticTypes.size(); 8256 LastPromotedArithmeticType = ArithmeticTypes.size(); 8257 // End of promoted types. 8258 8259 ArithmeticTypes.push_back(S.Context.BoolTy); 8260 ArithmeticTypes.push_back(S.Context.CharTy); 8261 ArithmeticTypes.push_back(S.Context.WCharTy); 8262 if (S.Context.getLangOpts().Char8) 8263 ArithmeticTypes.push_back(S.Context.Char8Ty); 8264 ArithmeticTypes.push_back(S.Context.Char16Ty); 8265 ArithmeticTypes.push_back(S.Context.Char32Ty); 8266 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8267 ArithmeticTypes.push_back(S.Context.ShortTy); 8268 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8269 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8270 LastIntegralType = ArithmeticTypes.size(); 8271 NumArithmeticTypes = ArithmeticTypes.size(); 8272 // End of integral types. 8273 // FIXME: What about complex? What about half? 8274 8275 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8276 "Enough inline storage for all arithmetic types."); 8277 } 8278 8279 /// Helper method to factor out the common pattern of adding overloads 8280 /// for '++' and '--' builtin operators. 8281 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8282 bool HasVolatile, 8283 bool HasRestrict) { 8284 QualType ParamTypes[2] = { 8285 S.Context.getLValueReferenceType(CandidateTy), 8286 S.Context.IntTy 8287 }; 8288 8289 // Non-volatile version. 8290 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8291 8292 // Use a heuristic to reduce number of builtin candidates in the set: 8293 // add volatile version only if there are conversions to a volatile type. 8294 if (HasVolatile) { 8295 ParamTypes[0] = 8296 S.Context.getLValueReferenceType( 8297 S.Context.getVolatileType(CandidateTy)); 8298 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8299 } 8300 8301 // Add restrict version only if there are conversions to a restrict type 8302 // and our candidate type is a non-restrict-qualified pointer. 8303 if (HasRestrict && CandidateTy->isAnyPointerType() && 8304 !CandidateTy.isRestrictQualified()) { 8305 ParamTypes[0] 8306 = S.Context.getLValueReferenceType( 8307 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8308 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8309 8310 if (HasVolatile) { 8311 ParamTypes[0] 8312 = S.Context.getLValueReferenceType( 8313 S.Context.getCVRQualifiedType(CandidateTy, 8314 (Qualifiers::Volatile | 8315 Qualifiers::Restrict))); 8316 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8317 } 8318 } 8319 8320 } 8321 8322 /// Helper to add an overload candidate for a binary builtin with types \p L 8323 /// and \p R. 8324 void AddCandidate(QualType L, QualType R) { 8325 QualType LandR[2] = {L, R}; 8326 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8327 } 8328 8329 public: 8330 BuiltinOperatorOverloadBuilder( 8331 Sema &S, ArrayRef<Expr *> Args, 8332 Qualifiers VisibleTypeConversionsQuals, 8333 bool HasArithmeticOrEnumeralCandidateType, 8334 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8335 OverloadCandidateSet &CandidateSet) 8336 : S(S), Args(Args), 8337 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8338 HasArithmeticOrEnumeralCandidateType( 8339 HasArithmeticOrEnumeralCandidateType), 8340 CandidateTypes(CandidateTypes), 8341 CandidateSet(CandidateSet) { 8342 8343 InitArithmeticTypes(); 8344 } 8345 8346 // Increment is deprecated for bool since C++17. 8347 // 8348 // C++ [over.built]p3: 8349 // 8350 // For every pair (T, VQ), where T is an arithmetic type other 8351 // than bool, and VQ is either volatile or empty, there exist 8352 // candidate operator functions of the form 8353 // 8354 // VQ T& operator++(VQ T&); 8355 // T operator++(VQ T&, int); 8356 // 8357 // C++ [over.built]p4: 8358 // 8359 // For every pair (T, VQ), where T is an arithmetic type other 8360 // than bool, and VQ is either volatile or empty, there exist 8361 // candidate operator functions of the form 8362 // 8363 // VQ T& operator--(VQ T&); 8364 // T operator--(VQ T&, int); 8365 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8366 if (!HasArithmeticOrEnumeralCandidateType) 8367 return; 8368 8369 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8370 const auto TypeOfT = ArithmeticTypes[Arith]; 8371 if (TypeOfT == S.Context.BoolTy) { 8372 if (Op == OO_MinusMinus) 8373 continue; 8374 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8375 continue; 8376 } 8377 addPlusPlusMinusMinusStyleOverloads( 8378 TypeOfT, 8379 VisibleTypeConversionsQuals.hasVolatile(), 8380 VisibleTypeConversionsQuals.hasRestrict()); 8381 } 8382 } 8383 8384 // C++ [over.built]p5: 8385 // 8386 // For every pair (T, VQ), where T is a cv-qualified or 8387 // cv-unqualified object type, and VQ is either volatile or 8388 // empty, there exist candidate operator functions of the form 8389 // 8390 // T*VQ& operator++(T*VQ&); 8391 // T*VQ& operator--(T*VQ&); 8392 // T* operator++(T*VQ&, int); 8393 // T* operator--(T*VQ&, int); 8394 void addPlusPlusMinusMinusPointerOverloads() { 8395 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8396 // Skip pointer types that aren't pointers to object types. 8397 if (!PtrTy->getPointeeType()->isObjectType()) 8398 continue; 8399 8400 addPlusPlusMinusMinusStyleOverloads( 8401 PtrTy, 8402 (!PtrTy.isVolatileQualified() && 8403 VisibleTypeConversionsQuals.hasVolatile()), 8404 (!PtrTy.isRestrictQualified() && 8405 VisibleTypeConversionsQuals.hasRestrict())); 8406 } 8407 } 8408 8409 // C++ [over.built]p6: 8410 // For every cv-qualified or cv-unqualified object type T, there 8411 // exist candidate operator functions of the form 8412 // 8413 // T& operator*(T*); 8414 // 8415 // C++ [over.built]p7: 8416 // For every function type T that does not have cv-qualifiers or a 8417 // ref-qualifier, there exist candidate operator functions of the form 8418 // T& operator*(T*); 8419 void addUnaryStarPointerOverloads() { 8420 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8421 QualType PointeeTy = ParamTy->getPointeeType(); 8422 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8423 continue; 8424 8425 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8426 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8427 continue; 8428 8429 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8430 } 8431 } 8432 8433 // C++ [over.built]p9: 8434 // For every promoted arithmetic type T, there exist candidate 8435 // operator functions of the form 8436 // 8437 // T operator+(T); 8438 // T operator-(T); 8439 void addUnaryPlusOrMinusArithmeticOverloads() { 8440 if (!HasArithmeticOrEnumeralCandidateType) 8441 return; 8442 8443 for (unsigned Arith = FirstPromotedArithmeticType; 8444 Arith < LastPromotedArithmeticType; ++Arith) { 8445 QualType ArithTy = ArithmeticTypes[Arith]; 8446 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8447 } 8448 8449 // Extension: We also add these operators for vector types. 8450 for (QualType VecTy : CandidateTypes[0].vector_types()) 8451 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8452 } 8453 8454 // C++ [over.built]p8: 8455 // For every type T, there exist candidate operator functions of 8456 // the form 8457 // 8458 // T* operator+(T*); 8459 void addUnaryPlusPointerOverloads() { 8460 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 8461 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8462 } 8463 8464 // C++ [over.built]p10: 8465 // For every promoted integral type T, there exist candidate 8466 // operator functions of the form 8467 // 8468 // T operator~(T); 8469 void addUnaryTildePromotedIntegralOverloads() { 8470 if (!HasArithmeticOrEnumeralCandidateType) 8471 return; 8472 8473 for (unsigned Int = FirstPromotedIntegralType; 8474 Int < LastPromotedIntegralType; ++Int) { 8475 QualType IntTy = ArithmeticTypes[Int]; 8476 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8477 } 8478 8479 // Extension: We also add this operator for vector types. 8480 for (QualType VecTy : CandidateTypes[0].vector_types()) 8481 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8482 } 8483 8484 // C++ [over.match.oper]p16: 8485 // For every pointer to member type T or type std::nullptr_t, there 8486 // exist candidate operator functions of the form 8487 // 8488 // bool operator==(T,T); 8489 // bool operator!=(T,T); 8490 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8491 /// Set of (canonical) types that we've already handled. 8492 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8493 8494 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8495 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8496 // Don't add the same builtin candidate twice. 8497 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8498 continue; 8499 8500 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 8501 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8502 } 8503 8504 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8505 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8506 if (AddedTypes.insert(NullPtrTy).second) { 8507 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8508 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8509 } 8510 } 8511 } 8512 } 8513 8514 // C++ [over.built]p15: 8515 // 8516 // For every T, where T is an enumeration type or a pointer type, 8517 // there exist candidate operator functions of the form 8518 // 8519 // bool operator<(T, T); 8520 // bool operator>(T, T); 8521 // bool operator<=(T, T); 8522 // bool operator>=(T, T); 8523 // bool operator==(T, T); 8524 // bool operator!=(T, T); 8525 // R operator<=>(T, T) 8526 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 8527 // C++ [over.match.oper]p3: 8528 // [...]the built-in candidates include all of the candidate operator 8529 // functions defined in 13.6 that, compared to the given operator, [...] 8530 // do not have the same parameter-type-list as any non-template non-member 8531 // candidate. 8532 // 8533 // Note that in practice, this only affects enumeration types because there 8534 // aren't any built-in candidates of record type, and a user-defined operator 8535 // must have an operand of record or enumeration type. Also, the only other 8536 // overloaded operator with enumeration arguments, operator=, 8537 // cannot be overloaded for enumeration types, so this is the only place 8538 // where we must suppress candidates like this. 8539 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8540 UserDefinedBinaryOperators; 8541 8542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8543 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 8544 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8545 CEnd = CandidateSet.end(); 8546 C != CEnd; ++C) { 8547 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8548 continue; 8549 8550 if (C->Function->isFunctionTemplateSpecialization()) 8551 continue; 8552 8553 // We interpret "same parameter-type-list" as applying to the 8554 // "synthesized candidate, with the order of the two parameters 8555 // reversed", not to the original function. 8556 bool Reversed = C->isReversed(); 8557 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8558 ->getType() 8559 .getUnqualifiedType(); 8560 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8561 ->getType() 8562 .getUnqualifiedType(); 8563 8564 // Skip if either parameter isn't of enumeral type. 8565 if (!FirstParamType->isEnumeralType() || 8566 !SecondParamType->isEnumeralType()) 8567 continue; 8568 8569 // Add this operator to the set of known user-defined operators. 8570 UserDefinedBinaryOperators.insert( 8571 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8572 S.Context.getCanonicalType(SecondParamType))); 8573 } 8574 } 8575 } 8576 8577 /// Set of (canonical) types that we've already handled. 8578 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8579 8580 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8581 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 8582 // Don't add the same builtin candidate twice. 8583 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8584 continue; 8585 if (IsSpaceship && PtrTy->isFunctionPointerType()) 8586 continue; 8587 8588 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8589 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8590 } 8591 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8592 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 8593 8594 // Don't add the same builtin candidate twice, or if a user defined 8595 // candidate exists. 8596 if (!AddedTypes.insert(CanonType).second || 8597 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8598 CanonType))) 8599 continue; 8600 QualType ParamTypes[2] = {EnumTy, EnumTy}; 8601 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8602 } 8603 } 8604 } 8605 8606 // C++ [over.built]p13: 8607 // 8608 // For every cv-qualified or cv-unqualified object type T 8609 // there exist candidate operator functions of the form 8610 // 8611 // T* operator+(T*, ptrdiff_t); 8612 // T& operator[](T*, ptrdiff_t); [BELOW] 8613 // T* operator-(T*, ptrdiff_t); 8614 // T* operator+(ptrdiff_t, T*); 8615 // T& operator[](ptrdiff_t, T*); [BELOW] 8616 // 8617 // C++ [over.built]p14: 8618 // 8619 // For every T, where T is a pointer to object type, there 8620 // exist candidate operator functions of the form 8621 // 8622 // ptrdiff_t operator-(T, T); 8623 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8624 /// Set of (canonical) types that we've already handled. 8625 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8626 8627 for (int Arg = 0; Arg < 2; ++Arg) { 8628 QualType AsymmetricParamTypes[2] = { 8629 S.Context.getPointerDiffType(), 8630 S.Context.getPointerDiffType(), 8631 }; 8632 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 8633 QualType PointeeTy = PtrTy->getPointeeType(); 8634 if (!PointeeTy->isObjectType()) 8635 continue; 8636 8637 AsymmetricParamTypes[Arg] = PtrTy; 8638 if (Arg == 0 || Op == OO_Plus) { 8639 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8640 // T* operator+(ptrdiff_t, T*); 8641 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8642 } 8643 if (Op == OO_Minus) { 8644 // ptrdiff_t operator-(T, T); 8645 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8646 continue; 8647 8648 QualType ParamTypes[2] = {PtrTy, PtrTy}; 8649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8650 } 8651 } 8652 } 8653 } 8654 8655 // C++ [over.built]p12: 8656 // 8657 // For every pair of promoted arithmetic types L and R, there 8658 // exist candidate operator functions of the form 8659 // 8660 // LR operator*(L, R); 8661 // LR operator/(L, R); 8662 // LR operator+(L, R); 8663 // LR operator-(L, R); 8664 // bool operator<(L, R); 8665 // bool operator>(L, R); 8666 // bool operator<=(L, R); 8667 // bool operator>=(L, R); 8668 // bool operator==(L, R); 8669 // bool operator!=(L, R); 8670 // 8671 // where LR is the result of the usual arithmetic conversions 8672 // between types L and R. 8673 // 8674 // C++ [over.built]p24: 8675 // 8676 // For every pair of promoted arithmetic types L and R, there exist 8677 // candidate operator functions of the form 8678 // 8679 // LR operator?(bool, L, R); 8680 // 8681 // where LR is the result of the usual arithmetic conversions 8682 // between types L and R. 8683 // Our candidates ignore the first parameter. 8684 void addGenericBinaryArithmeticOverloads() { 8685 if (!HasArithmeticOrEnumeralCandidateType) 8686 return; 8687 8688 for (unsigned Left = FirstPromotedArithmeticType; 8689 Left < LastPromotedArithmeticType; ++Left) { 8690 for (unsigned Right = FirstPromotedArithmeticType; 8691 Right < LastPromotedArithmeticType; ++Right) { 8692 QualType LandR[2] = { ArithmeticTypes[Left], 8693 ArithmeticTypes[Right] }; 8694 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8695 } 8696 } 8697 8698 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8699 // conditional operator for vector types. 8700 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8701 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8702 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8703 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8704 } 8705 } 8706 8707 /// Add binary operator overloads for each candidate matrix type M1, M2: 8708 /// * (M1, M1) -> M1 8709 /// * (M1, M1.getElementType()) -> M1 8710 /// * (M2.getElementType(), M2) -> M2 8711 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8712 void addMatrixBinaryArithmeticOverloads() { 8713 if (!HasArithmeticOrEnumeralCandidateType) 8714 return; 8715 8716 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8717 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8718 AddCandidate(M1, M1); 8719 } 8720 8721 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8722 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8723 if (!CandidateTypes[0].containsMatrixType(M2)) 8724 AddCandidate(M2, M2); 8725 } 8726 } 8727 8728 // C++2a [over.built]p14: 8729 // 8730 // For every integral type T there exists a candidate operator function 8731 // of the form 8732 // 8733 // std::strong_ordering operator<=>(T, T) 8734 // 8735 // C++2a [over.built]p15: 8736 // 8737 // For every pair of floating-point types L and R, there exists a candidate 8738 // operator function of the form 8739 // 8740 // std::partial_ordering operator<=>(L, R); 8741 // 8742 // FIXME: The current specification for integral types doesn't play nice with 8743 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8744 // comparisons. Under the current spec this can lead to ambiguity during 8745 // overload resolution. For example: 8746 // 8747 // enum A : int {a}; 8748 // auto x = (a <=> (long)42); 8749 // 8750 // error: call is ambiguous for arguments 'A' and 'long'. 8751 // note: candidate operator<=>(int, int) 8752 // note: candidate operator<=>(long, long) 8753 // 8754 // To avoid this error, this function deviates from the specification and adds 8755 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8756 // arithmetic types (the same as the generic relational overloads). 8757 // 8758 // For now this function acts as a placeholder. 8759 void addThreeWayArithmeticOverloads() { 8760 addGenericBinaryArithmeticOverloads(); 8761 } 8762 8763 // C++ [over.built]p17: 8764 // 8765 // For every pair of promoted integral types L and R, there 8766 // exist candidate operator functions of the form 8767 // 8768 // LR operator%(L, R); 8769 // LR operator&(L, R); 8770 // LR operator^(L, R); 8771 // LR operator|(L, R); 8772 // L operator<<(L, R); 8773 // L operator>>(L, R); 8774 // 8775 // where LR is the result of the usual arithmetic conversions 8776 // between types L and R. 8777 void addBinaryBitwiseArithmeticOverloads() { 8778 if (!HasArithmeticOrEnumeralCandidateType) 8779 return; 8780 8781 for (unsigned Left = FirstPromotedIntegralType; 8782 Left < LastPromotedIntegralType; ++Left) { 8783 for (unsigned Right = FirstPromotedIntegralType; 8784 Right < LastPromotedIntegralType; ++Right) { 8785 QualType LandR[2] = { ArithmeticTypes[Left], 8786 ArithmeticTypes[Right] }; 8787 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8788 } 8789 } 8790 } 8791 8792 // C++ [over.built]p20: 8793 // 8794 // For every pair (T, VQ), where T is an enumeration or 8795 // pointer to member type and VQ is either volatile or 8796 // empty, there exist candidate operator functions of the form 8797 // 8798 // VQ T& operator=(VQ T&, T); 8799 void addAssignmentMemberPointerOrEnumeralOverloads() { 8800 /// Set of (canonical) types that we've already handled. 8801 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8802 8803 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8804 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 8805 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 8806 continue; 8807 8808 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 8809 } 8810 8811 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 8812 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 8813 continue; 8814 8815 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 8816 } 8817 } 8818 } 8819 8820 // C++ [over.built]p19: 8821 // 8822 // For every pair (T, VQ), where T is any type and VQ is either 8823 // volatile or empty, there exist candidate operator functions 8824 // of the form 8825 // 8826 // T*VQ& operator=(T*VQ&, T*); 8827 // 8828 // C++ [over.built]p21: 8829 // 8830 // For every pair (T, VQ), where T is a cv-qualified or 8831 // cv-unqualified object type and VQ is either volatile or 8832 // empty, there exist candidate operator functions of the form 8833 // 8834 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8835 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8836 void addAssignmentPointerOverloads(bool isEqualOp) { 8837 /// Set of (canonical) types that we've already handled. 8838 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8839 8840 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8841 // If this is operator=, keep track of the builtin candidates we added. 8842 if (isEqualOp) 8843 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 8844 else if (!PtrTy->getPointeeType()->isObjectType()) 8845 continue; 8846 8847 // non-volatile version 8848 QualType ParamTypes[2] = { 8849 S.Context.getLValueReferenceType(PtrTy), 8850 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 8851 }; 8852 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8853 /*IsAssignmentOperator=*/ isEqualOp); 8854 8855 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8856 VisibleTypeConversionsQuals.hasVolatile(); 8857 if (NeedVolatile) { 8858 // volatile version 8859 ParamTypes[0] = 8860 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 8861 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8862 /*IsAssignmentOperator=*/isEqualOp); 8863 } 8864 8865 if (!PtrTy.isRestrictQualified() && 8866 VisibleTypeConversionsQuals.hasRestrict()) { 8867 // restrict version 8868 ParamTypes[0] = 8869 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 8870 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8871 /*IsAssignmentOperator=*/isEqualOp); 8872 8873 if (NeedVolatile) { 8874 // volatile restrict version 8875 ParamTypes[0] = 8876 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8877 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8878 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8879 /*IsAssignmentOperator=*/isEqualOp); 8880 } 8881 } 8882 } 8883 8884 if (isEqualOp) { 8885 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 8886 // Make sure we don't add the same candidate twice. 8887 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 8888 continue; 8889 8890 QualType ParamTypes[2] = { 8891 S.Context.getLValueReferenceType(PtrTy), 8892 PtrTy, 8893 }; 8894 8895 // non-volatile version 8896 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8897 /*IsAssignmentOperator=*/true); 8898 8899 bool NeedVolatile = !PtrTy.isVolatileQualified() && 8900 VisibleTypeConversionsQuals.hasVolatile(); 8901 if (NeedVolatile) { 8902 // volatile version 8903 ParamTypes[0] = S.Context.getLValueReferenceType( 8904 S.Context.getVolatileType(PtrTy)); 8905 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8906 /*IsAssignmentOperator=*/true); 8907 } 8908 8909 if (!PtrTy.isRestrictQualified() && 8910 VisibleTypeConversionsQuals.hasRestrict()) { 8911 // restrict version 8912 ParamTypes[0] = S.Context.getLValueReferenceType( 8913 S.Context.getRestrictType(PtrTy)); 8914 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8915 /*IsAssignmentOperator=*/true); 8916 8917 if (NeedVolatile) { 8918 // volatile restrict version 8919 ParamTypes[0] = 8920 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 8921 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 8922 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8923 /*IsAssignmentOperator=*/true); 8924 } 8925 } 8926 } 8927 } 8928 } 8929 8930 // C++ [over.built]p18: 8931 // 8932 // For every triple (L, VQ, R), where L is an arithmetic type, 8933 // VQ is either volatile or empty, and R is a promoted 8934 // arithmetic type, there exist candidate operator functions of 8935 // the form 8936 // 8937 // VQ L& operator=(VQ L&, R); 8938 // VQ L& operator*=(VQ L&, R); 8939 // VQ L& operator/=(VQ L&, R); 8940 // VQ L& operator+=(VQ L&, R); 8941 // VQ L& operator-=(VQ L&, R); 8942 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8943 if (!HasArithmeticOrEnumeralCandidateType) 8944 return; 8945 8946 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8947 for (unsigned Right = FirstPromotedArithmeticType; 8948 Right < LastPromotedArithmeticType; ++Right) { 8949 QualType ParamTypes[2]; 8950 ParamTypes[1] = ArithmeticTypes[Right]; 8951 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8952 S, ArithmeticTypes[Left], Args[0]); 8953 // Add this built-in operator as a candidate (VQ is empty). 8954 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8955 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8956 /*IsAssignmentOperator=*/isEqualOp); 8957 8958 // Add this built-in operator as a candidate (VQ is 'volatile'). 8959 if (VisibleTypeConversionsQuals.hasVolatile()) { 8960 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8961 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8962 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8963 /*IsAssignmentOperator=*/isEqualOp); 8964 } 8965 } 8966 } 8967 8968 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8969 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8970 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8971 QualType ParamTypes[2]; 8972 ParamTypes[1] = Vec2Ty; 8973 // Add this built-in operator as a candidate (VQ is empty). 8974 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8975 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8976 /*IsAssignmentOperator=*/isEqualOp); 8977 8978 // Add this built-in operator as a candidate (VQ is 'volatile'). 8979 if (VisibleTypeConversionsQuals.hasVolatile()) { 8980 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8981 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8982 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8983 /*IsAssignmentOperator=*/isEqualOp); 8984 } 8985 } 8986 } 8987 8988 // C++ [over.built]p22: 8989 // 8990 // For every triple (L, VQ, R), where L is an integral type, VQ 8991 // is either volatile or empty, and R is a promoted integral 8992 // type, there exist candidate operator functions of the form 8993 // 8994 // VQ L& operator%=(VQ L&, R); 8995 // VQ L& operator<<=(VQ L&, R); 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 void addAssignmentIntegralOverloads() { 9001 if (!HasArithmeticOrEnumeralCandidateType) 9002 return; 9003 9004 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9005 for (unsigned Right = FirstPromotedIntegralType; 9006 Right < LastPromotedIntegralType; ++Right) { 9007 QualType ParamTypes[2]; 9008 ParamTypes[1] = ArithmeticTypes[Right]; 9009 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9010 S, ArithmeticTypes[Left], Args[0]); 9011 // Add this built-in operator as a candidate (VQ is empty). 9012 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 9013 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9014 if (VisibleTypeConversionsQuals.hasVolatile()) { 9015 // Add this built-in operator as a candidate (VQ is 'volatile'). 9016 ParamTypes[0] = LeftBaseTy; 9017 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 9018 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9020 } 9021 } 9022 } 9023 } 9024 9025 // C++ [over.operator]p23: 9026 // 9027 // There also exist candidate operator functions of the form 9028 // 9029 // bool operator!(bool); 9030 // bool operator&&(bool, bool); 9031 // bool operator||(bool, bool); 9032 void addExclaimOverload() { 9033 QualType ParamTy = S.Context.BoolTy; 9034 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9035 /*IsAssignmentOperator=*/false, 9036 /*NumContextualBoolArguments=*/1); 9037 } 9038 void addAmpAmpOrPipePipeOverload() { 9039 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9040 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9041 /*IsAssignmentOperator=*/false, 9042 /*NumContextualBoolArguments=*/2); 9043 } 9044 9045 // C++ [over.built]p13: 9046 // 9047 // For every cv-qualified or cv-unqualified object type T there 9048 // exist candidate operator functions of the form 9049 // 9050 // T* operator+(T*, ptrdiff_t); [ABOVE] 9051 // T& operator[](T*, ptrdiff_t); 9052 // T* operator-(T*, ptrdiff_t); [ABOVE] 9053 // T* operator+(ptrdiff_t, T*); [ABOVE] 9054 // T& operator[](ptrdiff_t, T*); 9055 void addSubscriptOverloads() { 9056 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9057 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9058 QualType PointeeType = PtrTy->getPointeeType(); 9059 if (!PointeeType->isObjectType()) 9060 continue; 9061 9062 // T& operator[](T*, ptrdiff_t) 9063 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9064 } 9065 9066 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9067 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9068 QualType PointeeType = PtrTy->getPointeeType(); 9069 if (!PointeeType->isObjectType()) 9070 continue; 9071 9072 // T& operator[](ptrdiff_t, T*) 9073 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9074 } 9075 } 9076 9077 // C++ [over.built]p11: 9078 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9079 // C1 is the same type as C2 or is a derived class of C2, T is an object 9080 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9081 // there exist candidate operator functions of the form 9082 // 9083 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9084 // 9085 // where CV12 is the union of CV1 and CV2. 9086 void addArrowStarOverloads() { 9087 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9088 QualType C1Ty = PtrTy; 9089 QualType C1; 9090 QualifierCollector Q1; 9091 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9092 if (!isa<RecordType>(C1)) 9093 continue; 9094 // heuristic to reduce number of builtin candidates in the set. 9095 // Add volatile/restrict version only if there are conversions to a 9096 // volatile/restrict type. 9097 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9098 continue; 9099 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9100 continue; 9101 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9102 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9103 QualType C2 = QualType(mptr->getClass(), 0); 9104 C2 = C2.getUnqualifiedType(); 9105 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9106 break; 9107 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9108 // build CV12 T& 9109 QualType T = mptr->getPointeeType(); 9110 if (!VisibleTypeConversionsQuals.hasVolatile() && 9111 T.isVolatileQualified()) 9112 continue; 9113 if (!VisibleTypeConversionsQuals.hasRestrict() && 9114 T.isRestrictQualified()) 9115 continue; 9116 T = Q1.apply(S.Context, T); 9117 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9118 } 9119 } 9120 } 9121 9122 // Note that we don't consider the first argument, since it has been 9123 // contextually converted to bool long ago. The candidates below are 9124 // therefore added as binary. 9125 // 9126 // C++ [over.built]p25: 9127 // For every type T, where T is a pointer, pointer-to-member, or scoped 9128 // enumeration type, there exist candidate operator functions of the form 9129 // 9130 // T operator?(bool, T, T); 9131 // 9132 void addConditionalOperatorOverloads() { 9133 /// Set of (canonical) types that we've already handled. 9134 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9135 9136 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9137 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9138 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9139 continue; 9140 9141 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9142 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9143 } 9144 9145 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9146 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9147 continue; 9148 9149 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9150 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9151 } 9152 9153 if (S.getLangOpts().CPlusPlus11) { 9154 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9155 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9156 continue; 9157 9158 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9159 continue; 9160 9161 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9162 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9163 } 9164 } 9165 } 9166 } 9167 }; 9168 9169 } // end anonymous namespace 9170 9171 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9172 /// operator overloads to the candidate set (C++ [over.built]), based 9173 /// on the operator @p Op and the arguments given. For example, if the 9174 /// operator is a binary '+', this routine might add "int 9175 /// operator+(int, int)" to cover integer addition. 9176 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9177 SourceLocation OpLoc, 9178 ArrayRef<Expr *> Args, 9179 OverloadCandidateSet &CandidateSet) { 9180 // Find all of the types that the arguments can convert to, but only 9181 // if the operator we're looking at has built-in operator candidates 9182 // that make use of these types. Also record whether we encounter non-record 9183 // candidate types or either arithmetic or enumeral candidate types. 9184 Qualifiers VisibleTypeConversionsQuals; 9185 VisibleTypeConversionsQuals.addConst(); 9186 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9187 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9188 9189 bool HasNonRecordCandidateType = false; 9190 bool HasArithmeticOrEnumeralCandidateType = false; 9191 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9192 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9193 CandidateTypes.emplace_back(*this); 9194 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9195 OpLoc, 9196 true, 9197 (Op == OO_Exclaim || 9198 Op == OO_AmpAmp || 9199 Op == OO_PipePipe), 9200 VisibleTypeConversionsQuals); 9201 HasNonRecordCandidateType = HasNonRecordCandidateType || 9202 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9203 HasArithmeticOrEnumeralCandidateType = 9204 HasArithmeticOrEnumeralCandidateType || 9205 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9206 } 9207 9208 // Exit early when no non-record types have been added to the candidate set 9209 // for any of the arguments to the operator. 9210 // 9211 // We can't exit early for !, ||, or &&, since there we have always have 9212 // 'bool' overloads. 9213 if (!HasNonRecordCandidateType && 9214 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9215 return; 9216 9217 // Setup an object to manage the common state for building overloads. 9218 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9219 VisibleTypeConversionsQuals, 9220 HasArithmeticOrEnumeralCandidateType, 9221 CandidateTypes, CandidateSet); 9222 9223 // Dispatch over the operation to add in only those overloads which apply. 9224 switch (Op) { 9225 case OO_None: 9226 case NUM_OVERLOADED_OPERATORS: 9227 llvm_unreachable("Expected an overloaded operator"); 9228 9229 case OO_New: 9230 case OO_Delete: 9231 case OO_Array_New: 9232 case OO_Array_Delete: 9233 case OO_Call: 9234 llvm_unreachable( 9235 "Special operators don't use AddBuiltinOperatorCandidates"); 9236 9237 case OO_Comma: 9238 case OO_Arrow: 9239 case OO_Coawait: 9240 // C++ [over.match.oper]p3: 9241 // -- For the operator ',', the unary operator '&', the 9242 // operator '->', or the operator 'co_await', the 9243 // built-in candidates set is empty. 9244 break; 9245 9246 case OO_Plus: // '+' is either unary or binary 9247 if (Args.size() == 1) 9248 OpBuilder.addUnaryPlusPointerOverloads(); 9249 LLVM_FALLTHROUGH; 9250 9251 case OO_Minus: // '-' is either unary or binary 9252 if (Args.size() == 1) { 9253 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9254 } else { 9255 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9256 OpBuilder.addGenericBinaryArithmeticOverloads(); 9257 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9258 } 9259 break; 9260 9261 case OO_Star: // '*' is either unary or binary 9262 if (Args.size() == 1) 9263 OpBuilder.addUnaryStarPointerOverloads(); 9264 else { 9265 OpBuilder.addGenericBinaryArithmeticOverloads(); 9266 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9267 } 9268 break; 9269 9270 case OO_Slash: 9271 OpBuilder.addGenericBinaryArithmeticOverloads(); 9272 break; 9273 9274 case OO_PlusPlus: 9275 case OO_MinusMinus: 9276 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9277 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9278 break; 9279 9280 case OO_EqualEqual: 9281 case OO_ExclaimEqual: 9282 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9283 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9284 OpBuilder.addGenericBinaryArithmeticOverloads(); 9285 break; 9286 9287 case OO_Less: 9288 case OO_Greater: 9289 case OO_LessEqual: 9290 case OO_GreaterEqual: 9291 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9292 OpBuilder.addGenericBinaryArithmeticOverloads(); 9293 break; 9294 9295 case OO_Spaceship: 9296 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9297 OpBuilder.addThreeWayArithmeticOverloads(); 9298 break; 9299 9300 case OO_Percent: 9301 case OO_Caret: 9302 case OO_Pipe: 9303 case OO_LessLess: 9304 case OO_GreaterGreater: 9305 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9306 break; 9307 9308 case OO_Amp: // '&' is either unary or binary 9309 if (Args.size() == 1) 9310 // C++ [over.match.oper]p3: 9311 // -- For the operator ',', the unary operator '&', or the 9312 // operator '->', the built-in candidates set is empty. 9313 break; 9314 9315 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9316 break; 9317 9318 case OO_Tilde: 9319 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9320 break; 9321 9322 case OO_Equal: 9323 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9324 LLVM_FALLTHROUGH; 9325 9326 case OO_PlusEqual: 9327 case OO_MinusEqual: 9328 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9329 LLVM_FALLTHROUGH; 9330 9331 case OO_StarEqual: 9332 case OO_SlashEqual: 9333 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9334 break; 9335 9336 case OO_PercentEqual: 9337 case OO_LessLessEqual: 9338 case OO_GreaterGreaterEqual: 9339 case OO_AmpEqual: 9340 case OO_CaretEqual: 9341 case OO_PipeEqual: 9342 OpBuilder.addAssignmentIntegralOverloads(); 9343 break; 9344 9345 case OO_Exclaim: 9346 OpBuilder.addExclaimOverload(); 9347 break; 9348 9349 case OO_AmpAmp: 9350 case OO_PipePipe: 9351 OpBuilder.addAmpAmpOrPipePipeOverload(); 9352 break; 9353 9354 case OO_Subscript: 9355 OpBuilder.addSubscriptOverloads(); 9356 break; 9357 9358 case OO_ArrowStar: 9359 OpBuilder.addArrowStarOverloads(); 9360 break; 9361 9362 case OO_Conditional: 9363 OpBuilder.addConditionalOperatorOverloads(); 9364 OpBuilder.addGenericBinaryArithmeticOverloads(); 9365 break; 9366 } 9367 } 9368 9369 /// Add function candidates found via argument-dependent lookup 9370 /// to the set of overloading candidates. 9371 /// 9372 /// This routine performs argument-dependent name lookup based on the 9373 /// given function name (which may also be an operator name) and adds 9374 /// all of the overload candidates found by ADL to the overload 9375 /// candidate set (C++ [basic.lookup.argdep]). 9376 void 9377 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9378 SourceLocation Loc, 9379 ArrayRef<Expr *> Args, 9380 TemplateArgumentListInfo *ExplicitTemplateArgs, 9381 OverloadCandidateSet& CandidateSet, 9382 bool PartialOverloading) { 9383 ADLResult Fns; 9384 9385 // FIXME: This approach for uniquing ADL results (and removing 9386 // redundant candidates from the set) relies on pointer-equality, 9387 // which means we need to key off the canonical decl. However, 9388 // always going back to the canonical decl might not get us the 9389 // right set of default arguments. What default arguments are 9390 // we supposed to consider on ADL candidates, anyway? 9391 9392 // FIXME: Pass in the explicit template arguments? 9393 ArgumentDependentLookup(Name, Loc, Args, Fns); 9394 9395 // Erase all of the candidates we already knew about. 9396 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9397 CandEnd = CandidateSet.end(); 9398 Cand != CandEnd; ++Cand) 9399 if (Cand->Function) { 9400 Fns.erase(Cand->Function); 9401 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9402 Fns.erase(FunTmpl); 9403 } 9404 9405 // For each of the ADL candidates we found, add it to the overload 9406 // set. 9407 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9408 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9409 9410 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9411 if (ExplicitTemplateArgs) 9412 continue; 9413 9414 AddOverloadCandidate( 9415 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9416 PartialOverloading, /*AllowExplicit=*/true, 9417 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9418 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9419 AddOverloadCandidate( 9420 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9421 /*SuppressUserConversions=*/false, PartialOverloading, 9422 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9423 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9424 } 9425 } else { 9426 auto *FTD = cast<FunctionTemplateDecl>(*I); 9427 AddTemplateOverloadCandidate( 9428 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9429 /*SuppressUserConversions=*/false, PartialOverloading, 9430 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9431 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9432 Context, FTD->getTemplatedDecl())) { 9433 AddTemplateOverloadCandidate( 9434 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9435 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9436 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9437 OverloadCandidateParamOrder::Reversed); 9438 } 9439 } 9440 } 9441 } 9442 9443 namespace { 9444 enum class Comparison { Equal, Better, Worse }; 9445 } 9446 9447 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9448 /// overload resolution. 9449 /// 9450 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9451 /// Cand1's first N enable_if attributes have precisely the same conditions as 9452 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9453 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9454 /// 9455 /// Note that you can have a pair of candidates such that Cand1's enable_if 9456 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9457 /// worse than Cand1's. 9458 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9459 const FunctionDecl *Cand2) { 9460 // Common case: One (or both) decls don't have enable_if attrs. 9461 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9462 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9463 if (!Cand1Attr || !Cand2Attr) { 9464 if (Cand1Attr == Cand2Attr) 9465 return Comparison::Equal; 9466 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9467 } 9468 9469 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9470 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9471 9472 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9473 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9474 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9475 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9476 9477 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9478 // has fewer enable_if attributes than Cand2, and vice versa. 9479 if (!Cand1A) 9480 return Comparison::Worse; 9481 if (!Cand2A) 9482 return Comparison::Better; 9483 9484 Cand1ID.clear(); 9485 Cand2ID.clear(); 9486 9487 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9488 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9489 if (Cand1ID != Cand2ID) 9490 return Comparison::Worse; 9491 } 9492 9493 return Comparison::Equal; 9494 } 9495 9496 static Comparison 9497 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9498 const OverloadCandidate &Cand2) { 9499 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9500 !Cand2.Function->isMultiVersion()) 9501 return Comparison::Equal; 9502 9503 // If both are invalid, they are equal. If one of them is invalid, the other 9504 // is better. 9505 if (Cand1.Function->isInvalidDecl()) { 9506 if (Cand2.Function->isInvalidDecl()) 9507 return Comparison::Equal; 9508 return Comparison::Worse; 9509 } 9510 if (Cand2.Function->isInvalidDecl()) 9511 return Comparison::Better; 9512 9513 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9514 // cpu_dispatch, else arbitrarily based on the identifiers. 9515 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9516 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9517 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9518 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9519 9520 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9521 return Comparison::Equal; 9522 9523 if (Cand1CPUDisp && !Cand2CPUDisp) 9524 return Comparison::Better; 9525 if (Cand2CPUDisp && !Cand1CPUDisp) 9526 return Comparison::Worse; 9527 9528 if (Cand1CPUSpec && Cand2CPUSpec) { 9529 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9530 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9531 ? Comparison::Better 9532 : Comparison::Worse; 9533 9534 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9535 FirstDiff = std::mismatch( 9536 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9537 Cand2CPUSpec->cpus_begin(), 9538 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9539 return LHS->getName() == RHS->getName(); 9540 }); 9541 9542 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9543 "Two different cpu-specific versions should not have the same " 9544 "identifier list, otherwise they'd be the same decl!"); 9545 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9546 ? Comparison::Better 9547 : Comparison::Worse; 9548 } 9549 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9550 } 9551 9552 /// Compute the type of the implicit object parameter for the given function, 9553 /// if any. Returns None if there is no implicit object parameter, and a null 9554 /// QualType if there is a 'matches anything' implicit object parameter. 9555 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9556 const FunctionDecl *F) { 9557 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9558 return llvm::None; 9559 9560 auto *M = cast<CXXMethodDecl>(F); 9561 // Static member functions' object parameters match all types. 9562 if (M->isStatic()) 9563 return QualType(); 9564 9565 QualType T = M->getThisObjectType(); 9566 if (M->getRefQualifier() == RQ_RValue) 9567 return Context.getRValueReferenceType(T); 9568 return Context.getLValueReferenceType(T); 9569 } 9570 9571 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9572 const FunctionDecl *F2, unsigned NumParams) { 9573 if (declaresSameEntity(F1, F2)) 9574 return true; 9575 9576 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9577 if (First) { 9578 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9579 return *T; 9580 } 9581 assert(I < F->getNumParams()); 9582 return F->getParamDecl(I++)->getType(); 9583 }; 9584 9585 unsigned I1 = 0, I2 = 0; 9586 for (unsigned I = 0; I != NumParams; ++I) { 9587 QualType T1 = NextParam(F1, I1, I == 0); 9588 QualType T2 = NextParam(F2, I2, I == 0); 9589 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 9590 if (!Context.hasSameUnqualifiedType(T1, T2)) 9591 return false; 9592 } 9593 return true; 9594 } 9595 9596 /// isBetterOverloadCandidate - Determines whether the first overload 9597 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9598 bool clang::isBetterOverloadCandidate( 9599 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9600 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9601 // Define viable functions to be better candidates than non-viable 9602 // functions. 9603 if (!Cand2.Viable) 9604 return Cand1.Viable; 9605 else if (!Cand1.Viable) 9606 return false; 9607 9608 // [CUDA] A function with 'never' preference is marked not viable, therefore 9609 // is never shown up here. The worst preference shown up here is 'wrong side', 9610 // e.g. an H function called by a HD function in device compilation. This is 9611 // valid AST as long as the HD function is not emitted, e.g. it is an inline 9612 // function which is called only by an H function. A deferred diagnostic will 9613 // be triggered if it is emitted. However a wrong-sided function is still 9614 // a viable candidate here. 9615 // 9616 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 9617 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 9618 // can be emitted, Cand1 is not better than Cand2. This rule should have 9619 // precedence over other rules. 9620 // 9621 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 9622 // other rules should be used to determine which is better. This is because 9623 // host/device based overloading resolution is mostly for determining 9624 // viability of a function. If two functions are both viable, other factors 9625 // should take precedence in preference, e.g. the standard-defined preferences 9626 // like argument conversion ranks or enable_if partial-ordering. The 9627 // preference for pass-object-size parameters is probably most similar to a 9628 // type-based-overloading decision and so should take priority. 9629 // 9630 // If other rules cannot determine which is better, CUDA preference will be 9631 // used again to determine which is better. 9632 // 9633 // TODO: Currently IdentifyCUDAPreference does not return correct values 9634 // for functions called in global variable initializers due to missing 9635 // correct context about device/host. Therefore we can only enforce this 9636 // rule when there is a caller. We should enforce this rule for functions 9637 // in global variable initializers once proper context is added. 9638 // 9639 // TODO: We can only enable the hostness based overloading resolution when 9640 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 9641 // overloading resolution diagnostics. 9642 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 9643 S.getLangOpts().GPUExcludeWrongSideOverloads) { 9644 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) { 9645 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 9646 bool IsCand1ImplicitHD = 9647 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 9648 bool IsCand2ImplicitHD = 9649 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 9650 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 9651 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 9652 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 9653 // The implicit HD function may be a function in a system header which 9654 // is forced by pragma. In device compilation, if we prefer HD candidates 9655 // over wrong-sided candidates, overloading resolution may change, which 9656 // may result in non-deferrable diagnostics. As a workaround, we let 9657 // implicit HD candidates take equal preference as wrong-sided candidates. 9658 // This will preserve the overloading resolution. 9659 // TODO: We still need special handling of implicit HD functions since 9660 // they may incur other diagnostics to be deferred. We should make all 9661 // host/device related diagnostics deferrable and remove special handling 9662 // of implicit HD functions. 9663 auto EmitThreshold = 9664 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 9665 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 9666 ? Sema::CFP_Never 9667 : Sema::CFP_WrongSide; 9668 auto Cand1Emittable = P1 > EmitThreshold; 9669 auto Cand2Emittable = P2 > EmitThreshold; 9670 if (Cand1Emittable && !Cand2Emittable) 9671 return true; 9672 if (!Cand1Emittable && Cand2Emittable) 9673 return false; 9674 } 9675 } 9676 9677 // C++ [over.match.best]p1: 9678 // 9679 // -- if F is a static member function, ICS1(F) is defined such 9680 // that ICS1(F) is neither better nor worse than ICS1(G) for 9681 // any function G, and, symmetrically, ICS1(G) is neither 9682 // better nor worse than ICS1(F). 9683 unsigned StartArg = 0; 9684 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9685 StartArg = 1; 9686 9687 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9688 // We don't allow incompatible pointer conversions in C++. 9689 if (!S.getLangOpts().CPlusPlus) 9690 return ICS.isStandard() && 9691 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9692 9693 // The only ill-formed conversion we allow in C++ is the string literal to 9694 // char* conversion, which is only considered ill-formed after C++11. 9695 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9696 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9697 }; 9698 9699 // Define functions that don't require ill-formed conversions for a given 9700 // argument to be better candidates than functions that do. 9701 unsigned NumArgs = Cand1.Conversions.size(); 9702 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9703 bool HasBetterConversion = false; 9704 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9705 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9706 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9707 if (Cand1Bad != Cand2Bad) { 9708 if (Cand1Bad) 9709 return false; 9710 HasBetterConversion = true; 9711 } 9712 } 9713 9714 if (HasBetterConversion) 9715 return true; 9716 9717 // C++ [over.match.best]p1: 9718 // A viable function F1 is defined to be a better function than another 9719 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9720 // conversion sequence than ICSi(F2), and then... 9721 bool HasWorseConversion = false; 9722 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9723 switch (CompareImplicitConversionSequences(S, Loc, 9724 Cand1.Conversions[ArgIdx], 9725 Cand2.Conversions[ArgIdx])) { 9726 case ImplicitConversionSequence::Better: 9727 // Cand1 has a better conversion sequence. 9728 HasBetterConversion = true; 9729 break; 9730 9731 case ImplicitConversionSequence::Worse: 9732 if (Cand1.Function && Cand2.Function && 9733 Cand1.isReversed() != Cand2.isReversed() && 9734 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9735 NumArgs)) { 9736 // Work around large-scale breakage caused by considering reversed 9737 // forms of operator== in C++20: 9738 // 9739 // When comparing a function against a reversed function with the same 9740 // parameter types, if we have a better conversion for one argument and 9741 // a worse conversion for the other, the implicit conversion sequences 9742 // are treated as being equally good. 9743 // 9744 // This prevents a comparison function from being considered ambiguous 9745 // with a reversed form that is written in the same way. 9746 // 9747 // We diagnose this as an extension from CreateOverloadedBinOp. 9748 HasWorseConversion = true; 9749 break; 9750 } 9751 9752 // Cand1 can't be better than Cand2. 9753 return false; 9754 9755 case ImplicitConversionSequence::Indistinguishable: 9756 // Do nothing. 9757 break; 9758 } 9759 } 9760 9761 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9762 // ICSj(F2), or, if not that, 9763 if (HasBetterConversion && !HasWorseConversion) 9764 return true; 9765 9766 // -- the context is an initialization by user-defined conversion 9767 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9768 // from the return type of F1 to the destination type (i.e., 9769 // the type of the entity being initialized) is a better 9770 // conversion sequence than the standard conversion sequence 9771 // from the return type of F2 to the destination type. 9772 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9773 Cand1.Function && Cand2.Function && 9774 isa<CXXConversionDecl>(Cand1.Function) && 9775 isa<CXXConversionDecl>(Cand2.Function)) { 9776 // First check whether we prefer one of the conversion functions over the 9777 // other. This only distinguishes the results in non-standard, extension 9778 // cases such as the conversion from a lambda closure type to a function 9779 // pointer or block. 9780 ImplicitConversionSequence::CompareKind Result = 9781 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9782 if (Result == ImplicitConversionSequence::Indistinguishable) 9783 Result = CompareStandardConversionSequences(S, Loc, 9784 Cand1.FinalConversion, 9785 Cand2.FinalConversion); 9786 9787 if (Result != ImplicitConversionSequence::Indistinguishable) 9788 return Result == ImplicitConversionSequence::Better; 9789 9790 // FIXME: Compare kind of reference binding if conversion functions 9791 // convert to a reference type used in direct reference binding, per 9792 // C++14 [over.match.best]p1 section 2 bullet 3. 9793 } 9794 9795 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9796 // as combined with the resolution to CWG issue 243. 9797 // 9798 // When the context is initialization by constructor ([over.match.ctor] or 9799 // either phase of [over.match.list]), a constructor is preferred over 9800 // a conversion function. 9801 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9802 Cand1.Function && Cand2.Function && 9803 isa<CXXConstructorDecl>(Cand1.Function) != 9804 isa<CXXConstructorDecl>(Cand2.Function)) 9805 return isa<CXXConstructorDecl>(Cand1.Function); 9806 9807 // -- F1 is a non-template function and F2 is a function template 9808 // specialization, or, if not that, 9809 bool Cand1IsSpecialization = Cand1.Function && 9810 Cand1.Function->getPrimaryTemplate(); 9811 bool Cand2IsSpecialization = Cand2.Function && 9812 Cand2.Function->getPrimaryTemplate(); 9813 if (Cand1IsSpecialization != Cand2IsSpecialization) 9814 return Cand2IsSpecialization; 9815 9816 // -- F1 and F2 are function template specializations, and the function 9817 // template for F1 is more specialized than the template for F2 9818 // according to the partial ordering rules described in 14.5.5.2, or, 9819 // if not that, 9820 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9821 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9822 Cand1.Function->getPrimaryTemplate(), 9823 Cand2.Function->getPrimaryTemplate(), Loc, 9824 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9825 : TPOC_Call, 9826 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9827 Cand1.isReversed() ^ Cand2.isReversed())) 9828 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9829 } 9830 9831 // -— F1 and F2 are non-template functions with the same 9832 // parameter-type-lists, and F1 is more constrained than F2 [...], 9833 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9834 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9835 Cand2.Function->hasPrototype()) { 9836 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9837 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9838 if (PT1->getNumParams() == PT2->getNumParams() && 9839 PT1->isVariadic() == PT2->isVariadic() && 9840 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9841 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9842 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9843 if (RC1 && RC2) { 9844 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9845 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9846 {RC2}, AtLeastAsConstrained1) || 9847 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9848 {RC1}, AtLeastAsConstrained2)) 9849 return false; 9850 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9851 return AtLeastAsConstrained1; 9852 } else if (RC1 || RC2) { 9853 return RC1 != nullptr; 9854 } 9855 } 9856 } 9857 9858 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9859 // class B of D, and for all arguments the corresponding parameters of 9860 // F1 and F2 have the same type. 9861 // FIXME: Implement the "all parameters have the same type" check. 9862 bool Cand1IsInherited = 9863 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9864 bool Cand2IsInherited = 9865 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9866 if (Cand1IsInherited != Cand2IsInherited) 9867 return Cand2IsInherited; 9868 else if (Cand1IsInherited) { 9869 assert(Cand2IsInherited); 9870 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9871 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9872 if (Cand1Class->isDerivedFrom(Cand2Class)) 9873 return true; 9874 if (Cand2Class->isDerivedFrom(Cand1Class)) 9875 return false; 9876 // Inherited from sibling base classes: still ambiguous. 9877 } 9878 9879 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9880 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9881 // with reversed order of parameters and F1 is not 9882 // 9883 // We rank reversed + different operator as worse than just reversed, but 9884 // that comparison can never happen, because we only consider reversing for 9885 // the maximally-rewritten operator (== or <=>). 9886 if (Cand1.RewriteKind != Cand2.RewriteKind) 9887 return Cand1.RewriteKind < Cand2.RewriteKind; 9888 9889 // Check C++17 tie-breakers for deduction guides. 9890 { 9891 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9892 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9893 if (Guide1 && Guide2) { 9894 // -- F1 is generated from a deduction-guide and F2 is not 9895 if (Guide1->isImplicit() != Guide2->isImplicit()) 9896 return Guide2->isImplicit(); 9897 9898 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9899 if (Guide1->isCopyDeductionCandidate()) 9900 return true; 9901 } 9902 } 9903 9904 // Check for enable_if value-based overload resolution. 9905 if (Cand1.Function && Cand2.Function) { 9906 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9907 if (Cmp != Comparison::Equal) 9908 return Cmp == Comparison::Better; 9909 } 9910 9911 bool HasPS1 = Cand1.Function != nullptr && 9912 functionHasPassObjectSizeParams(Cand1.Function); 9913 bool HasPS2 = Cand2.Function != nullptr && 9914 functionHasPassObjectSizeParams(Cand2.Function); 9915 if (HasPS1 != HasPS2 && HasPS1) 9916 return true; 9917 9918 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 9919 if (MV == Comparison::Better) 9920 return true; 9921 if (MV == Comparison::Worse) 9922 return false; 9923 9924 // If other rules cannot determine which is better, CUDA preference is used 9925 // to determine which is better. 9926 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9927 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9928 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9929 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9930 } 9931 9932 // General member function overloading is handled above, so this only handles 9933 // constructors with address spaces. 9934 // This only handles address spaces since C++ has no other 9935 // qualifier that can be used with constructors. 9936 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 9937 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 9938 if (CD1 && CD2) { 9939 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 9940 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 9941 if (AS1 != AS2) { 9942 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 9943 return true; 9944 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 9945 return false; 9946 } 9947 } 9948 9949 return false; 9950 } 9951 9952 /// Determine whether two declarations are "equivalent" for the purposes of 9953 /// name lookup and overload resolution. This applies when the same internal/no 9954 /// linkage entity is defined by two modules (probably by textually including 9955 /// the same header). In such a case, we don't consider the declarations to 9956 /// declare the same entity, but we also don't want lookups with both 9957 /// declarations visible to be ambiguous in some cases (this happens when using 9958 /// a modularized libstdc++). 9959 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9960 const NamedDecl *B) { 9961 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9962 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9963 if (!VA || !VB) 9964 return false; 9965 9966 // The declarations must be declaring the same name as an internal linkage 9967 // entity in different modules. 9968 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9969 VB->getDeclContext()->getRedeclContext()) || 9970 getOwningModule(VA) == getOwningModule(VB) || 9971 VA->isExternallyVisible() || VB->isExternallyVisible()) 9972 return false; 9973 9974 // Check that the declarations appear to be equivalent. 9975 // 9976 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9977 // For constants and functions, we should check the initializer or body is 9978 // the same. For non-constant variables, we shouldn't allow it at all. 9979 if (Context.hasSameType(VA->getType(), VB->getType())) 9980 return true; 9981 9982 // Enum constants within unnamed enumerations will have different types, but 9983 // may still be similar enough to be interchangeable for our purposes. 9984 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9985 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9986 // Only handle anonymous enums. If the enumerations were named and 9987 // equivalent, they would have been merged to the same type. 9988 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9989 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9990 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9991 !Context.hasSameType(EnumA->getIntegerType(), 9992 EnumB->getIntegerType())) 9993 return false; 9994 // Allow this only if the value is the same for both enumerators. 9995 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9996 } 9997 } 9998 9999 // Nothing else is sufficiently similar. 10000 return false; 10001 } 10002 10003 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10004 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10005 assert(D && "Unknown declaration"); 10006 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10007 10008 Module *M = getOwningModule(D); 10009 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10010 << !M << (M ? M->getFullModuleName() : ""); 10011 10012 for (auto *E : Equiv) { 10013 Module *M = getOwningModule(E); 10014 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10015 << !M << (M ? M->getFullModuleName() : ""); 10016 } 10017 } 10018 10019 /// Computes the best viable function (C++ 13.3.3) 10020 /// within an overload candidate set. 10021 /// 10022 /// \param Loc The location of the function name (or operator symbol) for 10023 /// which overload resolution occurs. 10024 /// 10025 /// \param Best If overload resolution was successful or found a deleted 10026 /// function, \p Best points to the candidate function found. 10027 /// 10028 /// \returns The result of overload resolution. 10029 OverloadingResult 10030 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10031 iterator &Best) { 10032 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10033 std::transform(begin(), end(), std::back_inserter(Candidates), 10034 [](OverloadCandidate &Cand) { return &Cand; }); 10035 10036 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10037 // are accepted by both clang and NVCC. However, during a particular 10038 // compilation mode only one call variant is viable. We need to 10039 // exclude non-viable overload candidates from consideration based 10040 // only on their host/device attributes. Specifically, if one 10041 // candidate call is WrongSide and the other is SameSide, we ignore 10042 // the WrongSide candidate. 10043 // We only need to remove wrong-sided candidates here if 10044 // -fgpu-exclude-wrong-side-overloads is off. When 10045 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10046 // uniformly in isBetterOverloadCandidate. 10047 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10048 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 10049 bool ContainsSameSideCandidate = 10050 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10051 // Check viable function only. 10052 return Cand->Viable && Cand->Function && 10053 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10054 Sema::CFP_SameSide; 10055 }); 10056 if (ContainsSameSideCandidate) { 10057 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10058 // Check viable function only to avoid unnecessary data copying/moving. 10059 return Cand->Viable && Cand->Function && 10060 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10061 Sema::CFP_WrongSide; 10062 }; 10063 llvm::erase_if(Candidates, IsWrongSideCandidate); 10064 } 10065 } 10066 10067 // Find the best viable function. 10068 Best = end(); 10069 for (auto *Cand : Candidates) { 10070 Cand->Best = false; 10071 if (Cand->Viable) 10072 if (Best == end() || 10073 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10074 Best = Cand; 10075 } 10076 10077 // If we didn't find any viable functions, abort. 10078 if (Best == end()) 10079 return OR_No_Viable_Function; 10080 10081 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10082 10083 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10084 PendingBest.push_back(&*Best); 10085 Best->Best = true; 10086 10087 // Make sure that this function is better than every other viable 10088 // function. If not, we have an ambiguity. 10089 while (!PendingBest.empty()) { 10090 auto *Curr = PendingBest.pop_back_val(); 10091 for (auto *Cand : Candidates) { 10092 if (Cand->Viable && !Cand->Best && 10093 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10094 PendingBest.push_back(Cand); 10095 Cand->Best = true; 10096 10097 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10098 Curr->Function)) 10099 EquivalentCands.push_back(Cand->Function); 10100 else 10101 Best = end(); 10102 } 10103 } 10104 } 10105 10106 // If we found more than one best candidate, this is ambiguous. 10107 if (Best == end()) 10108 return OR_Ambiguous; 10109 10110 // Best is the best viable function. 10111 if (Best->Function && Best->Function->isDeleted()) 10112 return OR_Deleted; 10113 10114 if (!EquivalentCands.empty()) 10115 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10116 EquivalentCands); 10117 10118 return OR_Success; 10119 } 10120 10121 namespace { 10122 10123 enum OverloadCandidateKind { 10124 oc_function, 10125 oc_method, 10126 oc_reversed_binary_operator, 10127 oc_constructor, 10128 oc_implicit_default_constructor, 10129 oc_implicit_copy_constructor, 10130 oc_implicit_move_constructor, 10131 oc_implicit_copy_assignment, 10132 oc_implicit_move_assignment, 10133 oc_implicit_equality_comparison, 10134 oc_inherited_constructor 10135 }; 10136 10137 enum OverloadCandidateSelect { 10138 ocs_non_template, 10139 ocs_template, 10140 ocs_described_template, 10141 }; 10142 10143 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10144 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 10145 OverloadCandidateRewriteKind CRK, 10146 std::string &Description) { 10147 10148 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10149 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10150 isTemplate = true; 10151 Description = S.getTemplateArgumentBindingsText( 10152 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10153 } 10154 10155 OverloadCandidateSelect Select = [&]() { 10156 if (!Description.empty()) 10157 return ocs_described_template; 10158 return isTemplate ? ocs_template : ocs_non_template; 10159 }(); 10160 10161 OverloadCandidateKind Kind = [&]() { 10162 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10163 return oc_implicit_equality_comparison; 10164 10165 if (CRK & CRK_Reversed) 10166 return oc_reversed_binary_operator; 10167 10168 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10169 if (!Ctor->isImplicit()) { 10170 if (isa<ConstructorUsingShadowDecl>(Found)) 10171 return oc_inherited_constructor; 10172 else 10173 return oc_constructor; 10174 } 10175 10176 if (Ctor->isDefaultConstructor()) 10177 return oc_implicit_default_constructor; 10178 10179 if (Ctor->isMoveConstructor()) 10180 return oc_implicit_move_constructor; 10181 10182 assert(Ctor->isCopyConstructor() && 10183 "unexpected sort of implicit constructor"); 10184 return oc_implicit_copy_constructor; 10185 } 10186 10187 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10188 // This actually gets spelled 'candidate function' for now, but 10189 // it doesn't hurt to split it out. 10190 if (!Meth->isImplicit()) 10191 return oc_method; 10192 10193 if (Meth->isMoveAssignmentOperator()) 10194 return oc_implicit_move_assignment; 10195 10196 if (Meth->isCopyAssignmentOperator()) 10197 return oc_implicit_copy_assignment; 10198 10199 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10200 return oc_method; 10201 } 10202 10203 return oc_function; 10204 }(); 10205 10206 return std::make_pair(Kind, Select); 10207 } 10208 10209 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10210 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10211 // set. 10212 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10213 S.Diag(FoundDecl->getLocation(), 10214 diag::note_ovl_candidate_inherited_constructor) 10215 << Shadow->getNominatedBaseClass(); 10216 } 10217 10218 } // end anonymous namespace 10219 10220 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10221 const FunctionDecl *FD) { 10222 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10223 bool AlwaysTrue; 10224 if (EnableIf->getCond()->isValueDependent() || 10225 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10226 return false; 10227 if (!AlwaysTrue) 10228 return false; 10229 } 10230 return true; 10231 } 10232 10233 /// Returns true if we can take the address of the function. 10234 /// 10235 /// \param Complain - If true, we'll emit a diagnostic 10236 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10237 /// we in overload resolution? 10238 /// \param Loc - The location of the statement we're complaining about. Ignored 10239 /// if we're not complaining, or if we're in overload resolution. 10240 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10241 bool Complain, 10242 bool InOverloadResolution, 10243 SourceLocation Loc) { 10244 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10245 if (Complain) { 10246 if (InOverloadResolution) 10247 S.Diag(FD->getBeginLoc(), 10248 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10249 else 10250 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10251 } 10252 return false; 10253 } 10254 10255 if (FD->getTrailingRequiresClause()) { 10256 ConstraintSatisfaction Satisfaction; 10257 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10258 return false; 10259 if (!Satisfaction.IsSatisfied) { 10260 if (Complain) { 10261 if (InOverloadResolution) 10262 S.Diag(FD->getBeginLoc(), 10263 diag::note_ovl_candidate_unsatisfied_constraints); 10264 else 10265 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10266 << FD; 10267 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10268 } 10269 return false; 10270 } 10271 } 10272 10273 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10274 return P->hasAttr<PassObjectSizeAttr>(); 10275 }); 10276 if (I == FD->param_end()) 10277 return true; 10278 10279 if (Complain) { 10280 // Add one to ParamNo because it's user-facing 10281 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10282 if (InOverloadResolution) 10283 S.Diag(FD->getLocation(), 10284 diag::note_ovl_candidate_has_pass_object_size_params) 10285 << ParamNo; 10286 else 10287 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10288 << FD << ParamNo; 10289 } 10290 return false; 10291 } 10292 10293 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10294 const FunctionDecl *FD) { 10295 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10296 /*InOverloadResolution=*/true, 10297 /*Loc=*/SourceLocation()); 10298 } 10299 10300 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10301 bool Complain, 10302 SourceLocation Loc) { 10303 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10304 /*InOverloadResolution=*/false, 10305 Loc); 10306 } 10307 10308 // Don't print candidates other than the one that matches the calling 10309 // convention of the call operator, since that is guaranteed to exist. 10310 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) { 10311 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10312 10313 if (!ConvD) 10314 return false; 10315 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10316 if (!RD->isLambda()) 10317 return false; 10318 10319 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10320 CallingConv CallOpCC = 10321 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10322 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10323 CallingConv ConvToCC = 10324 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10325 10326 return ConvToCC != CallOpCC; 10327 } 10328 10329 // Notes the location of an overload candidate. 10330 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10331 OverloadCandidateRewriteKind RewriteKind, 10332 QualType DestType, bool TakingAddress) { 10333 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10334 return; 10335 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10336 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10337 return; 10338 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10339 return; 10340 10341 std::string FnDesc; 10342 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10343 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10344 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10345 << (unsigned)KSPair.first << (unsigned)KSPair.second 10346 << Fn << FnDesc; 10347 10348 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10349 Diag(Fn->getLocation(), PD); 10350 MaybeEmitInheritedConstructorNote(*this, Found); 10351 } 10352 10353 static void 10354 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10355 // Perhaps the ambiguity was caused by two atomic constraints that are 10356 // 'identical' but not equivalent: 10357 // 10358 // void foo() requires (sizeof(T) > 4) { } // #1 10359 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10360 // 10361 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10362 // #2 to subsume #1, but these constraint are not considered equivalent 10363 // according to the subsumption rules because they are not the same 10364 // source-level construct. This behavior is quite confusing and we should try 10365 // to help the user figure out what happened. 10366 10367 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10368 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10369 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10370 if (!I->Function) 10371 continue; 10372 SmallVector<const Expr *, 3> AC; 10373 if (auto *Template = I->Function->getPrimaryTemplate()) 10374 Template->getAssociatedConstraints(AC); 10375 else 10376 I->Function->getAssociatedConstraints(AC); 10377 if (AC.empty()) 10378 continue; 10379 if (FirstCand == nullptr) { 10380 FirstCand = I->Function; 10381 FirstAC = AC; 10382 } else if (SecondCand == nullptr) { 10383 SecondCand = I->Function; 10384 SecondAC = AC; 10385 } else { 10386 // We have more than one pair of constrained functions - this check is 10387 // expensive and we'd rather not try to diagnose it. 10388 return; 10389 } 10390 } 10391 if (!SecondCand) 10392 return; 10393 // The diagnostic can only happen if there are associated constraints on 10394 // both sides (there needs to be some identical atomic constraint). 10395 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10396 SecondCand, SecondAC)) 10397 // Just show the user one diagnostic, they'll probably figure it out 10398 // from here. 10399 return; 10400 } 10401 10402 // Notes the location of all overload candidates designated through 10403 // OverloadedExpr 10404 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10405 bool TakingAddress) { 10406 assert(OverloadedExpr->getType() == Context.OverloadTy); 10407 10408 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10409 OverloadExpr *OvlExpr = Ovl.Expression; 10410 10411 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10412 IEnd = OvlExpr->decls_end(); 10413 I != IEnd; ++I) { 10414 if (FunctionTemplateDecl *FunTmpl = 10415 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10416 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10417 TakingAddress); 10418 } else if (FunctionDecl *Fun 10419 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10420 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10421 } 10422 } 10423 } 10424 10425 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10426 /// "lead" diagnostic; it will be given two arguments, the source and 10427 /// target types of the conversion. 10428 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10429 Sema &S, 10430 SourceLocation CaretLoc, 10431 const PartialDiagnostic &PDiag) const { 10432 S.Diag(CaretLoc, PDiag) 10433 << Ambiguous.getFromType() << Ambiguous.getToType(); 10434 unsigned CandsShown = 0; 10435 AmbiguousConversionSequence::const_iterator I, E; 10436 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10437 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 10438 break; 10439 ++CandsShown; 10440 S.NoteOverloadCandidate(I->first, I->second); 10441 } 10442 S.Diags.overloadCandidatesShown(CandsShown); 10443 if (I != E) 10444 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10445 } 10446 10447 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10448 unsigned I, bool TakingCandidateAddress) { 10449 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10450 assert(Conv.isBad()); 10451 assert(Cand->Function && "for now, candidate must be a function"); 10452 FunctionDecl *Fn = Cand->Function; 10453 10454 // There's a conversion slot for the object argument if this is a 10455 // non-constructor method. Note that 'I' corresponds the 10456 // conversion-slot index. 10457 bool isObjectArgument = false; 10458 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10459 if (I == 0) 10460 isObjectArgument = true; 10461 else 10462 I--; 10463 } 10464 10465 std::string FnDesc; 10466 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10467 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10468 FnDesc); 10469 10470 Expr *FromExpr = Conv.Bad.FromExpr; 10471 QualType FromTy = Conv.Bad.getFromType(); 10472 QualType ToTy = Conv.Bad.getToType(); 10473 10474 if (FromTy == S.Context.OverloadTy) { 10475 assert(FromExpr && "overload set argument came from implicit argument?"); 10476 Expr *E = FromExpr->IgnoreParens(); 10477 if (isa<UnaryOperator>(E)) 10478 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10479 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10480 10481 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10482 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10483 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10484 << Name << I + 1; 10485 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10486 return; 10487 } 10488 10489 // Do some hand-waving analysis to see if the non-viability is due 10490 // to a qualifier mismatch. 10491 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10492 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10493 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10494 CToTy = RT->getPointeeType(); 10495 else { 10496 // TODO: detect and diagnose the full richness of const mismatches. 10497 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10498 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10499 CFromTy = FromPT->getPointeeType(); 10500 CToTy = ToPT->getPointeeType(); 10501 } 10502 } 10503 10504 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10505 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10506 Qualifiers FromQs = CFromTy.getQualifiers(); 10507 Qualifiers ToQs = CToTy.getQualifiers(); 10508 10509 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10510 if (isObjectArgument) 10511 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10512 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10513 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10514 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10515 else 10516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10517 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10518 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10519 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10520 << ToTy->isReferenceType() << I + 1; 10521 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10522 return; 10523 } 10524 10525 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10526 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10527 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10528 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10529 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10530 << (unsigned)isObjectArgument << I + 1; 10531 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10532 return; 10533 } 10534 10535 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10536 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10537 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10538 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10539 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10540 << (unsigned)isObjectArgument << I + 1; 10541 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10542 return; 10543 } 10544 10545 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10546 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10547 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10548 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10549 << FromQs.hasUnaligned() << I + 1; 10550 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10551 return; 10552 } 10553 10554 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10555 assert(CVR && "expected qualifiers mismatch"); 10556 10557 if (isObjectArgument) { 10558 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10559 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10560 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10561 << (CVR - 1); 10562 } else { 10563 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10564 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10565 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10566 << (CVR - 1) << I + 1; 10567 } 10568 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10569 return; 10570 } 10571 10572 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 10573 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 10574 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 10575 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10576 << (unsigned)isObjectArgument << I + 1 10577 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 10578 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10579 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10580 return; 10581 } 10582 10583 // Special diagnostic for failure to convert an initializer list, since 10584 // telling the user that it has type void is not useful. 10585 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10587 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10588 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10589 << ToTy << (unsigned)isObjectArgument << I + 1 10590 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 10591 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 10592 ? 2 10593 : 0); 10594 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10595 return; 10596 } 10597 10598 // Diagnose references or pointers to incomplete types differently, 10599 // since it's far from impossible that the incompleteness triggered 10600 // the failure. 10601 QualType TempFromTy = FromTy.getNonReferenceType(); 10602 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10603 TempFromTy = PTy->getPointeeType(); 10604 if (TempFromTy->isIncompleteType()) { 10605 // Emit the generic diagnostic and, optionally, add the hints to it. 10606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10607 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10608 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10609 << ToTy << (unsigned)isObjectArgument << I + 1 10610 << (unsigned)(Cand->Fix.Kind); 10611 10612 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10613 return; 10614 } 10615 10616 // Diagnose base -> derived pointer conversions. 10617 unsigned BaseToDerivedConversion = 0; 10618 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10619 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10620 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10621 FromPtrTy->getPointeeType()) && 10622 !FromPtrTy->getPointeeType()->isIncompleteType() && 10623 !ToPtrTy->getPointeeType()->isIncompleteType() && 10624 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10625 FromPtrTy->getPointeeType())) 10626 BaseToDerivedConversion = 1; 10627 } 10628 } else if (const ObjCObjectPointerType *FromPtrTy 10629 = FromTy->getAs<ObjCObjectPointerType>()) { 10630 if (const ObjCObjectPointerType *ToPtrTy 10631 = ToTy->getAs<ObjCObjectPointerType>()) 10632 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10633 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10634 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10635 FromPtrTy->getPointeeType()) && 10636 FromIface->isSuperClassOf(ToIface)) 10637 BaseToDerivedConversion = 2; 10638 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10639 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10640 !FromTy->isIncompleteType() && 10641 !ToRefTy->getPointeeType()->isIncompleteType() && 10642 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10643 BaseToDerivedConversion = 3; 10644 } 10645 } 10646 10647 if (BaseToDerivedConversion) { 10648 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10649 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10650 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10651 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10652 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10653 return; 10654 } 10655 10656 if (isa<ObjCObjectPointerType>(CFromTy) && 10657 isa<PointerType>(CToTy)) { 10658 Qualifiers FromQs = CFromTy.getQualifiers(); 10659 Qualifiers ToQs = CToTy.getQualifiers(); 10660 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10662 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10663 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10664 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10665 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10666 return; 10667 } 10668 } 10669 10670 if (TakingCandidateAddress && 10671 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10672 return; 10673 10674 // Emit the generic diagnostic and, optionally, add the hints to it. 10675 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10676 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10677 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10678 << ToTy << (unsigned)isObjectArgument << I + 1 10679 << (unsigned)(Cand->Fix.Kind); 10680 10681 // If we can fix the conversion, suggest the FixIts. 10682 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10683 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10684 FDiag << *HI; 10685 S.Diag(Fn->getLocation(), FDiag); 10686 10687 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10688 } 10689 10690 /// Additional arity mismatch diagnosis specific to a function overload 10691 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10692 /// over a candidate in any candidate set. 10693 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10694 unsigned NumArgs) { 10695 FunctionDecl *Fn = Cand->Function; 10696 unsigned MinParams = Fn->getMinRequiredArguments(); 10697 10698 // With invalid overloaded operators, it's possible that we think we 10699 // have an arity mismatch when in fact it looks like we have the 10700 // right number of arguments, because only overloaded operators have 10701 // the weird behavior of overloading member and non-member functions. 10702 // Just don't report anything. 10703 if (Fn->isInvalidDecl() && 10704 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10705 return true; 10706 10707 if (NumArgs < MinParams) { 10708 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10709 (Cand->FailureKind == ovl_fail_bad_deduction && 10710 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10711 } else { 10712 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10713 (Cand->FailureKind == ovl_fail_bad_deduction && 10714 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10715 } 10716 10717 return false; 10718 } 10719 10720 /// General arity mismatch diagnosis over a candidate in a candidate set. 10721 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10722 unsigned NumFormalArgs) { 10723 assert(isa<FunctionDecl>(D) && 10724 "The templated declaration should at least be a function" 10725 " when diagnosing bad template argument deduction due to too many" 10726 " or too few arguments"); 10727 10728 FunctionDecl *Fn = cast<FunctionDecl>(D); 10729 10730 // TODO: treat calls to a missing default constructor as a special case 10731 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10732 unsigned MinParams = Fn->getMinRequiredArguments(); 10733 10734 // at least / at most / exactly 10735 unsigned mode, modeCount; 10736 if (NumFormalArgs < MinParams) { 10737 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10738 FnTy->isTemplateVariadic()) 10739 mode = 0; // "at least" 10740 else 10741 mode = 2; // "exactly" 10742 modeCount = MinParams; 10743 } else { 10744 if (MinParams != FnTy->getNumParams()) 10745 mode = 1; // "at most" 10746 else 10747 mode = 2; // "exactly" 10748 modeCount = FnTy->getNumParams(); 10749 } 10750 10751 std::string Description; 10752 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10753 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10754 10755 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10756 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10757 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10758 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10759 else 10760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10761 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10762 << Description << mode << modeCount << NumFormalArgs; 10763 10764 MaybeEmitInheritedConstructorNote(S, Found); 10765 } 10766 10767 /// Arity mismatch diagnosis specific to a function overload candidate. 10768 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10769 unsigned NumFormalArgs) { 10770 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10771 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10772 } 10773 10774 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10775 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10776 return TD; 10777 llvm_unreachable("Unsupported: Getting the described template declaration" 10778 " for bad deduction diagnosis"); 10779 } 10780 10781 /// Diagnose a failed template-argument deduction. 10782 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10783 DeductionFailureInfo &DeductionFailure, 10784 unsigned NumArgs, 10785 bool TakingCandidateAddress) { 10786 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10787 NamedDecl *ParamD; 10788 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10789 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10790 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10791 switch (DeductionFailure.Result) { 10792 case Sema::TDK_Success: 10793 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10794 10795 case Sema::TDK_Incomplete: { 10796 assert(ParamD && "no parameter found for incomplete deduction result"); 10797 S.Diag(Templated->getLocation(), 10798 diag::note_ovl_candidate_incomplete_deduction) 10799 << ParamD->getDeclName(); 10800 MaybeEmitInheritedConstructorNote(S, Found); 10801 return; 10802 } 10803 10804 case Sema::TDK_IncompletePack: { 10805 assert(ParamD && "no parameter found for incomplete deduction result"); 10806 S.Diag(Templated->getLocation(), 10807 diag::note_ovl_candidate_incomplete_deduction_pack) 10808 << ParamD->getDeclName() 10809 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10810 << *DeductionFailure.getFirstArg(); 10811 MaybeEmitInheritedConstructorNote(S, Found); 10812 return; 10813 } 10814 10815 case Sema::TDK_Underqualified: { 10816 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10817 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10818 10819 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10820 10821 // Param will have been canonicalized, but it should just be a 10822 // qualified version of ParamD, so move the qualifiers to that. 10823 QualifierCollector Qs; 10824 Qs.strip(Param); 10825 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10826 assert(S.Context.hasSameType(Param, NonCanonParam)); 10827 10828 // Arg has also been canonicalized, but there's nothing we can do 10829 // about that. It also doesn't matter as much, because it won't 10830 // have any template parameters in it (because deduction isn't 10831 // done on dependent types). 10832 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10833 10834 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10835 << ParamD->getDeclName() << Arg << NonCanonParam; 10836 MaybeEmitInheritedConstructorNote(S, Found); 10837 return; 10838 } 10839 10840 case Sema::TDK_Inconsistent: { 10841 assert(ParamD && "no parameter found for inconsistent deduction result"); 10842 int which = 0; 10843 if (isa<TemplateTypeParmDecl>(ParamD)) 10844 which = 0; 10845 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10846 // Deduction might have failed because we deduced arguments of two 10847 // different types for a non-type template parameter. 10848 // FIXME: Use a different TDK value for this. 10849 QualType T1 = 10850 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10851 QualType T2 = 10852 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10853 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10854 S.Diag(Templated->getLocation(), 10855 diag::note_ovl_candidate_inconsistent_deduction_types) 10856 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10857 << *DeductionFailure.getSecondArg() << T2; 10858 MaybeEmitInheritedConstructorNote(S, Found); 10859 return; 10860 } 10861 10862 which = 1; 10863 } else { 10864 which = 2; 10865 } 10866 10867 // Tweak the diagnostic if the problem is that we deduced packs of 10868 // different arities. We'll print the actual packs anyway in case that 10869 // includes additional useful information. 10870 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10871 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10872 DeductionFailure.getFirstArg()->pack_size() != 10873 DeductionFailure.getSecondArg()->pack_size()) { 10874 which = 3; 10875 } 10876 10877 S.Diag(Templated->getLocation(), 10878 diag::note_ovl_candidate_inconsistent_deduction) 10879 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10880 << *DeductionFailure.getSecondArg(); 10881 MaybeEmitInheritedConstructorNote(S, Found); 10882 return; 10883 } 10884 10885 case Sema::TDK_InvalidExplicitArguments: 10886 assert(ParamD && "no parameter found for invalid explicit arguments"); 10887 if (ParamD->getDeclName()) 10888 S.Diag(Templated->getLocation(), 10889 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10890 << ParamD->getDeclName(); 10891 else { 10892 int index = 0; 10893 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10894 index = TTP->getIndex(); 10895 else if (NonTypeTemplateParmDecl *NTTP 10896 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10897 index = NTTP->getIndex(); 10898 else 10899 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10900 S.Diag(Templated->getLocation(), 10901 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10902 << (index + 1); 10903 } 10904 MaybeEmitInheritedConstructorNote(S, Found); 10905 return; 10906 10907 case Sema::TDK_ConstraintsNotSatisfied: { 10908 // Format the template argument list into the argument string. 10909 SmallString<128> TemplateArgString; 10910 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10911 TemplateArgString = " "; 10912 TemplateArgString += S.getTemplateArgumentBindingsText( 10913 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10914 if (TemplateArgString.size() == 1) 10915 TemplateArgString.clear(); 10916 S.Diag(Templated->getLocation(), 10917 diag::note_ovl_candidate_unsatisfied_constraints) 10918 << TemplateArgString; 10919 10920 S.DiagnoseUnsatisfiedConstraint( 10921 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10922 return; 10923 } 10924 case Sema::TDK_TooManyArguments: 10925 case Sema::TDK_TooFewArguments: 10926 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10927 return; 10928 10929 case Sema::TDK_InstantiationDepth: 10930 S.Diag(Templated->getLocation(), 10931 diag::note_ovl_candidate_instantiation_depth); 10932 MaybeEmitInheritedConstructorNote(S, Found); 10933 return; 10934 10935 case Sema::TDK_SubstitutionFailure: { 10936 // Format the template argument list into the argument string. 10937 SmallString<128> TemplateArgString; 10938 if (TemplateArgumentList *Args = 10939 DeductionFailure.getTemplateArgumentList()) { 10940 TemplateArgString = " "; 10941 TemplateArgString += S.getTemplateArgumentBindingsText( 10942 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10943 if (TemplateArgString.size() == 1) 10944 TemplateArgString.clear(); 10945 } 10946 10947 // If this candidate was disabled by enable_if, say so. 10948 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10949 if (PDiag && PDiag->second.getDiagID() == 10950 diag::err_typename_nested_not_found_enable_if) { 10951 // FIXME: Use the source range of the condition, and the fully-qualified 10952 // name of the enable_if template. These are both present in PDiag. 10953 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10954 << "'enable_if'" << TemplateArgString; 10955 return; 10956 } 10957 10958 // We found a specific requirement that disabled the enable_if. 10959 if (PDiag && PDiag->second.getDiagID() == 10960 diag::err_typename_nested_not_found_requirement) { 10961 S.Diag(Templated->getLocation(), 10962 diag::note_ovl_candidate_disabled_by_requirement) 10963 << PDiag->second.getStringArg(0) << TemplateArgString; 10964 return; 10965 } 10966 10967 // Format the SFINAE diagnostic into the argument string. 10968 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10969 // formatted message in another diagnostic. 10970 SmallString<128> SFINAEArgString; 10971 SourceRange R; 10972 if (PDiag) { 10973 SFINAEArgString = ": "; 10974 R = SourceRange(PDiag->first, PDiag->first); 10975 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10976 } 10977 10978 S.Diag(Templated->getLocation(), 10979 diag::note_ovl_candidate_substitution_failure) 10980 << TemplateArgString << SFINAEArgString << R; 10981 MaybeEmitInheritedConstructorNote(S, Found); 10982 return; 10983 } 10984 10985 case Sema::TDK_DeducedMismatch: 10986 case Sema::TDK_DeducedMismatchNested: { 10987 // Format the template argument list into the argument string. 10988 SmallString<128> TemplateArgString; 10989 if (TemplateArgumentList *Args = 10990 DeductionFailure.getTemplateArgumentList()) { 10991 TemplateArgString = " "; 10992 TemplateArgString += S.getTemplateArgumentBindingsText( 10993 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10994 if (TemplateArgString.size() == 1) 10995 TemplateArgString.clear(); 10996 } 10997 10998 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10999 << (*DeductionFailure.getCallArgIndex() + 1) 11000 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11001 << TemplateArgString 11002 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11003 break; 11004 } 11005 11006 case Sema::TDK_NonDeducedMismatch: { 11007 // FIXME: Provide a source location to indicate what we couldn't match. 11008 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11009 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11010 if (FirstTA.getKind() == TemplateArgument::Template && 11011 SecondTA.getKind() == TemplateArgument::Template) { 11012 TemplateName FirstTN = FirstTA.getAsTemplate(); 11013 TemplateName SecondTN = SecondTA.getAsTemplate(); 11014 if (FirstTN.getKind() == TemplateName::Template && 11015 SecondTN.getKind() == TemplateName::Template) { 11016 if (FirstTN.getAsTemplateDecl()->getName() == 11017 SecondTN.getAsTemplateDecl()->getName()) { 11018 // FIXME: This fixes a bad diagnostic where both templates are named 11019 // the same. This particular case is a bit difficult since: 11020 // 1) It is passed as a string to the diagnostic printer. 11021 // 2) The diagnostic printer only attempts to find a better 11022 // name for types, not decls. 11023 // Ideally, this should folded into the diagnostic printer. 11024 S.Diag(Templated->getLocation(), 11025 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11026 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11027 return; 11028 } 11029 } 11030 } 11031 11032 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11033 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11034 return; 11035 11036 // FIXME: For generic lambda parameters, check if the function is a lambda 11037 // call operator, and if so, emit a prettier and more informative 11038 // diagnostic that mentions 'auto' and lambda in addition to 11039 // (or instead of?) the canonical template type parameters. 11040 S.Diag(Templated->getLocation(), 11041 diag::note_ovl_candidate_non_deduced_mismatch) 11042 << FirstTA << SecondTA; 11043 return; 11044 } 11045 // TODO: diagnose these individually, then kill off 11046 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11047 case Sema::TDK_MiscellaneousDeductionFailure: 11048 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11049 MaybeEmitInheritedConstructorNote(S, Found); 11050 return; 11051 case Sema::TDK_CUDATargetMismatch: 11052 S.Diag(Templated->getLocation(), 11053 diag::note_cuda_ovl_candidate_target_mismatch); 11054 return; 11055 } 11056 } 11057 11058 /// Diagnose a failed template-argument deduction, for function calls. 11059 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11060 unsigned NumArgs, 11061 bool TakingCandidateAddress) { 11062 unsigned TDK = Cand->DeductionFailure.Result; 11063 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11064 if (CheckArityMismatch(S, Cand, NumArgs)) 11065 return; 11066 } 11067 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11068 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11069 } 11070 11071 /// CUDA: diagnose an invalid call across targets. 11072 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11073 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 11074 FunctionDecl *Callee = Cand->Function; 11075 11076 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11077 CalleeTarget = S.IdentifyCUDATarget(Callee); 11078 11079 std::string FnDesc; 11080 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11081 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11082 Cand->getRewriteKind(), FnDesc); 11083 11084 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11085 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11086 << FnDesc /* Ignored */ 11087 << CalleeTarget << CallerTarget; 11088 11089 // This could be an implicit constructor for which we could not infer the 11090 // target due to a collsion. Diagnose that case. 11091 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11092 if (Meth != nullptr && Meth->isImplicit()) { 11093 CXXRecordDecl *ParentClass = Meth->getParent(); 11094 Sema::CXXSpecialMember CSM; 11095 11096 switch (FnKindPair.first) { 11097 default: 11098 return; 11099 case oc_implicit_default_constructor: 11100 CSM = Sema::CXXDefaultConstructor; 11101 break; 11102 case oc_implicit_copy_constructor: 11103 CSM = Sema::CXXCopyConstructor; 11104 break; 11105 case oc_implicit_move_constructor: 11106 CSM = Sema::CXXMoveConstructor; 11107 break; 11108 case oc_implicit_copy_assignment: 11109 CSM = Sema::CXXCopyAssignment; 11110 break; 11111 case oc_implicit_move_assignment: 11112 CSM = Sema::CXXMoveAssignment; 11113 break; 11114 }; 11115 11116 bool ConstRHS = false; 11117 if (Meth->getNumParams()) { 11118 if (const ReferenceType *RT = 11119 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11120 ConstRHS = RT->getPointeeType().isConstQualified(); 11121 } 11122 } 11123 11124 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11125 /* ConstRHS */ ConstRHS, 11126 /* Diagnose */ true); 11127 } 11128 } 11129 11130 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11131 FunctionDecl *Callee = Cand->Function; 11132 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11133 11134 S.Diag(Callee->getLocation(), 11135 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11136 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11137 } 11138 11139 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11140 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11141 assert(ES.isExplicit() && "not an explicit candidate"); 11142 11143 unsigned Kind; 11144 switch (Cand->Function->getDeclKind()) { 11145 case Decl::Kind::CXXConstructor: 11146 Kind = 0; 11147 break; 11148 case Decl::Kind::CXXConversion: 11149 Kind = 1; 11150 break; 11151 case Decl::Kind::CXXDeductionGuide: 11152 Kind = Cand->Function->isImplicit() ? 0 : 2; 11153 break; 11154 default: 11155 llvm_unreachable("invalid Decl"); 11156 } 11157 11158 // Note the location of the first (in-class) declaration; a redeclaration 11159 // (particularly an out-of-class definition) will typically lack the 11160 // 'explicit' specifier. 11161 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11162 FunctionDecl *First = Cand->Function->getFirstDecl(); 11163 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11164 First = Pattern->getFirstDecl(); 11165 11166 S.Diag(First->getLocation(), 11167 diag::note_ovl_candidate_explicit) 11168 << Kind << (ES.getExpr() ? 1 : 0) 11169 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11170 } 11171 11172 /// Generates a 'note' diagnostic for an overload candidate. We've 11173 /// already generated a primary error at the call site. 11174 /// 11175 /// It really does need to be a single diagnostic with its caret 11176 /// pointed at the candidate declaration. Yes, this creates some 11177 /// major challenges of technical writing. Yes, this makes pointing 11178 /// out problems with specific arguments quite awkward. It's still 11179 /// better than generating twenty screens of text for every failed 11180 /// overload. 11181 /// 11182 /// It would be great to be able to express per-candidate problems 11183 /// more richly for those diagnostic clients that cared, but we'd 11184 /// still have to be just as careful with the default diagnostics. 11185 /// \param CtorDestAS Addr space of object being constructed (for ctor 11186 /// candidates only). 11187 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11188 unsigned NumArgs, 11189 bool TakingCandidateAddress, 11190 LangAS CtorDestAS = LangAS::Default) { 11191 FunctionDecl *Fn = Cand->Function; 11192 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11193 return; 11194 11195 // Note deleted candidates, but only if they're viable. 11196 if (Cand->Viable) { 11197 if (Fn->isDeleted()) { 11198 std::string FnDesc; 11199 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11200 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11201 Cand->getRewriteKind(), FnDesc); 11202 11203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11204 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11205 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11206 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11207 return; 11208 } 11209 11210 // We don't really have anything else to say about viable candidates. 11211 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11212 return; 11213 } 11214 11215 switch (Cand->FailureKind) { 11216 case ovl_fail_too_many_arguments: 11217 case ovl_fail_too_few_arguments: 11218 return DiagnoseArityMismatch(S, Cand, NumArgs); 11219 11220 case ovl_fail_bad_deduction: 11221 return DiagnoseBadDeduction(S, Cand, NumArgs, 11222 TakingCandidateAddress); 11223 11224 case ovl_fail_illegal_constructor: { 11225 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11226 << (Fn->getPrimaryTemplate() ? 1 : 0); 11227 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11228 return; 11229 } 11230 11231 case ovl_fail_object_addrspace_mismatch: { 11232 Qualifiers QualsForPrinting; 11233 QualsForPrinting.setAddressSpace(CtorDestAS); 11234 S.Diag(Fn->getLocation(), 11235 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11236 << QualsForPrinting; 11237 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11238 return; 11239 } 11240 11241 case ovl_fail_trivial_conversion: 11242 case ovl_fail_bad_final_conversion: 11243 case ovl_fail_final_conversion_not_exact: 11244 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11245 11246 case ovl_fail_bad_conversion: { 11247 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11248 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11249 if (Cand->Conversions[I].isBad()) 11250 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11251 11252 // FIXME: this currently happens when we're called from SemaInit 11253 // when user-conversion overload fails. Figure out how to handle 11254 // those conditions and diagnose them well. 11255 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11256 } 11257 11258 case ovl_fail_bad_target: 11259 return DiagnoseBadTarget(S, Cand); 11260 11261 case ovl_fail_enable_if: 11262 return DiagnoseFailedEnableIfAttr(S, Cand); 11263 11264 case ovl_fail_explicit: 11265 return DiagnoseFailedExplicitSpec(S, Cand); 11266 11267 case ovl_fail_inhctor_slice: 11268 // It's generally not interesting to note copy/move constructors here. 11269 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11270 return; 11271 S.Diag(Fn->getLocation(), 11272 diag::note_ovl_candidate_inherited_constructor_slice) 11273 << (Fn->getPrimaryTemplate() ? 1 : 0) 11274 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11275 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11276 return; 11277 11278 case ovl_fail_addr_not_available: { 11279 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11280 (void)Available; 11281 assert(!Available); 11282 break; 11283 } 11284 case ovl_non_default_multiversion_function: 11285 // Do nothing, these should simply be ignored. 11286 break; 11287 11288 case ovl_fail_constraints_not_satisfied: { 11289 std::string FnDesc; 11290 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11291 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11292 Cand->getRewriteKind(), FnDesc); 11293 11294 S.Diag(Fn->getLocation(), 11295 diag::note_ovl_candidate_constraints_not_satisfied) 11296 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11297 << FnDesc /* Ignored */; 11298 ConstraintSatisfaction Satisfaction; 11299 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11300 break; 11301 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11302 } 11303 } 11304 } 11305 11306 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11307 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11308 return; 11309 11310 // Desugar the type of the surrogate down to a function type, 11311 // retaining as many typedefs as possible while still showing 11312 // the function type (and, therefore, its parameter types). 11313 QualType FnType = Cand->Surrogate->getConversionType(); 11314 bool isLValueReference = false; 11315 bool isRValueReference = false; 11316 bool isPointer = false; 11317 if (const LValueReferenceType *FnTypeRef = 11318 FnType->getAs<LValueReferenceType>()) { 11319 FnType = FnTypeRef->getPointeeType(); 11320 isLValueReference = true; 11321 } else if (const RValueReferenceType *FnTypeRef = 11322 FnType->getAs<RValueReferenceType>()) { 11323 FnType = FnTypeRef->getPointeeType(); 11324 isRValueReference = true; 11325 } 11326 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11327 FnType = FnTypePtr->getPointeeType(); 11328 isPointer = true; 11329 } 11330 // Desugar down to a function type. 11331 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11332 // Reconstruct the pointer/reference as appropriate. 11333 if (isPointer) FnType = S.Context.getPointerType(FnType); 11334 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11335 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11336 11337 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11338 << FnType; 11339 } 11340 11341 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11342 SourceLocation OpLoc, 11343 OverloadCandidate *Cand) { 11344 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11345 std::string TypeStr("operator"); 11346 TypeStr += Opc; 11347 TypeStr += "("; 11348 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11349 if (Cand->Conversions.size() == 1) { 11350 TypeStr += ")"; 11351 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11352 } else { 11353 TypeStr += ", "; 11354 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11355 TypeStr += ")"; 11356 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11357 } 11358 } 11359 11360 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11361 OverloadCandidate *Cand) { 11362 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11363 if (ICS.isBad()) break; // all meaningless after first invalid 11364 if (!ICS.isAmbiguous()) continue; 11365 11366 ICS.DiagnoseAmbiguousConversion( 11367 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11368 } 11369 } 11370 11371 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11372 if (Cand->Function) 11373 return Cand->Function->getLocation(); 11374 if (Cand->IsSurrogate) 11375 return Cand->Surrogate->getLocation(); 11376 return SourceLocation(); 11377 } 11378 11379 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11380 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11381 case Sema::TDK_Success: 11382 case Sema::TDK_NonDependentConversionFailure: 11383 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11384 11385 case Sema::TDK_Invalid: 11386 case Sema::TDK_Incomplete: 11387 case Sema::TDK_IncompletePack: 11388 return 1; 11389 11390 case Sema::TDK_Underqualified: 11391 case Sema::TDK_Inconsistent: 11392 return 2; 11393 11394 case Sema::TDK_SubstitutionFailure: 11395 case Sema::TDK_DeducedMismatch: 11396 case Sema::TDK_ConstraintsNotSatisfied: 11397 case Sema::TDK_DeducedMismatchNested: 11398 case Sema::TDK_NonDeducedMismatch: 11399 case Sema::TDK_MiscellaneousDeductionFailure: 11400 case Sema::TDK_CUDATargetMismatch: 11401 return 3; 11402 11403 case Sema::TDK_InstantiationDepth: 11404 return 4; 11405 11406 case Sema::TDK_InvalidExplicitArguments: 11407 return 5; 11408 11409 case Sema::TDK_TooManyArguments: 11410 case Sema::TDK_TooFewArguments: 11411 return 6; 11412 } 11413 llvm_unreachable("Unhandled deduction result"); 11414 } 11415 11416 namespace { 11417 struct CompareOverloadCandidatesForDisplay { 11418 Sema &S; 11419 SourceLocation Loc; 11420 size_t NumArgs; 11421 OverloadCandidateSet::CandidateSetKind CSK; 11422 11423 CompareOverloadCandidatesForDisplay( 11424 Sema &S, SourceLocation Loc, size_t NArgs, 11425 OverloadCandidateSet::CandidateSetKind CSK) 11426 : S(S), NumArgs(NArgs), CSK(CSK) {} 11427 11428 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11429 // If there are too many or too few arguments, that's the high-order bit we 11430 // want to sort by, even if the immediate failure kind was something else. 11431 if (C->FailureKind == ovl_fail_too_many_arguments || 11432 C->FailureKind == ovl_fail_too_few_arguments) 11433 return static_cast<OverloadFailureKind>(C->FailureKind); 11434 11435 if (C->Function) { 11436 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11437 return ovl_fail_too_many_arguments; 11438 if (NumArgs < C->Function->getMinRequiredArguments()) 11439 return ovl_fail_too_few_arguments; 11440 } 11441 11442 return static_cast<OverloadFailureKind>(C->FailureKind); 11443 } 11444 11445 bool operator()(const OverloadCandidate *L, 11446 const OverloadCandidate *R) { 11447 // Fast-path this check. 11448 if (L == R) return false; 11449 11450 // Order first by viability. 11451 if (L->Viable) { 11452 if (!R->Viable) return true; 11453 11454 // TODO: introduce a tri-valued comparison for overload 11455 // candidates. Would be more worthwhile if we had a sort 11456 // that could exploit it. 11457 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11458 return true; 11459 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11460 return false; 11461 } else if (R->Viable) 11462 return false; 11463 11464 assert(L->Viable == R->Viable); 11465 11466 // Criteria by which we can sort non-viable candidates: 11467 if (!L->Viable) { 11468 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11469 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11470 11471 // 1. Arity mismatches come after other candidates. 11472 if (LFailureKind == ovl_fail_too_many_arguments || 11473 LFailureKind == ovl_fail_too_few_arguments) { 11474 if (RFailureKind == ovl_fail_too_many_arguments || 11475 RFailureKind == ovl_fail_too_few_arguments) { 11476 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11477 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11478 if (LDist == RDist) { 11479 if (LFailureKind == RFailureKind) 11480 // Sort non-surrogates before surrogates. 11481 return !L->IsSurrogate && R->IsSurrogate; 11482 // Sort candidates requiring fewer parameters than there were 11483 // arguments given after candidates requiring more parameters 11484 // than there were arguments given. 11485 return LFailureKind == ovl_fail_too_many_arguments; 11486 } 11487 return LDist < RDist; 11488 } 11489 return false; 11490 } 11491 if (RFailureKind == ovl_fail_too_many_arguments || 11492 RFailureKind == ovl_fail_too_few_arguments) 11493 return true; 11494 11495 // 2. Bad conversions come first and are ordered by the number 11496 // of bad conversions and quality of good conversions. 11497 if (LFailureKind == ovl_fail_bad_conversion) { 11498 if (RFailureKind != ovl_fail_bad_conversion) 11499 return true; 11500 11501 // The conversion that can be fixed with a smaller number of changes, 11502 // comes first. 11503 unsigned numLFixes = L->Fix.NumConversionsFixed; 11504 unsigned numRFixes = R->Fix.NumConversionsFixed; 11505 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11506 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11507 if (numLFixes != numRFixes) { 11508 return numLFixes < numRFixes; 11509 } 11510 11511 // If there's any ordering between the defined conversions... 11512 // FIXME: this might not be transitive. 11513 assert(L->Conversions.size() == R->Conversions.size()); 11514 11515 int leftBetter = 0; 11516 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11517 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11518 switch (CompareImplicitConversionSequences(S, Loc, 11519 L->Conversions[I], 11520 R->Conversions[I])) { 11521 case ImplicitConversionSequence::Better: 11522 leftBetter++; 11523 break; 11524 11525 case ImplicitConversionSequence::Worse: 11526 leftBetter--; 11527 break; 11528 11529 case ImplicitConversionSequence::Indistinguishable: 11530 break; 11531 } 11532 } 11533 if (leftBetter > 0) return true; 11534 if (leftBetter < 0) return false; 11535 11536 } else if (RFailureKind == ovl_fail_bad_conversion) 11537 return false; 11538 11539 if (LFailureKind == ovl_fail_bad_deduction) { 11540 if (RFailureKind != ovl_fail_bad_deduction) 11541 return true; 11542 11543 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11544 return RankDeductionFailure(L->DeductionFailure) 11545 < RankDeductionFailure(R->DeductionFailure); 11546 } else if (RFailureKind == ovl_fail_bad_deduction) 11547 return false; 11548 11549 // TODO: others? 11550 } 11551 11552 // Sort everything else by location. 11553 SourceLocation LLoc = GetLocationForCandidate(L); 11554 SourceLocation RLoc = GetLocationForCandidate(R); 11555 11556 // Put candidates without locations (e.g. builtins) at the end. 11557 if (LLoc.isInvalid()) return false; 11558 if (RLoc.isInvalid()) return true; 11559 11560 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11561 } 11562 }; 11563 } 11564 11565 /// CompleteNonViableCandidate - Normally, overload resolution only 11566 /// computes up to the first bad conversion. Produces the FixIt set if 11567 /// possible. 11568 static void 11569 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11570 ArrayRef<Expr *> Args, 11571 OverloadCandidateSet::CandidateSetKind CSK) { 11572 assert(!Cand->Viable); 11573 11574 // Don't do anything on failures other than bad conversion. 11575 if (Cand->FailureKind != ovl_fail_bad_conversion) 11576 return; 11577 11578 // We only want the FixIts if all the arguments can be corrected. 11579 bool Unfixable = false; 11580 // Use a implicit copy initialization to check conversion fixes. 11581 Cand->Fix.setConversionChecker(TryCopyInitialization); 11582 11583 // Attempt to fix the bad conversion. 11584 unsigned ConvCount = Cand->Conversions.size(); 11585 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11586 ++ConvIdx) { 11587 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11588 if (Cand->Conversions[ConvIdx].isInitialized() && 11589 Cand->Conversions[ConvIdx].isBad()) { 11590 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11591 break; 11592 } 11593 } 11594 11595 // FIXME: this should probably be preserved from the overload 11596 // operation somehow. 11597 bool SuppressUserConversions = false; 11598 11599 unsigned ConvIdx = 0; 11600 unsigned ArgIdx = 0; 11601 ArrayRef<QualType> ParamTypes; 11602 bool Reversed = Cand->isReversed(); 11603 11604 if (Cand->IsSurrogate) { 11605 QualType ConvType 11606 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11607 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11608 ConvType = ConvPtrType->getPointeeType(); 11609 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11610 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11611 ConvIdx = 1; 11612 } else if (Cand->Function) { 11613 ParamTypes = 11614 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11615 if (isa<CXXMethodDecl>(Cand->Function) && 11616 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11617 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11618 ConvIdx = 1; 11619 if (CSK == OverloadCandidateSet::CSK_Operator && 11620 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11621 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11622 ArgIdx = 1; 11623 } 11624 } else { 11625 // Builtin operator. 11626 assert(ConvCount <= 3); 11627 ParamTypes = Cand->BuiltinParamTypes; 11628 } 11629 11630 // Fill in the rest of the conversions. 11631 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11632 ConvIdx != ConvCount; 11633 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11634 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11635 if (Cand->Conversions[ConvIdx].isInitialized()) { 11636 // We've already checked this conversion. 11637 } else if (ParamIdx < ParamTypes.size()) { 11638 if (ParamTypes[ParamIdx]->isDependentType()) 11639 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11640 Args[ArgIdx]->getType()); 11641 else { 11642 Cand->Conversions[ConvIdx] = 11643 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11644 SuppressUserConversions, 11645 /*InOverloadResolution=*/true, 11646 /*AllowObjCWritebackConversion=*/ 11647 S.getLangOpts().ObjCAutoRefCount); 11648 // Store the FixIt in the candidate if it exists. 11649 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11650 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11651 } 11652 } else 11653 Cand->Conversions[ConvIdx].setEllipsis(); 11654 } 11655 } 11656 11657 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11658 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11659 SourceLocation OpLoc, 11660 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11661 // Sort the candidates by viability and position. Sorting directly would 11662 // be prohibitive, so we make a set of pointers and sort those. 11663 SmallVector<OverloadCandidate*, 32> Cands; 11664 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11665 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11666 if (!Filter(*Cand)) 11667 continue; 11668 switch (OCD) { 11669 case OCD_AllCandidates: 11670 if (!Cand->Viable) { 11671 if (!Cand->Function && !Cand->IsSurrogate) { 11672 // This a non-viable builtin candidate. We do not, in general, 11673 // want to list every possible builtin candidate. 11674 continue; 11675 } 11676 CompleteNonViableCandidate(S, Cand, Args, Kind); 11677 } 11678 break; 11679 11680 case OCD_ViableCandidates: 11681 if (!Cand->Viable) 11682 continue; 11683 break; 11684 11685 case OCD_AmbiguousCandidates: 11686 if (!Cand->Best) 11687 continue; 11688 break; 11689 } 11690 11691 Cands.push_back(Cand); 11692 } 11693 11694 llvm::stable_sort( 11695 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11696 11697 return Cands; 11698 } 11699 11700 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 11701 SourceLocation OpLoc) { 11702 bool DeferHint = false; 11703 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 11704 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 11705 // host device candidates. 11706 auto WrongSidedCands = 11707 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 11708 return (Cand.Viable == false && 11709 Cand.FailureKind == ovl_fail_bad_target) || 11710 (Cand.Function && 11711 Cand.Function->template hasAttr<CUDAHostAttr>() && 11712 Cand.Function->template hasAttr<CUDADeviceAttr>()); 11713 }); 11714 DeferHint = !WrongSidedCands.empty(); 11715 } 11716 return DeferHint; 11717 } 11718 11719 /// When overload resolution fails, prints diagnostic messages containing the 11720 /// candidates in the candidate set. 11721 void OverloadCandidateSet::NoteCandidates( 11722 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 11723 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 11724 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11725 11726 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11727 11728 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 11729 11730 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11731 11732 if (OCD == OCD_AmbiguousCandidates) 11733 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11734 } 11735 11736 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11737 ArrayRef<OverloadCandidate *> Cands, 11738 StringRef Opc, SourceLocation OpLoc) { 11739 bool ReportedAmbiguousConversions = false; 11740 11741 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11742 unsigned CandsShown = 0; 11743 auto I = Cands.begin(), E = Cands.end(); 11744 for (; I != E; ++I) { 11745 OverloadCandidate *Cand = *I; 11746 11747 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 11748 ShowOverloads == Ovl_Best) { 11749 break; 11750 } 11751 ++CandsShown; 11752 11753 if (Cand->Function) 11754 NoteFunctionCandidate(S, Cand, Args.size(), 11755 /*TakingCandidateAddress=*/false, DestAS); 11756 else if (Cand->IsSurrogate) 11757 NoteSurrogateCandidate(S, Cand); 11758 else { 11759 assert(Cand->Viable && 11760 "Non-viable built-in candidates are not added to Cands."); 11761 // Generally we only see ambiguities including viable builtin 11762 // operators if overload resolution got screwed up by an 11763 // ambiguous user-defined conversion. 11764 // 11765 // FIXME: It's quite possible for different conversions to see 11766 // different ambiguities, though. 11767 if (!ReportedAmbiguousConversions) { 11768 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11769 ReportedAmbiguousConversions = true; 11770 } 11771 11772 // If this is a viable builtin, print it. 11773 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11774 } 11775 } 11776 11777 // Inform S.Diags that we've shown an overload set with N elements. This may 11778 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 11779 S.Diags.overloadCandidatesShown(CandsShown); 11780 11781 if (I != E) 11782 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 11783 shouldDeferDiags(S, Args, OpLoc)) 11784 << int(E - I); 11785 } 11786 11787 static SourceLocation 11788 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11789 return Cand->Specialization ? Cand->Specialization->getLocation() 11790 : SourceLocation(); 11791 } 11792 11793 namespace { 11794 struct CompareTemplateSpecCandidatesForDisplay { 11795 Sema &S; 11796 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11797 11798 bool operator()(const TemplateSpecCandidate *L, 11799 const TemplateSpecCandidate *R) { 11800 // Fast-path this check. 11801 if (L == R) 11802 return false; 11803 11804 // Assuming that both candidates are not matches... 11805 11806 // Sort by the ranking of deduction failures. 11807 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11808 return RankDeductionFailure(L->DeductionFailure) < 11809 RankDeductionFailure(R->DeductionFailure); 11810 11811 // Sort everything else by location. 11812 SourceLocation LLoc = GetLocationForCandidate(L); 11813 SourceLocation RLoc = GetLocationForCandidate(R); 11814 11815 // Put candidates without locations (e.g. builtins) at the end. 11816 if (LLoc.isInvalid()) 11817 return false; 11818 if (RLoc.isInvalid()) 11819 return true; 11820 11821 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11822 } 11823 }; 11824 } 11825 11826 /// Diagnose a template argument deduction failure. 11827 /// We are treating these failures as overload failures due to bad 11828 /// deductions. 11829 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11830 bool ForTakingAddress) { 11831 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11832 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11833 } 11834 11835 void TemplateSpecCandidateSet::destroyCandidates() { 11836 for (iterator i = begin(), e = end(); i != e; ++i) { 11837 i->DeductionFailure.Destroy(); 11838 } 11839 } 11840 11841 void TemplateSpecCandidateSet::clear() { 11842 destroyCandidates(); 11843 Candidates.clear(); 11844 } 11845 11846 /// NoteCandidates - When no template specialization match is found, prints 11847 /// diagnostic messages containing the non-matching specializations that form 11848 /// the candidate set. 11849 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11850 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11851 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11852 // Sort the candidates by position (assuming no candidate is a match). 11853 // Sorting directly would be prohibitive, so we make a set of pointers 11854 // and sort those. 11855 SmallVector<TemplateSpecCandidate *, 32> Cands; 11856 Cands.reserve(size()); 11857 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11858 if (Cand->Specialization) 11859 Cands.push_back(Cand); 11860 // Otherwise, this is a non-matching builtin candidate. We do not, 11861 // in general, want to list every possible builtin candidate. 11862 } 11863 11864 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11865 11866 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11867 // for generalization purposes (?). 11868 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11869 11870 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11871 unsigned CandsShown = 0; 11872 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11873 TemplateSpecCandidate *Cand = *I; 11874 11875 // Set an arbitrary limit on the number of candidates we'll spam 11876 // the user with. FIXME: This limit should depend on details of the 11877 // candidate list. 11878 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11879 break; 11880 ++CandsShown; 11881 11882 assert(Cand->Specialization && 11883 "Non-matching built-in candidates are not added to Cands."); 11884 Cand->NoteDeductionFailure(S, ForTakingAddress); 11885 } 11886 11887 if (I != E) 11888 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11889 } 11890 11891 // [PossiblyAFunctionType] --> [Return] 11892 // NonFunctionType --> NonFunctionType 11893 // R (A) --> R(A) 11894 // R (*)(A) --> R (A) 11895 // R (&)(A) --> R (A) 11896 // R (S::*)(A) --> R (A) 11897 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11898 QualType Ret = PossiblyAFunctionType; 11899 if (const PointerType *ToTypePtr = 11900 PossiblyAFunctionType->getAs<PointerType>()) 11901 Ret = ToTypePtr->getPointeeType(); 11902 else if (const ReferenceType *ToTypeRef = 11903 PossiblyAFunctionType->getAs<ReferenceType>()) 11904 Ret = ToTypeRef->getPointeeType(); 11905 else if (const MemberPointerType *MemTypePtr = 11906 PossiblyAFunctionType->getAs<MemberPointerType>()) 11907 Ret = MemTypePtr->getPointeeType(); 11908 Ret = 11909 Context.getCanonicalType(Ret).getUnqualifiedType(); 11910 return Ret; 11911 } 11912 11913 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11914 bool Complain = true) { 11915 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11916 S.DeduceReturnType(FD, Loc, Complain)) 11917 return true; 11918 11919 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11920 if (S.getLangOpts().CPlusPlus17 && 11921 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11922 !S.ResolveExceptionSpec(Loc, FPT)) 11923 return true; 11924 11925 return false; 11926 } 11927 11928 namespace { 11929 // A helper class to help with address of function resolution 11930 // - allows us to avoid passing around all those ugly parameters 11931 class AddressOfFunctionResolver { 11932 Sema& S; 11933 Expr* SourceExpr; 11934 const QualType& TargetType; 11935 QualType TargetFunctionType; // Extracted function type from target type 11936 11937 bool Complain; 11938 //DeclAccessPair& ResultFunctionAccessPair; 11939 ASTContext& Context; 11940 11941 bool TargetTypeIsNonStaticMemberFunction; 11942 bool FoundNonTemplateFunction; 11943 bool StaticMemberFunctionFromBoundPointer; 11944 bool HasComplained; 11945 11946 OverloadExpr::FindResult OvlExprInfo; 11947 OverloadExpr *OvlExpr; 11948 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11949 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11950 TemplateSpecCandidateSet FailedCandidates; 11951 11952 public: 11953 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11954 const QualType &TargetType, bool Complain) 11955 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11956 Complain(Complain), Context(S.getASTContext()), 11957 TargetTypeIsNonStaticMemberFunction( 11958 !!TargetType->getAs<MemberPointerType>()), 11959 FoundNonTemplateFunction(false), 11960 StaticMemberFunctionFromBoundPointer(false), 11961 HasComplained(false), 11962 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11963 OvlExpr(OvlExprInfo.Expression), 11964 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11965 ExtractUnqualifiedFunctionTypeFromTargetType(); 11966 11967 if (TargetFunctionType->isFunctionType()) { 11968 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11969 if (!UME->isImplicitAccess() && 11970 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11971 StaticMemberFunctionFromBoundPointer = true; 11972 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11973 DeclAccessPair dap; 11974 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11975 OvlExpr, false, &dap)) { 11976 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11977 if (!Method->isStatic()) { 11978 // If the target type is a non-function type and the function found 11979 // is a non-static member function, pretend as if that was the 11980 // target, it's the only possible type to end up with. 11981 TargetTypeIsNonStaticMemberFunction = true; 11982 11983 // And skip adding the function if its not in the proper form. 11984 // We'll diagnose this due to an empty set of functions. 11985 if (!OvlExprInfo.HasFormOfMemberPointer) 11986 return; 11987 } 11988 11989 Matches.push_back(std::make_pair(dap, Fn)); 11990 } 11991 return; 11992 } 11993 11994 if (OvlExpr->hasExplicitTemplateArgs()) 11995 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11996 11997 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11998 // C++ [over.over]p4: 11999 // If more than one function is selected, [...] 12000 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12001 if (FoundNonTemplateFunction) 12002 EliminateAllTemplateMatches(); 12003 else 12004 EliminateAllExceptMostSpecializedTemplate(); 12005 } 12006 } 12007 12008 if (S.getLangOpts().CUDA && Matches.size() > 1) 12009 EliminateSuboptimalCudaMatches(); 12010 } 12011 12012 bool hasComplained() const { return HasComplained; } 12013 12014 private: 12015 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12016 QualType Discard; 12017 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12018 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12019 } 12020 12021 /// \return true if A is considered a better overload candidate for the 12022 /// desired type than B. 12023 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12024 // If A doesn't have exactly the correct type, we don't want to classify it 12025 // as "better" than anything else. This way, the user is required to 12026 // disambiguate for us if there are multiple candidates and no exact match. 12027 return candidateHasExactlyCorrectType(A) && 12028 (!candidateHasExactlyCorrectType(B) || 12029 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12030 } 12031 12032 /// \return true if we were able to eliminate all but one overload candidate, 12033 /// false otherwise. 12034 bool eliminiateSuboptimalOverloadCandidates() { 12035 // Same algorithm as overload resolution -- one pass to pick the "best", 12036 // another pass to be sure that nothing is better than the best. 12037 auto Best = Matches.begin(); 12038 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12039 if (isBetterCandidate(I->second, Best->second)) 12040 Best = I; 12041 12042 const FunctionDecl *BestFn = Best->second; 12043 auto IsBestOrInferiorToBest = [this, BestFn]( 12044 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12045 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12046 }; 12047 12048 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12049 // option, so we can potentially give the user a better error 12050 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12051 return false; 12052 Matches[0] = *Best; 12053 Matches.resize(1); 12054 return true; 12055 } 12056 12057 bool isTargetTypeAFunction() const { 12058 return TargetFunctionType->isFunctionType(); 12059 } 12060 12061 // [ToType] [Return] 12062 12063 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12064 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12065 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12066 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12067 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12068 } 12069 12070 // return true if any matching specializations were found 12071 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12072 const DeclAccessPair& CurAccessFunPair) { 12073 if (CXXMethodDecl *Method 12074 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12075 // Skip non-static function templates when converting to pointer, and 12076 // static when converting to member pointer. 12077 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12078 return false; 12079 } 12080 else if (TargetTypeIsNonStaticMemberFunction) 12081 return false; 12082 12083 // C++ [over.over]p2: 12084 // If the name is a function template, template argument deduction is 12085 // done (14.8.2.2), and if the argument deduction succeeds, the 12086 // resulting template argument list is used to generate a single 12087 // function template specialization, which is added to the set of 12088 // overloaded functions considered. 12089 FunctionDecl *Specialization = nullptr; 12090 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12091 if (Sema::TemplateDeductionResult Result 12092 = S.DeduceTemplateArguments(FunctionTemplate, 12093 &OvlExplicitTemplateArgs, 12094 TargetFunctionType, Specialization, 12095 Info, /*IsAddressOfFunction*/true)) { 12096 // Make a note of the failed deduction for diagnostics. 12097 FailedCandidates.addCandidate() 12098 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12099 MakeDeductionFailureInfo(Context, Result, Info)); 12100 return false; 12101 } 12102 12103 // Template argument deduction ensures that we have an exact match or 12104 // compatible pointer-to-function arguments that would be adjusted by ICS. 12105 // This function template specicalization works. 12106 assert(S.isSameOrCompatibleFunctionType( 12107 Context.getCanonicalType(Specialization->getType()), 12108 Context.getCanonicalType(TargetFunctionType))); 12109 12110 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12111 return false; 12112 12113 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12114 return true; 12115 } 12116 12117 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12118 const DeclAccessPair& CurAccessFunPair) { 12119 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12120 // Skip non-static functions when converting to pointer, and static 12121 // when converting to member pointer. 12122 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 12123 return false; 12124 } 12125 else if (TargetTypeIsNonStaticMemberFunction) 12126 return false; 12127 12128 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12129 if (S.getLangOpts().CUDA) 12130 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 12131 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 12132 return false; 12133 if (FunDecl->isMultiVersion()) { 12134 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12135 if (TA && !TA->isDefaultVersion()) 12136 return false; 12137 } 12138 12139 // If any candidate has a placeholder return type, trigger its deduction 12140 // now. 12141 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12142 Complain)) { 12143 HasComplained |= Complain; 12144 return false; 12145 } 12146 12147 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12148 return false; 12149 12150 // If we're in C, we need to support types that aren't exactly identical. 12151 if (!S.getLangOpts().CPlusPlus || 12152 candidateHasExactlyCorrectType(FunDecl)) { 12153 Matches.push_back(std::make_pair( 12154 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12155 FoundNonTemplateFunction = true; 12156 return true; 12157 } 12158 } 12159 12160 return false; 12161 } 12162 12163 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12164 bool Ret = false; 12165 12166 // If the overload expression doesn't have the form of a pointer to 12167 // member, don't try to convert it to a pointer-to-member type. 12168 if (IsInvalidFormOfPointerToMemberFunction()) 12169 return false; 12170 12171 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12172 E = OvlExpr->decls_end(); 12173 I != E; ++I) { 12174 // Look through any using declarations to find the underlying function. 12175 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12176 12177 // C++ [over.over]p3: 12178 // Non-member functions and static member functions match 12179 // targets of type "pointer-to-function" or "reference-to-function." 12180 // Nonstatic member functions match targets of 12181 // type "pointer-to-member-function." 12182 // Note that according to DR 247, the containing class does not matter. 12183 if (FunctionTemplateDecl *FunctionTemplate 12184 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12185 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12186 Ret = true; 12187 } 12188 // If we have explicit template arguments supplied, skip non-templates. 12189 else if (!OvlExpr->hasExplicitTemplateArgs() && 12190 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12191 Ret = true; 12192 } 12193 assert(Ret || Matches.empty()); 12194 return Ret; 12195 } 12196 12197 void EliminateAllExceptMostSpecializedTemplate() { 12198 // [...] and any given function template specialization F1 is 12199 // eliminated if the set contains a second function template 12200 // specialization whose function template is more specialized 12201 // than the function template of F1 according to the partial 12202 // ordering rules of 14.5.5.2. 12203 12204 // The algorithm specified above is quadratic. We instead use a 12205 // two-pass algorithm (similar to the one used to identify the 12206 // best viable function in an overload set) that identifies the 12207 // best function template (if it exists). 12208 12209 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12210 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12211 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12212 12213 // TODO: It looks like FailedCandidates does not serve much purpose 12214 // here, since the no_viable diagnostic has index 0. 12215 UnresolvedSetIterator Result = S.getMostSpecialized( 12216 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12217 SourceExpr->getBeginLoc(), S.PDiag(), 12218 S.PDiag(diag::err_addr_ovl_ambiguous) 12219 << Matches[0].second->getDeclName(), 12220 S.PDiag(diag::note_ovl_candidate) 12221 << (unsigned)oc_function << (unsigned)ocs_described_template, 12222 Complain, TargetFunctionType); 12223 12224 if (Result != MatchesCopy.end()) { 12225 // Make it the first and only element 12226 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12227 Matches[0].second = cast<FunctionDecl>(*Result); 12228 Matches.resize(1); 12229 } else 12230 HasComplained |= Complain; 12231 } 12232 12233 void EliminateAllTemplateMatches() { 12234 // [...] any function template specializations in the set are 12235 // eliminated if the set also contains a non-template function, [...] 12236 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12237 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12238 ++I; 12239 else { 12240 Matches[I] = Matches[--N]; 12241 Matches.resize(N); 12242 } 12243 } 12244 } 12245 12246 void EliminateSuboptimalCudaMatches() { 12247 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12248 } 12249 12250 public: 12251 void ComplainNoMatchesFound() const { 12252 assert(Matches.empty()); 12253 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12254 << OvlExpr->getName() << TargetFunctionType 12255 << OvlExpr->getSourceRange(); 12256 if (FailedCandidates.empty()) 12257 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12258 /*TakingAddress=*/true); 12259 else { 12260 // We have some deduction failure messages. Use them to diagnose 12261 // the function templates, and diagnose the non-template candidates 12262 // normally. 12263 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12264 IEnd = OvlExpr->decls_end(); 12265 I != IEnd; ++I) 12266 if (FunctionDecl *Fun = 12267 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12268 if (!functionHasPassObjectSizeParams(Fun)) 12269 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12270 /*TakingAddress=*/true); 12271 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12272 } 12273 } 12274 12275 bool IsInvalidFormOfPointerToMemberFunction() const { 12276 return TargetTypeIsNonStaticMemberFunction && 12277 !OvlExprInfo.HasFormOfMemberPointer; 12278 } 12279 12280 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12281 // TODO: Should we condition this on whether any functions might 12282 // have matched, or is it more appropriate to do that in callers? 12283 // TODO: a fixit wouldn't hurt. 12284 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12285 << TargetType << OvlExpr->getSourceRange(); 12286 } 12287 12288 bool IsStaticMemberFunctionFromBoundPointer() const { 12289 return StaticMemberFunctionFromBoundPointer; 12290 } 12291 12292 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12293 S.Diag(OvlExpr->getBeginLoc(), 12294 diag::err_invalid_form_pointer_member_function) 12295 << OvlExpr->getSourceRange(); 12296 } 12297 12298 void ComplainOfInvalidConversion() const { 12299 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12300 << OvlExpr->getName() << TargetType; 12301 } 12302 12303 void ComplainMultipleMatchesFound() const { 12304 assert(Matches.size() > 1); 12305 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12306 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12307 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12308 /*TakingAddress=*/true); 12309 } 12310 12311 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12312 12313 int getNumMatches() const { return Matches.size(); } 12314 12315 FunctionDecl* getMatchingFunctionDecl() const { 12316 if (Matches.size() != 1) return nullptr; 12317 return Matches[0].second; 12318 } 12319 12320 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12321 if (Matches.size() != 1) return nullptr; 12322 return &Matches[0].first; 12323 } 12324 }; 12325 } 12326 12327 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12328 /// an overloaded function (C++ [over.over]), where @p From is an 12329 /// expression with overloaded function type and @p ToType is the type 12330 /// we're trying to resolve to. For example: 12331 /// 12332 /// @code 12333 /// int f(double); 12334 /// int f(int); 12335 /// 12336 /// int (*pfd)(double) = f; // selects f(double) 12337 /// @endcode 12338 /// 12339 /// This routine returns the resulting FunctionDecl if it could be 12340 /// resolved, and NULL otherwise. When @p Complain is true, this 12341 /// routine will emit diagnostics if there is an error. 12342 FunctionDecl * 12343 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12344 QualType TargetType, 12345 bool Complain, 12346 DeclAccessPair &FoundResult, 12347 bool *pHadMultipleCandidates) { 12348 assert(AddressOfExpr->getType() == Context.OverloadTy); 12349 12350 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12351 Complain); 12352 int NumMatches = Resolver.getNumMatches(); 12353 FunctionDecl *Fn = nullptr; 12354 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12355 if (NumMatches == 0 && ShouldComplain) { 12356 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12357 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12358 else 12359 Resolver.ComplainNoMatchesFound(); 12360 } 12361 else if (NumMatches > 1 && ShouldComplain) 12362 Resolver.ComplainMultipleMatchesFound(); 12363 else if (NumMatches == 1) { 12364 Fn = Resolver.getMatchingFunctionDecl(); 12365 assert(Fn); 12366 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12367 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12368 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12369 if (Complain) { 12370 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12371 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12372 else 12373 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12374 } 12375 } 12376 12377 if (pHadMultipleCandidates) 12378 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12379 return Fn; 12380 } 12381 12382 /// Given an expression that refers to an overloaded function, try to 12383 /// resolve that function to a single function that can have its address taken. 12384 /// This will modify `Pair` iff it returns non-null. 12385 /// 12386 /// This routine can only succeed if from all of the candidates in the overload 12387 /// set for SrcExpr that can have their addresses taken, there is one candidate 12388 /// that is more constrained than the rest. 12389 FunctionDecl * 12390 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12391 OverloadExpr::FindResult R = OverloadExpr::find(E); 12392 OverloadExpr *Ovl = R.Expression; 12393 bool IsResultAmbiguous = false; 12394 FunctionDecl *Result = nullptr; 12395 DeclAccessPair DAP; 12396 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12397 12398 auto CheckMoreConstrained = 12399 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12400 SmallVector<const Expr *, 1> AC1, AC2; 12401 FD1->getAssociatedConstraints(AC1); 12402 FD2->getAssociatedConstraints(AC2); 12403 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12404 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12405 return None; 12406 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12407 return None; 12408 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12409 return None; 12410 return AtLeastAsConstrained1; 12411 }; 12412 12413 // Don't use the AddressOfResolver because we're specifically looking for 12414 // cases where we have one overload candidate that lacks 12415 // enable_if/pass_object_size/... 12416 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12417 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12418 if (!FD) 12419 return nullptr; 12420 12421 if (!checkAddressOfFunctionIsAvailable(FD)) 12422 continue; 12423 12424 // We have more than one result - see if it is more constrained than the 12425 // previous one. 12426 if (Result) { 12427 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12428 Result); 12429 if (!MoreConstrainedThanPrevious) { 12430 IsResultAmbiguous = true; 12431 AmbiguousDecls.push_back(FD); 12432 continue; 12433 } 12434 if (!*MoreConstrainedThanPrevious) 12435 continue; 12436 // FD is more constrained - replace Result with it. 12437 } 12438 IsResultAmbiguous = false; 12439 DAP = I.getPair(); 12440 Result = FD; 12441 } 12442 12443 if (IsResultAmbiguous) 12444 return nullptr; 12445 12446 if (Result) { 12447 SmallVector<const Expr *, 1> ResultAC; 12448 // We skipped over some ambiguous declarations which might be ambiguous with 12449 // the selected result. 12450 for (FunctionDecl *Skipped : AmbiguousDecls) 12451 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12452 return nullptr; 12453 Pair = DAP; 12454 } 12455 return Result; 12456 } 12457 12458 /// Given an overloaded function, tries to turn it into a non-overloaded 12459 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12460 /// will perform access checks, diagnose the use of the resultant decl, and, if 12461 /// requested, potentially perform a function-to-pointer decay. 12462 /// 12463 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12464 /// Otherwise, returns true. This may emit diagnostics and return true. 12465 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12466 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12467 Expr *E = SrcExpr.get(); 12468 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12469 12470 DeclAccessPair DAP; 12471 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12472 if (!Found || Found->isCPUDispatchMultiVersion() || 12473 Found->isCPUSpecificMultiVersion()) 12474 return false; 12475 12476 // Emitting multiple diagnostics for a function that is both inaccessible and 12477 // unavailable is consistent with our behavior elsewhere. So, always check 12478 // for both. 12479 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12480 CheckAddressOfMemberAccess(E, DAP); 12481 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12482 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12483 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12484 else 12485 SrcExpr = Fixed; 12486 return true; 12487 } 12488 12489 /// Given an expression that refers to an overloaded function, try to 12490 /// resolve that overloaded function expression down to a single function. 12491 /// 12492 /// This routine can only resolve template-ids that refer to a single function 12493 /// template, where that template-id refers to a single template whose template 12494 /// arguments are either provided by the template-id or have defaults, 12495 /// as described in C++0x [temp.arg.explicit]p3. 12496 /// 12497 /// If no template-ids are found, no diagnostics are emitted and NULL is 12498 /// returned. 12499 FunctionDecl * 12500 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12501 bool Complain, 12502 DeclAccessPair *FoundResult) { 12503 // C++ [over.over]p1: 12504 // [...] [Note: any redundant set of parentheses surrounding the 12505 // overloaded function name is ignored (5.1). ] 12506 // C++ [over.over]p1: 12507 // [...] The overloaded function name can be preceded by the & 12508 // operator. 12509 12510 // If we didn't actually find any template-ids, we're done. 12511 if (!ovl->hasExplicitTemplateArgs()) 12512 return nullptr; 12513 12514 TemplateArgumentListInfo ExplicitTemplateArgs; 12515 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12516 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12517 12518 // Look through all of the overloaded functions, searching for one 12519 // whose type matches exactly. 12520 FunctionDecl *Matched = nullptr; 12521 for (UnresolvedSetIterator I = ovl->decls_begin(), 12522 E = ovl->decls_end(); I != E; ++I) { 12523 // C++0x [temp.arg.explicit]p3: 12524 // [...] In contexts where deduction is done and fails, or in contexts 12525 // where deduction is not done, if a template argument list is 12526 // specified and it, along with any default template arguments, 12527 // identifies a single function template specialization, then the 12528 // template-id is an lvalue for the function template specialization. 12529 FunctionTemplateDecl *FunctionTemplate 12530 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12531 12532 // C++ [over.over]p2: 12533 // If the name is a function template, template argument deduction is 12534 // done (14.8.2.2), and if the argument deduction succeeds, the 12535 // resulting template argument list is used to generate a single 12536 // function template specialization, which is added to the set of 12537 // overloaded functions considered. 12538 FunctionDecl *Specialization = nullptr; 12539 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12540 if (TemplateDeductionResult Result 12541 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12542 Specialization, Info, 12543 /*IsAddressOfFunction*/true)) { 12544 // Make a note of the failed deduction for diagnostics. 12545 // TODO: Actually use the failed-deduction info? 12546 FailedCandidates.addCandidate() 12547 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12548 MakeDeductionFailureInfo(Context, Result, Info)); 12549 continue; 12550 } 12551 12552 assert(Specialization && "no specialization and no error?"); 12553 12554 // Multiple matches; we can't resolve to a single declaration. 12555 if (Matched) { 12556 if (Complain) { 12557 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12558 << ovl->getName(); 12559 NoteAllOverloadCandidates(ovl); 12560 } 12561 return nullptr; 12562 } 12563 12564 Matched = Specialization; 12565 if (FoundResult) *FoundResult = I.getPair(); 12566 } 12567 12568 if (Matched && 12569 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12570 return nullptr; 12571 12572 return Matched; 12573 } 12574 12575 // Resolve and fix an overloaded expression that can be resolved 12576 // because it identifies a single function template specialization. 12577 // 12578 // Last three arguments should only be supplied if Complain = true 12579 // 12580 // Return true if it was logically possible to so resolve the 12581 // expression, regardless of whether or not it succeeded. Always 12582 // returns true if 'complain' is set. 12583 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12584 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12585 bool complain, SourceRange OpRangeForComplaining, 12586 QualType DestTypeForComplaining, 12587 unsigned DiagIDForComplaining) { 12588 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12589 12590 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12591 12592 DeclAccessPair found; 12593 ExprResult SingleFunctionExpression; 12594 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12595 ovl.Expression, /*complain*/ false, &found)) { 12596 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12597 SrcExpr = ExprError(); 12598 return true; 12599 } 12600 12601 // It is only correct to resolve to an instance method if we're 12602 // resolving a form that's permitted to be a pointer to member. 12603 // Otherwise we'll end up making a bound member expression, which 12604 // is illegal in all the contexts we resolve like this. 12605 if (!ovl.HasFormOfMemberPointer && 12606 isa<CXXMethodDecl>(fn) && 12607 cast<CXXMethodDecl>(fn)->isInstance()) { 12608 if (!complain) return false; 12609 12610 Diag(ovl.Expression->getExprLoc(), 12611 diag::err_bound_member_function) 12612 << 0 << ovl.Expression->getSourceRange(); 12613 12614 // TODO: I believe we only end up here if there's a mix of 12615 // static and non-static candidates (otherwise the expression 12616 // would have 'bound member' type, not 'overload' type). 12617 // Ideally we would note which candidate was chosen and why 12618 // the static candidates were rejected. 12619 SrcExpr = ExprError(); 12620 return true; 12621 } 12622 12623 // Fix the expression to refer to 'fn'. 12624 SingleFunctionExpression = 12625 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12626 12627 // If desired, do function-to-pointer decay. 12628 if (doFunctionPointerConverion) { 12629 SingleFunctionExpression = 12630 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12631 if (SingleFunctionExpression.isInvalid()) { 12632 SrcExpr = ExprError(); 12633 return true; 12634 } 12635 } 12636 } 12637 12638 if (!SingleFunctionExpression.isUsable()) { 12639 if (complain) { 12640 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12641 << ovl.Expression->getName() 12642 << DestTypeForComplaining 12643 << OpRangeForComplaining 12644 << ovl.Expression->getQualifierLoc().getSourceRange(); 12645 NoteAllOverloadCandidates(SrcExpr.get()); 12646 12647 SrcExpr = ExprError(); 12648 return true; 12649 } 12650 12651 return false; 12652 } 12653 12654 SrcExpr = SingleFunctionExpression; 12655 return true; 12656 } 12657 12658 /// Add a single candidate to the overload set. 12659 static void AddOverloadedCallCandidate(Sema &S, 12660 DeclAccessPair FoundDecl, 12661 TemplateArgumentListInfo *ExplicitTemplateArgs, 12662 ArrayRef<Expr *> Args, 12663 OverloadCandidateSet &CandidateSet, 12664 bool PartialOverloading, 12665 bool KnownValid) { 12666 NamedDecl *Callee = FoundDecl.getDecl(); 12667 if (isa<UsingShadowDecl>(Callee)) 12668 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12669 12670 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12671 if (ExplicitTemplateArgs) { 12672 assert(!KnownValid && "Explicit template arguments?"); 12673 return; 12674 } 12675 // Prevent ill-formed function decls to be added as overload candidates. 12676 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12677 return; 12678 12679 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12680 /*SuppressUserConversions=*/false, 12681 PartialOverloading); 12682 return; 12683 } 12684 12685 if (FunctionTemplateDecl *FuncTemplate 12686 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12687 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12688 ExplicitTemplateArgs, Args, CandidateSet, 12689 /*SuppressUserConversions=*/false, 12690 PartialOverloading); 12691 return; 12692 } 12693 12694 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12695 } 12696 12697 /// Add the overload candidates named by callee and/or found by argument 12698 /// dependent lookup to the given overload set. 12699 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12700 ArrayRef<Expr *> Args, 12701 OverloadCandidateSet &CandidateSet, 12702 bool PartialOverloading) { 12703 12704 #ifndef NDEBUG 12705 // Verify that ArgumentDependentLookup is consistent with the rules 12706 // in C++0x [basic.lookup.argdep]p3: 12707 // 12708 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12709 // and let Y be the lookup set produced by argument dependent 12710 // lookup (defined as follows). If X contains 12711 // 12712 // -- a declaration of a class member, or 12713 // 12714 // -- a block-scope function declaration that is not a 12715 // using-declaration, or 12716 // 12717 // -- a declaration that is neither a function or a function 12718 // template 12719 // 12720 // then Y is empty. 12721 12722 if (ULE->requiresADL()) { 12723 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12724 E = ULE->decls_end(); I != E; ++I) { 12725 assert(!(*I)->getDeclContext()->isRecord()); 12726 assert(isa<UsingShadowDecl>(*I) || 12727 !(*I)->getDeclContext()->isFunctionOrMethod()); 12728 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12729 } 12730 } 12731 #endif 12732 12733 // It would be nice to avoid this copy. 12734 TemplateArgumentListInfo TABuffer; 12735 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12736 if (ULE->hasExplicitTemplateArgs()) { 12737 ULE->copyTemplateArgumentsInto(TABuffer); 12738 ExplicitTemplateArgs = &TABuffer; 12739 } 12740 12741 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12742 E = ULE->decls_end(); I != E; ++I) 12743 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12744 CandidateSet, PartialOverloading, 12745 /*KnownValid*/ true); 12746 12747 if (ULE->requiresADL()) 12748 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12749 Args, ExplicitTemplateArgs, 12750 CandidateSet, PartialOverloading); 12751 } 12752 12753 /// Add the call candidates from the given set of lookup results to the given 12754 /// overload set. Non-function lookup results are ignored. 12755 void Sema::AddOverloadedCallCandidates( 12756 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 12757 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 12758 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12759 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12760 CandidateSet, false, /*KnownValid*/ false); 12761 } 12762 12763 /// Determine whether a declaration with the specified name could be moved into 12764 /// a different namespace. 12765 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12766 switch (Name.getCXXOverloadedOperator()) { 12767 case OO_New: case OO_Array_New: 12768 case OO_Delete: case OO_Array_Delete: 12769 return false; 12770 12771 default: 12772 return true; 12773 } 12774 } 12775 12776 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12777 /// template, where the non-dependent name was declared after the template 12778 /// was defined. This is common in code written for a compilers which do not 12779 /// correctly implement two-stage name lookup. 12780 /// 12781 /// Returns true if a viable candidate was found and a diagnostic was issued. 12782 static bool DiagnoseTwoPhaseLookup( 12783 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 12784 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 12785 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12786 CXXRecordDecl **FoundInClass = nullptr) { 12787 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12788 return false; 12789 12790 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12791 if (DC->isTransparentContext()) 12792 continue; 12793 12794 SemaRef.LookupQualifiedName(R, DC); 12795 12796 if (!R.empty()) { 12797 R.suppressDiagnostics(); 12798 12799 OverloadCandidateSet Candidates(FnLoc, CSK); 12800 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 12801 Candidates); 12802 12803 OverloadCandidateSet::iterator Best; 12804 OverloadingResult OR = 12805 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 12806 12807 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 12808 // We either found non-function declarations or a best viable function 12809 // at class scope. A class-scope lookup result disables ADL. Don't 12810 // look past this, but let the caller know that we found something that 12811 // either is, or might be, usable in this class. 12812 if (FoundInClass) { 12813 *FoundInClass = RD; 12814 if (OR == OR_Success) { 12815 R.clear(); 12816 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 12817 R.resolveKind(); 12818 } 12819 } 12820 return false; 12821 } 12822 12823 if (OR != OR_Success) { 12824 // There wasn't a unique best function or function template. 12825 return false; 12826 } 12827 12828 // Find the namespaces where ADL would have looked, and suggest 12829 // declaring the function there instead. 12830 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12831 Sema::AssociatedClassSet AssociatedClasses; 12832 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12833 AssociatedNamespaces, 12834 AssociatedClasses); 12835 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12836 if (canBeDeclaredInNamespace(R.getLookupName())) { 12837 DeclContext *Std = SemaRef.getStdNamespace(); 12838 for (Sema::AssociatedNamespaceSet::iterator 12839 it = AssociatedNamespaces.begin(), 12840 end = AssociatedNamespaces.end(); it != end; ++it) { 12841 // Never suggest declaring a function within namespace 'std'. 12842 if (Std && Std->Encloses(*it)) 12843 continue; 12844 12845 // Never suggest declaring a function within a namespace with a 12846 // reserved name, like __gnu_cxx. 12847 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12848 if (NS && 12849 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12850 continue; 12851 12852 SuggestedNamespaces.insert(*it); 12853 } 12854 } 12855 12856 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12857 << R.getLookupName(); 12858 if (SuggestedNamespaces.empty()) { 12859 SemaRef.Diag(Best->Function->getLocation(), 12860 diag::note_not_found_by_two_phase_lookup) 12861 << R.getLookupName() << 0; 12862 } else if (SuggestedNamespaces.size() == 1) { 12863 SemaRef.Diag(Best->Function->getLocation(), 12864 diag::note_not_found_by_two_phase_lookup) 12865 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12866 } else { 12867 // FIXME: It would be useful to list the associated namespaces here, 12868 // but the diagnostics infrastructure doesn't provide a way to produce 12869 // a localized representation of a list of items. 12870 SemaRef.Diag(Best->Function->getLocation(), 12871 diag::note_not_found_by_two_phase_lookup) 12872 << R.getLookupName() << 2; 12873 } 12874 12875 // Try to recover by calling this function. 12876 return true; 12877 } 12878 12879 R.clear(); 12880 } 12881 12882 return false; 12883 } 12884 12885 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12886 /// template, where the non-dependent operator was declared after the template 12887 /// was defined. 12888 /// 12889 /// Returns true if a viable candidate was found and a diagnostic was issued. 12890 static bool 12891 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12892 SourceLocation OpLoc, 12893 ArrayRef<Expr *> Args) { 12894 DeclarationName OpName = 12895 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12896 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12897 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12898 OverloadCandidateSet::CSK_Operator, 12899 /*ExplicitTemplateArgs=*/nullptr, Args); 12900 } 12901 12902 namespace { 12903 class BuildRecoveryCallExprRAII { 12904 Sema &SemaRef; 12905 public: 12906 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12907 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12908 SemaRef.IsBuildingRecoveryCallExpr = true; 12909 } 12910 12911 ~BuildRecoveryCallExprRAII() { 12912 SemaRef.IsBuildingRecoveryCallExpr = false; 12913 } 12914 }; 12915 12916 } 12917 12918 /// Attempts to recover from a call where no functions were found. 12919 /// 12920 /// This function will do one of three things: 12921 /// * Diagnose, recover, and return a recovery expression. 12922 /// * Diagnose, fail to recover, and return ExprError(). 12923 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 12924 /// expected to diagnose as appropriate. 12925 static ExprResult 12926 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12927 UnresolvedLookupExpr *ULE, 12928 SourceLocation LParenLoc, 12929 MutableArrayRef<Expr *> Args, 12930 SourceLocation RParenLoc, 12931 bool EmptyLookup, bool AllowTypoCorrection) { 12932 // Do not try to recover if it is already building a recovery call. 12933 // This stops infinite loops for template instantiations like 12934 // 12935 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12936 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12937 if (SemaRef.IsBuildingRecoveryCallExpr) 12938 return ExprResult(); 12939 BuildRecoveryCallExprRAII RCE(SemaRef); 12940 12941 CXXScopeSpec SS; 12942 SS.Adopt(ULE->getQualifierLoc()); 12943 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12944 12945 TemplateArgumentListInfo TABuffer; 12946 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12947 if (ULE->hasExplicitTemplateArgs()) { 12948 ULE->copyTemplateArgumentsInto(TABuffer); 12949 ExplicitTemplateArgs = &TABuffer; 12950 } 12951 12952 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12953 Sema::LookupOrdinaryName); 12954 CXXRecordDecl *FoundInClass = nullptr; 12955 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 12956 OverloadCandidateSet::CSK_Normal, 12957 ExplicitTemplateArgs, Args, &FoundInClass)) { 12958 // OK, diagnosed a two-phase lookup issue. 12959 } else if (EmptyLookup) { 12960 // Try to recover from an empty lookup with typo correction. 12961 R.clear(); 12962 NoTypoCorrectionCCC NoTypoValidator{}; 12963 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12964 ExplicitTemplateArgs != nullptr, 12965 dyn_cast<MemberExpr>(Fn)); 12966 CorrectionCandidateCallback &Validator = 12967 AllowTypoCorrection 12968 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12969 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12970 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12971 Args)) 12972 return ExprError(); 12973 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 12974 // We found a usable declaration of the name in a dependent base of some 12975 // enclosing class. 12976 // FIXME: We should also explain why the candidates found by name lookup 12977 // were not viable. 12978 if (SemaRef.DiagnoseDependentMemberLookup(R)) 12979 return ExprError(); 12980 } else { 12981 // We had viable candidates and couldn't recover; let the caller diagnose 12982 // this. 12983 return ExprResult(); 12984 } 12985 12986 // If we get here, we should have issued a diagnostic and formed a recovery 12987 // lookup result. 12988 assert(!R.empty() && "lookup results empty despite recovery"); 12989 12990 // If recovery created an ambiguity, just bail out. 12991 if (R.isAmbiguous()) { 12992 R.suppressDiagnostics(); 12993 return ExprError(); 12994 } 12995 12996 // Build an implicit member call if appropriate. Just drop the 12997 // casts and such from the call, we don't really care. 12998 ExprResult NewFn = ExprError(); 12999 if ((*R.begin())->isCXXClassMember()) 13000 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13001 ExplicitTemplateArgs, S); 13002 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13003 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13004 ExplicitTemplateArgs); 13005 else 13006 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13007 13008 if (NewFn.isInvalid()) 13009 return ExprError(); 13010 13011 // This shouldn't cause an infinite loop because we're giving it 13012 // an expression with viable lookup results, which should never 13013 // end up here. 13014 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13015 MultiExprArg(Args.data(), Args.size()), 13016 RParenLoc); 13017 } 13018 13019 /// Constructs and populates an OverloadedCandidateSet from 13020 /// the given function. 13021 /// \returns true when an the ExprResult output parameter has been set. 13022 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13023 UnresolvedLookupExpr *ULE, 13024 MultiExprArg Args, 13025 SourceLocation RParenLoc, 13026 OverloadCandidateSet *CandidateSet, 13027 ExprResult *Result) { 13028 #ifndef NDEBUG 13029 if (ULE->requiresADL()) { 13030 // To do ADL, we must have found an unqualified name. 13031 assert(!ULE->getQualifier() && "qualified name with ADL"); 13032 13033 // We don't perform ADL for implicit declarations of builtins. 13034 // Verify that this was correctly set up. 13035 FunctionDecl *F; 13036 if (ULE->decls_begin() != ULE->decls_end() && 13037 ULE->decls_begin() + 1 == ULE->decls_end() && 13038 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13039 F->getBuiltinID() && F->isImplicit()) 13040 llvm_unreachable("performing ADL for builtin"); 13041 13042 // We don't perform ADL in C. 13043 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13044 } 13045 #endif 13046 13047 UnbridgedCastsSet UnbridgedCasts; 13048 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13049 *Result = ExprError(); 13050 return true; 13051 } 13052 13053 // Add the functions denoted by the callee to the set of candidate 13054 // functions, including those from argument-dependent lookup. 13055 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13056 13057 if (getLangOpts().MSVCCompat && 13058 CurContext->isDependentContext() && !isSFINAEContext() && 13059 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13060 13061 OverloadCandidateSet::iterator Best; 13062 if (CandidateSet->empty() || 13063 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13064 OR_No_Viable_Function) { 13065 // In Microsoft mode, if we are inside a template class member function 13066 // then create a type dependent CallExpr. The goal is to postpone name 13067 // lookup to instantiation time to be able to search into type dependent 13068 // base classes. 13069 CallExpr *CE = 13070 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13071 RParenLoc, CurFPFeatureOverrides()); 13072 CE->markDependentForPostponedNameLookup(); 13073 *Result = CE; 13074 return true; 13075 } 13076 } 13077 13078 if (CandidateSet->empty()) 13079 return false; 13080 13081 UnbridgedCasts.restore(); 13082 return false; 13083 } 13084 13085 // Guess at what the return type for an unresolvable overload should be. 13086 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13087 OverloadCandidateSet::iterator *Best) { 13088 llvm::Optional<QualType> Result; 13089 // Adjust Type after seeing a candidate. 13090 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13091 if (!Candidate.Function) 13092 return; 13093 if (Candidate.Function->isInvalidDecl()) 13094 return; 13095 QualType T = Candidate.Function->getReturnType(); 13096 if (T.isNull()) 13097 return; 13098 if (!Result) 13099 Result = T; 13100 else if (Result != T) 13101 Result = QualType(); 13102 }; 13103 13104 // Look for an unambiguous type from a progressively larger subset. 13105 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13106 // 13107 // First, consider only the best candidate. 13108 if (Best && *Best != CS.end()) 13109 ConsiderCandidate(**Best); 13110 // Next, consider only viable candidates. 13111 if (!Result) 13112 for (const auto &C : CS) 13113 if (C.Viable) 13114 ConsiderCandidate(C); 13115 // Finally, consider all candidates. 13116 if (!Result) 13117 for (const auto &C : CS) 13118 ConsiderCandidate(C); 13119 13120 if (!Result) 13121 return QualType(); 13122 auto Value = Result.getValue(); 13123 if (Value.isNull() || Value->isUndeducedType()) 13124 return QualType(); 13125 return Value; 13126 } 13127 13128 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13129 /// the completed call expression. If overload resolution fails, emits 13130 /// diagnostics and returns ExprError() 13131 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13132 UnresolvedLookupExpr *ULE, 13133 SourceLocation LParenLoc, 13134 MultiExprArg Args, 13135 SourceLocation RParenLoc, 13136 Expr *ExecConfig, 13137 OverloadCandidateSet *CandidateSet, 13138 OverloadCandidateSet::iterator *Best, 13139 OverloadingResult OverloadResult, 13140 bool AllowTypoCorrection) { 13141 switch (OverloadResult) { 13142 case OR_Success: { 13143 FunctionDecl *FDecl = (*Best)->Function; 13144 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13145 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13146 return ExprError(); 13147 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13148 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13149 ExecConfig, /*IsExecConfig=*/false, 13150 (*Best)->IsADLCandidate); 13151 } 13152 13153 case OR_No_Viable_Function: { 13154 // Try to recover by looking for viable functions which the user might 13155 // have meant to call. 13156 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13157 Args, RParenLoc, 13158 CandidateSet->empty(), 13159 AllowTypoCorrection); 13160 if (Recovery.isInvalid() || Recovery.isUsable()) 13161 return Recovery; 13162 13163 // If the user passes in a function that we can't take the address of, we 13164 // generally end up emitting really bad error messages. Here, we attempt to 13165 // emit better ones. 13166 for (const Expr *Arg : Args) { 13167 if (!Arg->getType()->isFunctionType()) 13168 continue; 13169 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13170 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13171 if (FD && 13172 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13173 Arg->getExprLoc())) 13174 return ExprError(); 13175 } 13176 } 13177 13178 CandidateSet->NoteCandidates( 13179 PartialDiagnosticAt( 13180 Fn->getBeginLoc(), 13181 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13182 << ULE->getName() << Fn->getSourceRange()), 13183 SemaRef, OCD_AllCandidates, Args); 13184 break; 13185 } 13186 13187 case OR_Ambiguous: 13188 CandidateSet->NoteCandidates( 13189 PartialDiagnosticAt(Fn->getBeginLoc(), 13190 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13191 << ULE->getName() << Fn->getSourceRange()), 13192 SemaRef, OCD_AmbiguousCandidates, Args); 13193 break; 13194 13195 case OR_Deleted: { 13196 CandidateSet->NoteCandidates( 13197 PartialDiagnosticAt(Fn->getBeginLoc(), 13198 SemaRef.PDiag(diag::err_ovl_deleted_call) 13199 << ULE->getName() << Fn->getSourceRange()), 13200 SemaRef, OCD_AllCandidates, Args); 13201 13202 // We emitted an error for the unavailable/deleted function call but keep 13203 // the call in the AST. 13204 FunctionDecl *FDecl = (*Best)->Function; 13205 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13206 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 13207 ExecConfig, /*IsExecConfig=*/false, 13208 (*Best)->IsADLCandidate); 13209 } 13210 } 13211 13212 // Overload resolution failed, try to recover. 13213 SmallVector<Expr *, 8> SubExprs = {Fn}; 13214 SubExprs.append(Args.begin(), Args.end()); 13215 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13216 chooseRecoveryType(*CandidateSet, Best)); 13217 } 13218 13219 static void markUnaddressableCandidatesUnviable(Sema &S, 13220 OverloadCandidateSet &CS) { 13221 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13222 if (I->Viable && 13223 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13224 I->Viable = false; 13225 I->FailureKind = ovl_fail_addr_not_available; 13226 } 13227 } 13228 } 13229 13230 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13231 /// (which eventually refers to the declaration Func) and the call 13232 /// arguments Args/NumArgs, attempt to resolve the function call down 13233 /// to a specific function. If overload resolution succeeds, returns 13234 /// the call expression produced by overload resolution. 13235 /// Otherwise, emits diagnostics and returns ExprError. 13236 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13237 UnresolvedLookupExpr *ULE, 13238 SourceLocation LParenLoc, 13239 MultiExprArg Args, 13240 SourceLocation RParenLoc, 13241 Expr *ExecConfig, 13242 bool AllowTypoCorrection, 13243 bool CalleesAddressIsTaken) { 13244 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13245 OverloadCandidateSet::CSK_Normal); 13246 ExprResult result; 13247 13248 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13249 &result)) 13250 return result; 13251 13252 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 13253 // functions that aren't addressible are considered unviable. 13254 if (CalleesAddressIsTaken) 13255 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13256 13257 OverloadCandidateSet::iterator Best; 13258 OverloadingResult OverloadResult = 13259 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13260 13261 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13262 ExecConfig, &CandidateSet, &Best, 13263 OverloadResult, AllowTypoCorrection); 13264 } 13265 13266 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13267 return Functions.size() > 1 || 13268 (Functions.size() == 1 && 13269 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13270 } 13271 13272 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13273 NestedNameSpecifierLoc NNSLoc, 13274 DeclarationNameInfo DNI, 13275 const UnresolvedSetImpl &Fns, 13276 bool PerformADL) { 13277 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13278 PerformADL, IsOverloaded(Fns), 13279 Fns.begin(), Fns.end()); 13280 } 13281 13282 /// Create a unary operation that may resolve to an overloaded 13283 /// operator. 13284 /// 13285 /// \param OpLoc The location of the operator itself (e.g., '*'). 13286 /// 13287 /// \param Opc The UnaryOperatorKind that describes this operator. 13288 /// 13289 /// \param Fns The set of non-member functions that will be 13290 /// considered by overload resolution. The caller needs to build this 13291 /// set based on the context using, e.g., 13292 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13293 /// set should not contain any member functions; those will be added 13294 /// by CreateOverloadedUnaryOp(). 13295 /// 13296 /// \param Input The input argument. 13297 ExprResult 13298 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13299 const UnresolvedSetImpl &Fns, 13300 Expr *Input, bool PerformADL) { 13301 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13302 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13303 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13304 // TODO: provide better source location info. 13305 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13306 13307 if (checkPlaceholderForOverload(*this, Input)) 13308 return ExprError(); 13309 13310 Expr *Args[2] = { Input, nullptr }; 13311 unsigned NumArgs = 1; 13312 13313 // For post-increment and post-decrement, add the implicit '0' as 13314 // the second argument, so that we know this is a post-increment or 13315 // post-decrement. 13316 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13317 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13318 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13319 SourceLocation()); 13320 NumArgs = 2; 13321 } 13322 13323 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13324 13325 if (Input->isTypeDependent()) { 13326 if (Fns.empty()) 13327 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13328 VK_PRValue, OK_Ordinary, OpLoc, false, 13329 CurFPFeatureOverrides()); 13330 13331 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13332 ExprResult Fn = CreateUnresolvedLookupExpr( 13333 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13334 if (Fn.isInvalid()) 13335 return ExprError(); 13336 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13337 Context.DependentTy, VK_PRValue, OpLoc, 13338 CurFPFeatureOverrides()); 13339 } 13340 13341 // Build an empty overload set. 13342 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13343 13344 // Add the candidates from the given function set. 13345 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13346 13347 // Add operator candidates that are member functions. 13348 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13349 13350 // Add candidates from ADL. 13351 if (PerformADL) { 13352 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13353 /*ExplicitTemplateArgs*/nullptr, 13354 CandidateSet); 13355 } 13356 13357 // Add builtin operator candidates. 13358 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13359 13360 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13361 13362 // Perform overload resolution. 13363 OverloadCandidateSet::iterator Best; 13364 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13365 case OR_Success: { 13366 // We found a built-in operator or an overloaded operator. 13367 FunctionDecl *FnDecl = Best->Function; 13368 13369 if (FnDecl) { 13370 Expr *Base = nullptr; 13371 // We matched an overloaded operator. Build a call to that 13372 // operator. 13373 13374 // Convert the arguments. 13375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13376 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13377 13378 ExprResult InputRes = 13379 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13380 Best->FoundDecl, Method); 13381 if (InputRes.isInvalid()) 13382 return ExprError(); 13383 Base = Input = InputRes.get(); 13384 } else { 13385 // Convert the arguments. 13386 ExprResult InputInit 13387 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13388 Context, 13389 FnDecl->getParamDecl(0)), 13390 SourceLocation(), 13391 Input); 13392 if (InputInit.isInvalid()) 13393 return ExprError(); 13394 Input = InputInit.get(); 13395 } 13396 13397 // Build the actual expression node. 13398 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13399 Base, HadMultipleCandidates, 13400 OpLoc); 13401 if (FnExpr.isInvalid()) 13402 return ExprError(); 13403 13404 // Determine the result type. 13405 QualType ResultTy = FnDecl->getReturnType(); 13406 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13407 ResultTy = ResultTy.getNonLValueExprType(Context); 13408 13409 Args[0] = Input; 13410 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13411 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13412 CurFPFeatureOverrides(), Best->IsADLCandidate); 13413 13414 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13415 return ExprError(); 13416 13417 if (CheckFunctionCall(FnDecl, TheCall, 13418 FnDecl->getType()->castAs<FunctionProtoType>())) 13419 return ExprError(); 13420 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13421 } else { 13422 // We matched a built-in operator. Convert the arguments, then 13423 // break out so that we will build the appropriate built-in 13424 // operator node. 13425 ExprResult InputRes = PerformImplicitConversion( 13426 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13427 CCK_ForBuiltinOverloadedOp); 13428 if (InputRes.isInvalid()) 13429 return ExprError(); 13430 Input = InputRes.get(); 13431 break; 13432 } 13433 } 13434 13435 case OR_No_Viable_Function: 13436 // This is an erroneous use of an operator which can be overloaded by 13437 // a non-member function. Check for non-member operators which were 13438 // defined too late to be candidates. 13439 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13440 // FIXME: Recover by calling the found function. 13441 return ExprError(); 13442 13443 // No viable function; fall through to handling this as a 13444 // built-in operator, which will produce an error message for us. 13445 break; 13446 13447 case OR_Ambiguous: 13448 CandidateSet.NoteCandidates( 13449 PartialDiagnosticAt(OpLoc, 13450 PDiag(diag::err_ovl_ambiguous_oper_unary) 13451 << UnaryOperator::getOpcodeStr(Opc) 13452 << Input->getType() << Input->getSourceRange()), 13453 *this, OCD_AmbiguousCandidates, ArgsArray, 13454 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13455 return ExprError(); 13456 13457 case OR_Deleted: 13458 CandidateSet.NoteCandidates( 13459 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13460 << UnaryOperator::getOpcodeStr(Opc) 13461 << Input->getSourceRange()), 13462 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13463 OpLoc); 13464 return ExprError(); 13465 } 13466 13467 // Either we found no viable overloaded operator or we matched a 13468 // built-in operator. In either case, fall through to trying to 13469 // build a built-in operation. 13470 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13471 } 13472 13473 /// Perform lookup for an overloaded binary operator. 13474 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13475 OverloadedOperatorKind Op, 13476 const UnresolvedSetImpl &Fns, 13477 ArrayRef<Expr *> Args, bool PerformADL) { 13478 SourceLocation OpLoc = CandidateSet.getLocation(); 13479 13480 OverloadedOperatorKind ExtraOp = 13481 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13482 ? getRewrittenOverloadedOperator(Op) 13483 : OO_None; 13484 13485 // Add the candidates from the given function set. This also adds the 13486 // rewritten candidates using these functions if necessary. 13487 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13488 13489 // Add operator candidates that are member functions. 13490 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13491 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13492 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13493 OverloadCandidateParamOrder::Reversed); 13494 13495 // In C++20, also add any rewritten member candidates. 13496 if (ExtraOp) { 13497 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13498 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13499 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13500 CandidateSet, 13501 OverloadCandidateParamOrder::Reversed); 13502 } 13503 13504 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13505 // performed for an assignment operator (nor for operator[] nor operator->, 13506 // which don't get here). 13507 if (Op != OO_Equal && PerformADL) { 13508 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13509 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13510 /*ExplicitTemplateArgs*/ nullptr, 13511 CandidateSet); 13512 if (ExtraOp) { 13513 DeclarationName ExtraOpName = 13514 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13515 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13516 /*ExplicitTemplateArgs*/ nullptr, 13517 CandidateSet); 13518 } 13519 } 13520 13521 // Add builtin operator candidates. 13522 // 13523 // FIXME: We don't add any rewritten candidates here. This is strictly 13524 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13525 // resulting in our selecting a rewritten builtin candidate. For example: 13526 // 13527 // enum class E { e }; 13528 // bool operator!=(E, E) requires false; 13529 // bool k = E::e != E::e; 13530 // 13531 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13532 // it seems unreasonable to consider rewritten builtin candidates. A core 13533 // issue has been filed proposing to removed this requirement. 13534 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13535 } 13536 13537 /// Create a binary operation that may resolve to an overloaded 13538 /// operator. 13539 /// 13540 /// \param OpLoc The location of the operator itself (e.g., '+'). 13541 /// 13542 /// \param Opc The BinaryOperatorKind that describes this operator. 13543 /// 13544 /// \param Fns The set of non-member functions that will be 13545 /// considered by overload resolution. The caller needs to build this 13546 /// set based on the context using, e.g., 13547 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13548 /// set should not contain any member functions; those will be added 13549 /// by CreateOverloadedBinOp(). 13550 /// 13551 /// \param LHS Left-hand argument. 13552 /// \param RHS Right-hand argument. 13553 /// \param PerformADL Whether to consider operator candidates found by ADL. 13554 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13555 /// C++20 operator rewrites. 13556 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13557 /// the function in question. Such a function is never a candidate in 13558 /// our overload resolution. This also enables synthesizing a three-way 13559 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13560 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13561 BinaryOperatorKind Opc, 13562 const UnresolvedSetImpl &Fns, Expr *LHS, 13563 Expr *RHS, bool PerformADL, 13564 bool AllowRewrittenCandidates, 13565 FunctionDecl *DefaultedFn) { 13566 Expr *Args[2] = { LHS, RHS }; 13567 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13568 13569 if (!getLangOpts().CPlusPlus20) 13570 AllowRewrittenCandidates = false; 13571 13572 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13573 13574 // If either side is type-dependent, create an appropriate dependent 13575 // expression. 13576 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13577 if (Fns.empty()) { 13578 // If there are no functions to store, just build a dependent 13579 // BinaryOperator or CompoundAssignment. 13580 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 13581 return CompoundAssignOperator::Create( 13582 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13583 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13584 Context.DependentTy); 13585 return BinaryOperator::Create( 13586 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 13587 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13588 } 13589 13590 // FIXME: save results of ADL from here? 13591 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13592 // TODO: provide better source location info in DNLoc component. 13593 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13594 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13595 ExprResult Fn = CreateUnresolvedLookupExpr( 13596 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13597 if (Fn.isInvalid()) 13598 return ExprError(); 13599 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13600 Context.DependentTy, VK_PRValue, OpLoc, 13601 CurFPFeatureOverrides()); 13602 } 13603 13604 // Always do placeholder-like conversions on the RHS. 13605 if (checkPlaceholderForOverload(*this, Args[1])) 13606 return ExprError(); 13607 13608 // Do placeholder-like conversion on the LHS; note that we should 13609 // not get here with a PseudoObject LHS. 13610 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13611 if (checkPlaceholderForOverload(*this, Args[0])) 13612 return ExprError(); 13613 13614 // If this is the assignment operator, we only perform overload resolution 13615 // if the left-hand side is a class or enumeration type. This is actually 13616 // a hack. The standard requires that we do overload resolution between the 13617 // various built-in candidates, but as DR507 points out, this can lead to 13618 // problems. So we do it this way, which pretty much follows what GCC does. 13619 // Note that we go the traditional code path for compound assignment forms. 13620 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13621 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13622 13623 // If this is the .* operator, which is not overloadable, just 13624 // create a built-in binary operator. 13625 if (Opc == BO_PtrMemD) 13626 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13627 13628 // Build the overload set. 13629 OverloadCandidateSet CandidateSet( 13630 OpLoc, OverloadCandidateSet::CSK_Operator, 13631 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13632 if (DefaultedFn) 13633 CandidateSet.exclude(DefaultedFn); 13634 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13635 13636 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13637 13638 // Perform overload resolution. 13639 OverloadCandidateSet::iterator Best; 13640 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13641 case OR_Success: { 13642 // We found a built-in operator or an overloaded operator. 13643 FunctionDecl *FnDecl = Best->Function; 13644 13645 bool IsReversed = Best->isReversed(); 13646 if (IsReversed) 13647 std::swap(Args[0], Args[1]); 13648 13649 if (FnDecl) { 13650 Expr *Base = nullptr; 13651 // We matched an overloaded operator. Build a call to that 13652 // operator. 13653 13654 OverloadedOperatorKind ChosenOp = 13655 FnDecl->getDeclName().getCXXOverloadedOperator(); 13656 13657 // C++2a [over.match.oper]p9: 13658 // If a rewritten operator== candidate is selected by overload 13659 // resolution for an operator@, its return type shall be cv bool 13660 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13661 !FnDecl->getReturnType()->isBooleanType()) { 13662 bool IsExtension = 13663 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13664 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13665 : diag::err_ovl_rewrite_equalequal_not_bool) 13666 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13667 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13668 Diag(FnDecl->getLocation(), diag::note_declared_at); 13669 if (!IsExtension) 13670 return ExprError(); 13671 } 13672 13673 if (AllowRewrittenCandidates && !IsReversed && 13674 CandidateSet.getRewriteInfo().isReversible()) { 13675 // We could have reversed this operator, but didn't. Check if some 13676 // reversed form was a viable candidate, and if so, if it had a 13677 // better conversion for either parameter. If so, this call is 13678 // formally ambiguous, and allowing it is an extension. 13679 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13680 for (OverloadCandidate &Cand : CandidateSet) { 13681 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13682 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13683 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13684 if (CompareImplicitConversionSequences( 13685 *this, OpLoc, Cand.Conversions[ArgIdx], 13686 Best->Conversions[ArgIdx]) == 13687 ImplicitConversionSequence::Better) { 13688 AmbiguousWith.push_back(Cand.Function); 13689 break; 13690 } 13691 } 13692 } 13693 } 13694 13695 if (!AmbiguousWith.empty()) { 13696 bool AmbiguousWithSelf = 13697 AmbiguousWith.size() == 1 && 13698 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13699 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13700 << BinaryOperator::getOpcodeStr(Opc) 13701 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13702 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13703 if (AmbiguousWithSelf) { 13704 Diag(FnDecl->getLocation(), 13705 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13706 } else { 13707 Diag(FnDecl->getLocation(), 13708 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13709 for (auto *F : AmbiguousWith) 13710 Diag(F->getLocation(), 13711 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13712 } 13713 } 13714 } 13715 13716 // Convert the arguments. 13717 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13718 // Best->Access is only meaningful for class members. 13719 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13720 13721 ExprResult Arg1 = 13722 PerformCopyInitialization( 13723 InitializedEntity::InitializeParameter(Context, 13724 FnDecl->getParamDecl(0)), 13725 SourceLocation(), Args[1]); 13726 if (Arg1.isInvalid()) 13727 return ExprError(); 13728 13729 ExprResult Arg0 = 13730 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13731 Best->FoundDecl, Method); 13732 if (Arg0.isInvalid()) 13733 return ExprError(); 13734 Base = Args[0] = Arg0.getAs<Expr>(); 13735 Args[1] = RHS = Arg1.getAs<Expr>(); 13736 } else { 13737 // Convert the arguments. 13738 ExprResult Arg0 = PerformCopyInitialization( 13739 InitializedEntity::InitializeParameter(Context, 13740 FnDecl->getParamDecl(0)), 13741 SourceLocation(), Args[0]); 13742 if (Arg0.isInvalid()) 13743 return ExprError(); 13744 13745 ExprResult Arg1 = 13746 PerformCopyInitialization( 13747 InitializedEntity::InitializeParameter(Context, 13748 FnDecl->getParamDecl(1)), 13749 SourceLocation(), Args[1]); 13750 if (Arg1.isInvalid()) 13751 return ExprError(); 13752 Args[0] = LHS = Arg0.getAs<Expr>(); 13753 Args[1] = RHS = Arg1.getAs<Expr>(); 13754 } 13755 13756 // Build the actual expression node. 13757 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13758 Best->FoundDecl, Base, 13759 HadMultipleCandidates, OpLoc); 13760 if (FnExpr.isInvalid()) 13761 return ExprError(); 13762 13763 // Determine the result type. 13764 QualType ResultTy = FnDecl->getReturnType(); 13765 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13766 ResultTy = ResultTy.getNonLValueExprType(Context); 13767 13768 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13769 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13770 CurFPFeatureOverrides(), Best->IsADLCandidate); 13771 13772 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13773 FnDecl)) 13774 return ExprError(); 13775 13776 ArrayRef<const Expr *> ArgsArray(Args, 2); 13777 const Expr *ImplicitThis = nullptr; 13778 // Cut off the implicit 'this'. 13779 if (isa<CXXMethodDecl>(FnDecl)) { 13780 ImplicitThis = ArgsArray[0]; 13781 ArgsArray = ArgsArray.slice(1); 13782 } 13783 13784 // Check for a self move. 13785 if (Op == OO_Equal) 13786 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13787 13788 if (ImplicitThis) { 13789 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 13790 QualType ThisTypeFromDecl = Context.getPointerType( 13791 cast<CXXMethodDecl>(FnDecl)->getThisObjectType()); 13792 13793 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 13794 ThisTypeFromDecl); 13795 } 13796 13797 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13798 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13799 VariadicDoesNotApply); 13800 13801 ExprResult R = MaybeBindToTemporary(TheCall); 13802 if (R.isInvalid()) 13803 return ExprError(); 13804 13805 R = CheckForImmediateInvocation(R, FnDecl); 13806 if (R.isInvalid()) 13807 return ExprError(); 13808 13809 // For a rewritten candidate, we've already reversed the arguments 13810 // if needed. Perform the rest of the rewrite now. 13811 if ((Best->RewriteKind & CRK_DifferentOperator) || 13812 (Op == OO_Spaceship && IsReversed)) { 13813 if (Op == OO_ExclaimEqual) { 13814 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13815 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13816 } else { 13817 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13818 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13819 Expr *ZeroLiteral = 13820 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13821 13822 Sema::CodeSynthesisContext Ctx; 13823 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13824 Ctx.Entity = FnDecl; 13825 pushCodeSynthesisContext(Ctx); 13826 13827 R = CreateOverloadedBinOp( 13828 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13829 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13830 /*AllowRewrittenCandidates=*/false); 13831 13832 popCodeSynthesisContext(); 13833 } 13834 if (R.isInvalid()) 13835 return ExprError(); 13836 } else { 13837 assert(ChosenOp == Op && "unexpected operator name"); 13838 } 13839 13840 // Make a note in the AST if we did any rewriting. 13841 if (Best->RewriteKind != CRK_None) 13842 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13843 13844 return R; 13845 } else { 13846 // We matched a built-in operator. Convert the arguments, then 13847 // break out so that we will build the appropriate built-in 13848 // operator node. 13849 ExprResult ArgsRes0 = PerformImplicitConversion( 13850 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13851 AA_Passing, CCK_ForBuiltinOverloadedOp); 13852 if (ArgsRes0.isInvalid()) 13853 return ExprError(); 13854 Args[0] = ArgsRes0.get(); 13855 13856 ExprResult ArgsRes1 = PerformImplicitConversion( 13857 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13858 AA_Passing, CCK_ForBuiltinOverloadedOp); 13859 if (ArgsRes1.isInvalid()) 13860 return ExprError(); 13861 Args[1] = ArgsRes1.get(); 13862 break; 13863 } 13864 } 13865 13866 case OR_No_Viable_Function: { 13867 // C++ [over.match.oper]p9: 13868 // If the operator is the operator , [...] and there are no 13869 // viable functions, then the operator is assumed to be the 13870 // built-in operator and interpreted according to clause 5. 13871 if (Opc == BO_Comma) 13872 break; 13873 13874 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13875 // compare result using '==' and '<'. 13876 if (DefaultedFn && Opc == BO_Cmp) { 13877 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13878 Args[1], DefaultedFn); 13879 if (E.isInvalid() || E.isUsable()) 13880 return E; 13881 } 13882 13883 // For class as left operand for assignment or compound assignment 13884 // operator do not fall through to handling in built-in, but report that 13885 // no overloaded assignment operator found 13886 ExprResult Result = ExprError(); 13887 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13888 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13889 Args, OpLoc); 13890 DeferDiagsRAII DDR(*this, 13891 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 13892 if (Args[0]->getType()->isRecordType() && 13893 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13894 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13895 << BinaryOperator::getOpcodeStr(Opc) 13896 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13897 if (Args[0]->getType()->isIncompleteType()) { 13898 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13899 << Args[0]->getType() 13900 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13901 } 13902 } else { 13903 // This is an erroneous use of an operator which can be overloaded by 13904 // a non-member function. Check for non-member operators which were 13905 // defined too late to be candidates. 13906 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13907 // FIXME: Recover by calling the found function. 13908 return ExprError(); 13909 13910 // No viable function; try to create a built-in operation, which will 13911 // produce an error. Then, show the non-viable candidates. 13912 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13913 } 13914 assert(Result.isInvalid() && 13915 "C++ binary operator overloading is missing candidates!"); 13916 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13917 return Result; 13918 } 13919 13920 case OR_Ambiguous: 13921 CandidateSet.NoteCandidates( 13922 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13923 << BinaryOperator::getOpcodeStr(Opc) 13924 << Args[0]->getType() 13925 << Args[1]->getType() 13926 << Args[0]->getSourceRange() 13927 << Args[1]->getSourceRange()), 13928 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13929 OpLoc); 13930 return ExprError(); 13931 13932 case OR_Deleted: 13933 if (isImplicitlyDeleted(Best->Function)) { 13934 FunctionDecl *DeletedFD = Best->Function; 13935 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13936 if (DFK.isSpecialMember()) { 13937 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13938 << Args[0]->getType() << DFK.asSpecialMember(); 13939 } else { 13940 assert(DFK.isComparison()); 13941 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13942 << Args[0]->getType() << DeletedFD; 13943 } 13944 13945 // The user probably meant to call this special member. Just 13946 // explain why it's deleted. 13947 NoteDeletedFunction(DeletedFD); 13948 return ExprError(); 13949 } 13950 CandidateSet.NoteCandidates( 13951 PartialDiagnosticAt( 13952 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13953 << getOperatorSpelling(Best->Function->getDeclName() 13954 .getCXXOverloadedOperator()) 13955 << Args[0]->getSourceRange() 13956 << Args[1]->getSourceRange()), 13957 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13958 OpLoc); 13959 return ExprError(); 13960 } 13961 13962 // We matched a built-in operator; build it. 13963 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13964 } 13965 13966 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13967 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13968 FunctionDecl *DefaultedFn) { 13969 const ComparisonCategoryInfo *Info = 13970 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13971 // If we're not producing a known comparison category type, we can't 13972 // synthesize a three-way comparison. Let the caller diagnose this. 13973 if (!Info) 13974 return ExprResult((Expr*)nullptr); 13975 13976 // If we ever want to perform this synthesis more generally, we will need to 13977 // apply the temporary materialization conversion to the operands. 13978 assert(LHS->isGLValue() && RHS->isGLValue() && 13979 "cannot use prvalue expressions more than once"); 13980 Expr *OrigLHS = LHS; 13981 Expr *OrigRHS = RHS; 13982 13983 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13984 // each of them multiple times below. 13985 LHS = new (Context) 13986 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13987 LHS->getObjectKind(), LHS); 13988 RHS = new (Context) 13989 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13990 RHS->getObjectKind(), RHS); 13991 13992 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13993 DefaultedFn); 13994 if (Eq.isInvalid()) 13995 return ExprError(); 13996 13997 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13998 true, DefaultedFn); 13999 if (Less.isInvalid()) 14000 return ExprError(); 14001 14002 ExprResult Greater; 14003 if (Info->isPartial()) { 14004 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14005 DefaultedFn); 14006 if (Greater.isInvalid()) 14007 return ExprError(); 14008 } 14009 14010 // Form the list of comparisons we're going to perform. 14011 struct Comparison { 14012 ExprResult Cmp; 14013 ComparisonCategoryResult Result; 14014 } Comparisons[4] = 14015 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14016 : ComparisonCategoryResult::Equivalent}, 14017 {Less, ComparisonCategoryResult::Less}, 14018 {Greater, ComparisonCategoryResult::Greater}, 14019 {ExprResult(), ComparisonCategoryResult::Unordered}, 14020 }; 14021 14022 int I = Info->isPartial() ? 3 : 2; 14023 14024 // Combine the comparisons with suitable conditional expressions. 14025 ExprResult Result; 14026 for (; I >= 0; --I) { 14027 // Build a reference to the comparison category constant. 14028 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14029 // FIXME: Missing a constant for a comparison category. Diagnose this? 14030 if (!VI) 14031 return ExprResult((Expr*)nullptr); 14032 ExprResult ThisResult = 14033 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14034 if (ThisResult.isInvalid()) 14035 return ExprError(); 14036 14037 // Build a conditional unless this is the final case. 14038 if (Result.get()) { 14039 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14040 ThisResult.get(), Result.get()); 14041 if (Result.isInvalid()) 14042 return ExprError(); 14043 } else { 14044 Result = ThisResult; 14045 } 14046 } 14047 14048 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14049 // bind the OpaqueValueExprs before they're (repeatedly) used. 14050 Expr *SyntacticForm = BinaryOperator::Create( 14051 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14052 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14053 CurFPFeatureOverrides()); 14054 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14055 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14056 } 14057 14058 ExprResult 14059 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14060 SourceLocation RLoc, 14061 Expr *Base, Expr *Idx) { 14062 Expr *Args[2] = { Base, Idx }; 14063 DeclarationName OpName = 14064 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14065 14066 // If either side is type-dependent, create an appropriate dependent 14067 // expression. 14068 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 14069 14070 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14071 // CHECKME: no 'operator' keyword? 14072 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14073 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14074 ExprResult Fn = CreateUnresolvedLookupExpr( 14075 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14076 if (Fn.isInvalid()) 14077 return ExprError(); 14078 // Can't add any actual overloads yet 14079 14080 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 14081 Context.DependentTy, VK_PRValue, RLoc, 14082 CurFPFeatureOverrides()); 14083 } 14084 14085 // Handle placeholders on both operands. 14086 if (checkPlaceholderForOverload(*this, Args[0])) 14087 return ExprError(); 14088 if (checkPlaceholderForOverload(*this, Args[1])) 14089 return ExprError(); 14090 14091 // Build an empty overload set. 14092 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 14093 14094 // Subscript can only be overloaded as a member function. 14095 14096 // Add operator candidates that are member functions. 14097 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14098 14099 // Add builtin operator candidates. 14100 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 14101 14102 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14103 14104 // Perform overload resolution. 14105 OverloadCandidateSet::iterator Best; 14106 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 14107 case OR_Success: { 14108 // We found a built-in operator or an overloaded operator. 14109 FunctionDecl *FnDecl = Best->Function; 14110 14111 if (FnDecl) { 14112 // We matched an overloaded operator. Build a call to that 14113 // operator. 14114 14115 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 14116 14117 // Convert the arguments. 14118 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 14119 ExprResult Arg0 = 14120 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 14121 Best->FoundDecl, Method); 14122 if (Arg0.isInvalid()) 14123 return ExprError(); 14124 Args[0] = Arg0.get(); 14125 14126 // Convert the arguments. 14127 ExprResult InputInit 14128 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14129 Context, 14130 FnDecl->getParamDecl(0)), 14131 SourceLocation(), 14132 Args[1]); 14133 if (InputInit.isInvalid()) 14134 return ExprError(); 14135 14136 Args[1] = InputInit.getAs<Expr>(); 14137 14138 // Build the actual expression node. 14139 DeclarationNameInfo OpLocInfo(OpName, LLoc); 14140 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14141 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14142 Best->FoundDecl, 14143 Base, 14144 HadMultipleCandidates, 14145 OpLocInfo.getLoc(), 14146 OpLocInfo.getInfo()); 14147 if (FnExpr.isInvalid()) 14148 return ExprError(); 14149 14150 // Determine the result type 14151 QualType ResultTy = FnDecl->getReturnType(); 14152 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14153 ResultTy = ResultTy.getNonLValueExprType(Context); 14154 14155 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14156 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 14157 CurFPFeatureOverrides()); 14158 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 14159 return ExprError(); 14160 14161 if (CheckFunctionCall(Method, TheCall, 14162 Method->getType()->castAs<FunctionProtoType>())) 14163 return ExprError(); 14164 14165 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14166 FnDecl); 14167 } else { 14168 // We matched a built-in operator. Convert the arguments, then 14169 // break out so that we will build the appropriate built-in 14170 // operator node. 14171 ExprResult ArgsRes0 = PerformImplicitConversion( 14172 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14173 AA_Passing, CCK_ForBuiltinOverloadedOp); 14174 if (ArgsRes0.isInvalid()) 14175 return ExprError(); 14176 Args[0] = ArgsRes0.get(); 14177 14178 ExprResult ArgsRes1 = PerformImplicitConversion( 14179 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14180 AA_Passing, CCK_ForBuiltinOverloadedOp); 14181 if (ArgsRes1.isInvalid()) 14182 return ExprError(); 14183 Args[1] = ArgsRes1.get(); 14184 14185 break; 14186 } 14187 } 14188 14189 case OR_No_Viable_Function: { 14190 PartialDiagnostic PD = CandidateSet.empty() 14191 ? (PDiag(diag::err_ovl_no_oper) 14192 << Args[0]->getType() << /*subscript*/ 0 14193 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 14194 : (PDiag(diag::err_ovl_no_viable_subscript) 14195 << Args[0]->getType() << Args[0]->getSourceRange() 14196 << Args[1]->getSourceRange()); 14197 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 14198 OCD_AllCandidates, Args, "[]", LLoc); 14199 return ExprError(); 14200 } 14201 14202 case OR_Ambiguous: 14203 CandidateSet.NoteCandidates( 14204 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14205 << "[]" << Args[0]->getType() 14206 << Args[1]->getType() 14207 << Args[0]->getSourceRange() 14208 << Args[1]->getSourceRange()), 14209 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 14210 return ExprError(); 14211 14212 case OR_Deleted: 14213 CandidateSet.NoteCandidates( 14214 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 14215 << "[]" << Args[0]->getSourceRange() 14216 << Args[1]->getSourceRange()), 14217 *this, OCD_AllCandidates, Args, "[]", LLoc); 14218 return ExprError(); 14219 } 14220 14221 // We matched a built-in operator; build it. 14222 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 14223 } 14224 14225 /// BuildCallToMemberFunction - Build a call to a member 14226 /// function. MemExpr is the expression that refers to the member 14227 /// function (and includes the object parameter), Args/NumArgs are the 14228 /// arguments to the function call (not including the object 14229 /// parameter). The caller needs to validate that the member 14230 /// expression refers to a non-static member function or an overloaded 14231 /// member function. 14232 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 14233 SourceLocation LParenLoc, 14234 MultiExprArg Args, 14235 SourceLocation RParenLoc, 14236 Expr *ExecConfig, bool IsExecConfig, 14237 bool AllowRecovery) { 14238 assert(MemExprE->getType() == Context.BoundMemberTy || 14239 MemExprE->getType() == Context.OverloadTy); 14240 14241 // Dig out the member expression. This holds both the object 14242 // argument and the member function we're referring to. 14243 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 14244 14245 // Determine whether this is a call to a pointer-to-member function. 14246 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 14247 assert(op->getType() == Context.BoundMemberTy); 14248 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 14249 14250 QualType fnType = 14251 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 14252 14253 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 14254 QualType resultType = proto->getCallResultType(Context); 14255 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 14256 14257 // Check that the object type isn't more qualified than the 14258 // member function we're calling. 14259 Qualifiers funcQuals = proto->getMethodQuals(); 14260 14261 QualType objectType = op->getLHS()->getType(); 14262 if (op->getOpcode() == BO_PtrMemI) 14263 objectType = objectType->castAs<PointerType>()->getPointeeType(); 14264 Qualifiers objectQuals = objectType.getQualifiers(); 14265 14266 Qualifiers difference = objectQuals - funcQuals; 14267 difference.removeObjCGCAttr(); 14268 difference.removeAddressSpace(); 14269 if (difference) { 14270 std::string qualsString = difference.getAsString(); 14271 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14272 << fnType.getUnqualifiedType() 14273 << qualsString 14274 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14275 } 14276 14277 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14278 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14279 CurFPFeatureOverrides(), proto->getNumParams()); 14280 14281 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14282 call, nullptr)) 14283 return ExprError(); 14284 14285 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14286 return ExprError(); 14287 14288 if (CheckOtherCall(call, proto)) 14289 return ExprError(); 14290 14291 return MaybeBindToTemporary(call); 14292 } 14293 14294 // We only try to build a recovery expr at this level if we can preserve 14295 // the return type, otherwise we return ExprError() and let the caller 14296 // recover. 14297 auto BuildRecoveryExpr = [&](QualType Type) { 14298 if (!AllowRecovery) 14299 return ExprError(); 14300 std::vector<Expr *> SubExprs = {MemExprE}; 14301 llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); }); 14302 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 14303 Type); 14304 }; 14305 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14306 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 14307 RParenLoc, CurFPFeatureOverrides()); 14308 14309 UnbridgedCastsSet UnbridgedCasts; 14310 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14311 return ExprError(); 14312 14313 MemberExpr *MemExpr; 14314 CXXMethodDecl *Method = nullptr; 14315 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14316 NestedNameSpecifier *Qualifier = nullptr; 14317 if (isa<MemberExpr>(NakedMemExpr)) { 14318 MemExpr = cast<MemberExpr>(NakedMemExpr); 14319 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14320 FoundDecl = MemExpr->getFoundDecl(); 14321 Qualifier = MemExpr->getQualifier(); 14322 UnbridgedCasts.restore(); 14323 } else { 14324 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14325 Qualifier = UnresExpr->getQualifier(); 14326 14327 QualType ObjectType = UnresExpr->getBaseType(); 14328 Expr::Classification ObjectClassification 14329 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14330 : UnresExpr->getBase()->Classify(Context); 14331 14332 // Add overload candidates 14333 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14334 OverloadCandidateSet::CSK_Normal); 14335 14336 // FIXME: avoid copy. 14337 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14338 if (UnresExpr->hasExplicitTemplateArgs()) { 14339 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14340 TemplateArgs = &TemplateArgsBuffer; 14341 } 14342 14343 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14344 E = UnresExpr->decls_end(); I != E; ++I) { 14345 14346 NamedDecl *Func = *I; 14347 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14348 if (isa<UsingShadowDecl>(Func)) 14349 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14350 14351 14352 // Microsoft supports direct constructor calls. 14353 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14354 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14355 CandidateSet, 14356 /*SuppressUserConversions*/ false); 14357 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14358 // If explicit template arguments were provided, we can't call a 14359 // non-template member function. 14360 if (TemplateArgs) 14361 continue; 14362 14363 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14364 ObjectClassification, Args, CandidateSet, 14365 /*SuppressUserConversions=*/false); 14366 } else { 14367 AddMethodTemplateCandidate( 14368 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14369 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14370 /*SuppressUserConversions=*/false); 14371 } 14372 } 14373 14374 DeclarationName DeclName = UnresExpr->getMemberName(); 14375 14376 UnbridgedCasts.restore(); 14377 14378 OverloadCandidateSet::iterator Best; 14379 bool Succeeded = false; 14380 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14381 Best)) { 14382 case OR_Success: 14383 Method = cast<CXXMethodDecl>(Best->Function); 14384 FoundDecl = Best->FoundDecl; 14385 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14386 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14387 break; 14388 // If FoundDecl is different from Method (such as if one is a template 14389 // and the other a specialization), make sure DiagnoseUseOfDecl is 14390 // called on both. 14391 // FIXME: This would be more comprehensively addressed by modifying 14392 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14393 // being used. 14394 if (Method != FoundDecl.getDecl() && 14395 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14396 break; 14397 Succeeded = true; 14398 break; 14399 14400 case OR_No_Viable_Function: 14401 CandidateSet.NoteCandidates( 14402 PartialDiagnosticAt( 14403 UnresExpr->getMemberLoc(), 14404 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14405 << DeclName << MemExprE->getSourceRange()), 14406 *this, OCD_AllCandidates, Args); 14407 break; 14408 case OR_Ambiguous: 14409 CandidateSet.NoteCandidates( 14410 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14411 PDiag(diag::err_ovl_ambiguous_member_call) 14412 << DeclName << MemExprE->getSourceRange()), 14413 *this, OCD_AmbiguousCandidates, Args); 14414 break; 14415 case OR_Deleted: 14416 CandidateSet.NoteCandidates( 14417 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14418 PDiag(diag::err_ovl_deleted_member_call) 14419 << DeclName << MemExprE->getSourceRange()), 14420 *this, OCD_AllCandidates, Args); 14421 break; 14422 } 14423 // Overload resolution fails, try to recover. 14424 if (!Succeeded) 14425 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 14426 14427 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14428 14429 // If overload resolution picked a static member, build a 14430 // non-member call based on that function. 14431 if (Method->isStatic()) { 14432 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 14433 ExecConfig, IsExecConfig); 14434 } 14435 14436 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14437 } 14438 14439 QualType ResultType = Method->getReturnType(); 14440 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14441 ResultType = ResultType.getNonLValueExprType(Context); 14442 14443 assert(Method && "Member call to something that isn't a method?"); 14444 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14445 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14446 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14447 CurFPFeatureOverrides(), Proto->getNumParams()); 14448 14449 // Check for a valid return type. 14450 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14451 TheCall, Method)) 14452 return BuildRecoveryExpr(ResultType); 14453 14454 // Convert the object argument (for a non-static member function call). 14455 // We only need to do this if there was actually an overload; otherwise 14456 // it was done at lookup. 14457 if (!Method->isStatic()) { 14458 ExprResult ObjectArg = 14459 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14460 FoundDecl, Method); 14461 if (ObjectArg.isInvalid()) 14462 return ExprError(); 14463 MemExpr->setBase(ObjectArg.get()); 14464 } 14465 14466 // Convert the rest of the arguments 14467 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14468 RParenLoc)) 14469 return BuildRecoveryExpr(ResultType); 14470 14471 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14472 14473 if (CheckFunctionCall(Method, TheCall, Proto)) 14474 return ExprError(); 14475 14476 // In the case the method to call was not selected by the overloading 14477 // resolution process, we still need to handle the enable_if attribute. Do 14478 // that here, so it will not hide previous -- and more relevant -- errors. 14479 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14480 if (const EnableIfAttr *Attr = 14481 CheckEnableIf(Method, LParenLoc, Args, true)) { 14482 Diag(MemE->getMemberLoc(), 14483 diag::err_ovl_no_viable_member_function_in_call) 14484 << Method << Method->getSourceRange(); 14485 Diag(Method->getLocation(), 14486 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14487 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14488 return ExprError(); 14489 } 14490 } 14491 14492 if ((isa<CXXConstructorDecl>(CurContext) || 14493 isa<CXXDestructorDecl>(CurContext)) && 14494 TheCall->getMethodDecl()->isPure()) { 14495 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14496 14497 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14498 MemExpr->performsVirtualDispatch(getLangOpts())) { 14499 Diag(MemExpr->getBeginLoc(), 14500 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14501 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14502 << MD->getParent(); 14503 14504 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14505 if (getLangOpts().AppleKext) 14506 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14507 << MD->getParent() << MD->getDeclName(); 14508 } 14509 } 14510 14511 if (CXXDestructorDecl *DD = 14512 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14513 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14514 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14515 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14516 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14517 MemExpr->getMemberLoc()); 14518 } 14519 14520 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14521 TheCall->getMethodDecl()); 14522 } 14523 14524 /// BuildCallToObjectOfClassType - Build a call to an object of class 14525 /// type (C++ [over.call.object]), which can end up invoking an 14526 /// overloaded function call operator (@c operator()) or performing a 14527 /// user-defined conversion on the object argument. 14528 ExprResult 14529 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14530 SourceLocation LParenLoc, 14531 MultiExprArg Args, 14532 SourceLocation RParenLoc) { 14533 if (checkPlaceholderForOverload(*this, Obj)) 14534 return ExprError(); 14535 ExprResult Object = Obj; 14536 14537 UnbridgedCastsSet UnbridgedCasts; 14538 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14539 return ExprError(); 14540 14541 assert(Object.get()->getType()->isRecordType() && 14542 "Requires object type argument"); 14543 14544 // C++ [over.call.object]p1: 14545 // If the primary-expression E in the function call syntax 14546 // evaluates to a class object of type "cv T", then the set of 14547 // candidate functions includes at least the function call 14548 // operators of T. The function call operators of T are obtained by 14549 // ordinary lookup of the name operator() in the context of 14550 // (E).operator(). 14551 OverloadCandidateSet CandidateSet(LParenLoc, 14552 OverloadCandidateSet::CSK_Operator); 14553 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14554 14555 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14556 diag::err_incomplete_object_call, Object.get())) 14557 return true; 14558 14559 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14560 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14561 LookupQualifiedName(R, Record->getDecl()); 14562 R.suppressDiagnostics(); 14563 14564 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14565 Oper != OperEnd; ++Oper) { 14566 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14567 Object.get()->Classify(Context), Args, CandidateSet, 14568 /*SuppressUserConversion=*/false); 14569 } 14570 14571 // C++ [over.call.object]p2: 14572 // In addition, for each (non-explicit in C++0x) conversion function 14573 // declared in T of the form 14574 // 14575 // operator conversion-type-id () cv-qualifier; 14576 // 14577 // where cv-qualifier is the same cv-qualification as, or a 14578 // greater cv-qualification than, cv, and where conversion-type-id 14579 // denotes the type "pointer to function of (P1,...,Pn) returning 14580 // R", or the type "reference to pointer to function of 14581 // (P1,...,Pn) returning R", or the type "reference to function 14582 // of (P1,...,Pn) returning R", a surrogate call function [...] 14583 // is also considered as a candidate function. Similarly, 14584 // surrogate call functions are added to the set of candidate 14585 // functions for each conversion function declared in an 14586 // accessible base class provided the function is not hidden 14587 // within T by another intervening declaration. 14588 const auto &Conversions = 14589 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14590 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14591 NamedDecl *D = *I; 14592 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14593 if (isa<UsingShadowDecl>(D)) 14594 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14595 14596 // Skip over templated conversion functions; they aren't 14597 // surrogates. 14598 if (isa<FunctionTemplateDecl>(D)) 14599 continue; 14600 14601 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14602 if (!Conv->isExplicit()) { 14603 // Strip the reference type (if any) and then the pointer type (if 14604 // any) to get down to what might be a function type. 14605 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14606 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14607 ConvType = ConvPtrType->getPointeeType(); 14608 14609 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14610 { 14611 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14612 Object.get(), Args, CandidateSet); 14613 } 14614 } 14615 } 14616 14617 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14618 14619 // Perform overload resolution. 14620 OverloadCandidateSet::iterator Best; 14621 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14622 Best)) { 14623 case OR_Success: 14624 // Overload resolution succeeded; we'll build the appropriate call 14625 // below. 14626 break; 14627 14628 case OR_No_Viable_Function: { 14629 PartialDiagnostic PD = 14630 CandidateSet.empty() 14631 ? (PDiag(diag::err_ovl_no_oper) 14632 << Object.get()->getType() << /*call*/ 1 14633 << Object.get()->getSourceRange()) 14634 : (PDiag(diag::err_ovl_no_viable_object_call) 14635 << Object.get()->getType() << Object.get()->getSourceRange()); 14636 CandidateSet.NoteCandidates( 14637 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14638 OCD_AllCandidates, Args); 14639 break; 14640 } 14641 case OR_Ambiguous: 14642 CandidateSet.NoteCandidates( 14643 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14644 PDiag(diag::err_ovl_ambiguous_object_call) 14645 << Object.get()->getType() 14646 << Object.get()->getSourceRange()), 14647 *this, OCD_AmbiguousCandidates, Args); 14648 break; 14649 14650 case OR_Deleted: 14651 CandidateSet.NoteCandidates( 14652 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14653 PDiag(diag::err_ovl_deleted_object_call) 14654 << Object.get()->getType() 14655 << Object.get()->getSourceRange()), 14656 *this, OCD_AllCandidates, Args); 14657 break; 14658 } 14659 14660 if (Best == CandidateSet.end()) 14661 return true; 14662 14663 UnbridgedCasts.restore(); 14664 14665 if (Best->Function == nullptr) { 14666 // Since there is no function declaration, this is one of the 14667 // surrogate candidates. Dig out the conversion function. 14668 CXXConversionDecl *Conv 14669 = cast<CXXConversionDecl>( 14670 Best->Conversions[0].UserDefined.ConversionFunction); 14671 14672 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14673 Best->FoundDecl); 14674 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14675 return ExprError(); 14676 assert(Conv == Best->FoundDecl.getDecl() && 14677 "Found Decl & conversion-to-functionptr should be same, right?!"); 14678 // We selected one of the surrogate functions that converts the 14679 // object parameter to a function pointer. Perform the conversion 14680 // on the object argument, then let BuildCallExpr finish the job. 14681 14682 // Create an implicit member expr to refer to the conversion operator. 14683 // and then call it. 14684 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14685 Conv, HadMultipleCandidates); 14686 if (Call.isInvalid()) 14687 return ExprError(); 14688 // Record usage of conversion in an implicit cast. 14689 Call = ImplicitCastExpr::Create( 14690 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 14691 nullptr, VK_PRValue, CurFPFeatureOverrides()); 14692 14693 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14694 } 14695 14696 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14697 14698 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14699 // that calls this method, using Object for the implicit object 14700 // parameter and passing along the remaining arguments. 14701 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14702 14703 // An error diagnostic has already been printed when parsing the declaration. 14704 if (Method->isInvalidDecl()) 14705 return ExprError(); 14706 14707 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14708 unsigned NumParams = Proto->getNumParams(); 14709 14710 DeclarationNameInfo OpLocInfo( 14711 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14712 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14713 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14714 Obj, HadMultipleCandidates, 14715 OpLocInfo.getLoc(), 14716 OpLocInfo.getInfo()); 14717 if (NewFn.isInvalid()) 14718 return true; 14719 14720 // The number of argument slots to allocate in the call. If we have default 14721 // arguments we need to allocate space for them as well. We additionally 14722 // need one more slot for the object parameter. 14723 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14724 14725 // Build the full argument list for the method call (the implicit object 14726 // parameter is placed at the beginning of the list). 14727 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14728 14729 bool IsError = false; 14730 14731 // Initialize the implicit object parameter. 14732 ExprResult ObjRes = 14733 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14734 Best->FoundDecl, Method); 14735 if (ObjRes.isInvalid()) 14736 IsError = true; 14737 else 14738 Object = ObjRes; 14739 MethodArgs[0] = Object.get(); 14740 14741 // Check the argument types. 14742 for (unsigned i = 0; i != NumParams; i++) { 14743 Expr *Arg; 14744 if (i < Args.size()) { 14745 Arg = Args[i]; 14746 14747 // Pass the argument. 14748 14749 ExprResult InputInit 14750 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14751 Context, 14752 Method->getParamDecl(i)), 14753 SourceLocation(), Arg); 14754 14755 IsError |= InputInit.isInvalid(); 14756 Arg = InputInit.getAs<Expr>(); 14757 } else { 14758 ExprResult DefArg 14759 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14760 if (DefArg.isInvalid()) { 14761 IsError = true; 14762 break; 14763 } 14764 14765 Arg = DefArg.getAs<Expr>(); 14766 } 14767 14768 MethodArgs[i + 1] = Arg; 14769 } 14770 14771 // If this is a variadic call, handle args passed through "...". 14772 if (Proto->isVariadic()) { 14773 // Promote the arguments (C99 6.5.2.2p7). 14774 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14775 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14776 nullptr); 14777 IsError |= Arg.isInvalid(); 14778 MethodArgs[i + 1] = Arg.get(); 14779 } 14780 } 14781 14782 if (IsError) 14783 return true; 14784 14785 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14786 14787 // Once we've built TheCall, all of the expressions are properly owned. 14788 QualType ResultTy = Method->getReturnType(); 14789 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14790 ResultTy = ResultTy.getNonLValueExprType(Context); 14791 14792 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14793 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14794 CurFPFeatureOverrides()); 14795 14796 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14797 return true; 14798 14799 if (CheckFunctionCall(Method, TheCall, Proto)) 14800 return true; 14801 14802 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14803 } 14804 14805 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14806 /// (if one exists), where @c Base is an expression of class type and 14807 /// @c Member is the name of the member we're trying to find. 14808 ExprResult 14809 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14810 bool *NoArrowOperatorFound) { 14811 assert(Base->getType()->isRecordType() && 14812 "left-hand side must have class type"); 14813 14814 if (checkPlaceholderForOverload(*this, Base)) 14815 return ExprError(); 14816 14817 SourceLocation Loc = Base->getExprLoc(); 14818 14819 // C++ [over.ref]p1: 14820 // 14821 // [...] An expression x->m is interpreted as (x.operator->())->m 14822 // for a class object x of type T if T::operator->() exists and if 14823 // the operator is selected as the best match function by the 14824 // overload resolution mechanism (13.3). 14825 DeclarationName OpName = 14826 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14827 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14828 14829 if (RequireCompleteType(Loc, Base->getType(), 14830 diag::err_typecheck_incomplete_tag, Base)) 14831 return ExprError(); 14832 14833 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14834 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14835 R.suppressDiagnostics(); 14836 14837 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14838 Oper != OperEnd; ++Oper) { 14839 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14840 None, CandidateSet, /*SuppressUserConversion=*/false); 14841 } 14842 14843 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14844 14845 // Perform overload resolution. 14846 OverloadCandidateSet::iterator Best; 14847 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14848 case OR_Success: 14849 // Overload resolution succeeded; we'll build the call below. 14850 break; 14851 14852 case OR_No_Viable_Function: { 14853 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14854 if (CandidateSet.empty()) { 14855 QualType BaseType = Base->getType(); 14856 if (NoArrowOperatorFound) { 14857 // Report this specific error to the caller instead of emitting a 14858 // diagnostic, as requested. 14859 *NoArrowOperatorFound = true; 14860 return ExprError(); 14861 } 14862 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14863 << BaseType << Base->getSourceRange(); 14864 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14865 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14866 << FixItHint::CreateReplacement(OpLoc, "."); 14867 } 14868 } else 14869 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14870 << "operator->" << Base->getSourceRange(); 14871 CandidateSet.NoteCandidates(*this, Base, Cands); 14872 return ExprError(); 14873 } 14874 case OR_Ambiguous: 14875 CandidateSet.NoteCandidates( 14876 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14877 << "->" << Base->getType() 14878 << Base->getSourceRange()), 14879 *this, OCD_AmbiguousCandidates, Base); 14880 return ExprError(); 14881 14882 case OR_Deleted: 14883 CandidateSet.NoteCandidates( 14884 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14885 << "->" << Base->getSourceRange()), 14886 *this, OCD_AllCandidates, Base); 14887 return ExprError(); 14888 } 14889 14890 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14891 14892 // Convert the object parameter. 14893 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14894 ExprResult BaseResult = 14895 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14896 Best->FoundDecl, Method); 14897 if (BaseResult.isInvalid()) 14898 return ExprError(); 14899 Base = BaseResult.get(); 14900 14901 // Build the operator call. 14902 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14903 Base, HadMultipleCandidates, OpLoc); 14904 if (FnExpr.isInvalid()) 14905 return ExprError(); 14906 14907 QualType ResultTy = Method->getReturnType(); 14908 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14909 ResultTy = ResultTy.getNonLValueExprType(Context); 14910 CXXOperatorCallExpr *TheCall = 14911 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14912 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14913 14914 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14915 return ExprError(); 14916 14917 if (CheckFunctionCall(Method, TheCall, 14918 Method->getType()->castAs<FunctionProtoType>())) 14919 return ExprError(); 14920 14921 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14922 } 14923 14924 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14925 /// a literal operator described by the provided lookup results. 14926 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14927 DeclarationNameInfo &SuffixInfo, 14928 ArrayRef<Expr*> Args, 14929 SourceLocation LitEndLoc, 14930 TemplateArgumentListInfo *TemplateArgs) { 14931 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14932 14933 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14934 OverloadCandidateSet::CSK_Normal); 14935 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14936 TemplateArgs); 14937 14938 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14939 14940 // Perform overload resolution. This will usually be trivial, but might need 14941 // to perform substitutions for a literal operator template. 14942 OverloadCandidateSet::iterator Best; 14943 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14944 case OR_Success: 14945 case OR_Deleted: 14946 break; 14947 14948 case OR_No_Viable_Function: 14949 CandidateSet.NoteCandidates( 14950 PartialDiagnosticAt(UDSuffixLoc, 14951 PDiag(diag::err_ovl_no_viable_function_in_call) 14952 << R.getLookupName()), 14953 *this, OCD_AllCandidates, Args); 14954 return ExprError(); 14955 14956 case OR_Ambiguous: 14957 CandidateSet.NoteCandidates( 14958 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14959 << R.getLookupName()), 14960 *this, OCD_AmbiguousCandidates, Args); 14961 return ExprError(); 14962 } 14963 14964 FunctionDecl *FD = Best->Function; 14965 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14966 nullptr, HadMultipleCandidates, 14967 SuffixInfo.getLoc(), 14968 SuffixInfo.getInfo()); 14969 if (Fn.isInvalid()) 14970 return true; 14971 14972 // Check the argument types. This should almost always be a no-op, except 14973 // that array-to-pointer decay is applied to string literals. 14974 Expr *ConvArgs[2]; 14975 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14976 ExprResult InputInit = PerformCopyInitialization( 14977 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14978 SourceLocation(), Args[ArgIdx]); 14979 if (InputInit.isInvalid()) 14980 return true; 14981 ConvArgs[ArgIdx] = InputInit.get(); 14982 } 14983 14984 QualType ResultTy = FD->getReturnType(); 14985 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14986 ResultTy = ResultTy.getNonLValueExprType(Context); 14987 14988 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14989 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14990 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14991 14992 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14993 return ExprError(); 14994 14995 if (CheckFunctionCall(FD, UDL, nullptr)) 14996 return ExprError(); 14997 14998 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14999 } 15000 15001 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 15002 /// given LookupResult is non-empty, it is assumed to describe a member which 15003 /// will be invoked. Otherwise, the function will be found via argument 15004 /// dependent lookup. 15005 /// CallExpr is set to a valid expression and FRS_Success returned on success, 15006 /// otherwise CallExpr is set to ExprError() and some non-success value 15007 /// is returned. 15008 Sema::ForRangeStatus 15009 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 15010 SourceLocation RangeLoc, 15011 const DeclarationNameInfo &NameInfo, 15012 LookupResult &MemberLookup, 15013 OverloadCandidateSet *CandidateSet, 15014 Expr *Range, ExprResult *CallExpr) { 15015 Scope *S = nullptr; 15016 15017 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 15018 if (!MemberLookup.empty()) { 15019 ExprResult MemberRef = 15020 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 15021 /*IsPtr=*/false, CXXScopeSpec(), 15022 /*TemplateKWLoc=*/SourceLocation(), 15023 /*FirstQualifierInScope=*/nullptr, 15024 MemberLookup, 15025 /*TemplateArgs=*/nullptr, S); 15026 if (MemberRef.isInvalid()) { 15027 *CallExpr = ExprError(); 15028 return FRS_DiagnosticIssued; 15029 } 15030 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 15031 if (CallExpr->isInvalid()) { 15032 *CallExpr = ExprError(); 15033 return FRS_DiagnosticIssued; 15034 } 15035 } else { 15036 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 15037 NestedNameSpecifierLoc(), 15038 NameInfo, UnresolvedSet<0>()); 15039 if (FnR.isInvalid()) 15040 return FRS_DiagnosticIssued; 15041 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 15042 15043 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 15044 CandidateSet, CallExpr); 15045 if (CandidateSet->empty() || CandidateSetError) { 15046 *CallExpr = ExprError(); 15047 return FRS_NoViableFunction; 15048 } 15049 OverloadCandidateSet::iterator Best; 15050 OverloadingResult OverloadResult = 15051 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 15052 15053 if (OverloadResult == OR_No_Viable_Function) { 15054 *CallExpr = ExprError(); 15055 return FRS_NoViableFunction; 15056 } 15057 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 15058 Loc, nullptr, CandidateSet, &Best, 15059 OverloadResult, 15060 /*AllowTypoCorrection=*/false); 15061 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 15062 *CallExpr = ExprError(); 15063 return FRS_DiagnosticIssued; 15064 } 15065 } 15066 return FRS_Success; 15067 } 15068 15069 15070 /// FixOverloadedFunctionReference - E is an expression that refers to 15071 /// a C++ overloaded function (possibly with some parentheses and 15072 /// perhaps a '&' around it). We have resolved the overloaded function 15073 /// to the function declaration Fn, so patch up the expression E to 15074 /// refer (possibly indirectly) to Fn. Returns the new expr. 15075 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 15076 FunctionDecl *Fn) { 15077 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 15078 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 15079 Found, Fn); 15080 if (SubExpr == PE->getSubExpr()) 15081 return PE; 15082 15083 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 15084 } 15085 15086 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 15087 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 15088 Found, Fn); 15089 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 15090 SubExpr->getType()) && 15091 "Implicit cast type cannot be determined from overload"); 15092 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 15093 if (SubExpr == ICE->getSubExpr()) 15094 return ICE; 15095 15096 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 15097 SubExpr, nullptr, ICE->getValueKind(), 15098 CurFPFeatureOverrides()); 15099 } 15100 15101 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 15102 if (!GSE->isResultDependent()) { 15103 Expr *SubExpr = 15104 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 15105 if (SubExpr == GSE->getResultExpr()) 15106 return GSE; 15107 15108 // Replace the resulting type information before rebuilding the generic 15109 // selection expression. 15110 ArrayRef<Expr *> A = GSE->getAssocExprs(); 15111 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 15112 unsigned ResultIdx = GSE->getResultIndex(); 15113 AssocExprs[ResultIdx] = SubExpr; 15114 15115 return GenericSelectionExpr::Create( 15116 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 15117 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 15118 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 15119 ResultIdx); 15120 } 15121 // Rather than fall through to the unreachable, return the original generic 15122 // selection expression. 15123 return GSE; 15124 } 15125 15126 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 15127 assert(UnOp->getOpcode() == UO_AddrOf && 15128 "Can only take the address of an overloaded function"); 15129 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 15130 if (Method->isStatic()) { 15131 // Do nothing: static member functions aren't any different 15132 // from non-member functions. 15133 } else { 15134 // Fix the subexpression, which really has to be an 15135 // UnresolvedLookupExpr holding an overloaded member function 15136 // or template. 15137 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15138 Found, Fn); 15139 if (SubExpr == UnOp->getSubExpr()) 15140 return UnOp; 15141 15142 assert(isa<DeclRefExpr>(SubExpr) 15143 && "fixed to something other than a decl ref"); 15144 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 15145 && "fixed to a member ref with no nested name qualifier"); 15146 15147 // We have taken the address of a pointer to member 15148 // function. Perform the computation here so that we get the 15149 // appropriate pointer to member type. 15150 QualType ClassType 15151 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 15152 QualType MemPtrType 15153 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 15154 // Under the MS ABI, lock down the inheritance model now. 15155 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 15156 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 15157 15158 return UnaryOperator::Create( 15159 Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary, 15160 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 15161 } 15162 } 15163 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 15164 Found, Fn); 15165 if (SubExpr == UnOp->getSubExpr()) 15166 return UnOp; 15167 15168 return UnaryOperator::Create( 15169 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()), 15170 VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false, 15171 CurFPFeatureOverrides()); 15172 } 15173 15174 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15175 // FIXME: avoid copy. 15176 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15177 if (ULE->hasExplicitTemplateArgs()) { 15178 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 15179 TemplateArgs = &TemplateArgsBuffer; 15180 } 15181 15182 DeclRefExpr *DRE = 15183 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 15184 ULE->getQualifierLoc(), Found.getDecl(), 15185 ULE->getTemplateKeywordLoc(), TemplateArgs); 15186 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 15187 return DRE; 15188 } 15189 15190 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 15191 // FIXME: avoid copy. 15192 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15193 if (MemExpr->hasExplicitTemplateArgs()) { 15194 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15195 TemplateArgs = &TemplateArgsBuffer; 15196 } 15197 15198 Expr *Base; 15199 15200 // If we're filling in a static method where we used to have an 15201 // implicit member access, rewrite to a simple decl ref. 15202 if (MemExpr->isImplicitAccess()) { 15203 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15204 DeclRefExpr *DRE = BuildDeclRefExpr( 15205 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 15206 MemExpr->getQualifierLoc(), Found.getDecl(), 15207 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 15208 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 15209 return DRE; 15210 } else { 15211 SourceLocation Loc = MemExpr->getMemberLoc(); 15212 if (MemExpr->getQualifier()) 15213 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 15214 Base = 15215 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 15216 } 15217 } else 15218 Base = MemExpr->getBase(); 15219 15220 ExprValueKind valueKind; 15221 QualType type; 15222 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 15223 valueKind = VK_LValue; 15224 type = Fn->getType(); 15225 } else { 15226 valueKind = VK_PRValue; 15227 type = Context.BoundMemberTy; 15228 } 15229 15230 return BuildMemberExpr( 15231 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 15232 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 15233 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 15234 type, valueKind, OK_Ordinary, TemplateArgs); 15235 } 15236 15237 llvm_unreachable("Invalid reference to overloaded function"); 15238 } 15239 15240 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 15241 DeclAccessPair Found, 15242 FunctionDecl *Fn) { 15243 return FixOverloadedFunctionReference(E.get(), Found, Fn); 15244 } 15245 15246 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 15247 FunctionDecl *Function) { 15248 if (!PartialOverloading || !Function) 15249 return true; 15250 if (Function->isVariadic()) 15251 return false; 15252 if (const auto *Proto = 15253 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 15254 if (Proto->isTemplateVariadic()) 15255 return false; 15256 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 15257 if (const auto *Proto = 15258 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 15259 if (Proto->isTemplateVariadic()) 15260 return false; 15261 return true; 15262 } 15263