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/ASTLambda.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/DependenceFlags.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/AST/Type.h" 23 #include "clang/AST/TypeOrdering.h" 24 #include "clang/Basic/Diagnostic.h" 25 #include "clang/Basic/DiagnosticOptions.h" 26 #include "clang/Basic/OperatorKinds.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/EnterExpressionEvaluationContext.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/Overload.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "clang/Sema/Template.h" 36 #include "clang/Sema/TemplateDeduction.h" 37 #include "llvm/ADT/DenseSet.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/SmallString.h" 41 #include "llvm/ADT/SmallVector.h" 42 #include "llvm/Support/Casting.h" 43 #include <algorithm> 44 #include <cstddef> 45 #include <cstdlib> 46 #include <optional> 47 48 using namespace clang; 49 using namespace sema; 50 51 using AllowedExplicit = Sema::AllowedExplicit; 52 53 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 54 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 55 return P->hasAttr<PassObjectSizeAttr>(); 56 }); 57 } 58 59 /// A convenience routine for creating a decayed reference to a function. 60 static ExprResult CreateFunctionRefExpr( 61 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, 62 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(), 63 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) { 64 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 65 return ExprError(); 66 // If FoundDecl is different from Fn (such as if one is a template 67 // and the other a specialization), make sure DiagnoseUseOfDecl is 68 // called on both. 69 // FIXME: This would be more comprehensively addressed by modifying 70 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 71 // being used. 72 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 73 return ExprError(); 74 DeclRefExpr *DRE = new (S.Context) 75 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 76 if (HadMultipleCandidates) 77 DRE->setHadMultipleCandidates(true); 78 79 S.MarkDeclRefReferenced(DRE, Base); 80 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 81 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 82 S.ResolveExceptionSpec(Loc, FPT); 83 DRE->setType(Fn->getType()); 84 } 85 } 86 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 87 CK_FunctionToPointerDecay); 88 } 89 90 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle, 94 bool AllowObjCWritebackConversion); 95 96 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 97 QualType &ToType, 98 bool InOverloadResolution, 99 StandardConversionSequence &SCS, 100 bool CStyle); 101 static OverloadingResult 102 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 103 UserDefinedConversionSequence& User, 104 OverloadCandidateSet& Conversions, 105 AllowedExplicit AllowExplicit, 106 bool AllowObjCConversionOnExplicit); 107 108 static ImplicitConversionSequence::CompareKind 109 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 110 const StandardConversionSequence& SCS1, 111 const StandardConversionSequence& SCS2); 112 113 static ImplicitConversionSequence::CompareKind 114 CompareQualificationConversions(Sema &S, 115 const StandardConversionSequence& SCS1, 116 const StandardConversionSequence& SCS2); 117 118 static ImplicitConversionSequence::CompareKind 119 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 120 const StandardConversionSequence& SCS1, 121 const StandardConversionSequence& SCS2); 122 123 /// GetConversionRank - Retrieve the implicit conversion rank 124 /// corresponding to the given implicit conversion kind. 125 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 126 static const ImplicitConversionRank 127 Rank[] = { 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Promotion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Conversion, 148 ICR_Conversion, 149 ICR_OCL_Scalar_Widening, 150 ICR_Complex_Real_Conversion, 151 ICR_Conversion, 152 ICR_Conversion, 153 ICR_Writeback_Conversion, 154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 155 // it was omitted by the patch that added 156 // ICK_Zero_Event_Conversion 157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right -- 158 // it was omitted by the patch that added 159 // ICK_Zero_Queue_Conversion 160 ICR_C_Conversion, 161 ICR_C_Conversion_Extension, 162 ICR_Conversion, 163 }; 164 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds); 165 return Rank[(int)Kind]; 166 } 167 168 /// GetImplicitConversionName - Return the name of this kind of 169 /// implicit conversion. 170 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 171 static const char* const Name[] = { 172 "No conversion", 173 "Lvalue-to-rvalue", 174 "Array-to-pointer", 175 "Function-to-pointer", 176 "Function pointer conversion", 177 "Qualification", 178 "Integral promotion", 179 "Floating point promotion", 180 "Complex promotion", 181 "Integral conversion", 182 "Floating conversion", 183 "Complex conversion", 184 "Floating-integral conversion", 185 "Pointer conversion", 186 "Pointer-to-member conversion", 187 "Boolean conversion", 188 "Compatible-types conversion", 189 "Derived-to-base conversion", 190 "Vector conversion", 191 "SVE Vector conversion", 192 "RVV Vector conversion", 193 "Vector splat", 194 "Complex-real conversion", 195 "Block Pointer conversion", 196 "Transparent Union Conversion", 197 "Writeback conversion", 198 "OpenCL Zero Event Conversion", 199 "OpenCL Zero Queue Conversion", 200 "C specific type conversion", 201 "Incompatible pointer conversion", 202 "Fixed point conversion", 203 }; 204 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds); 205 return Name[Kind]; 206 } 207 208 /// StandardConversionSequence - Set the standard conversion 209 /// sequence to the identity conversion. 210 void StandardConversionSequence::setAsIdentityConversion() { 211 First = ICK_Identity; 212 Second = ICK_Identity; 213 Third = ICK_Identity; 214 DeprecatedStringLiteralToCharPtr = false; 215 QualificationIncludesObjCLifetime = false; 216 ReferenceBinding = false; 217 DirectBinding = false; 218 IsLvalueReference = true; 219 BindsToFunctionLvalue = false; 220 BindsToRvalue = false; 221 BindsImplicitObjectArgumentWithoutRefQualifier = false; 222 ObjCLifetimeConversionBinding = false; 223 CopyConstructor = nullptr; 224 } 225 226 /// getRank - Retrieve the rank of this standard conversion sequence 227 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 228 /// implicit conversions. 229 ImplicitConversionRank StandardConversionSequence::getRank() const { 230 ImplicitConversionRank Rank = ICR_Exact_Match; 231 if (GetConversionRank(First) > Rank) 232 Rank = GetConversionRank(First); 233 if (GetConversionRank(Second) > Rank) 234 Rank = GetConversionRank(Second); 235 if (GetConversionRank(Third) > Rank) 236 Rank = GetConversionRank(Third); 237 return Rank; 238 } 239 240 /// isPointerConversionToBool - Determines whether this conversion is 241 /// a conversion of a pointer or pointer-to-member to bool. This is 242 /// used as part of the ranking of standard conversion sequences 243 /// (C++ 13.3.3.2p4). 244 bool StandardConversionSequence::isPointerConversionToBool() const { 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer or function-to-pointer implicit conversions, so 247 // check for their presence as well as checking whether FromType is 248 // a pointer. 249 if (getToType(1)->isBooleanType() && 250 (getFromType()->isPointerType() || 251 getFromType()->isMemberPointerType() || 252 getFromType()->isObjCObjectPointerType() || 253 getFromType()->isBlockPointerType() || 254 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 255 return true; 256 257 return false; 258 } 259 260 /// isPointerConversionToVoidPointer - Determines whether this 261 /// conversion is a conversion of a pointer to a void pointer. This is 262 /// used as part of the ranking of standard conversion sequences (C++ 263 /// 13.3.3.2p4). 264 bool 265 StandardConversionSequence:: 266 isPointerConversionToVoidPointer(ASTContext& Context) const { 267 QualType FromType = getFromType(); 268 QualType ToType = getToType(1); 269 270 // Note that FromType has not necessarily been transformed by the 271 // array-to-pointer implicit conversion, so check for its presence 272 // and redo the conversion to get a pointer. 273 if (First == ICK_Array_To_Pointer) 274 FromType = Context.getArrayDecayedType(FromType); 275 276 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 277 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 278 return ToPtrType->getPointeeType()->isVoidType(); 279 280 return false; 281 } 282 283 /// Skip any implicit casts which could be either part of a narrowing conversion 284 /// or after one in an implicit conversion. 285 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 286 const Expr *Converted) { 287 // We can have cleanups wrapping the converted expression; these need to be 288 // preserved so that destructors run if necessary. 289 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 290 Expr *Inner = 291 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 292 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 293 EWC->getObjects()); 294 } 295 296 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 297 switch (ICE->getCastKind()) { 298 case CK_NoOp: 299 case CK_IntegralCast: 300 case CK_IntegralToBoolean: 301 case CK_IntegralToFloating: 302 case CK_BooleanToSignedIntegral: 303 case CK_FloatingToIntegral: 304 case CK_FloatingToBoolean: 305 case CK_FloatingCast: 306 Converted = ICE->getSubExpr(); 307 continue; 308 309 default: 310 return Converted; 311 } 312 } 313 314 return Converted; 315 } 316 317 /// Check if this standard conversion sequence represents a narrowing 318 /// conversion, according to C++11 [dcl.init.list]p7. 319 /// 320 /// \param Ctx The AST context. 321 /// \param Converted The result of applying this standard conversion sequence. 322 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 323 /// value of the expression prior to the narrowing conversion. 324 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 325 /// type of the expression prior to the narrowing conversion. 326 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 327 /// from floating point types to integral types should be ignored. 328 NarrowingKind StandardConversionSequence::getNarrowingKind( 329 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 330 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 331 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 332 333 // C++11 [dcl.init.list]p7: 334 // A narrowing conversion is an implicit conversion ... 335 QualType FromType = getToType(0); 336 QualType ToType = getToType(1); 337 338 // A conversion to an enumeration type is narrowing if the conversion to 339 // the underlying type is narrowing. This only arises for expressions of 340 // the form 'Enum{init}'. 341 if (auto *ET = ToType->getAs<EnumType>()) 342 ToType = ET->getDecl()->getIntegerType(); 343 344 switch (Second) { 345 // 'bool' is an integral type; dispatch to the right place to handle it. 346 case ICK_Boolean_Conversion: 347 if (FromType->isRealFloatingType()) 348 goto FloatingIntegralConversion; 349 if (FromType->isIntegralOrUnscopedEnumerationType()) 350 goto IntegralConversion; 351 // -- from a pointer type or pointer-to-member type to bool, or 352 return NK_Type_Narrowing; 353 354 // -- from a floating-point type to an integer type, or 355 // 356 // -- from an integer type or unscoped enumeration type to a floating-point 357 // type, except where the source is a constant expression and the actual 358 // value after conversion will fit into the target type and will produce 359 // the original value when converted back to the original type, or 360 case ICK_Floating_Integral: 361 FloatingIntegralConversion: 362 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 363 return NK_Type_Narrowing; 364 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 365 ToType->isRealFloatingType()) { 366 if (IgnoreFloatToIntegralConversion) 367 return NK_Not_Narrowing; 368 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 369 assert(Initializer && "Unknown conversion expression"); 370 371 // If it's value-dependent, we can't tell whether it's narrowing. 372 if (Initializer->isValueDependent()) 373 return NK_Dependent_Narrowing; 374 375 if (std::optional<llvm::APSInt> IntConstantValue = 376 Initializer->getIntegerConstantExpr(Ctx)) { 377 // Convert the integer to the floating type. 378 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 379 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 380 llvm::APFloat::rmNearestTiesToEven); 381 // And back. 382 llvm::APSInt ConvertedValue = *IntConstantValue; 383 bool ignored; 384 Result.convertToInteger(ConvertedValue, 385 llvm::APFloat::rmTowardZero, &ignored); 386 // If the resulting value is different, this was a narrowing conversion. 387 if (*IntConstantValue != ConvertedValue) { 388 ConstantValue = APValue(*IntConstantValue); 389 ConstantType = Initializer->getType(); 390 return NK_Constant_Narrowing; 391 } 392 } else { 393 // Variables are always narrowings. 394 return NK_Variable_Narrowing; 395 } 396 } 397 return NK_Not_Narrowing; 398 399 // -- from long double to double or float, or from double to float, except 400 // where the source is a constant expression and the actual value after 401 // conversion is within the range of values that can be represented (even 402 // if it cannot be represented exactly), or 403 case ICK_Floating_Conversion: 404 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 405 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 406 // FromType is larger than ToType. 407 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 408 409 // If it's value-dependent, we can't tell whether it's narrowing. 410 if (Initializer->isValueDependent()) 411 return NK_Dependent_Narrowing; 412 413 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 414 // Constant! 415 assert(ConstantValue.isFloat()); 416 llvm::APFloat FloatVal = ConstantValue.getFloat(); 417 // Convert the source value into the target type. 418 bool ignored; 419 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 420 Ctx.getFloatTypeSemantics(ToType), 421 llvm::APFloat::rmNearestTiesToEven, &ignored); 422 // If there was no overflow, the source value is within the range of 423 // values that can be represented. 424 if (ConvertStatus & llvm::APFloat::opOverflow) { 425 ConstantType = Initializer->getType(); 426 return NK_Constant_Narrowing; 427 } 428 } else { 429 return NK_Variable_Narrowing; 430 } 431 } 432 return NK_Not_Narrowing; 433 434 // -- from an integer type or unscoped enumeration type to an integer type 435 // that cannot represent all the values of the original type, except where 436 // the source is a constant expression and the actual value after 437 // conversion will fit into the target type and will produce the original 438 // value when converted back to the original type. 439 case ICK_Integral_Conversion: 440 IntegralConversion: { 441 assert(FromType->isIntegralOrUnscopedEnumerationType()); 442 assert(ToType->isIntegralOrUnscopedEnumerationType()); 443 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 444 const unsigned FromWidth = Ctx.getIntWidth(FromType); 445 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 446 const unsigned ToWidth = Ctx.getIntWidth(ToType); 447 448 if (FromWidth > ToWidth || 449 (FromWidth == ToWidth && FromSigned != ToSigned) || 450 (FromSigned && !ToSigned)) { 451 // Not all values of FromType can be represented in ToType. 452 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 453 454 // If it's value-dependent, we can't tell whether it's narrowing. 455 if (Initializer->isValueDependent()) 456 return NK_Dependent_Narrowing; 457 458 std::optional<llvm::APSInt> OptInitializerValue; 459 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 460 // Such conversions on variables are always narrowing. 461 return NK_Variable_Narrowing; 462 } 463 llvm::APSInt &InitializerValue = *OptInitializerValue; 464 bool Narrowing = false; 465 if (FromWidth < ToWidth) { 466 // Negative -> unsigned is narrowing. Otherwise, more bits is never 467 // narrowing. 468 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 469 Narrowing = true; 470 } else { 471 // Add a bit to the InitializerValue so we don't have to worry about 472 // signed vs. unsigned comparisons. 473 InitializerValue = InitializerValue.extend( 474 InitializerValue.getBitWidth() + 1); 475 // Convert the initializer to and from the target width and signed-ness. 476 llvm::APSInt ConvertedValue = InitializerValue; 477 ConvertedValue = ConvertedValue.trunc(ToWidth); 478 ConvertedValue.setIsSigned(ToSigned); 479 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 480 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 481 // If the result is different, this was a narrowing conversion. 482 if (ConvertedValue != InitializerValue) 483 Narrowing = true; 484 } 485 if (Narrowing) { 486 ConstantType = Initializer->getType(); 487 ConstantValue = APValue(InitializerValue); 488 return NK_Constant_Narrowing; 489 } 490 } 491 return NK_Not_Narrowing; 492 } 493 494 default: 495 // Other kinds of conversions are not narrowings. 496 return NK_Not_Narrowing; 497 } 498 } 499 500 /// dump - Print this standard conversion sequence to standard 501 /// error. Useful for debugging overloading issues. 502 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 503 raw_ostream &OS = llvm::errs(); 504 bool PrintedSomething = false; 505 if (First != ICK_Identity) { 506 OS << GetImplicitConversionName(First); 507 PrintedSomething = true; 508 } 509 510 if (Second != ICK_Identity) { 511 if (PrintedSomething) { 512 OS << " -> "; 513 } 514 OS << GetImplicitConversionName(Second); 515 516 if (CopyConstructor) { 517 OS << " (by copy constructor)"; 518 } else if (DirectBinding) { 519 OS << " (direct reference binding)"; 520 } else if (ReferenceBinding) { 521 OS << " (reference binding)"; 522 } 523 PrintedSomething = true; 524 } 525 526 if (Third != ICK_Identity) { 527 if (PrintedSomething) { 528 OS << " -> "; 529 } 530 OS << GetImplicitConversionName(Third); 531 PrintedSomething = true; 532 } 533 534 if (!PrintedSomething) { 535 OS << "No conversions required"; 536 } 537 } 538 539 /// dump - Print this user-defined conversion sequence to standard 540 /// error. Useful for debugging overloading issues. 541 void UserDefinedConversionSequence::dump() const { 542 raw_ostream &OS = llvm::errs(); 543 if (Before.First || Before.Second || Before.Third) { 544 Before.dump(); 545 OS << " -> "; 546 } 547 if (ConversionFunction) 548 OS << '\'' << *ConversionFunction << '\''; 549 else 550 OS << "aggregate initialization"; 551 if (After.First || After.Second || After.Third) { 552 OS << " -> "; 553 After.dump(); 554 } 555 } 556 557 /// dump - Print this implicit conversion sequence to standard 558 /// error. Useful for debugging overloading issues. 559 void ImplicitConversionSequence::dump() const { 560 raw_ostream &OS = llvm::errs(); 561 if (hasInitializerListContainerType()) 562 OS << "Worst list element conversion: "; 563 switch (ConversionKind) { 564 case StandardConversion: 565 OS << "Standard conversion: "; 566 Standard.dump(); 567 break; 568 case UserDefinedConversion: 569 OS << "User-defined conversion: "; 570 UserDefined.dump(); 571 break; 572 case EllipsisConversion: 573 OS << "Ellipsis conversion"; 574 break; 575 case AmbiguousConversion: 576 OS << "Ambiguous conversion"; 577 break; 578 case BadConversion: 579 OS << "Bad conversion"; 580 break; 581 } 582 583 OS << "\n"; 584 } 585 586 void AmbiguousConversionSequence::construct() { 587 new (&conversions()) ConversionSet(); 588 } 589 590 void AmbiguousConversionSequence::destruct() { 591 conversions().~ConversionSet(); 592 } 593 594 void 595 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 596 FromTypePtr = O.FromTypePtr; 597 ToTypePtr = O.ToTypePtr; 598 new (&conversions()) ConversionSet(O.conversions()); 599 } 600 601 namespace { 602 // Structure used by DeductionFailureInfo to store 603 // template argument information. 604 struct DFIArguments { 605 TemplateArgument FirstArg; 606 TemplateArgument SecondArg; 607 }; 608 // Structure used by DeductionFailureInfo to store 609 // template parameter and template argument information. 610 struct DFIParamWithArguments : DFIArguments { 611 TemplateParameter Param; 612 }; 613 // Structure used by DeductionFailureInfo to store template argument 614 // information and the index of the problematic call argument. 615 struct DFIDeducedMismatchArgs : DFIArguments { 616 TemplateArgumentList *TemplateArgs; 617 unsigned CallArgIndex; 618 }; 619 // Structure used by DeductionFailureInfo to store information about 620 // unsatisfied constraints. 621 struct CNSInfo { 622 TemplateArgumentList *TemplateArgs; 623 ConstraintSatisfaction Satisfaction; 624 }; 625 } 626 627 /// Convert from Sema's representation of template deduction information 628 /// to the form used in overload-candidate information. 629 DeductionFailureInfo 630 clang::MakeDeductionFailureInfo(ASTContext &Context, 631 Sema::TemplateDeductionResult TDK, 632 TemplateDeductionInfo &Info) { 633 DeductionFailureInfo Result; 634 Result.Result = static_cast<unsigned>(TDK); 635 Result.HasDiagnostic = false; 636 switch (TDK) { 637 case Sema::TDK_Invalid: 638 case Sema::TDK_InstantiationDepth: 639 case Sema::TDK_TooManyArguments: 640 case Sema::TDK_TooFewArguments: 641 case Sema::TDK_MiscellaneousDeductionFailure: 642 case Sema::TDK_CUDATargetMismatch: 643 Result.Data = nullptr; 644 break; 645 646 case Sema::TDK_Incomplete: 647 case Sema::TDK_InvalidExplicitArguments: 648 Result.Data = Info.Param.getOpaqueValue(); 649 break; 650 651 case Sema::TDK_DeducedMismatch: 652 case Sema::TDK_DeducedMismatchNested: { 653 // FIXME: Should allocate from normal heap so that we can free this later. 654 auto *Saved = new (Context) DFIDeducedMismatchArgs; 655 Saved->FirstArg = Info.FirstArg; 656 Saved->SecondArg = Info.SecondArg; 657 Saved->TemplateArgs = Info.takeSugared(); 658 Saved->CallArgIndex = Info.CallArgIndex; 659 Result.Data = Saved; 660 break; 661 } 662 663 case Sema::TDK_NonDeducedMismatch: { 664 // FIXME: Should allocate from normal heap so that we can free this later. 665 DFIArguments *Saved = new (Context) DFIArguments; 666 Saved->FirstArg = Info.FirstArg; 667 Saved->SecondArg = Info.SecondArg; 668 Result.Data = Saved; 669 break; 670 } 671 672 case Sema::TDK_IncompletePack: 673 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 674 case Sema::TDK_Inconsistent: 675 case Sema::TDK_Underqualified: { 676 // FIXME: Should allocate from normal heap so that we can free this later. 677 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 678 Saved->Param = Info.Param; 679 Saved->FirstArg = Info.FirstArg; 680 Saved->SecondArg = Info.SecondArg; 681 Result.Data = Saved; 682 break; 683 } 684 685 case Sema::TDK_SubstitutionFailure: 686 Result.Data = Info.takeSugared(); 687 if (Info.hasSFINAEDiagnostic()) { 688 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 689 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 690 Info.takeSFINAEDiagnostic(*Diag); 691 Result.HasDiagnostic = true; 692 } 693 break; 694 695 case Sema::TDK_ConstraintsNotSatisfied: { 696 CNSInfo *Saved = new (Context) CNSInfo; 697 Saved->TemplateArgs = Info.takeSugared(); 698 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 699 Result.Data = Saved; 700 break; 701 } 702 703 case Sema::TDK_Success: 704 case Sema::TDK_NonDependentConversionFailure: 705 case Sema::TDK_AlreadyDiagnosed: 706 llvm_unreachable("not a deduction failure"); 707 } 708 709 return Result; 710 } 711 712 void DeductionFailureInfo::Destroy() { 713 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 714 case Sema::TDK_Success: 715 case Sema::TDK_Invalid: 716 case Sema::TDK_InstantiationDepth: 717 case Sema::TDK_Incomplete: 718 case Sema::TDK_TooManyArguments: 719 case Sema::TDK_TooFewArguments: 720 case Sema::TDK_InvalidExplicitArguments: 721 case Sema::TDK_CUDATargetMismatch: 722 case Sema::TDK_NonDependentConversionFailure: 723 break; 724 725 case Sema::TDK_IncompletePack: 726 case Sema::TDK_Inconsistent: 727 case Sema::TDK_Underqualified: 728 case Sema::TDK_DeducedMismatch: 729 case Sema::TDK_DeducedMismatchNested: 730 case Sema::TDK_NonDeducedMismatch: 731 // FIXME: Destroy the data? 732 Data = nullptr; 733 break; 734 735 case Sema::TDK_SubstitutionFailure: 736 // FIXME: Destroy the template argument list? 737 Data = nullptr; 738 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 739 Diag->~PartialDiagnosticAt(); 740 HasDiagnostic = false; 741 } 742 break; 743 744 case Sema::TDK_ConstraintsNotSatisfied: 745 // FIXME: Destroy the template argument list? 746 Data = nullptr; 747 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 748 Diag->~PartialDiagnosticAt(); 749 HasDiagnostic = false; 750 } 751 break; 752 753 // Unhandled 754 case Sema::TDK_MiscellaneousDeductionFailure: 755 case Sema::TDK_AlreadyDiagnosed: 756 break; 757 } 758 } 759 760 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 761 if (HasDiagnostic) 762 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 763 return nullptr; 764 } 765 766 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 767 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 768 case Sema::TDK_Success: 769 case Sema::TDK_Invalid: 770 case Sema::TDK_InstantiationDepth: 771 case Sema::TDK_TooManyArguments: 772 case Sema::TDK_TooFewArguments: 773 case Sema::TDK_SubstitutionFailure: 774 case Sema::TDK_DeducedMismatch: 775 case Sema::TDK_DeducedMismatchNested: 776 case Sema::TDK_NonDeducedMismatch: 777 case Sema::TDK_CUDATargetMismatch: 778 case Sema::TDK_NonDependentConversionFailure: 779 case Sema::TDK_ConstraintsNotSatisfied: 780 return TemplateParameter(); 781 782 case Sema::TDK_Incomplete: 783 case Sema::TDK_InvalidExplicitArguments: 784 return TemplateParameter::getFromOpaqueValue(Data); 785 786 case Sema::TDK_IncompletePack: 787 case Sema::TDK_Inconsistent: 788 case Sema::TDK_Underqualified: 789 return static_cast<DFIParamWithArguments*>(Data)->Param; 790 791 // Unhandled 792 case Sema::TDK_MiscellaneousDeductionFailure: 793 case Sema::TDK_AlreadyDiagnosed: 794 break; 795 } 796 797 return TemplateParameter(); 798 } 799 800 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 801 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 802 case Sema::TDK_Success: 803 case Sema::TDK_Invalid: 804 case Sema::TDK_InstantiationDepth: 805 case Sema::TDK_TooManyArguments: 806 case Sema::TDK_TooFewArguments: 807 case Sema::TDK_Incomplete: 808 case Sema::TDK_IncompletePack: 809 case Sema::TDK_InvalidExplicitArguments: 810 case Sema::TDK_Inconsistent: 811 case Sema::TDK_Underqualified: 812 case Sema::TDK_NonDeducedMismatch: 813 case Sema::TDK_CUDATargetMismatch: 814 case Sema::TDK_NonDependentConversionFailure: 815 return nullptr; 816 817 case Sema::TDK_DeducedMismatch: 818 case Sema::TDK_DeducedMismatchNested: 819 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 820 821 case Sema::TDK_SubstitutionFailure: 822 return static_cast<TemplateArgumentList*>(Data); 823 824 case Sema::TDK_ConstraintsNotSatisfied: 825 return static_cast<CNSInfo*>(Data)->TemplateArgs; 826 827 // Unhandled 828 case Sema::TDK_MiscellaneousDeductionFailure: 829 case Sema::TDK_AlreadyDiagnosed: 830 break; 831 } 832 833 return nullptr; 834 } 835 836 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 837 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 838 case Sema::TDK_Success: 839 case Sema::TDK_Invalid: 840 case Sema::TDK_InstantiationDepth: 841 case Sema::TDK_Incomplete: 842 case Sema::TDK_TooManyArguments: 843 case Sema::TDK_TooFewArguments: 844 case Sema::TDK_InvalidExplicitArguments: 845 case Sema::TDK_SubstitutionFailure: 846 case Sema::TDK_CUDATargetMismatch: 847 case Sema::TDK_NonDependentConversionFailure: 848 case Sema::TDK_ConstraintsNotSatisfied: 849 return nullptr; 850 851 case Sema::TDK_IncompletePack: 852 case Sema::TDK_Inconsistent: 853 case Sema::TDK_Underqualified: 854 case Sema::TDK_DeducedMismatch: 855 case Sema::TDK_DeducedMismatchNested: 856 case Sema::TDK_NonDeducedMismatch: 857 return &static_cast<DFIArguments*>(Data)->FirstArg; 858 859 // Unhandled 860 case Sema::TDK_MiscellaneousDeductionFailure: 861 case Sema::TDK_AlreadyDiagnosed: 862 break; 863 } 864 865 return nullptr; 866 } 867 868 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 869 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 870 case Sema::TDK_Success: 871 case Sema::TDK_Invalid: 872 case Sema::TDK_InstantiationDepth: 873 case Sema::TDK_Incomplete: 874 case Sema::TDK_IncompletePack: 875 case Sema::TDK_TooManyArguments: 876 case Sema::TDK_TooFewArguments: 877 case Sema::TDK_InvalidExplicitArguments: 878 case Sema::TDK_SubstitutionFailure: 879 case Sema::TDK_CUDATargetMismatch: 880 case Sema::TDK_NonDependentConversionFailure: 881 case Sema::TDK_ConstraintsNotSatisfied: 882 return nullptr; 883 884 case Sema::TDK_Inconsistent: 885 case Sema::TDK_Underqualified: 886 case Sema::TDK_DeducedMismatch: 887 case Sema::TDK_DeducedMismatchNested: 888 case Sema::TDK_NonDeducedMismatch: 889 return &static_cast<DFIArguments*>(Data)->SecondArg; 890 891 // Unhandled 892 case Sema::TDK_MiscellaneousDeductionFailure: 893 case Sema::TDK_AlreadyDiagnosed: 894 break; 895 } 896 897 return nullptr; 898 } 899 900 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 901 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 902 case Sema::TDK_DeducedMismatch: 903 case Sema::TDK_DeducedMismatchNested: 904 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 905 906 default: 907 return std::nullopt; 908 } 909 } 910 911 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, 912 const FunctionDecl *Y) { 913 if (!X || !Y) 914 return false; 915 if (X->getNumParams() != Y->getNumParams()) 916 return false; 917 // FIXME: when do rewritten comparison operators 918 // with explicit object parameters correspond? 919 // https://cplusplus.github.io/CWG/issues/2797.html 920 for (unsigned I = 0; I < X->getNumParams(); ++I) 921 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(), 922 Y->getParamDecl(I)->getType())) 923 return false; 924 if (auto *FTX = X->getDescribedFunctionTemplate()) { 925 auto *FTY = Y->getDescribedFunctionTemplate(); 926 if (!FTY) 927 return false; 928 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(), 929 FTY->getTemplateParameters())) 930 return false; 931 } 932 return true; 933 } 934 935 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, 936 Expr *FirstOperand, FunctionDecl *EqFD) { 937 assert(EqFD->getOverloadedOperator() == 938 OverloadedOperatorKind::OO_EqualEqual); 939 // C++2a [over.match.oper]p4: 940 // A non-template function or function template F named operator== is a 941 // rewrite target with first operand o unless a search for the name operator!= 942 // in the scope S from the instantiation context of the operator expression 943 // finds a function or function template that would correspond 944 // ([basic.scope.scope]) to F if its name were operator==, where S is the 945 // scope of the class type of o if F is a class member, and the namespace 946 // scope of which F is a member otherwise. A function template specialization 947 // named operator== is a rewrite target if its function template is a rewrite 948 // target. 949 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName( 950 OverloadedOperatorKind::OO_ExclaimEqual); 951 if (isa<CXXMethodDecl>(EqFD)) { 952 // If F is a class member, search scope is class type of first operand. 953 QualType RHS = FirstOperand->getType(); 954 auto *RHSRec = RHS->getAs<RecordType>(); 955 if (!RHSRec) 956 return true; 957 LookupResult Members(S, NotEqOp, OpLoc, 958 Sema::LookupNameKind::LookupMemberName); 959 S.LookupQualifiedName(Members, RHSRec->getDecl()); 960 Members.suppressAccessDiagnostics(); 961 for (NamedDecl *Op : Members) 962 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction())) 963 return false; 964 return true; 965 } 966 // Otherwise the search scope is the namespace scope of which F is a member. 967 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) { 968 auto *NotEqFD = Op->getAsFunction(); 969 if (auto *UD = dyn_cast<UsingShadowDecl>(Op)) 970 NotEqFD = UD->getUnderlyingDecl()->getAsFunction(); 971 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) && 972 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()), 973 cast<Decl>(Op->getLexicalDeclContext()))) 974 return false; 975 } 976 return true; 977 } 978 979 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed( 980 OverloadedOperatorKind Op) { 981 if (!AllowRewrittenCandidates) 982 return false; 983 return Op == OO_EqualEqual || Op == OO_Spaceship; 984 } 985 986 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 987 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) { 988 auto Op = FD->getOverloadedOperator(); 989 if (!allowsReversed(Op)) 990 return false; 991 if (Op == OverloadedOperatorKind::OO_EqualEqual) { 992 assert(OriginalArgs.size() == 2); 993 if (!shouldAddReversedEqEq( 994 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD)) 995 return false; 996 } 997 // Don't bother adding a reversed candidate that can never be a better 998 // match than the non-reversed version. 999 return FD->getNumNonObjectParams() != 2 || 1000 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 1001 FD->getParamDecl(1)->getType()) || 1002 FD->hasAttr<EnableIfAttr>(); 1003 } 1004 1005 void OverloadCandidateSet::destroyCandidates() { 1006 for (iterator i = begin(), e = end(); i != e; ++i) { 1007 for (auto &C : i->Conversions) 1008 C.~ImplicitConversionSequence(); 1009 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 1010 i->DeductionFailure.Destroy(); 1011 } 1012 } 1013 1014 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 1015 destroyCandidates(); 1016 SlabAllocator.Reset(); 1017 NumInlineBytesUsed = 0; 1018 Candidates.clear(); 1019 Functions.clear(); 1020 Kind = CSK; 1021 } 1022 1023 namespace { 1024 class UnbridgedCastsSet { 1025 struct Entry { 1026 Expr **Addr; 1027 Expr *Saved; 1028 }; 1029 SmallVector<Entry, 2> Entries; 1030 1031 public: 1032 void save(Sema &S, Expr *&E) { 1033 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 1034 Entry entry = { &E, E }; 1035 Entries.push_back(entry); 1036 E = S.stripARCUnbridgedCast(E); 1037 } 1038 1039 void restore() { 1040 for (SmallVectorImpl<Entry>::iterator 1041 i = Entries.begin(), e = Entries.end(); i != e; ++i) 1042 *i->Addr = i->Saved; 1043 } 1044 }; 1045 } 1046 1047 /// checkPlaceholderForOverload - Do any interesting placeholder-like 1048 /// preprocessing on the given expression. 1049 /// 1050 /// \param unbridgedCasts a collection to which to add unbridged casts; 1051 /// without this, they will be immediately diagnosed as errors 1052 /// 1053 /// Return true on unrecoverable error. 1054 static bool 1055 checkPlaceholderForOverload(Sema &S, Expr *&E, 1056 UnbridgedCastsSet *unbridgedCasts = nullptr) { 1057 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 1058 // We can't handle overloaded expressions here because overload 1059 // resolution might reasonably tweak them. 1060 if (placeholder->getKind() == BuiltinType::Overload) return false; 1061 1062 // If the context potentially accepts unbridged ARC casts, strip 1063 // the unbridged cast and add it to the collection for later restoration. 1064 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 1065 unbridgedCasts) { 1066 unbridgedCasts->save(S, E); 1067 return false; 1068 } 1069 1070 // Go ahead and check everything else. 1071 ExprResult result = S.CheckPlaceholderExpr(E); 1072 if (result.isInvalid()) 1073 return true; 1074 1075 E = result.get(); 1076 return false; 1077 } 1078 1079 // Nothing to do. 1080 return false; 1081 } 1082 1083 /// checkArgPlaceholdersForOverload - Check a set of call operands for 1084 /// placeholders. 1085 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, 1086 UnbridgedCastsSet &unbridged) { 1087 for (unsigned i = 0, e = Args.size(); i != e; ++i) 1088 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 1089 return true; 1090 1091 return false; 1092 } 1093 1094 /// Determine whether the given New declaration is an overload of the 1095 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 1096 /// New and Old cannot be overloaded, e.g., if New has the same signature as 1097 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 1098 /// functions (or function templates) at all. When it does return Ovl_Match or 1099 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1100 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1101 /// declaration. 1102 /// 1103 /// Example: Given the following input: 1104 /// 1105 /// void f(int, float); // #1 1106 /// void f(int, int); // #2 1107 /// int f(int, int); // #3 1108 /// 1109 /// When we process #1, there is no previous declaration of "f", so IsOverload 1110 /// will not be used. 1111 /// 1112 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1113 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1114 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1115 /// unchanged. 1116 /// 1117 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1118 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1119 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1120 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1121 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1122 /// 1123 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1124 /// by a using declaration. The rules for whether to hide shadow declarations 1125 /// ignore some properties which otherwise figure into a function template's 1126 /// signature. 1127 Sema::OverloadKind 1128 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1129 NamedDecl *&Match, bool NewIsUsingDecl) { 1130 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1131 I != E; ++I) { 1132 NamedDecl *OldD = *I; 1133 1134 bool OldIsUsingDecl = false; 1135 if (isa<UsingShadowDecl>(OldD)) { 1136 OldIsUsingDecl = true; 1137 1138 // We can always introduce two using declarations into the same 1139 // context, even if they have identical signatures. 1140 if (NewIsUsingDecl) continue; 1141 1142 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1143 } 1144 1145 // A using-declaration does not conflict with another declaration 1146 // if one of them is hidden. 1147 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1148 continue; 1149 1150 // If either declaration was introduced by a using declaration, 1151 // we'll need to use slightly different rules for matching. 1152 // Essentially, these rules are the normal rules, except that 1153 // function templates hide function templates with different 1154 // return types or template parameter lists. 1155 bool UseMemberUsingDeclRules = 1156 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1157 !New->getFriendObjectKind(); 1158 1159 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1160 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1161 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1162 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1163 continue; 1164 } 1165 1166 if (!isa<FunctionTemplateDecl>(OldD) && 1167 !shouldLinkPossiblyHiddenDecl(*I, New)) 1168 continue; 1169 1170 Match = *I; 1171 return Ovl_Match; 1172 } 1173 1174 // Builtins that have custom typechecking or have a reference should 1175 // not be overloadable or redeclarable. 1176 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1177 Match = *I; 1178 return Ovl_NonFunction; 1179 } 1180 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1181 // We can overload with these, which can show up when doing 1182 // redeclaration checks for UsingDecls. 1183 assert(Old.getLookupKind() == LookupUsingDeclName); 1184 } else if (isa<TagDecl>(OldD)) { 1185 // We can always overload with tags by hiding them. 1186 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1187 // Optimistically assume that an unresolved using decl will 1188 // overload; if it doesn't, we'll have to diagnose during 1189 // template instantiation. 1190 // 1191 // Exception: if the scope is dependent and this is not a class 1192 // member, the using declaration can only introduce an enumerator. 1193 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1194 Match = *I; 1195 return Ovl_NonFunction; 1196 } 1197 } else { 1198 // (C++ 13p1): 1199 // Only function declarations can be overloaded; object and type 1200 // declarations cannot be overloaded. 1201 Match = *I; 1202 return Ovl_NonFunction; 1203 } 1204 } 1205 1206 // C++ [temp.friend]p1: 1207 // For a friend function declaration that is not a template declaration: 1208 // -- if the name of the friend is a qualified or unqualified template-id, 1209 // [...], otherwise 1210 // -- if the name of the friend is a qualified-id and a matching 1211 // non-template function is found in the specified class or namespace, 1212 // the friend declaration refers to that function, otherwise, 1213 // -- if the name of the friend is a qualified-id and a matching function 1214 // template is found in the specified class or namespace, the friend 1215 // declaration refers to the deduced specialization of that function 1216 // template, otherwise 1217 // -- the name shall be an unqualified-id [...] 1218 // If we get here for a qualified friend declaration, we've just reached the 1219 // third bullet. If the type of the friend is dependent, skip this lookup 1220 // until instantiation. 1221 if (New->getFriendObjectKind() && New->getQualifier() && 1222 !New->getDescribedFunctionTemplate() && 1223 !New->getDependentSpecializationInfo() && 1224 !New->getType()->isDependentType()) { 1225 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1226 TemplateSpecResult.addAllDecls(Old); 1227 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1228 /*QualifiedFriend*/true)) { 1229 New->setInvalidDecl(); 1230 return Ovl_Overload; 1231 } 1232 1233 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1234 return Ovl_Match; 1235 } 1236 1237 return Ovl_Overload; 1238 } 1239 1240 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, 1241 FunctionDecl *Old, 1242 bool UseMemberUsingDeclRules, 1243 bool ConsiderCudaAttrs, 1244 bool UseOverrideRules = false) { 1245 // C++ [basic.start.main]p2: This function shall not be overloaded. 1246 if (New->isMain()) 1247 return false; 1248 1249 // MSVCRT user defined entry points cannot be overloaded. 1250 if (New->isMSVCRTEntryPoint()) 1251 return false; 1252 1253 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1254 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1255 1256 // C++ [temp.fct]p2: 1257 // A function template can be overloaded with other function templates 1258 // and with normal (non-template) functions. 1259 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1260 return true; 1261 1262 if (NewTemplate) { 1263 // C++ [temp.over.link]p4: 1264 // The signature of a function template consists of its function 1265 // signature, its return type and its template parameter list. The names 1266 // of the template parameters are significant only for establishing the 1267 // relationship between the template parameters and the rest of the 1268 // signature. 1269 // 1270 // We check the return type and template parameter lists for function 1271 // templates first; the remaining checks follow. 1272 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual( 1273 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate, 1274 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch); 1275 bool SameReturnType = SemaRef.Context.hasSameType( 1276 Old->getDeclaredReturnType(), New->getDeclaredReturnType()); 1277 // FIXME(GH58571): Match template parameter list even for non-constrained 1278 // template heads. This currently ensures that the code prior to C++20 is 1279 // not newly broken. 1280 bool ConstraintsInTemplateHead = 1281 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() || 1282 OldTemplate->getTemplateParameters()->hasAssociatedConstraints(); 1283 // C++ [namespace.udecl]p11: 1284 // The set of declarations named by a using-declarator that inhabits a 1285 // class C does not include member functions and member function 1286 // templates of a base class that "correspond" to (and thus would 1287 // conflict with) a declaration of a function or function template in 1288 // C. 1289 // Comparing return types is not required for the "correspond" check to 1290 // decide whether a member introduced by a shadow declaration is hidden. 1291 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead && 1292 !SameTemplateParameterList) 1293 return true; 1294 if (!UseMemberUsingDeclRules && 1295 (!SameTemplateParameterList || !SameReturnType)) 1296 return true; 1297 } 1298 1299 // Is the function New an overload of the function Old? 1300 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType()); 1301 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType()); 1302 1303 // Compare the signatures (C++ 1.3.10) of the two functions to 1304 // determine whether they are overloads. If we find any mismatch 1305 // in the signature, they are overloads. 1306 1307 // If either of these functions is a K&R-style function (no 1308 // prototype), then we consider them to have matching signatures. 1309 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1310 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1311 return false; 1312 1313 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1314 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1315 1316 // The signature of a function includes the types of its 1317 // parameters (C++ 1.3.10), which includes the presence or absence 1318 // of the ellipsis; see C++ DR 357). 1319 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic()) 1320 return true; 1321 1322 // For member-like friends, the enclosing class is part of the signature. 1323 if ((New->isMemberLikeConstrainedFriend() || 1324 Old->isMemberLikeConstrainedFriend()) && 1325 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext())) 1326 return true; 1327 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1328 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New); 1329 1330 int OldParamsOffset = 0; 1331 int NewParamsOffset = 0; 1332 1333 // When determining if a method is an overload from a base class, act as if 1334 // the implicit object parameter are of the same type. 1335 1336 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) { 1337 if (M->isExplicitObjectMemberFunction()) 1338 return Q; 1339 1340 // We do not allow overloading based off of '__restrict'. 1341 Q.removeRestrict(); 1342 1343 // We may not have applied the implicit const for a constexpr member 1344 // function yet (because we haven't yet resolved whether this is a static 1345 // or non-static member function). Add it now, on the assumption that this 1346 // is a redeclaration of OldMethod. 1347 if (!SemaRef.getLangOpts().CPlusPlus14 && 1348 (M->isConstexpr() || M->isConsteval()) && 1349 !isa<CXXConstructorDecl>(NewMethod)) 1350 Q.addConst(); 1351 return Q; 1352 }; 1353 1354 auto CompareType = [&](QualType Base, QualType D) { 1355 auto BS = Base.getNonReferenceType().getCanonicalType().split(); 1356 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals); 1357 1358 auto DS = D.getNonReferenceType().getCanonicalType().split(); 1359 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals); 1360 1361 if (BS.Quals != DS.Quals) 1362 return false; 1363 1364 if (OldMethod->isImplicitObjectMemberFunction() && 1365 OldMethod->getParent() != NewMethod->getParent()) { 1366 QualType ParentType = 1367 SemaRef.Context.getTypeDeclType(OldMethod->getParent()) 1368 .getCanonicalType(); 1369 if (ParentType.getTypePtr() != BS.Ty) 1370 return false; 1371 BS.Ty = DS.Ty; 1372 } 1373 1374 // FIXME: should we ignore some type attributes here? 1375 if (BS.Ty != DS.Ty) 1376 return false; 1377 1378 if (Base->isLValueReferenceType()) 1379 return D->isLValueReferenceType(); 1380 return Base->isRValueReferenceType() == D->isRValueReferenceType(); 1381 }; 1382 1383 // If the function is a class member, its signature includes the 1384 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1385 auto DiagnoseInconsistentRefQualifiers = [&]() { 1386 if (SemaRef.LangOpts.CPlusPlus23) 1387 return false; 1388 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier()) 1389 return false; 1390 if (OldMethod->isExplicitObjectMemberFunction() || 1391 NewMethod->isExplicitObjectMemberFunction()) 1392 return false; 1393 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None || 1394 NewMethod->getRefQualifier() == RQ_None)) { 1395 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1396 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1397 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1398 return true; 1399 } 1400 return false; 1401 }; 1402 1403 if (OldMethod && OldMethod->isExplicitObjectMemberFunction()) 1404 OldParamsOffset++; 1405 if (NewMethod && NewMethod->isExplicitObjectMemberFunction()) 1406 NewParamsOffset++; 1407 1408 if (OldType->getNumParams() - OldParamsOffset != 1409 NewType->getNumParams() - NewParamsOffset || 1410 !SemaRef.FunctionParamTypesAreEqual( 1411 {OldType->param_type_begin() + OldParamsOffset, 1412 OldType->param_type_end()}, 1413 {NewType->param_type_begin() + NewParamsOffset, 1414 NewType->param_type_end()}, 1415 nullptr)) { 1416 return true; 1417 } 1418 1419 if (OldMethod && NewMethod && !OldMethod->isStatic() && 1420 !OldMethod->isStatic()) { 1421 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old, 1422 const CXXMethodDecl *New) { 1423 auto NewObjectType = New->getFunctionObjectParameterReferenceType(); 1424 auto OldObjectType = Old->getFunctionObjectParameterReferenceType(); 1425 1426 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) { 1427 return F->getRefQualifier() == RQ_None && 1428 !F->isExplicitObjectMemberFunction(); 1429 }; 1430 1431 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) && 1432 CompareType(OldObjectType.getNonReferenceType(), 1433 NewObjectType.getNonReferenceType())) 1434 return true; 1435 return CompareType(OldObjectType, NewObjectType); 1436 }(OldMethod, NewMethod); 1437 1438 if (!HaveCorrespondingObjectParameters) { 1439 if (DiagnoseInconsistentRefQualifiers()) 1440 return true; 1441 // CWG2554 1442 // and, if at least one is an explicit object member function, ignoring 1443 // object parameters 1444 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() && 1445 !OldMethod->isExplicitObjectMemberFunction())) 1446 return true; 1447 } 1448 } 1449 1450 if (!UseOverrideRules) { 1451 Expr *NewRC = New->getTrailingRequiresClause(), 1452 *OldRC = Old->getTrailingRequiresClause(); 1453 if ((NewRC != nullptr) != (OldRC != nullptr)) 1454 return true; 1455 1456 if (NewRC && !SemaRef.AreConstraintExpressionsEqual(Old, OldRC, New, NewRC)) 1457 return true; 1458 } 1459 1460 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() && 1461 NewMethod->isImplicitObjectMemberFunction()) { 1462 if (DiagnoseInconsistentRefQualifiers()) 1463 return true; 1464 } 1465 1466 // Though pass_object_size is placed on parameters and takes an argument, we 1467 // consider it to be a function-level modifier for the sake of function 1468 // identity. Either the function has one or more parameters with 1469 // pass_object_size or it doesn't. 1470 if (functionHasPassObjectSizeParams(New) != 1471 functionHasPassObjectSizeParams(Old)) 1472 return true; 1473 1474 // enable_if attributes are an order-sensitive part of the signature. 1475 for (specific_attr_iterator<EnableIfAttr> 1476 NewI = New->specific_attr_begin<EnableIfAttr>(), 1477 NewE = New->specific_attr_end<EnableIfAttr>(), 1478 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1479 OldE = Old->specific_attr_end<EnableIfAttr>(); 1480 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1481 if (NewI == NewE || OldI == OldE) 1482 return true; 1483 llvm::FoldingSetNodeID NewID, OldID; 1484 NewI->getCond()->Profile(NewID, SemaRef.Context, true); 1485 OldI->getCond()->Profile(OldID, SemaRef.Context, true); 1486 if (NewID != OldID) 1487 return true; 1488 } 1489 1490 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) { 1491 // Don't allow overloading of destructors. (In theory we could, but it 1492 // would be a giant change to clang.) 1493 if (!isa<CXXDestructorDecl>(New)) { 1494 Sema::CUDAFunctionTarget NewTarget = SemaRef.IdentifyCUDATarget(New), 1495 OldTarget = SemaRef.IdentifyCUDATarget(Old); 1496 if (NewTarget != Sema::CFT_InvalidTarget) { 1497 assert((OldTarget != Sema::CFT_InvalidTarget) && 1498 "Unexpected invalid target."); 1499 1500 // Allow overloading of functions with same signature and different CUDA 1501 // target attributes. 1502 if (NewTarget != OldTarget) 1503 return true; 1504 } 1505 } 1506 } 1507 1508 // The signatures match; this is not an overload. 1509 return false; 1510 } 1511 1512 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1513 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1514 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules, 1515 ConsiderCudaAttrs); 1516 } 1517 1518 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, 1519 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1520 return IsOverloadOrOverrideImpl(*this, MD, BaseMD, 1521 /*UseMemberUsingDeclRules=*/false, 1522 /*ConsiderCudaAttrs=*/true, 1523 /*UseOverrideRules=*/true); 1524 } 1525 1526 /// Tries a user-defined conversion from From to ToType. 1527 /// 1528 /// Produces an implicit conversion sequence for when a standard conversion 1529 /// is not an option. See TryImplicitConversion for more information. 1530 static ImplicitConversionSequence 1531 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1532 bool SuppressUserConversions, 1533 AllowedExplicit AllowExplicit, 1534 bool InOverloadResolution, 1535 bool CStyle, 1536 bool AllowObjCWritebackConversion, 1537 bool AllowObjCConversionOnExplicit) { 1538 ImplicitConversionSequence ICS; 1539 1540 if (SuppressUserConversions) { 1541 // We're not in the case above, so there is no conversion that 1542 // we can perform. 1543 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1544 return ICS; 1545 } 1546 1547 // Attempt user-defined conversion. 1548 OverloadCandidateSet Conversions(From->getExprLoc(), 1549 OverloadCandidateSet::CSK_Normal); 1550 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1551 Conversions, AllowExplicit, 1552 AllowObjCConversionOnExplicit)) { 1553 case OR_Success: 1554 case OR_Deleted: 1555 ICS.setUserDefined(); 1556 // C++ [over.ics.user]p4: 1557 // A conversion of an expression of class type to the same class 1558 // type is given Exact Match rank, and a conversion of an 1559 // expression of class type to a base class of that type is 1560 // given Conversion rank, in spite of the fact that a copy 1561 // constructor (i.e., a user-defined conversion function) is 1562 // called for those cases. 1563 if (CXXConstructorDecl *Constructor 1564 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1565 QualType FromCanon 1566 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1567 QualType ToCanon 1568 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1569 if (Constructor->isCopyConstructor() && 1570 (FromCanon == ToCanon || 1571 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1572 // Turn this into a "standard" conversion sequence, so that it 1573 // gets ranked with standard conversion sequences. 1574 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1575 ICS.setStandard(); 1576 ICS.Standard.setAsIdentityConversion(); 1577 ICS.Standard.setFromType(From->getType()); 1578 ICS.Standard.setAllToTypes(ToType); 1579 ICS.Standard.CopyConstructor = Constructor; 1580 ICS.Standard.FoundCopyConstructor = Found; 1581 if (ToCanon != FromCanon) 1582 ICS.Standard.Second = ICK_Derived_To_Base; 1583 } 1584 } 1585 break; 1586 1587 case OR_Ambiguous: 1588 ICS.setAmbiguous(); 1589 ICS.Ambiguous.setFromType(From->getType()); 1590 ICS.Ambiguous.setToType(ToType); 1591 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1592 Cand != Conversions.end(); ++Cand) 1593 if (Cand->Best) 1594 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1595 break; 1596 1597 // Fall through. 1598 case OR_No_Viable_Function: 1599 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1600 break; 1601 } 1602 1603 return ICS; 1604 } 1605 1606 /// TryImplicitConversion - Attempt to perform an implicit conversion 1607 /// from the given expression (Expr) to the given type (ToType). This 1608 /// function returns an implicit conversion sequence that can be used 1609 /// to perform the initialization. Given 1610 /// 1611 /// void f(float f); 1612 /// void g(int i) { f(i); } 1613 /// 1614 /// this routine would produce an implicit conversion sequence to 1615 /// describe the initialization of f from i, which will be a standard 1616 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1617 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1618 // 1619 /// Note that this routine only determines how the conversion can be 1620 /// performed; it does not actually perform the conversion. As such, 1621 /// it will not produce any diagnostics if no conversion is available, 1622 /// but will instead return an implicit conversion sequence of kind 1623 /// "BadConversion". 1624 /// 1625 /// If @p SuppressUserConversions, then user-defined conversions are 1626 /// not permitted. 1627 /// If @p AllowExplicit, then explicit user-defined conversions are 1628 /// permitted. 1629 /// 1630 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1631 /// writeback conversion, which allows __autoreleasing id* parameters to 1632 /// be initialized with __strong id* or __weak id* arguments. 1633 static ImplicitConversionSequence 1634 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1635 bool SuppressUserConversions, 1636 AllowedExplicit AllowExplicit, 1637 bool InOverloadResolution, 1638 bool CStyle, 1639 bool AllowObjCWritebackConversion, 1640 bool AllowObjCConversionOnExplicit) { 1641 ImplicitConversionSequence ICS; 1642 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1643 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1644 ICS.setStandard(); 1645 return ICS; 1646 } 1647 1648 if (!S.getLangOpts().CPlusPlus) { 1649 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1650 return ICS; 1651 } 1652 1653 // C++ [over.ics.user]p4: 1654 // A conversion of an expression of class type to the same class 1655 // type is given Exact Match rank, and a conversion of an 1656 // expression of class type to a base class of that type is 1657 // given Conversion rank, in spite of the fact that a copy/move 1658 // constructor (i.e., a user-defined conversion function) is 1659 // called for those cases. 1660 QualType FromType = From->getType(); 1661 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1662 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1663 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1664 ICS.setStandard(); 1665 ICS.Standard.setAsIdentityConversion(); 1666 ICS.Standard.setFromType(FromType); 1667 ICS.Standard.setAllToTypes(ToType); 1668 1669 // We don't actually check at this point whether there is a valid 1670 // copy/move constructor, since overloading just assumes that it 1671 // exists. When we actually perform initialization, we'll find the 1672 // appropriate constructor to copy the returned object, if needed. 1673 ICS.Standard.CopyConstructor = nullptr; 1674 1675 // Determine whether this is considered a derived-to-base conversion. 1676 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1677 ICS.Standard.Second = ICK_Derived_To_Base; 1678 1679 return ICS; 1680 } 1681 1682 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1683 AllowExplicit, InOverloadResolution, CStyle, 1684 AllowObjCWritebackConversion, 1685 AllowObjCConversionOnExplicit); 1686 } 1687 1688 ImplicitConversionSequence 1689 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1690 bool SuppressUserConversions, 1691 AllowedExplicit AllowExplicit, 1692 bool InOverloadResolution, 1693 bool CStyle, 1694 bool AllowObjCWritebackConversion) { 1695 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1696 AllowExplicit, InOverloadResolution, CStyle, 1697 AllowObjCWritebackConversion, 1698 /*AllowObjCConversionOnExplicit=*/false); 1699 } 1700 1701 /// PerformImplicitConversion - Perform an implicit conversion of the 1702 /// expression From to the type ToType. Returns the 1703 /// converted expression. Flavor is the kind of conversion we're 1704 /// performing, used in the error message. If @p AllowExplicit, 1705 /// explicit user-defined conversions are permitted. 1706 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1707 AssignmentAction Action, 1708 bool AllowExplicit) { 1709 if (checkPlaceholderForOverload(*this, From)) 1710 return ExprError(); 1711 1712 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1713 bool AllowObjCWritebackConversion 1714 = getLangOpts().ObjCAutoRefCount && 1715 (Action == AA_Passing || Action == AA_Sending); 1716 if (getLangOpts().ObjC) 1717 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1718 From->getType(), From); 1719 ImplicitConversionSequence ICS = ::TryImplicitConversion( 1720 *this, From, ToType, 1721 /*SuppressUserConversions=*/false, 1722 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None, 1723 /*InOverloadResolution=*/false, 1724 /*CStyle=*/false, AllowObjCWritebackConversion, 1725 /*AllowObjCConversionOnExplicit=*/false); 1726 return PerformImplicitConversion(From, ToType, ICS, Action); 1727 } 1728 1729 /// Determine whether the conversion from FromType to ToType is a valid 1730 /// conversion that strips "noexcept" or "noreturn" off the nested function 1731 /// type. 1732 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1733 QualType &ResultTy) { 1734 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1735 return false; 1736 1737 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1738 // or F(t noexcept) -> F(t) 1739 // where F adds one of the following at most once: 1740 // - a pointer 1741 // - a member pointer 1742 // - a block pointer 1743 // Changes here need matching changes in FindCompositePointerType. 1744 CanQualType CanTo = Context.getCanonicalType(ToType); 1745 CanQualType CanFrom = Context.getCanonicalType(FromType); 1746 Type::TypeClass TyClass = CanTo->getTypeClass(); 1747 if (TyClass != CanFrom->getTypeClass()) return false; 1748 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1749 if (TyClass == Type::Pointer) { 1750 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1751 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1752 } else if (TyClass == Type::BlockPointer) { 1753 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1754 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1755 } else if (TyClass == Type::MemberPointer) { 1756 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1757 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1758 // A function pointer conversion cannot change the class of the function. 1759 if (ToMPT->getClass() != FromMPT->getClass()) 1760 return false; 1761 CanTo = ToMPT->getPointeeType(); 1762 CanFrom = FromMPT->getPointeeType(); 1763 } else { 1764 return false; 1765 } 1766 1767 TyClass = CanTo->getTypeClass(); 1768 if (TyClass != CanFrom->getTypeClass()) return false; 1769 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1770 return false; 1771 } 1772 1773 const auto *FromFn = cast<FunctionType>(CanFrom); 1774 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1775 1776 const auto *ToFn = cast<FunctionType>(CanTo); 1777 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1778 1779 bool Changed = false; 1780 1781 // Drop 'noreturn' if not present in target type. 1782 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1783 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1784 Changed = true; 1785 } 1786 1787 // Drop the 'arm_preserves_za' if not present in the target type (we can do 1788 // that because it is merely a hint). 1789 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1790 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1791 if (ExtInfo.AArch64SMEAttributes & 1792 FunctionType::SME_PStateZAPreservedMask) { 1793 unsigned ToFlags = 0; 1794 if (const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn)) 1795 ToFlags = ToFPT->getExtProtoInfo().AArch64SMEAttributes; 1796 if (!(ToFlags & FunctionType::SME_PStateZAPreservedMask)) { 1797 ExtInfo.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask, 1798 false); 1799 QualType QT = Context.getFunctionType( 1800 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo); 1801 FromFn = QT->getAs<FunctionType>(); 1802 Changed = true; 1803 } 1804 } 1805 } 1806 1807 // Drop 'noexcept' if not present in target type. 1808 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1809 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1810 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1811 FromFn = cast<FunctionType>( 1812 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1813 EST_None) 1814 .getTypePtr()); 1815 Changed = true; 1816 } 1817 1818 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1819 // only if the ExtParameterInfo lists of the two function prototypes can be 1820 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1821 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1822 bool CanUseToFPT, CanUseFromFPT; 1823 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1824 CanUseFromFPT, NewParamInfos) && 1825 CanUseToFPT && !CanUseFromFPT) { 1826 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1827 ExtInfo.ExtParameterInfos = 1828 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1829 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1830 FromFPT->getParamTypes(), ExtInfo); 1831 FromFn = QT->getAs<FunctionType>(); 1832 Changed = true; 1833 } 1834 } 1835 1836 if (!Changed) 1837 return false; 1838 1839 assert(QualType(FromFn, 0).isCanonical()); 1840 if (QualType(FromFn, 0) != CanTo) return false; 1841 1842 ResultTy = ToType; 1843 return true; 1844 } 1845 1846 /// Determine whether the conversion from FromType to ToType is a valid 1847 /// vector conversion. 1848 /// 1849 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1850 /// conversion. 1851 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, 1852 ImplicitConversionKind &ICK, Expr *From, 1853 bool InOverloadResolution, bool CStyle) { 1854 // We need at least one of these types to be a vector type to have a vector 1855 // conversion. 1856 if (!ToType->isVectorType() && !FromType->isVectorType()) 1857 return false; 1858 1859 // Identical types require no conversions. 1860 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1861 return false; 1862 1863 // There are no conversions between extended vector types, only identity. 1864 if (ToType->isExtVectorType()) { 1865 // There are no conversions between extended vector types other than the 1866 // identity conversion. 1867 if (FromType->isExtVectorType()) 1868 return false; 1869 1870 // Vector splat from any arithmetic type to a vector. 1871 if (FromType->isArithmeticType()) { 1872 ICK = ICK_Vector_Splat; 1873 return true; 1874 } 1875 } 1876 1877 if (ToType->isSVESizelessBuiltinType() || 1878 FromType->isSVESizelessBuiltinType()) 1879 if (S.Context.areCompatibleSveTypes(FromType, ToType) || 1880 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) { 1881 ICK = ICK_SVE_Vector_Conversion; 1882 return true; 1883 } 1884 1885 if (ToType->isRVVSizelessBuiltinType() || 1886 FromType->isRVVSizelessBuiltinType()) 1887 if (S.Context.areCompatibleRVVTypes(FromType, ToType) || 1888 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) { 1889 ICK = ICK_RVV_Vector_Conversion; 1890 return true; 1891 } 1892 1893 // We can perform the conversion between vector types in the following cases: 1894 // 1)vector types are equivalent AltiVec and GCC vector types 1895 // 2)lax vector conversions are permitted and the vector types are of the 1896 // same size 1897 // 3)the destination type does not have the ARM MVE strict-polymorphism 1898 // attribute, which inhibits lax vector conversion for overload resolution 1899 // only 1900 if (ToType->isVectorType() && FromType->isVectorType()) { 1901 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1902 (S.isLaxVectorConversion(FromType, ToType) && 1903 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1904 if (S.getASTContext().getTargetInfo().getTriple().isPPC() && 1905 S.isLaxVectorConversion(FromType, ToType) && 1906 S.anyAltivecTypes(FromType, ToType) && 1907 !S.Context.areCompatibleVectorTypes(FromType, ToType) && 1908 !InOverloadResolution && !CStyle) { 1909 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all) 1910 << FromType << ToType; 1911 } 1912 ICK = ICK_Vector_Conversion; 1913 return true; 1914 } 1915 } 1916 1917 return false; 1918 } 1919 1920 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1921 bool InOverloadResolution, 1922 StandardConversionSequence &SCS, 1923 bool CStyle); 1924 1925 /// IsStandardConversion - Determines whether there is a standard 1926 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1927 /// expression From to the type ToType. Standard conversion sequences 1928 /// only consider non-class types; for conversions that involve class 1929 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1930 /// contain the standard conversion sequence required to perform this 1931 /// conversion and this routine will return true. Otherwise, this 1932 /// routine will return false and the value of SCS is unspecified. 1933 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1934 bool InOverloadResolution, 1935 StandardConversionSequence &SCS, 1936 bool CStyle, 1937 bool AllowObjCWritebackConversion) { 1938 QualType FromType = From->getType(); 1939 1940 // Standard conversions (C++ [conv]) 1941 SCS.setAsIdentityConversion(); 1942 SCS.IncompatibleObjC = false; 1943 SCS.setFromType(FromType); 1944 SCS.CopyConstructor = nullptr; 1945 1946 // There are no standard conversions for class types in C++, so 1947 // abort early. When overloading in C, however, we do permit them. 1948 if (S.getLangOpts().CPlusPlus && 1949 (FromType->isRecordType() || ToType->isRecordType())) 1950 return false; 1951 1952 // The first conversion can be an lvalue-to-rvalue conversion, 1953 // array-to-pointer conversion, or function-to-pointer conversion 1954 // (C++ 4p1). 1955 1956 if (FromType == S.Context.OverloadTy) { 1957 DeclAccessPair AccessPair; 1958 if (FunctionDecl *Fn 1959 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1960 AccessPair)) { 1961 // We were able to resolve the address of the overloaded function, 1962 // so we can convert to the type of that function. 1963 FromType = Fn->getType(); 1964 SCS.setFromType(FromType); 1965 1966 // we can sometimes resolve &foo<int> regardless of ToType, so check 1967 // if the type matches (identity) or we are converting to bool 1968 if (!S.Context.hasSameUnqualifiedType( 1969 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1970 QualType resultTy; 1971 // if the function type matches except for [[noreturn]], it's ok 1972 if (!S.IsFunctionConversion(FromType, 1973 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1974 // otherwise, only a boolean conversion is standard 1975 if (!ToType->isBooleanType()) 1976 return false; 1977 } 1978 1979 // Check if the "from" expression is taking the address of an overloaded 1980 // function and recompute the FromType accordingly. Take advantage of the 1981 // fact that non-static member functions *must* have such an address-of 1982 // expression. 1983 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1984 if (Method && !Method->isStatic() && 1985 !Method->isExplicitObjectMemberFunction()) { 1986 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1987 "Non-unary operator on non-static member address"); 1988 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1989 == UO_AddrOf && 1990 "Non-address-of operator on non-static member address"); 1991 const Type *ClassType 1992 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1993 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1994 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1995 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1996 UO_AddrOf && 1997 "Non-address-of operator for overloaded function expression"); 1998 FromType = S.Context.getPointerType(FromType); 1999 } 2000 } else { 2001 return false; 2002 } 2003 } 2004 // Lvalue-to-rvalue conversion (C++11 4.1): 2005 // A glvalue (3.10) of a non-function, non-array type T can 2006 // be converted to a prvalue. 2007 bool argIsLValue = From->isGLValue(); 2008 if (argIsLValue && 2009 !FromType->isFunctionType() && !FromType->isArrayType() && 2010 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 2011 SCS.First = ICK_Lvalue_To_Rvalue; 2012 2013 // C11 6.3.2.1p2: 2014 // ... if the lvalue has atomic type, the value has the non-atomic version 2015 // of the type of the lvalue ... 2016 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 2017 FromType = Atomic->getValueType(); 2018 2019 // If T is a non-class type, the type of the rvalue is the 2020 // cv-unqualified version of T. Otherwise, the type of the rvalue 2021 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 2022 // just strip the qualifiers because they don't matter. 2023 FromType = FromType.getUnqualifiedType(); 2024 } else if (FromType->isArrayType()) { 2025 // Array-to-pointer conversion (C++ 4.2) 2026 SCS.First = ICK_Array_To_Pointer; 2027 2028 // An lvalue or rvalue of type "array of N T" or "array of unknown 2029 // bound of T" can be converted to an rvalue of type "pointer to 2030 // T" (C++ 4.2p1). 2031 FromType = S.Context.getArrayDecayedType(FromType); 2032 2033 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 2034 // This conversion is deprecated in C++03 (D.4) 2035 SCS.DeprecatedStringLiteralToCharPtr = true; 2036 2037 // For the purpose of ranking in overload resolution 2038 // (13.3.3.1.1), this conversion is considered an 2039 // array-to-pointer conversion followed by a qualification 2040 // conversion (4.4). (C++ 4.2p2) 2041 SCS.Second = ICK_Identity; 2042 SCS.Third = ICK_Qualification; 2043 SCS.QualificationIncludesObjCLifetime = false; 2044 SCS.setAllToTypes(FromType); 2045 return true; 2046 } 2047 } else if (FromType->isFunctionType() && argIsLValue) { 2048 // Function-to-pointer conversion (C++ 4.3). 2049 SCS.First = ICK_Function_To_Pointer; 2050 2051 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 2052 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 2053 if (!S.checkAddressOfFunctionIsAvailable(FD)) 2054 return false; 2055 2056 // An lvalue of function type T can be converted to an rvalue of 2057 // type "pointer to T." The result is a pointer to the 2058 // function. (C++ 4.3p1). 2059 FromType = S.Context.getPointerType(FromType); 2060 } else { 2061 // We don't require any conversions for the first step. 2062 SCS.First = ICK_Identity; 2063 } 2064 SCS.setToType(0, FromType); 2065 2066 // The second conversion can be an integral promotion, floating 2067 // point promotion, integral conversion, floating point conversion, 2068 // floating-integral conversion, pointer conversion, 2069 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 2070 // For overloading in C, this can also be a "compatible-type" 2071 // conversion. 2072 bool IncompatibleObjC = false; 2073 ImplicitConversionKind SecondICK = ICK_Identity; 2074 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 2075 // The unqualified versions of the types are the same: there's no 2076 // conversion to do. 2077 SCS.Second = ICK_Identity; 2078 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 2079 // Integral promotion (C++ 4.5). 2080 SCS.Second = ICK_Integral_Promotion; 2081 FromType = ToType.getUnqualifiedType(); 2082 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 2083 // Floating point promotion (C++ 4.6). 2084 SCS.Second = ICK_Floating_Promotion; 2085 FromType = ToType.getUnqualifiedType(); 2086 } else if (S.IsComplexPromotion(FromType, ToType)) { 2087 // Complex promotion (Clang extension) 2088 SCS.Second = ICK_Complex_Promotion; 2089 FromType = ToType.getUnqualifiedType(); 2090 } else if (ToType->isBooleanType() && 2091 (FromType->isArithmeticType() || 2092 FromType->isAnyPointerType() || 2093 FromType->isBlockPointerType() || 2094 FromType->isMemberPointerType())) { 2095 // Boolean conversions (C++ 4.12). 2096 SCS.Second = ICK_Boolean_Conversion; 2097 FromType = S.Context.BoolTy; 2098 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 2099 ToType->isIntegralType(S.Context)) { 2100 // Integral conversions (C++ 4.7). 2101 SCS.Second = ICK_Integral_Conversion; 2102 FromType = ToType.getUnqualifiedType(); 2103 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 2104 // Complex conversions (C99 6.3.1.6) 2105 SCS.Second = ICK_Complex_Conversion; 2106 FromType = ToType.getUnqualifiedType(); 2107 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 2108 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 2109 // Complex-real conversions (C99 6.3.1.7) 2110 SCS.Second = ICK_Complex_Real; 2111 FromType = ToType.getUnqualifiedType(); 2112 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 2113 // FIXME: disable conversions between long double, __ibm128 and __float128 2114 // if their representation is different until there is back end support 2115 // We of course allow this conversion if long double is really double. 2116 2117 // Conversions between bfloat16 and float16 are currently not supported. 2118 if ((FromType->isBFloat16Type() && 2119 (ToType->isFloat16Type() || ToType->isHalfType())) || 2120 (ToType->isBFloat16Type() && 2121 (FromType->isFloat16Type() || FromType->isHalfType()))) 2122 return false; 2123 2124 // Conversions between IEEE-quad and IBM-extended semantics are not 2125 // permitted. 2126 const llvm::fltSemantics &FromSem = 2127 S.Context.getFloatTypeSemantics(FromType); 2128 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType); 2129 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() && 2130 &ToSem == &llvm::APFloat::IEEEquad()) || 2131 (&FromSem == &llvm::APFloat::IEEEquad() && 2132 &ToSem == &llvm::APFloat::PPCDoubleDouble())) 2133 return false; 2134 2135 // Floating point conversions (C++ 4.8). 2136 SCS.Second = ICK_Floating_Conversion; 2137 FromType = ToType.getUnqualifiedType(); 2138 } else if ((FromType->isRealFloatingType() && 2139 ToType->isIntegralType(S.Context)) || 2140 (FromType->isIntegralOrUnscopedEnumerationType() && 2141 ToType->isRealFloatingType())) { 2142 2143 // Floating-integral conversions (C++ 4.9). 2144 SCS.Second = ICK_Floating_Integral; 2145 FromType = ToType.getUnqualifiedType(); 2146 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 2147 SCS.Second = ICK_Block_Pointer_Conversion; 2148 } else if (AllowObjCWritebackConversion && 2149 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 2150 SCS.Second = ICK_Writeback_Conversion; 2151 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 2152 FromType, IncompatibleObjC)) { 2153 // Pointer conversions (C++ 4.10). 2154 SCS.Second = ICK_Pointer_Conversion; 2155 SCS.IncompatibleObjC = IncompatibleObjC; 2156 FromType = FromType.getUnqualifiedType(); 2157 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 2158 InOverloadResolution, FromType)) { 2159 // Pointer to member conversions (4.11). 2160 SCS.Second = ICK_Pointer_Member; 2161 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From, 2162 InOverloadResolution, CStyle)) { 2163 SCS.Second = SecondICK; 2164 FromType = ToType.getUnqualifiedType(); 2165 } else if (!S.getLangOpts().CPlusPlus && 2166 S.Context.typesAreCompatible(ToType, FromType)) { 2167 // Compatible conversions (Clang extension for C function overloading) 2168 SCS.Second = ICK_Compatible_Conversion; 2169 FromType = ToType.getUnqualifiedType(); 2170 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 2171 InOverloadResolution, 2172 SCS, CStyle)) { 2173 SCS.Second = ICK_TransparentUnionConversion; 2174 FromType = ToType; 2175 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 2176 CStyle)) { 2177 // tryAtomicConversion has updated the standard conversion sequence 2178 // appropriately. 2179 return true; 2180 } else if (ToType->isEventT() && 2181 From->isIntegerConstantExpr(S.getASTContext()) && 2182 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 2183 SCS.Second = ICK_Zero_Event_Conversion; 2184 FromType = ToType; 2185 } else if (ToType->isQueueT() && 2186 From->isIntegerConstantExpr(S.getASTContext()) && 2187 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 2188 SCS.Second = ICK_Zero_Queue_Conversion; 2189 FromType = ToType; 2190 } else if (ToType->isSamplerT() && 2191 From->isIntegerConstantExpr(S.getASTContext())) { 2192 SCS.Second = ICK_Compatible_Conversion; 2193 FromType = ToType; 2194 } else if (ToType->isFixedPointType() || FromType->isFixedPointType()) { 2195 SCS.Second = ICK_Fixed_Point_Conversion; 2196 FromType = ToType; 2197 } else { 2198 // No second conversion required. 2199 SCS.Second = ICK_Identity; 2200 } 2201 SCS.setToType(1, FromType); 2202 2203 // The third conversion can be a function pointer conversion or a 2204 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 2205 bool ObjCLifetimeConversion; 2206 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 2207 // Function pointer conversions (removing 'noexcept') including removal of 2208 // 'noreturn' (Clang extension). 2209 SCS.Third = ICK_Function_Conversion; 2210 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 2211 ObjCLifetimeConversion)) { 2212 SCS.Third = ICK_Qualification; 2213 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 2214 FromType = ToType; 2215 } else { 2216 // No conversion required 2217 SCS.Third = ICK_Identity; 2218 } 2219 2220 // C++ [over.best.ics]p6: 2221 // [...] Any difference in top-level cv-qualification is 2222 // subsumed by the initialization itself and does not constitute 2223 // a conversion. [...] 2224 QualType CanonFrom = S.Context.getCanonicalType(FromType); 2225 QualType CanonTo = S.Context.getCanonicalType(ToType); 2226 if (CanonFrom.getLocalUnqualifiedType() 2227 == CanonTo.getLocalUnqualifiedType() && 2228 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 2229 FromType = ToType; 2230 CanonFrom = CanonTo; 2231 } 2232 2233 SCS.setToType(2, FromType); 2234 2235 if (CanonFrom == CanonTo) 2236 return true; 2237 2238 // If we have not converted the argument type to the parameter type, 2239 // this is a bad conversion sequence, unless we're resolving an overload in C. 2240 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 2241 return false; 2242 2243 ExprResult ER = ExprResult{From}; 2244 Sema::AssignConvertType Conv = 2245 S.CheckSingleAssignmentConstraints(ToType, ER, 2246 /*Diagnose=*/false, 2247 /*DiagnoseCFAudited=*/false, 2248 /*ConvertRHS=*/false); 2249 ImplicitConversionKind SecondConv; 2250 switch (Conv) { 2251 case Sema::Compatible: 2252 SecondConv = ICK_C_Only_Conversion; 2253 break; 2254 // For our purposes, discarding qualifiers is just as bad as using an 2255 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2256 // qualifiers, as well. 2257 case Sema::CompatiblePointerDiscardsQualifiers: 2258 case Sema::IncompatiblePointer: 2259 case Sema::IncompatiblePointerSign: 2260 SecondConv = ICK_Incompatible_Pointer_Conversion; 2261 break; 2262 default: 2263 return false; 2264 } 2265 2266 // First can only be an lvalue conversion, so we pretend that this was the 2267 // second conversion. First should already be valid from earlier in the 2268 // function. 2269 SCS.Second = SecondConv; 2270 SCS.setToType(1, ToType); 2271 2272 // Third is Identity, because Second should rank us worse than any other 2273 // conversion. This could also be ICK_Qualification, but it's simpler to just 2274 // lump everything in with the second conversion, and we don't gain anything 2275 // from making this ICK_Qualification. 2276 SCS.Third = ICK_Identity; 2277 SCS.setToType(2, ToType); 2278 return true; 2279 } 2280 2281 static bool 2282 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2283 QualType &ToType, 2284 bool InOverloadResolution, 2285 StandardConversionSequence &SCS, 2286 bool CStyle) { 2287 2288 const RecordType *UT = ToType->getAsUnionType(); 2289 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2290 return false; 2291 // The field to initialize within the transparent union. 2292 RecordDecl *UD = UT->getDecl(); 2293 // It's compatible if the expression matches any of the fields. 2294 for (const auto *it : UD->fields()) { 2295 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2296 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2297 ToType = it->getType(); 2298 return true; 2299 } 2300 } 2301 return false; 2302 } 2303 2304 /// IsIntegralPromotion - Determines whether the conversion from the 2305 /// expression From (whose potentially-adjusted type is FromType) to 2306 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2307 /// sets PromotedType to the promoted type. 2308 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2309 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2310 // All integers are built-in. 2311 if (!To) { 2312 return false; 2313 } 2314 2315 // An rvalue of type char, signed char, unsigned char, short int, or 2316 // unsigned short int can be converted to an rvalue of type int if 2317 // int can represent all the values of the source type; otherwise, 2318 // the source rvalue can be converted to an rvalue of type unsigned 2319 // int (C++ 4.5p1). 2320 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() && 2321 !FromType->isEnumeralType()) { 2322 if ( // We can promote any signed, promotable integer type to an int 2323 (FromType->isSignedIntegerType() || 2324 // We can promote any unsigned integer type whose size is 2325 // less than int to an int. 2326 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2327 return To->getKind() == BuiltinType::Int; 2328 } 2329 2330 return To->getKind() == BuiltinType::UInt; 2331 } 2332 2333 // C++11 [conv.prom]p3: 2334 // A prvalue of an unscoped enumeration type whose underlying type is not 2335 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2336 // following types that can represent all the values of the enumeration 2337 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2338 // unsigned int, long int, unsigned long int, long long int, or unsigned 2339 // long long int. If none of the types in that list can represent all the 2340 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2341 // type can be converted to an rvalue a prvalue of the extended integer type 2342 // with lowest integer conversion rank (4.13) greater than the rank of long 2343 // long in which all the values of the enumeration can be represented. If 2344 // there are two such extended types, the signed one is chosen. 2345 // C++11 [conv.prom]p4: 2346 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2347 // can be converted to a prvalue of its underlying type. Moreover, if 2348 // integral promotion can be applied to its underlying type, a prvalue of an 2349 // unscoped enumeration type whose underlying type is fixed can also be 2350 // converted to a prvalue of the promoted underlying type. 2351 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2352 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2353 // provided for a scoped enumeration. 2354 if (FromEnumType->getDecl()->isScoped()) 2355 return false; 2356 2357 // We can perform an integral promotion to the underlying type of the enum, 2358 // even if that's not the promoted type. Note that the check for promoting 2359 // the underlying type is based on the type alone, and does not consider 2360 // the bitfield-ness of the actual source expression. 2361 if (FromEnumType->getDecl()->isFixed()) { 2362 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2363 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2364 IsIntegralPromotion(nullptr, Underlying, ToType); 2365 } 2366 2367 // We have already pre-calculated the promotion type, so this is trivial. 2368 if (ToType->isIntegerType() && 2369 isCompleteType(From->getBeginLoc(), FromType)) 2370 return Context.hasSameUnqualifiedType( 2371 ToType, FromEnumType->getDecl()->getPromotionType()); 2372 2373 // C++ [conv.prom]p5: 2374 // If the bit-field has an enumerated type, it is treated as any other 2375 // value of that type for promotion purposes. 2376 // 2377 // ... so do not fall through into the bit-field checks below in C++. 2378 if (getLangOpts().CPlusPlus) 2379 return false; 2380 } 2381 2382 // C++0x [conv.prom]p2: 2383 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2384 // to an rvalue a prvalue of the first of the following types that can 2385 // represent all the values of its underlying type: int, unsigned int, 2386 // long int, unsigned long int, long long int, or unsigned long long int. 2387 // If none of the types in that list can represent all the values of its 2388 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2389 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2390 // type. 2391 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2392 ToType->isIntegerType()) { 2393 // Determine whether the type we're converting from is signed or 2394 // unsigned. 2395 bool FromIsSigned = FromType->isSignedIntegerType(); 2396 uint64_t FromSize = Context.getTypeSize(FromType); 2397 2398 // The types we'll try to promote to, in the appropriate 2399 // order. Try each of these types. 2400 QualType PromoteTypes[6] = { 2401 Context.IntTy, Context.UnsignedIntTy, 2402 Context.LongTy, Context.UnsignedLongTy , 2403 Context.LongLongTy, Context.UnsignedLongLongTy 2404 }; 2405 for (int Idx = 0; Idx < 6; ++Idx) { 2406 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2407 if (FromSize < ToSize || 2408 (FromSize == ToSize && 2409 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2410 // We found the type that we can promote to. If this is the 2411 // type we wanted, we have a promotion. Otherwise, no 2412 // promotion. 2413 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2414 } 2415 } 2416 } 2417 2418 // An rvalue for an integral bit-field (9.6) can be converted to an 2419 // rvalue of type int if int can represent all the values of the 2420 // bit-field; otherwise, it can be converted to unsigned int if 2421 // unsigned int can represent all the values of the bit-field. If 2422 // the bit-field is larger yet, no integral promotion applies to 2423 // it. If the bit-field has an enumerated type, it is treated as any 2424 // other value of that type for promotion purposes (C++ 4.5p3). 2425 // FIXME: We should delay checking of bit-fields until we actually perform the 2426 // conversion. 2427 // 2428 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2429 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2430 // bit-fields and those whose underlying type is larger than int) for GCC 2431 // compatibility. 2432 if (From) { 2433 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2434 std::optional<llvm::APSInt> BitWidth; 2435 if (FromType->isIntegralType(Context) && 2436 (BitWidth = 2437 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2438 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2439 ToSize = Context.getTypeSize(ToType); 2440 2441 // Are we promoting to an int from a bitfield that fits in an int? 2442 if (*BitWidth < ToSize || 2443 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2444 return To->getKind() == BuiltinType::Int; 2445 } 2446 2447 // Are we promoting to an unsigned int from an unsigned bitfield 2448 // that fits into an unsigned int? 2449 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2450 return To->getKind() == BuiltinType::UInt; 2451 } 2452 2453 return false; 2454 } 2455 } 2456 } 2457 2458 // An rvalue of type bool can be converted to an rvalue of type int, 2459 // with false becoming zero and true becoming one (C++ 4.5p4). 2460 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2461 return true; 2462 } 2463 2464 return false; 2465 } 2466 2467 /// IsFloatingPointPromotion - Determines whether the conversion from 2468 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2469 /// returns true and sets PromotedType to the promoted type. 2470 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2471 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2472 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2473 /// An rvalue of type float can be converted to an rvalue of type 2474 /// double. (C++ 4.6p1). 2475 if (FromBuiltin->getKind() == BuiltinType::Float && 2476 ToBuiltin->getKind() == BuiltinType::Double) 2477 return true; 2478 2479 // C99 6.3.1.5p1: 2480 // When a float is promoted to double or long double, or a 2481 // double is promoted to long double [...]. 2482 if (!getLangOpts().CPlusPlus && 2483 (FromBuiltin->getKind() == BuiltinType::Float || 2484 FromBuiltin->getKind() == BuiltinType::Double) && 2485 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2486 ToBuiltin->getKind() == BuiltinType::Float128 || 2487 ToBuiltin->getKind() == BuiltinType::Ibm128)) 2488 return true; 2489 2490 // Half can be promoted to float. 2491 if (!getLangOpts().NativeHalfType && 2492 FromBuiltin->getKind() == BuiltinType::Half && 2493 ToBuiltin->getKind() == BuiltinType::Float) 2494 return true; 2495 } 2496 2497 return false; 2498 } 2499 2500 /// Determine if a conversion is a complex promotion. 2501 /// 2502 /// A complex promotion is defined as a complex -> complex conversion 2503 /// where the conversion between the underlying real types is a 2504 /// floating-point or integral promotion. 2505 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2506 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2507 if (!FromComplex) 2508 return false; 2509 2510 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2511 if (!ToComplex) 2512 return false; 2513 2514 return IsFloatingPointPromotion(FromComplex->getElementType(), 2515 ToComplex->getElementType()) || 2516 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2517 ToComplex->getElementType()); 2518 } 2519 2520 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2521 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2522 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2523 /// if non-empty, will be a pointer to ToType that may or may not have 2524 /// the right set of qualifiers on its pointee. 2525 /// 2526 static QualType 2527 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2528 QualType ToPointee, QualType ToType, 2529 ASTContext &Context, 2530 bool StripObjCLifetime = false) { 2531 assert((FromPtr->getTypeClass() == Type::Pointer || 2532 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2533 "Invalid similarly-qualified pointer type"); 2534 2535 /// Conversions to 'id' subsume cv-qualifier conversions. 2536 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2537 return ToType.getUnqualifiedType(); 2538 2539 QualType CanonFromPointee 2540 = Context.getCanonicalType(FromPtr->getPointeeType()); 2541 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2542 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2543 2544 if (StripObjCLifetime) 2545 Quals.removeObjCLifetime(); 2546 2547 // Exact qualifier match -> return the pointer type we're converting to. 2548 if (CanonToPointee.getLocalQualifiers() == Quals) { 2549 // ToType is exactly what we need. Return it. 2550 if (!ToType.isNull()) 2551 return ToType.getUnqualifiedType(); 2552 2553 // Build a pointer to ToPointee. It has the right qualifiers 2554 // already. 2555 if (isa<ObjCObjectPointerType>(ToType)) 2556 return Context.getObjCObjectPointerType(ToPointee); 2557 return Context.getPointerType(ToPointee); 2558 } 2559 2560 // Just build a canonical type that has the right qualifiers. 2561 QualType QualifiedCanonToPointee 2562 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2563 2564 if (isa<ObjCObjectPointerType>(ToType)) 2565 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2566 return Context.getPointerType(QualifiedCanonToPointee); 2567 } 2568 2569 static bool isNullPointerConstantForConversion(Expr *Expr, 2570 bool InOverloadResolution, 2571 ASTContext &Context) { 2572 // Handle value-dependent integral null pointer constants correctly. 2573 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2574 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2575 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2576 return !InOverloadResolution; 2577 2578 return Expr->isNullPointerConstant(Context, 2579 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2580 : Expr::NPC_ValueDependentIsNull); 2581 } 2582 2583 /// IsPointerConversion - Determines whether the conversion of the 2584 /// expression From, which has the (possibly adjusted) type FromType, 2585 /// can be converted to the type ToType via a pointer conversion (C++ 2586 /// 4.10). If so, returns true and places the converted type (that 2587 /// might differ from ToType in its cv-qualifiers at some level) into 2588 /// ConvertedType. 2589 /// 2590 /// This routine also supports conversions to and from block pointers 2591 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2592 /// pointers to interfaces. FIXME: Once we've determined the 2593 /// appropriate overloading rules for Objective-C, we may want to 2594 /// split the Objective-C checks into a different routine; however, 2595 /// GCC seems to consider all of these conversions to be pointer 2596 /// conversions, so for now they live here. IncompatibleObjC will be 2597 /// set if the conversion is an allowed Objective-C conversion that 2598 /// should result in a warning. 2599 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2600 bool InOverloadResolution, 2601 QualType& ConvertedType, 2602 bool &IncompatibleObjC) { 2603 IncompatibleObjC = false; 2604 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2605 IncompatibleObjC)) 2606 return true; 2607 2608 // Conversion from a null pointer constant to any Objective-C pointer type. 2609 if (ToType->isObjCObjectPointerType() && 2610 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2611 ConvertedType = ToType; 2612 return true; 2613 } 2614 2615 // Blocks: Block pointers can be converted to void*. 2616 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2617 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2618 ConvertedType = ToType; 2619 return true; 2620 } 2621 // Blocks: A null pointer constant can be converted to a block 2622 // pointer type. 2623 if (ToType->isBlockPointerType() && 2624 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2625 ConvertedType = ToType; 2626 return true; 2627 } 2628 2629 // If the left-hand-side is nullptr_t, the right side can be a null 2630 // pointer constant. 2631 if (ToType->isNullPtrType() && 2632 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2633 ConvertedType = ToType; 2634 return true; 2635 } 2636 2637 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2638 if (!ToTypePtr) 2639 return false; 2640 2641 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2642 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2643 ConvertedType = ToType; 2644 return true; 2645 } 2646 2647 // Beyond this point, both types need to be pointers 2648 // , including objective-c pointers. 2649 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2650 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2651 !getLangOpts().ObjCAutoRefCount) { 2652 ConvertedType = BuildSimilarlyQualifiedPointerType( 2653 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType, 2654 Context); 2655 return true; 2656 } 2657 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2658 if (!FromTypePtr) 2659 return false; 2660 2661 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2662 2663 // If the unqualified pointee types are the same, this can't be a 2664 // pointer conversion, so don't do all of the work below. 2665 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2666 return false; 2667 2668 // An rvalue of type "pointer to cv T," where T is an object type, 2669 // can be converted to an rvalue of type "pointer to cv void" (C++ 2670 // 4.10p2). 2671 if (FromPointeeType->isIncompleteOrObjectType() && 2672 ToPointeeType->isVoidType()) { 2673 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2674 ToPointeeType, 2675 ToType, Context, 2676 /*StripObjCLifetime=*/true); 2677 return true; 2678 } 2679 2680 // MSVC allows implicit function to void* type conversion. 2681 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2682 ToPointeeType->isVoidType()) { 2683 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2684 ToPointeeType, 2685 ToType, Context); 2686 return true; 2687 } 2688 2689 // When we're overloading in C, we allow a special kind of pointer 2690 // conversion for compatible-but-not-identical pointee types. 2691 if (!getLangOpts().CPlusPlus && 2692 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2693 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2694 ToPointeeType, 2695 ToType, Context); 2696 return true; 2697 } 2698 2699 // C++ [conv.ptr]p3: 2700 // 2701 // An rvalue of type "pointer to cv D," where D is a class type, 2702 // can be converted to an rvalue of type "pointer to cv B," where 2703 // B is a base class (clause 10) of D. If B is an inaccessible 2704 // (clause 11) or ambiguous (10.2) base class of D, a program that 2705 // necessitates this conversion is ill-formed. The result of the 2706 // conversion is a pointer to the base class sub-object of the 2707 // derived class object. The null pointer value is converted to 2708 // the null pointer value of the destination type. 2709 // 2710 // Note that we do not check for ambiguity or inaccessibility 2711 // here. That is handled by CheckPointerConversion. 2712 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2713 ToPointeeType->isRecordType() && 2714 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2715 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2716 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2717 ToPointeeType, 2718 ToType, Context); 2719 return true; 2720 } 2721 2722 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2723 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2724 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2725 ToPointeeType, 2726 ToType, Context); 2727 return true; 2728 } 2729 2730 return false; 2731 } 2732 2733 /// Adopt the given qualifiers for the given type. 2734 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2735 Qualifiers TQs = T.getQualifiers(); 2736 2737 // Check whether qualifiers already match. 2738 if (TQs == Qs) 2739 return T; 2740 2741 if (Qs.compatiblyIncludes(TQs)) 2742 return Context.getQualifiedType(T, Qs); 2743 2744 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2745 } 2746 2747 /// isObjCPointerConversion - Determines whether this is an 2748 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2749 /// with the same arguments and return values. 2750 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2751 QualType& ConvertedType, 2752 bool &IncompatibleObjC) { 2753 if (!getLangOpts().ObjC) 2754 return false; 2755 2756 // The set of qualifiers on the type we're converting from. 2757 Qualifiers FromQualifiers = FromType.getQualifiers(); 2758 2759 // First, we handle all conversions on ObjC object pointer types. 2760 const ObjCObjectPointerType* ToObjCPtr = 2761 ToType->getAs<ObjCObjectPointerType>(); 2762 const ObjCObjectPointerType *FromObjCPtr = 2763 FromType->getAs<ObjCObjectPointerType>(); 2764 2765 if (ToObjCPtr && FromObjCPtr) { 2766 // If the pointee types are the same (ignoring qualifications), 2767 // then this is not a pointer conversion. 2768 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2769 FromObjCPtr->getPointeeType())) 2770 return false; 2771 2772 // Conversion between Objective-C pointers. 2773 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2774 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2775 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2776 if (getLangOpts().CPlusPlus && LHS && RHS && 2777 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2778 FromObjCPtr->getPointeeType())) 2779 return false; 2780 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2781 ToObjCPtr->getPointeeType(), 2782 ToType, Context); 2783 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2784 return true; 2785 } 2786 2787 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2788 // Okay: this is some kind of implicit downcast of Objective-C 2789 // interfaces, which is permitted. However, we're going to 2790 // complain about it. 2791 IncompatibleObjC = true; 2792 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2793 ToObjCPtr->getPointeeType(), 2794 ToType, Context); 2795 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2796 return true; 2797 } 2798 } 2799 // Beyond this point, both types need to be C pointers or block pointers. 2800 QualType ToPointeeType; 2801 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2802 ToPointeeType = ToCPtr->getPointeeType(); 2803 else if (const BlockPointerType *ToBlockPtr = 2804 ToType->getAs<BlockPointerType>()) { 2805 // Objective C++: We're able to convert from a pointer to any object 2806 // to a block pointer type. 2807 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2808 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2809 return true; 2810 } 2811 ToPointeeType = ToBlockPtr->getPointeeType(); 2812 } 2813 else if (FromType->getAs<BlockPointerType>() && 2814 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2815 // Objective C++: We're able to convert from a block pointer type to a 2816 // pointer to any object. 2817 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2818 return true; 2819 } 2820 else 2821 return false; 2822 2823 QualType FromPointeeType; 2824 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2825 FromPointeeType = FromCPtr->getPointeeType(); 2826 else if (const BlockPointerType *FromBlockPtr = 2827 FromType->getAs<BlockPointerType>()) 2828 FromPointeeType = FromBlockPtr->getPointeeType(); 2829 else 2830 return false; 2831 2832 // If we have pointers to pointers, recursively check whether this 2833 // is an Objective-C conversion. 2834 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2835 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2836 IncompatibleObjC)) { 2837 // We always complain about this conversion. 2838 IncompatibleObjC = true; 2839 ConvertedType = Context.getPointerType(ConvertedType); 2840 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2841 return true; 2842 } 2843 // Allow conversion of pointee being objective-c pointer to another one; 2844 // as in I* to id. 2845 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2846 ToPointeeType->getAs<ObjCObjectPointerType>() && 2847 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2848 IncompatibleObjC)) { 2849 2850 ConvertedType = Context.getPointerType(ConvertedType); 2851 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2852 return true; 2853 } 2854 2855 // If we have pointers to functions or blocks, check whether the only 2856 // differences in the argument and result types are in Objective-C 2857 // pointer conversions. If so, we permit the conversion (but 2858 // complain about it). 2859 const FunctionProtoType *FromFunctionType 2860 = FromPointeeType->getAs<FunctionProtoType>(); 2861 const FunctionProtoType *ToFunctionType 2862 = ToPointeeType->getAs<FunctionProtoType>(); 2863 if (FromFunctionType && ToFunctionType) { 2864 // If the function types are exactly the same, this isn't an 2865 // Objective-C pointer conversion. 2866 if (Context.getCanonicalType(FromPointeeType) 2867 == Context.getCanonicalType(ToPointeeType)) 2868 return false; 2869 2870 // Perform the quick checks that will tell us whether these 2871 // function types are obviously different. 2872 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2873 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2874 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2875 return false; 2876 2877 bool HasObjCConversion = false; 2878 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2879 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2880 // Okay, the types match exactly. Nothing to do. 2881 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2882 ToFunctionType->getReturnType(), 2883 ConvertedType, IncompatibleObjC)) { 2884 // Okay, we have an Objective-C pointer conversion. 2885 HasObjCConversion = true; 2886 } else { 2887 // Function types are too different. Abort. 2888 return false; 2889 } 2890 2891 // Check argument types. 2892 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2893 ArgIdx != NumArgs; ++ArgIdx) { 2894 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2895 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2896 if (Context.getCanonicalType(FromArgType) 2897 == Context.getCanonicalType(ToArgType)) { 2898 // Okay, the types match exactly. Nothing to do. 2899 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2900 ConvertedType, IncompatibleObjC)) { 2901 // Okay, we have an Objective-C pointer conversion. 2902 HasObjCConversion = true; 2903 } else { 2904 // Argument types are too different. Abort. 2905 return false; 2906 } 2907 } 2908 2909 if (HasObjCConversion) { 2910 // We had an Objective-C conversion. Allow this pointer 2911 // conversion, but complain about it. 2912 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2913 IncompatibleObjC = true; 2914 return true; 2915 } 2916 } 2917 2918 return false; 2919 } 2920 2921 /// Determine whether this is an Objective-C writeback conversion, 2922 /// used for parameter passing when performing automatic reference counting. 2923 /// 2924 /// \param FromType The type we're converting form. 2925 /// 2926 /// \param ToType The type we're converting to. 2927 /// 2928 /// \param ConvertedType The type that will be produced after applying 2929 /// this conversion. 2930 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2931 QualType &ConvertedType) { 2932 if (!getLangOpts().ObjCAutoRefCount || 2933 Context.hasSameUnqualifiedType(FromType, ToType)) 2934 return false; 2935 2936 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2937 QualType ToPointee; 2938 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2939 ToPointee = ToPointer->getPointeeType(); 2940 else 2941 return false; 2942 2943 Qualifiers ToQuals = ToPointee.getQualifiers(); 2944 if (!ToPointee->isObjCLifetimeType() || 2945 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2946 !ToQuals.withoutObjCLifetime().empty()) 2947 return false; 2948 2949 // Argument must be a pointer to __strong to __weak. 2950 QualType FromPointee; 2951 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2952 FromPointee = FromPointer->getPointeeType(); 2953 else 2954 return false; 2955 2956 Qualifiers FromQuals = FromPointee.getQualifiers(); 2957 if (!FromPointee->isObjCLifetimeType() || 2958 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2959 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2960 return false; 2961 2962 // Make sure that we have compatible qualifiers. 2963 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2964 if (!ToQuals.compatiblyIncludes(FromQuals)) 2965 return false; 2966 2967 // Remove qualifiers from the pointee type we're converting from; they 2968 // aren't used in the compatibility check belong, and we'll be adding back 2969 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2970 FromPointee = FromPointee.getUnqualifiedType(); 2971 2972 // The unqualified form of the pointee types must be compatible. 2973 ToPointee = ToPointee.getUnqualifiedType(); 2974 bool IncompatibleObjC; 2975 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2976 FromPointee = ToPointee; 2977 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2978 IncompatibleObjC)) 2979 return false; 2980 2981 /// Construct the type we're converting to, which is a pointer to 2982 /// __autoreleasing pointee. 2983 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2984 ConvertedType = Context.getPointerType(FromPointee); 2985 return true; 2986 } 2987 2988 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2989 QualType& ConvertedType) { 2990 QualType ToPointeeType; 2991 if (const BlockPointerType *ToBlockPtr = 2992 ToType->getAs<BlockPointerType>()) 2993 ToPointeeType = ToBlockPtr->getPointeeType(); 2994 else 2995 return false; 2996 2997 QualType FromPointeeType; 2998 if (const BlockPointerType *FromBlockPtr = 2999 FromType->getAs<BlockPointerType>()) 3000 FromPointeeType = FromBlockPtr->getPointeeType(); 3001 else 3002 return false; 3003 // We have pointer to blocks, check whether the only 3004 // differences in the argument and result types are in Objective-C 3005 // pointer conversions. If so, we permit the conversion. 3006 3007 const FunctionProtoType *FromFunctionType 3008 = FromPointeeType->getAs<FunctionProtoType>(); 3009 const FunctionProtoType *ToFunctionType 3010 = ToPointeeType->getAs<FunctionProtoType>(); 3011 3012 if (!FromFunctionType || !ToFunctionType) 3013 return false; 3014 3015 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 3016 return true; 3017 3018 // Perform the quick checks that will tell us whether these 3019 // function types are obviously different. 3020 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 3021 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 3022 return false; 3023 3024 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 3025 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 3026 if (FromEInfo != ToEInfo) 3027 return false; 3028 3029 bool IncompatibleObjC = false; 3030 if (Context.hasSameType(FromFunctionType->getReturnType(), 3031 ToFunctionType->getReturnType())) { 3032 // Okay, the types match exactly. Nothing to do. 3033 } else { 3034 QualType RHS = FromFunctionType->getReturnType(); 3035 QualType LHS = ToFunctionType->getReturnType(); 3036 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 3037 !RHS.hasQualifiers() && LHS.hasQualifiers()) 3038 LHS = LHS.getUnqualifiedType(); 3039 3040 if (Context.hasSameType(RHS,LHS)) { 3041 // OK exact match. 3042 } else if (isObjCPointerConversion(RHS, LHS, 3043 ConvertedType, IncompatibleObjC)) { 3044 if (IncompatibleObjC) 3045 return false; 3046 // Okay, we have an Objective-C pointer conversion. 3047 } 3048 else 3049 return false; 3050 } 3051 3052 // Check argument types. 3053 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 3054 ArgIdx != NumArgs; ++ArgIdx) { 3055 IncompatibleObjC = false; 3056 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 3057 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 3058 if (Context.hasSameType(FromArgType, ToArgType)) { 3059 // Okay, the types match exactly. Nothing to do. 3060 } else if (isObjCPointerConversion(ToArgType, FromArgType, 3061 ConvertedType, IncompatibleObjC)) { 3062 if (IncompatibleObjC) 3063 return false; 3064 // Okay, we have an Objective-C pointer conversion. 3065 } else 3066 // Argument types are too different. Abort. 3067 return false; 3068 } 3069 3070 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 3071 bool CanUseToFPT, CanUseFromFPT; 3072 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 3073 CanUseToFPT, CanUseFromFPT, 3074 NewParamInfos)) 3075 return false; 3076 3077 ConvertedType = ToType; 3078 return true; 3079 } 3080 3081 enum { 3082 ft_default, 3083 ft_different_class, 3084 ft_parameter_arity, 3085 ft_parameter_mismatch, 3086 ft_return_type, 3087 ft_qualifer_mismatch, 3088 ft_noexcept 3089 }; 3090 3091 /// Attempts to get the FunctionProtoType from a Type. Handles 3092 /// MemberFunctionPointers properly. 3093 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 3094 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 3095 return FPT; 3096 3097 if (auto *MPT = FromType->getAs<MemberPointerType>()) 3098 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 3099 3100 return nullptr; 3101 } 3102 3103 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 3104 /// function types. Catches different number of parameter, mismatch in 3105 /// parameter types, and different return types. 3106 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3107 QualType FromType, QualType ToType) { 3108 // If either type is not valid, include no extra info. 3109 if (FromType.isNull() || ToType.isNull()) { 3110 PDiag << ft_default; 3111 return; 3112 } 3113 3114 // Get the function type from the pointers. 3115 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 3116 const auto *FromMember = FromType->castAs<MemberPointerType>(), 3117 *ToMember = ToType->castAs<MemberPointerType>(); 3118 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 3119 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 3120 << QualType(FromMember->getClass(), 0); 3121 return; 3122 } 3123 FromType = FromMember->getPointeeType(); 3124 ToType = ToMember->getPointeeType(); 3125 } 3126 3127 if (FromType->isPointerType()) 3128 FromType = FromType->getPointeeType(); 3129 if (ToType->isPointerType()) 3130 ToType = ToType->getPointeeType(); 3131 3132 // Remove references. 3133 FromType = FromType.getNonReferenceType(); 3134 ToType = ToType.getNonReferenceType(); 3135 3136 // Don't print extra info for non-specialized template functions. 3137 if (FromType->isInstantiationDependentType() && 3138 !FromType->getAs<TemplateSpecializationType>()) { 3139 PDiag << ft_default; 3140 return; 3141 } 3142 3143 // No extra info for same types. 3144 if (Context.hasSameType(FromType, ToType)) { 3145 PDiag << ft_default; 3146 return; 3147 } 3148 3149 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 3150 *ToFunction = tryGetFunctionProtoType(ToType); 3151 3152 // Both types need to be function types. 3153 if (!FromFunction || !ToFunction) { 3154 PDiag << ft_default; 3155 return; 3156 } 3157 3158 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 3159 PDiag << ft_parameter_arity << ToFunction->getNumParams() 3160 << FromFunction->getNumParams(); 3161 return; 3162 } 3163 3164 // Handle different parameter types. 3165 unsigned ArgPos; 3166 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 3167 PDiag << ft_parameter_mismatch << ArgPos + 1 3168 << ToFunction->getParamType(ArgPos) 3169 << FromFunction->getParamType(ArgPos); 3170 return; 3171 } 3172 3173 // Handle different return type. 3174 if (!Context.hasSameType(FromFunction->getReturnType(), 3175 ToFunction->getReturnType())) { 3176 PDiag << ft_return_type << ToFunction->getReturnType() 3177 << FromFunction->getReturnType(); 3178 return; 3179 } 3180 3181 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 3182 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 3183 << FromFunction->getMethodQuals(); 3184 return; 3185 } 3186 3187 // Handle exception specification differences on canonical type (in C++17 3188 // onwards). 3189 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 3190 ->isNothrow() != 3191 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 3192 ->isNothrow()) { 3193 PDiag << ft_noexcept; 3194 return; 3195 } 3196 3197 // Unable to find a difference, so add no extra info. 3198 PDiag << ft_default; 3199 } 3200 3201 /// FunctionParamTypesAreEqual - This routine checks two function proto types 3202 /// for equality of their parameter types. Caller has already checked that 3203 /// they have same number of parameters. If the parameters are different, 3204 /// ArgPos will have the parameter index of the first different parameter. 3205 /// If `Reversed` is true, the parameters of `NewType` will be compared in 3206 /// reverse order. That's useful if one of the functions is being used as a C++20 3207 /// synthesized operator overload with a reversed parameter order. 3208 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old, 3209 ArrayRef<QualType> New, unsigned *ArgPos, 3210 bool Reversed) { 3211 assert(llvm::size(Old) == llvm::size(New) && 3212 "Can't compare parameters of functions with different number of " 3213 "parameters!"); 3214 3215 for (auto &&[Idx, Type] : llvm::enumerate(Old)) { 3216 // Reverse iterate over the parameters of `OldType` if `Reversed` is true. 3217 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx; 3218 3219 // Ignore address spaces in pointee type. This is to disallow overloading 3220 // on __ptr32/__ptr64 address spaces. 3221 QualType OldType = 3222 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType()); 3223 QualType NewType = 3224 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType()); 3225 3226 if (!Context.hasSameType(OldType, NewType)) { 3227 if (ArgPos) 3228 *ArgPos = Idx; 3229 return false; 3230 } 3231 } 3232 return true; 3233 } 3234 3235 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3236 const FunctionProtoType *NewType, 3237 unsigned *ArgPos, bool Reversed) { 3238 return FunctionParamTypesAreEqual(OldType->param_types(), 3239 NewType->param_types(), ArgPos, Reversed); 3240 } 3241 3242 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, 3243 const FunctionDecl *NewFunction, 3244 unsigned *ArgPos, 3245 bool Reversed) { 3246 3247 if (OldFunction->getNumNonObjectParams() != 3248 NewFunction->getNumNonObjectParams()) 3249 return false; 3250 3251 unsigned OldIgnore = 3252 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter()); 3253 unsigned NewIgnore = 3254 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter()); 3255 3256 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType()); 3257 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType()); 3258 3259 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore), 3260 NewPT->param_types().slice(NewIgnore), 3261 ArgPos, Reversed); 3262 } 3263 3264 /// CheckPointerConversion - Check the pointer conversion from the 3265 /// expression From to the type ToType. This routine checks for 3266 /// ambiguous or inaccessible derived-to-base pointer 3267 /// conversions for which IsPointerConversion has already returned 3268 /// true. It returns true and produces a diagnostic if there was an 3269 /// error, or returns false otherwise. 3270 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 3271 CastKind &Kind, 3272 CXXCastPath& BasePath, 3273 bool IgnoreBaseAccess, 3274 bool Diagnose) { 3275 QualType FromType = From->getType(); 3276 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 3277 3278 Kind = CK_BitCast; 3279 3280 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 3281 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 3282 Expr::NPCK_ZeroExpression) { 3283 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 3284 DiagRuntimeBehavior(From->getExprLoc(), From, 3285 PDiag(diag::warn_impcast_bool_to_null_pointer) 3286 << ToType << From->getSourceRange()); 3287 else if (!isUnevaluatedContext()) 3288 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3289 << ToType << From->getSourceRange(); 3290 } 3291 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3292 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3293 QualType FromPointeeType = FromPtrType->getPointeeType(), 3294 ToPointeeType = ToPtrType->getPointeeType(); 3295 3296 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3297 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3298 // We must have a derived-to-base conversion. Check an 3299 // ambiguous or inaccessible conversion. 3300 unsigned InaccessibleID = 0; 3301 unsigned AmbiguousID = 0; 3302 if (Diagnose) { 3303 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3304 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3305 } 3306 if (CheckDerivedToBaseConversion( 3307 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3308 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3309 &BasePath, IgnoreBaseAccess)) 3310 return true; 3311 3312 // The conversion was successful. 3313 Kind = CK_DerivedToBase; 3314 } 3315 3316 if (Diagnose && !IsCStyleOrFunctionalCast && 3317 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3318 assert(getLangOpts().MSVCCompat && 3319 "this should only be possible with MSVCCompat!"); 3320 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3321 << From->getSourceRange(); 3322 } 3323 } 3324 } else if (const ObjCObjectPointerType *ToPtrType = 3325 ToType->getAs<ObjCObjectPointerType>()) { 3326 if (const ObjCObjectPointerType *FromPtrType = 3327 FromType->getAs<ObjCObjectPointerType>()) { 3328 // Objective-C++ conversions are always okay. 3329 // FIXME: We should have a different class of conversions for the 3330 // Objective-C++ implicit conversions. 3331 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3332 return false; 3333 } else if (FromType->isBlockPointerType()) { 3334 Kind = CK_BlockPointerToObjCPointerCast; 3335 } else { 3336 Kind = CK_CPointerToObjCPointerCast; 3337 } 3338 } else if (ToType->isBlockPointerType()) { 3339 if (!FromType->isBlockPointerType()) 3340 Kind = CK_AnyPointerToBlockPointerCast; 3341 } 3342 3343 // We shouldn't fall into this case unless it's valid for other 3344 // reasons. 3345 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3346 Kind = CK_NullToPointer; 3347 3348 return false; 3349 } 3350 3351 /// IsMemberPointerConversion - Determines whether the conversion of the 3352 /// expression From, which has the (possibly adjusted) type FromType, can be 3353 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3354 /// If so, returns true and places the converted type (that might differ from 3355 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3356 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3357 QualType ToType, 3358 bool InOverloadResolution, 3359 QualType &ConvertedType) { 3360 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3361 if (!ToTypePtr) 3362 return false; 3363 3364 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3365 if (From->isNullPointerConstant(Context, 3366 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3367 : Expr::NPC_ValueDependentIsNull)) { 3368 ConvertedType = ToType; 3369 return true; 3370 } 3371 3372 // Otherwise, both types have to be member pointers. 3373 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3374 if (!FromTypePtr) 3375 return false; 3376 3377 // A pointer to member of B can be converted to a pointer to member of D, 3378 // where D is derived from B (C++ 4.11p2). 3379 QualType FromClass(FromTypePtr->getClass(), 0); 3380 QualType ToClass(ToTypePtr->getClass(), 0); 3381 3382 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3383 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3384 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3385 ToClass.getTypePtr()); 3386 return true; 3387 } 3388 3389 return false; 3390 } 3391 3392 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3393 /// expression From to the type ToType. This routine checks for ambiguous or 3394 /// virtual or inaccessible base-to-derived member pointer conversions 3395 /// for which IsMemberPointerConversion has already returned true. It returns 3396 /// true and produces a diagnostic if there was an error, or returns false 3397 /// otherwise. 3398 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3399 CastKind &Kind, 3400 CXXCastPath &BasePath, 3401 bool IgnoreBaseAccess) { 3402 QualType FromType = From->getType(); 3403 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3404 if (!FromPtrType) { 3405 // This must be a null pointer to member pointer conversion 3406 assert(From->isNullPointerConstant(Context, 3407 Expr::NPC_ValueDependentIsNull) && 3408 "Expr must be null pointer constant!"); 3409 Kind = CK_NullToMemberPointer; 3410 return false; 3411 } 3412 3413 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3414 assert(ToPtrType && "No member pointer cast has a target type " 3415 "that is not a member pointer."); 3416 3417 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3418 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3419 3420 // FIXME: What about dependent types? 3421 assert(FromClass->isRecordType() && "Pointer into non-class."); 3422 assert(ToClass->isRecordType() && "Pointer into non-class."); 3423 3424 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3425 /*DetectVirtual=*/true); 3426 bool DerivationOkay = 3427 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3428 assert(DerivationOkay && 3429 "Should not have been called if derivation isn't OK."); 3430 (void)DerivationOkay; 3431 3432 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3433 getUnqualifiedType())) { 3434 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3435 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3436 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3437 return true; 3438 } 3439 3440 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3441 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3442 << FromClass << ToClass << QualType(VBase, 0) 3443 << From->getSourceRange(); 3444 return true; 3445 } 3446 3447 if (!IgnoreBaseAccess) 3448 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3449 Paths.front(), 3450 diag::err_downcast_from_inaccessible_base); 3451 3452 // Must be a base to derived member conversion. 3453 BuildBasePathArray(Paths, BasePath); 3454 Kind = CK_BaseToDerivedMemberPointer; 3455 return false; 3456 } 3457 3458 /// Determine whether the lifetime conversion between the two given 3459 /// qualifiers sets is nontrivial. 3460 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3461 Qualifiers ToQuals) { 3462 // Converting anything to const __unsafe_unretained is trivial. 3463 if (ToQuals.hasConst() && 3464 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3465 return false; 3466 3467 return true; 3468 } 3469 3470 /// Perform a single iteration of the loop for checking if a qualification 3471 /// conversion is valid. 3472 /// 3473 /// Specifically, check whether any change between the qualifiers of \p 3474 /// FromType and \p ToType is permissible, given knowledge about whether every 3475 /// outer layer is const-qualified. 3476 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3477 bool CStyle, bool IsTopLevel, 3478 bool &PreviousToQualsIncludeConst, 3479 bool &ObjCLifetimeConversion) { 3480 Qualifiers FromQuals = FromType.getQualifiers(); 3481 Qualifiers ToQuals = ToType.getQualifiers(); 3482 3483 // Ignore __unaligned qualifier. 3484 FromQuals.removeUnaligned(); 3485 3486 // Objective-C ARC: 3487 // Check Objective-C lifetime conversions. 3488 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3489 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3490 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3491 ObjCLifetimeConversion = true; 3492 FromQuals.removeObjCLifetime(); 3493 ToQuals.removeObjCLifetime(); 3494 } else { 3495 // Qualification conversions cannot cast between different 3496 // Objective-C lifetime qualifiers. 3497 return false; 3498 } 3499 } 3500 3501 // Allow addition/removal of GC attributes but not changing GC attributes. 3502 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3503 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3504 FromQuals.removeObjCGCAttr(); 3505 ToQuals.removeObjCGCAttr(); 3506 } 3507 3508 // -- for every j > 0, if const is in cv 1,j then const is in cv 3509 // 2,j, and similarly for volatile. 3510 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3511 return false; 3512 3513 // If address spaces mismatch: 3514 // - in top level it is only valid to convert to addr space that is a 3515 // superset in all cases apart from C-style casts where we allow 3516 // conversions between overlapping address spaces. 3517 // - in non-top levels it is not a valid conversion. 3518 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3519 (!IsTopLevel || 3520 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3521 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3522 return false; 3523 3524 // -- if the cv 1,j and cv 2,j are different, then const is in 3525 // every cv for 0 < k < j. 3526 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3527 !PreviousToQualsIncludeConst) 3528 return false; 3529 3530 // The following wording is from C++20, where the result of the conversion 3531 // is T3, not T2. 3532 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is 3533 // "array of unknown bound of" 3534 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType()) 3535 return false; 3536 3537 // -- if the resulting P3,i is different from P1,i [...], then const is 3538 // added to every cv 3_k for 0 < k < i. 3539 if (!CStyle && FromType->isConstantArrayType() && 3540 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst) 3541 return false; 3542 3543 // Keep track of whether all prior cv-qualifiers in the "to" type 3544 // include const. 3545 PreviousToQualsIncludeConst = 3546 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3547 return true; 3548 } 3549 3550 /// IsQualificationConversion - Determines whether the conversion from 3551 /// an rvalue of type FromType to ToType is a qualification conversion 3552 /// (C++ 4.4). 3553 /// 3554 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3555 /// when the qualification conversion involves a change in the Objective-C 3556 /// object lifetime. 3557 bool 3558 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3559 bool CStyle, bool &ObjCLifetimeConversion) { 3560 FromType = Context.getCanonicalType(FromType); 3561 ToType = Context.getCanonicalType(ToType); 3562 ObjCLifetimeConversion = false; 3563 3564 // If FromType and ToType are the same type, this is not a 3565 // qualification conversion. 3566 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3567 return false; 3568 3569 // (C++ 4.4p4): 3570 // A conversion can add cv-qualifiers at levels other than the first 3571 // in multi-level pointers, subject to the following rules: [...] 3572 bool PreviousToQualsIncludeConst = true; 3573 bool UnwrappedAnyPointer = false; 3574 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3575 if (!isQualificationConversionStep( 3576 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3577 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3578 return false; 3579 UnwrappedAnyPointer = true; 3580 } 3581 3582 // We are left with FromType and ToType being the pointee types 3583 // after unwrapping the original FromType and ToType the same number 3584 // of times. If we unwrapped any pointers, and if FromType and 3585 // ToType have the same unqualified type (since we checked 3586 // qualifiers above), then this is a qualification conversion. 3587 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3588 } 3589 3590 /// - Determine whether this is a conversion from a scalar type to an 3591 /// atomic type. 3592 /// 3593 /// If successful, updates \c SCS's second and third steps in the conversion 3594 /// sequence to finish the conversion. 3595 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3596 bool InOverloadResolution, 3597 StandardConversionSequence &SCS, 3598 bool CStyle) { 3599 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3600 if (!ToAtomic) 3601 return false; 3602 3603 StandardConversionSequence InnerSCS; 3604 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3605 InOverloadResolution, InnerSCS, 3606 CStyle, /*AllowObjCWritebackConversion=*/false)) 3607 return false; 3608 3609 SCS.Second = InnerSCS.Second; 3610 SCS.setToType(1, InnerSCS.getToType(1)); 3611 SCS.Third = InnerSCS.Third; 3612 SCS.QualificationIncludesObjCLifetime 3613 = InnerSCS.QualificationIncludesObjCLifetime; 3614 SCS.setToType(2, InnerSCS.getToType(2)); 3615 return true; 3616 } 3617 3618 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3619 CXXConstructorDecl *Constructor, 3620 QualType Type) { 3621 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3622 if (CtorType->getNumParams() > 0) { 3623 QualType FirstArg = CtorType->getParamType(0); 3624 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3625 return true; 3626 } 3627 return false; 3628 } 3629 3630 static OverloadingResult 3631 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3632 CXXRecordDecl *To, 3633 UserDefinedConversionSequence &User, 3634 OverloadCandidateSet &CandidateSet, 3635 bool AllowExplicit) { 3636 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3637 for (auto *D : S.LookupConstructors(To)) { 3638 auto Info = getConstructorInfo(D); 3639 if (!Info) 3640 continue; 3641 3642 bool Usable = !Info.Constructor->isInvalidDecl() && 3643 S.isInitListConstructor(Info.Constructor); 3644 if (Usable) { 3645 bool SuppressUserConversions = false; 3646 if (Info.ConstructorTmpl) 3647 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3648 /*ExplicitArgs*/ nullptr, From, 3649 CandidateSet, SuppressUserConversions, 3650 /*PartialOverloading*/ false, 3651 AllowExplicit); 3652 else 3653 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3654 CandidateSet, SuppressUserConversions, 3655 /*PartialOverloading*/ false, AllowExplicit); 3656 } 3657 } 3658 3659 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3660 3661 OverloadCandidateSet::iterator Best; 3662 switch (auto Result = 3663 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3664 case OR_Deleted: 3665 case OR_Success: { 3666 // Record the standard conversion we used and the conversion function. 3667 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3668 QualType ThisType = Constructor->getFunctionObjectParameterType(); 3669 // Initializer lists don't have conversions as such. 3670 User.Before.setAsIdentityConversion(); 3671 User.HadMultipleCandidates = HadMultipleCandidates; 3672 User.ConversionFunction = Constructor; 3673 User.FoundConversionFunction = Best->FoundDecl; 3674 User.After.setAsIdentityConversion(); 3675 User.After.setFromType(ThisType); 3676 User.After.setAllToTypes(ToType); 3677 return Result; 3678 } 3679 3680 case OR_No_Viable_Function: 3681 return OR_No_Viable_Function; 3682 case OR_Ambiguous: 3683 return OR_Ambiguous; 3684 } 3685 3686 llvm_unreachable("Invalid OverloadResult!"); 3687 } 3688 3689 /// Determines whether there is a user-defined conversion sequence 3690 /// (C++ [over.ics.user]) that converts expression From to the type 3691 /// ToType. If such a conversion exists, User will contain the 3692 /// user-defined conversion sequence that performs such a conversion 3693 /// and this routine will return true. Otherwise, this routine returns 3694 /// false and User is unspecified. 3695 /// 3696 /// \param AllowExplicit true if the conversion should consider C++0x 3697 /// "explicit" conversion functions as well as non-explicit conversion 3698 /// functions (C++0x [class.conv.fct]p2). 3699 /// 3700 /// \param AllowObjCConversionOnExplicit true if the conversion should 3701 /// allow an extra Objective-C pointer conversion on uses of explicit 3702 /// constructors. Requires \c AllowExplicit to also be set. 3703 static OverloadingResult 3704 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3705 UserDefinedConversionSequence &User, 3706 OverloadCandidateSet &CandidateSet, 3707 AllowedExplicit AllowExplicit, 3708 bool AllowObjCConversionOnExplicit) { 3709 assert(AllowExplicit != AllowedExplicit::None || 3710 !AllowObjCConversionOnExplicit); 3711 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3712 3713 // Whether we will only visit constructors. 3714 bool ConstructorsOnly = false; 3715 3716 // If the type we are conversion to is a class type, enumerate its 3717 // constructors. 3718 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3719 // C++ [over.match.ctor]p1: 3720 // When objects of class type are direct-initialized (8.5), or 3721 // copy-initialized from an expression of the same or a 3722 // derived class type (8.5), overload resolution selects the 3723 // constructor. [...] For copy-initialization, the candidate 3724 // functions are all the converting constructors (12.3.1) of 3725 // that class. The argument list is the expression-list within 3726 // the parentheses of the initializer. 3727 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3728 (From->getType()->getAs<RecordType>() && 3729 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3730 ConstructorsOnly = true; 3731 3732 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3733 // We're not going to find any constructors. 3734 } else if (CXXRecordDecl *ToRecordDecl 3735 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3736 3737 Expr **Args = &From; 3738 unsigned NumArgs = 1; 3739 bool ListInitializing = false; 3740 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3741 // But first, see if there is an init-list-constructor that will work. 3742 OverloadingResult Result = IsInitializerListConstructorConversion( 3743 S, From, ToType, ToRecordDecl, User, CandidateSet, 3744 AllowExplicit == AllowedExplicit::All); 3745 if (Result != OR_No_Viable_Function) 3746 return Result; 3747 // Never mind. 3748 CandidateSet.clear( 3749 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3750 3751 // If we're list-initializing, we pass the individual elements as 3752 // arguments, not the entire list. 3753 Args = InitList->getInits(); 3754 NumArgs = InitList->getNumInits(); 3755 ListInitializing = true; 3756 } 3757 3758 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3759 auto Info = getConstructorInfo(D); 3760 if (!Info) 3761 continue; 3762 3763 bool Usable = !Info.Constructor->isInvalidDecl(); 3764 if (!ListInitializing) 3765 Usable = Usable && Info.Constructor->isConvertingConstructor( 3766 /*AllowExplicit*/ true); 3767 if (Usable) { 3768 bool SuppressUserConversions = !ConstructorsOnly; 3769 // C++20 [over.best.ics.general]/4.5: 3770 // if the target is the first parameter of a constructor [of class 3771 // X] and the constructor [...] is a candidate by [...] the second 3772 // phase of [over.match.list] when the initializer list has exactly 3773 // one element that is itself an initializer list, [...] and the 3774 // conversion is to X or reference to cv X, user-defined conversion 3775 // sequences are not cnosidered. 3776 if (SuppressUserConversions && ListInitializing) { 3777 SuppressUserConversions = 3778 NumArgs == 1 && isa<InitListExpr>(Args[0]) && 3779 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor, 3780 ToType); 3781 } 3782 if (Info.ConstructorTmpl) 3783 S.AddTemplateOverloadCandidate( 3784 Info.ConstructorTmpl, Info.FoundDecl, 3785 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs), 3786 CandidateSet, SuppressUserConversions, 3787 /*PartialOverloading*/ false, 3788 AllowExplicit == AllowedExplicit::All); 3789 else 3790 // Allow one user-defined conversion when user specifies a 3791 // From->ToType conversion via an static cast (c-style, etc). 3792 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3793 llvm::ArrayRef(Args, NumArgs), CandidateSet, 3794 SuppressUserConversions, 3795 /*PartialOverloading*/ false, 3796 AllowExplicit == AllowedExplicit::All); 3797 } 3798 } 3799 } 3800 } 3801 3802 // Enumerate conversion functions, if we're allowed to. 3803 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3804 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3805 // No conversion functions from incomplete types. 3806 } else if (const RecordType *FromRecordType = 3807 From->getType()->getAs<RecordType>()) { 3808 if (CXXRecordDecl *FromRecordDecl 3809 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3810 // Add all of the conversion functions as candidates. 3811 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3812 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3813 DeclAccessPair FoundDecl = I.getPair(); 3814 NamedDecl *D = FoundDecl.getDecl(); 3815 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3816 if (isa<UsingShadowDecl>(D)) 3817 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3818 3819 CXXConversionDecl *Conv; 3820 FunctionTemplateDecl *ConvTemplate; 3821 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3822 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3823 else 3824 Conv = cast<CXXConversionDecl>(D); 3825 3826 if (ConvTemplate) 3827 S.AddTemplateConversionCandidate( 3828 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3829 CandidateSet, AllowObjCConversionOnExplicit, 3830 AllowExplicit != AllowedExplicit::None); 3831 else 3832 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3833 CandidateSet, AllowObjCConversionOnExplicit, 3834 AllowExplicit != AllowedExplicit::None); 3835 } 3836 } 3837 } 3838 3839 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3840 3841 OverloadCandidateSet::iterator Best; 3842 switch (auto Result = 3843 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3844 case OR_Success: 3845 case OR_Deleted: 3846 // Record the standard conversion we used and the conversion function. 3847 if (CXXConstructorDecl *Constructor 3848 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3849 // C++ [over.ics.user]p1: 3850 // If the user-defined conversion is specified by a 3851 // constructor (12.3.1), the initial standard conversion 3852 // sequence converts the source type to the type required by 3853 // the argument of the constructor. 3854 // 3855 if (isa<InitListExpr>(From)) { 3856 // Initializer lists don't have conversions as such. 3857 User.Before.setAsIdentityConversion(); 3858 } else { 3859 if (Best->Conversions[0].isEllipsis()) 3860 User.EllipsisConversion = true; 3861 else { 3862 User.Before = Best->Conversions[0].Standard; 3863 User.EllipsisConversion = false; 3864 } 3865 } 3866 User.HadMultipleCandidates = HadMultipleCandidates; 3867 User.ConversionFunction = Constructor; 3868 User.FoundConversionFunction = Best->FoundDecl; 3869 User.After.setAsIdentityConversion(); 3870 User.After.setFromType(Constructor->getFunctionObjectParameterType()); 3871 User.After.setAllToTypes(ToType); 3872 return Result; 3873 } 3874 if (CXXConversionDecl *Conversion 3875 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3876 // C++ [over.ics.user]p1: 3877 // 3878 // [...] If the user-defined conversion is specified by a 3879 // conversion function (12.3.2), the initial standard 3880 // conversion sequence converts the source type to the 3881 // implicit object parameter of the conversion function. 3882 User.Before = Best->Conversions[0].Standard; 3883 User.HadMultipleCandidates = HadMultipleCandidates; 3884 User.ConversionFunction = Conversion; 3885 User.FoundConversionFunction = Best->FoundDecl; 3886 User.EllipsisConversion = false; 3887 3888 // C++ [over.ics.user]p2: 3889 // The second standard conversion sequence converts the 3890 // result of the user-defined conversion to the target type 3891 // for the sequence. Since an implicit conversion sequence 3892 // is an initialization, the special rules for 3893 // initialization by user-defined conversion apply when 3894 // selecting the best user-defined conversion for a 3895 // user-defined conversion sequence (see 13.3.3 and 3896 // 13.3.3.1). 3897 User.After = Best->FinalConversion; 3898 return Result; 3899 } 3900 llvm_unreachable("Not a constructor or conversion function?"); 3901 3902 case OR_No_Viable_Function: 3903 return OR_No_Viable_Function; 3904 3905 case OR_Ambiguous: 3906 return OR_Ambiguous; 3907 } 3908 3909 llvm_unreachable("Invalid OverloadResult!"); 3910 } 3911 3912 bool 3913 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3914 ImplicitConversionSequence ICS; 3915 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3916 OverloadCandidateSet::CSK_Normal); 3917 OverloadingResult OvResult = 3918 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3919 CandidateSet, AllowedExplicit::None, false); 3920 3921 if (!(OvResult == OR_Ambiguous || 3922 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3923 return false; 3924 3925 auto Cands = CandidateSet.CompleteCandidates( 3926 *this, 3927 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3928 From); 3929 if (OvResult == OR_Ambiguous) 3930 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3931 << From->getType() << ToType << From->getSourceRange(); 3932 else { // OR_No_Viable_Function && !CandidateSet.empty() 3933 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3934 diag::err_typecheck_nonviable_condition_incomplete, 3935 From->getType(), From->getSourceRange())) 3936 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3937 << false << From->getType() << From->getSourceRange() << ToType; 3938 } 3939 3940 CandidateSet.NoteCandidates( 3941 *this, From, Cands); 3942 return true; 3943 } 3944 3945 // Helper for compareConversionFunctions that gets the FunctionType that the 3946 // conversion-operator return value 'points' to, or nullptr. 3947 static const FunctionType * 3948 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) { 3949 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>(); 3950 const PointerType *RetPtrTy = 3951 ConvFuncTy->getReturnType()->getAs<PointerType>(); 3952 3953 if (!RetPtrTy) 3954 return nullptr; 3955 3956 return RetPtrTy->getPointeeType()->getAs<FunctionType>(); 3957 } 3958 3959 /// Compare the user-defined conversion functions or constructors 3960 /// of two user-defined conversion sequences to determine whether any ordering 3961 /// is possible. 3962 static ImplicitConversionSequence::CompareKind 3963 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3964 FunctionDecl *Function2) { 3965 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3966 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2); 3967 if (!Conv1 || !Conv2) 3968 return ImplicitConversionSequence::Indistinguishable; 3969 3970 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda()) 3971 return ImplicitConversionSequence::Indistinguishable; 3972 3973 // Objective-C++: 3974 // If both conversion functions are implicitly-declared conversions from 3975 // a lambda closure type to a function pointer and a block pointer, 3976 // respectively, always prefer the conversion to a function pointer, 3977 // because the function pointer is more lightweight and is more likely 3978 // to keep code working. 3979 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) { 3980 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3981 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3982 if (Block1 != Block2) 3983 return Block1 ? ImplicitConversionSequence::Worse 3984 : ImplicitConversionSequence::Better; 3985 } 3986 3987 // In order to support multiple calling conventions for the lambda conversion 3988 // operator (such as when the free and member function calling convention is 3989 // different), prefer the 'free' mechanism, followed by the calling-convention 3990 // of operator(). The latter is in place to support the MSVC-like solution of 3991 // defining ALL of the possible conversions in regards to calling-convention. 3992 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1); 3993 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2); 3994 3995 if (Conv1FuncRet && Conv2FuncRet && 3996 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) { 3997 CallingConv Conv1CC = Conv1FuncRet->getCallConv(); 3998 CallingConv Conv2CC = Conv2FuncRet->getCallConv(); 3999 4000 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator(); 4001 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>(); 4002 4003 CallingConv CallOpCC = 4004 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 4005 CallingConv DefaultFree = S.Context.getDefaultCallingConvention( 4006 CallOpProto->isVariadic(), /*IsCXXMethod=*/false); 4007 CallingConv DefaultMember = S.Context.getDefaultCallingConvention( 4008 CallOpProto->isVariadic(), /*IsCXXMethod=*/true); 4009 4010 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC}; 4011 for (CallingConv CC : PrefOrder) { 4012 if (Conv1CC == CC) 4013 return ImplicitConversionSequence::Better; 4014 if (Conv2CC == CC) 4015 return ImplicitConversionSequence::Worse; 4016 } 4017 } 4018 4019 return ImplicitConversionSequence::Indistinguishable; 4020 } 4021 4022 static bool hasDeprecatedStringLiteralToCharPtrConversion( 4023 const ImplicitConversionSequence &ICS) { 4024 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 4025 (ICS.isUserDefined() && 4026 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 4027 } 4028 4029 /// CompareImplicitConversionSequences - Compare two implicit 4030 /// conversion sequences to determine whether one is better than the 4031 /// other or if they are indistinguishable (C++ 13.3.3.2). 4032 static ImplicitConversionSequence::CompareKind 4033 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 4034 const ImplicitConversionSequence& ICS1, 4035 const ImplicitConversionSequence& ICS2) 4036 { 4037 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 4038 // conversion sequences (as defined in 13.3.3.1) 4039 // -- a standard conversion sequence (13.3.3.1.1) is a better 4040 // conversion sequence than a user-defined conversion sequence or 4041 // an ellipsis conversion sequence, and 4042 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 4043 // conversion sequence than an ellipsis conversion sequence 4044 // (13.3.3.1.3). 4045 // 4046 // C++0x [over.best.ics]p10: 4047 // For the purpose of ranking implicit conversion sequences as 4048 // described in 13.3.3.2, the ambiguous conversion sequence is 4049 // treated as a user-defined sequence that is indistinguishable 4050 // from any other user-defined conversion sequence. 4051 4052 // String literal to 'char *' conversion has been deprecated in C++03. It has 4053 // been removed from C++11. We still accept this conversion, if it happens at 4054 // the best viable function. Otherwise, this conversion is considered worse 4055 // than ellipsis conversion. Consider this as an extension; this is not in the 4056 // standard. For example: 4057 // 4058 // int &f(...); // #1 4059 // void f(char*); // #2 4060 // void g() { int &r = f("foo"); } 4061 // 4062 // In C++03, we pick #2 as the best viable function. 4063 // In C++11, we pick #1 as the best viable function, because ellipsis 4064 // conversion is better than string-literal to char* conversion (since there 4065 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 4066 // convert arguments, #2 would be the best viable function in C++11. 4067 // If the best viable function has this conversion, a warning will be issued 4068 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 4069 4070 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 4071 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 4072 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) && 4073 // Ill-formedness must not differ 4074 ICS1.isBad() == ICS2.isBad()) 4075 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 4076 ? ImplicitConversionSequence::Worse 4077 : ImplicitConversionSequence::Better; 4078 4079 if (ICS1.getKindRank() < ICS2.getKindRank()) 4080 return ImplicitConversionSequence::Better; 4081 if (ICS2.getKindRank() < ICS1.getKindRank()) 4082 return ImplicitConversionSequence::Worse; 4083 4084 // The following checks require both conversion sequences to be of 4085 // the same kind. 4086 if (ICS1.getKind() != ICS2.getKind()) 4087 return ImplicitConversionSequence::Indistinguishable; 4088 4089 ImplicitConversionSequence::CompareKind Result = 4090 ImplicitConversionSequence::Indistinguishable; 4091 4092 // Two implicit conversion sequences of the same form are 4093 // indistinguishable conversion sequences unless one of the 4094 // following rules apply: (C++ 13.3.3.2p3): 4095 4096 // List-initialization sequence L1 is a better conversion sequence than 4097 // list-initialization sequence L2 if: 4098 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 4099 // if not that, 4100 // — L1 and L2 convert to arrays of the same element type, and either the 4101 // number of elements n_1 initialized by L1 is less than the number of 4102 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to 4103 // an array of unknown bound and L1 does not, 4104 // even if one of the other rules in this paragraph would otherwise apply. 4105 if (!ICS1.isBad()) { 4106 bool StdInit1 = false, StdInit2 = false; 4107 if (ICS1.hasInitializerListContainerType()) 4108 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(), 4109 nullptr); 4110 if (ICS2.hasInitializerListContainerType()) 4111 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(), 4112 nullptr); 4113 if (StdInit1 != StdInit2) 4114 return StdInit1 ? ImplicitConversionSequence::Better 4115 : ImplicitConversionSequence::Worse; 4116 4117 if (ICS1.hasInitializerListContainerType() && 4118 ICS2.hasInitializerListContainerType()) 4119 if (auto *CAT1 = S.Context.getAsConstantArrayType( 4120 ICS1.getInitializerListContainerType())) 4121 if (auto *CAT2 = S.Context.getAsConstantArrayType( 4122 ICS2.getInitializerListContainerType())) { 4123 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(), 4124 CAT2->getElementType())) { 4125 // Both to arrays of the same element type 4126 if (CAT1->getSize() != CAT2->getSize()) 4127 // Different sized, the smaller wins 4128 return CAT1->getSize().ult(CAT2->getSize()) 4129 ? ImplicitConversionSequence::Better 4130 : ImplicitConversionSequence::Worse; 4131 if (ICS1.isInitializerListOfIncompleteArray() != 4132 ICS2.isInitializerListOfIncompleteArray()) 4133 // One is incomplete, it loses 4134 return ICS2.isInitializerListOfIncompleteArray() 4135 ? ImplicitConversionSequence::Better 4136 : ImplicitConversionSequence::Worse; 4137 } 4138 } 4139 } 4140 4141 if (ICS1.isStandard()) 4142 // Standard conversion sequence S1 is a better conversion sequence than 4143 // standard conversion sequence S2 if [...] 4144 Result = CompareStandardConversionSequences(S, Loc, 4145 ICS1.Standard, ICS2.Standard); 4146 else if (ICS1.isUserDefined()) { 4147 // User-defined conversion sequence U1 is a better conversion 4148 // sequence than another user-defined conversion sequence U2 if 4149 // they contain the same user-defined conversion function or 4150 // constructor and if the second standard conversion sequence of 4151 // U1 is better than the second standard conversion sequence of 4152 // U2 (C++ 13.3.3.2p3). 4153 if (ICS1.UserDefined.ConversionFunction == 4154 ICS2.UserDefined.ConversionFunction) 4155 Result = CompareStandardConversionSequences(S, Loc, 4156 ICS1.UserDefined.After, 4157 ICS2.UserDefined.After); 4158 else 4159 Result = compareConversionFunctions(S, 4160 ICS1.UserDefined.ConversionFunction, 4161 ICS2.UserDefined.ConversionFunction); 4162 } 4163 4164 return Result; 4165 } 4166 4167 // Per 13.3.3.2p3, compare the given standard conversion sequences to 4168 // determine if one is a proper subset of the other. 4169 static ImplicitConversionSequence::CompareKind 4170 compareStandardConversionSubsets(ASTContext &Context, 4171 const StandardConversionSequence& SCS1, 4172 const StandardConversionSequence& SCS2) { 4173 ImplicitConversionSequence::CompareKind Result 4174 = ImplicitConversionSequence::Indistinguishable; 4175 4176 // the identity conversion sequence is considered to be a subsequence of 4177 // any non-identity conversion sequence 4178 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 4179 return ImplicitConversionSequence::Better; 4180 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 4181 return ImplicitConversionSequence::Worse; 4182 4183 if (SCS1.Second != SCS2.Second) { 4184 if (SCS1.Second == ICK_Identity) 4185 Result = ImplicitConversionSequence::Better; 4186 else if (SCS2.Second == ICK_Identity) 4187 Result = ImplicitConversionSequence::Worse; 4188 else 4189 return ImplicitConversionSequence::Indistinguishable; 4190 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 4191 return ImplicitConversionSequence::Indistinguishable; 4192 4193 if (SCS1.Third == SCS2.Third) { 4194 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 4195 : ImplicitConversionSequence::Indistinguishable; 4196 } 4197 4198 if (SCS1.Third == ICK_Identity) 4199 return Result == ImplicitConversionSequence::Worse 4200 ? ImplicitConversionSequence::Indistinguishable 4201 : ImplicitConversionSequence::Better; 4202 4203 if (SCS2.Third == ICK_Identity) 4204 return Result == ImplicitConversionSequence::Better 4205 ? ImplicitConversionSequence::Indistinguishable 4206 : ImplicitConversionSequence::Worse; 4207 4208 return ImplicitConversionSequence::Indistinguishable; 4209 } 4210 4211 /// Determine whether one of the given reference bindings is better 4212 /// than the other based on what kind of bindings they are. 4213 static bool 4214 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 4215 const StandardConversionSequence &SCS2) { 4216 // C++0x [over.ics.rank]p3b4: 4217 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 4218 // implicit object parameter of a non-static member function declared 4219 // without a ref-qualifier, and *either* S1 binds an rvalue reference 4220 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 4221 // lvalue reference to a function lvalue and S2 binds an rvalue 4222 // reference*. 4223 // 4224 // FIXME: Rvalue references. We're going rogue with the above edits, 4225 // because the semantics in the current C++0x working paper (N3225 at the 4226 // time of this writing) break the standard definition of std::forward 4227 // and std::reference_wrapper when dealing with references to functions. 4228 // Proposed wording changes submitted to CWG for consideration. 4229 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 4230 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 4231 return false; 4232 4233 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 4234 SCS2.IsLvalueReference) || 4235 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 4236 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 4237 } 4238 4239 enum class FixedEnumPromotion { 4240 None, 4241 ToUnderlyingType, 4242 ToPromotedUnderlyingType 4243 }; 4244 4245 /// Returns kind of fixed enum promotion the \a SCS uses. 4246 static FixedEnumPromotion 4247 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 4248 4249 if (SCS.Second != ICK_Integral_Promotion) 4250 return FixedEnumPromotion::None; 4251 4252 QualType FromType = SCS.getFromType(); 4253 if (!FromType->isEnumeralType()) 4254 return FixedEnumPromotion::None; 4255 4256 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl(); 4257 if (!Enum->isFixed()) 4258 return FixedEnumPromotion::None; 4259 4260 QualType UnderlyingType = Enum->getIntegerType(); 4261 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 4262 return FixedEnumPromotion::ToUnderlyingType; 4263 4264 return FixedEnumPromotion::ToPromotedUnderlyingType; 4265 } 4266 4267 /// CompareStandardConversionSequences - Compare two standard 4268 /// conversion sequences to determine whether one is better than the 4269 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 4270 static ImplicitConversionSequence::CompareKind 4271 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 4272 const StandardConversionSequence& SCS1, 4273 const StandardConversionSequence& SCS2) 4274 { 4275 // Standard conversion sequence S1 is a better conversion sequence 4276 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 4277 4278 // -- S1 is a proper subsequence of S2 (comparing the conversion 4279 // sequences in the canonical form defined by 13.3.3.1.1, 4280 // excluding any Lvalue Transformation; the identity conversion 4281 // sequence is considered to be a subsequence of any 4282 // non-identity conversion sequence) or, if not that, 4283 if (ImplicitConversionSequence::CompareKind CK 4284 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 4285 return CK; 4286 4287 // -- the rank of S1 is better than the rank of S2 (by the rules 4288 // defined below), or, if not that, 4289 ImplicitConversionRank Rank1 = SCS1.getRank(); 4290 ImplicitConversionRank Rank2 = SCS2.getRank(); 4291 if (Rank1 < Rank2) 4292 return ImplicitConversionSequence::Better; 4293 else if (Rank2 < Rank1) 4294 return ImplicitConversionSequence::Worse; 4295 4296 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 4297 // are indistinguishable unless one of the following rules 4298 // applies: 4299 4300 // A conversion that is not a conversion of a pointer, or 4301 // pointer to member, to bool is better than another conversion 4302 // that is such a conversion. 4303 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 4304 return SCS2.isPointerConversionToBool() 4305 ? ImplicitConversionSequence::Better 4306 : ImplicitConversionSequence::Worse; 4307 4308 // C++14 [over.ics.rank]p4b2: 4309 // This is retroactively applied to C++11 by CWG 1601. 4310 // 4311 // A conversion that promotes an enumeration whose underlying type is fixed 4312 // to its underlying type is better than one that promotes to the promoted 4313 // underlying type, if the two are different. 4314 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 4315 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 4316 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 4317 FEP1 != FEP2) 4318 return FEP1 == FixedEnumPromotion::ToUnderlyingType 4319 ? ImplicitConversionSequence::Better 4320 : ImplicitConversionSequence::Worse; 4321 4322 // C++ [over.ics.rank]p4b2: 4323 // 4324 // If class B is derived directly or indirectly from class A, 4325 // conversion of B* to A* is better than conversion of B* to 4326 // void*, and conversion of A* to void* is better than conversion 4327 // of B* to void*. 4328 bool SCS1ConvertsToVoid 4329 = SCS1.isPointerConversionToVoidPointer(S.Context); 4330 bool SCS2ConvertsToVoid 4331 = SCS2.isPointerConversionToVoidPointer(S.Context); 4332 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 4333 // Exactly one of the conversion sequences is a conversion to 4334 // a void pointer; it's the worse conversion. 4335 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 4336 : ImplicitConversionSequence::Worse; 4337 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 4338 // Neither conversion sequence converts to a void pointer; compare 4339 // their derived-to-base conversions. 4340 if (ImplicitConversionSequence::CompareKind DerivedCK 4341 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 4342 return DerivedCK; 4343 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 4344 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 4345 // Both conversion sequences are conversions to void 4346 // pointers. Compare the source types to determine if there's an 4347 // inheritance relationship in their sources. 4348 QualType FromType1 = SCS1.getFromType(); 4349 QualType FromType2 = SCS2.getFromType(); 4350 4351 // Adjust the types we're converting from via the array-to-pointer 4352 // conversion, if we need to. 4353 if (SCS1.First == ICK_Array_To_Pointer) 4354 FromType1 = S.Context.getArrayDecayedType(FromType1); 4355 if (SCS2.First == ICK_Array_To_Pointer) 4356 FromType2 = S.Context.getArrayDecayedType(FromType2); 4357 4358 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 4359 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 4360 4361 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4362 return ImplicitConversionSequence::Better; 4363 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4364 return ImplicitConversionSequence::Worse; 4365 4366 // Objective-C++: If one interface is more specific than the 4367 // other, it is the better one. 4368 const ObjCObjectPointerType* FromObjCPtr1 4369 = FromType1->getAs<ObjCObjectPointerType>(); 4370 const ObjCObjectPointerType* FromObjCPtr2 4371 = FromType2->getAs<ObjCObjectPointerType>(); 4372 if (FromObjCPtr1 && FromObjCPtr2) { 4373 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4374 FromObjCPtr2); 4375 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4376 FromObjCPtr1); 4377 if (AssignLeft != AssignRight) { 4378 return AssignLeft? ImplicitConversionSequence::Better 4379 : ImplicitConversionSequence::Worse; 4380 } 4381 } 4382 } 4383 4384 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4385 // Check for a better reference binding based on the kind of bindings. 4386 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4387 return ImplicitConversionSequence::Better; 4388 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4389 return ImplicitConversionSequence::Worse; 4390 } 4391 4392 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4393 // bullet 3). 4394 if (ImplicitConversionSequence::CompareKind QualCK 4395 = CompareQualificationConversions(S, SCS1, SCS2)) 4396 return QualCK; 4397 4398 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4399 // C++ [over.ics.rank]p3b4: 4400 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4401 // which the references refer are the same type except for 4402 // top-level cv-qualifiers, and the type to which the reference 4403 // initialized by S2 refers is more cv-qualified than the type 4404 // to which the reference initialized by S1 refers. 4405 QualType T1 = SCS1.getToType(2); 4406 QualType T2 = SCS2.getToType(2); 4407 T1 = S.Context.getCanonicalType(T1); 4408 T2 = S.Context.getCanonicalType(T2); 4409 Qualifiers T1Quals, T2Quals; 4410 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4411 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4412 if (UnqualT1 == UnqualT2) { 4413 // Objective-C++ ARC: If the references refer to objects with different 4414 // lifetimes, prefer bindings that don't change lifetime. 4415 if (SCS1.ObjCLifetimeConversionBinding != 4416 SCS2.ObjCLifetimeConversionBinding) { 4417 return SCS1.ObjCLifetimeConversionBinding 4418 ? ImplicitConversionSequence::Worse 4419 : ImplicitConversionSequence::Better; 4420 } 4421 4422 // If the type is an array type, promote the element qualifiers to the 4423 // type for comparison. 4424 if (isa<ArrayType>(T1) && T1Quals) 4425 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4426 if (isa<ArrayType>(T2) && T2Quals) 4427 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4428 if (T2.isMoreQualifiedThan(T1)) 4429 return ImplicitConversionSequence::Better; 4430 if (T1.isMoreQualifiedThan(T2)) 4431 return ImplicitConversionSequence::Worse; 4432 } 4433 } 4434 4435 // In Microsoft mode (below 19.28), prefer an integral conversion to a 4436 // floating-to-integral conversion if the integral conversion 4437 // is between types of the same size. 4438 // For example: 4439 // void f(float); 4440 // void f(int); 4441 // int main { 4442 // long a; 4443 // f(a); 4444 // } 4445 // Here, MSVC will call f(int) instead of generating a compile error 4446 // as clang will do in standard mode. 4447 if (S.getLangOpts().MSVCCompat && 4448 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) && 4449 SCS1.Second == ICK_Integral_Conversion && 4450 SCS2.Second == ICK_Floating_Integral && 4451 S.Context.getTypeSize(SCS1.getFromType()) == 4452 S.Context.getTypeSize(SCS1.getToType(2))) 4453 return ImplicitConversionSequence::Better; 4454 4455 // Prefer a compatible vector conversion over a lax vector conversion 4456 // For example: 4457 // 4458 // typedef float __v4sf __attribute__((__vector_size__(16))); 4459 // void f(vector float); 4460 // void f(vector signed int); 4461 // int main() { 4462 // __v4sf a; 4463 // f(a); 4464 // } 4465 // Here, we'd like to choose f(vector float) and not 4466 // report an ambiguous call error 4467 if (SCS1.Second == ICK_Vector_Conversion && 4468 SCS2.Second == ICK_Vector_Conversion) { 4469 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4470 SCS1.getFromType(), SCS1.getToType(2)); 4471 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4472 SCS2.getFromType(), SCS2.getToType(2)); 4473 4474 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4475 return SCS1IsCompatibleVectorConversion 4476 ? ImplicitConversionSequence::Better 4477 : ImplicitConversionSequence::Worse; 4478 } 4479 4480 if (SCS1.Second == ICK_SVE_Vector_Conversion && 4481 SCS2.Second == ICK_SVE_Vector_Conversion) { 4482 bool SCS1IsCompatibleSVEVectorConversion = 4483 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2)); 4484 bool SCS2IsCompatibleSVEVectorConversion = 4485 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2)); 4486 4487 if (SCS1IsCompatibleSVEVectorConversion != 4488 SCS2IsCompatibleSVEVectorConversion) 4489 return SCS1IsCompatibleSVEVectorConversion 4490 ? ImplicitConversionSequence::Better 4491 : ImplicitConversionSequence::Worse; 4492 } 4493 4494 if (SCS1.Second == ICK_RVV_Vector_Conversion && 4495 SCS2.Second == ICK_RVV_Vector_Conversion) { 4496 bool SCS1IsCompatibleRVVVectorConversion = 4497 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2)); 4498 bool SCS2IsCompatibleRVVVectorConversion = 4499 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2)); 4500 4501 if (SCS1IsCompatibleRVVVectorConversion != 4502 SCS2IsCompatibleRVVVectorConversion) 4503 return SCS1IsCompatibleRVVVectorConversion 4504 ? ImplicitConversionSequence::Better 4505 : ImplicitConversionSequence::Worse; 4506 } 4507 4508 return ImplicitConversionSequence::Indistinguishable; 4509 } 4510 4511 /// CompareQualificationConversions - Compares two standard conversion 4512 /// sequences to determine whether they can be ranked based on their 4513 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4514 static ImplicitConversionSequence::CompareKind 4515 CompareQualificationConversions(Sema &S, 4516 const StandardConversionSequence& SCS1, 4517 const StandardConversionSequence& SCS2) { 4518 // C++ [over.ics.rank]p3: 4519 // -- S1 and S2 differ only in their qualification conversion and 4520 // yield similar types T1 and T2 (C++ 4.4), respectively, [...] 4521 // [C++98] 4522 // [...] and the cv-qualification signature of type T1 is a proper subset 4523 // of the cv-qualification signature of type T2, and S1 is not the 4524 // deprecated string literal array-to-pointer conversion (4.2). 4525 // [C++2a] 4526 // [...] where T1 can be converted to T2 by a qualification conversion. 4527 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4528 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4529 return ImplicitConversionSequence::Indistinguishable; 4530 4531 // FIXME: the example in the standard doesn't use a qualification 4532 // conversion (!) 4533 QualType T1 = SCS1.getToType(2); 4534 QualType T2 = SCS2.getToType(2); 4535 T1 = S.Context.getCanonicalType(T1); 4536 T2 = S.Context.getCanonicalType(T2); 4537 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4538 Qualifiers T1Quals, T2Quals; 4539 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4540 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4541 4542 // If the types are the same, we won't learn anything by unwrapping 4543 // them. 4544 if (UnqualT1 == UnqualT2) 4545 return ImplicitConversionSequence::Indistinguishable; 4546 4547 // Don't ever prefer a standard conversion sequence that uses the deprecated 4548 // string literal array to pointer conversion. 4549 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr; 4550 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr; 4551 4552 // Objective-C++ ARC: 4553 // Prefer qualification conversions not involving a change in lifetime 4554 // to qualification conversions that do change lifetime. 4555 if (SCS1.QualificationIncludesObjCLifetime && 4556 !SCS2.QualificationIncludesObjCLifetime) 4557 CanPick1 = false; 4558 if (SCS2.QualificationIncludesObjCLifetime && 4559 !SCS1.QualificationIncludesObjCLifetime) 4560 CanPick2 = false; 4561 4562 bool ObjCLifetimeConversion; 4563 if (CanPick1 && 4564 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion)) 4565 CanPick1 = false; 4566 // FIXME: In Objective-C ARC, we can have qualification conversions in both 4567 // directions, so we can't short-cut this second check in general. 4568 if (CanPick2 && 4569 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion)) 4570 CanPick2 = false; 4571 4572 if (CanPick1 != CanPick2) 4573 return CanPick1 ? ImplicitConversionSequence::Better 4574 : ImplicitConversionSequence::Worse; 4575 return ImplicitConversionSequence::Indistinguishable; 4576 } 4577 4578 /// CompareDerivedToBaseConversions - Compares two standard conversion 4579 /// sequences to determine whether they can be ranked based on their 4580 /// various kinds of derived-to-base conversions (C++ 4581 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4582 /// conversions between Objective-C interface types. 4583 static ImplicitConversionSequence::CompareKind 4584 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4585 const StandardConversionSequence& SCS1, 4586 const StandardConversionSequence& SCS2) { 4587 QualType FromType1 = SCS1.getFromType(); 4588 QualType ToType1 = SCS1.getToType(1); 4589 QualType FromType2 = SCS2.getFromType(); 4590 QualType ToType2 = SCS2.getToType(1); 4591 4592 // Adjust the types we're converting from via the array-to-pointer 4593 // conversion, if we need to. 4594 if (SCS1.First == ICK_Array_To_Pointer) 4595 FromType1 = S.Context.getArrayDecayedType(FromType1); 4596 if (SCS2.First == ICK_Array_To_Pointer) 4597 FromType2 = S.Context.getArrayDecayedType(FromType2); 4598 4599 // Canonicalize all of the types. 4600 FromType1 = S.Context.getCanonicalType(FromType1); 4601 ToType1 = S.Context.getCanonicalType(ToType1); 4602 FromType2 = S.Context.getCanonicalType(FromType2); 4603 ToType2 = S.Context.getCanonicalType(ToType2); 4604 4605 // C++ [over.ics.rank]p4b3: 4606 // 4607 // If class B is derived directly or indirectly from class A and 4608 // class C is derived directly or indirectly from B, 4609 // 4610 // Compare based on pointer conversions. 4611 if (SCS1.Second == ICK_Pointer_Conversion && 4612 SCS2.Second == ICK_Pointer_Conversion && 4613 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4614 FromType1->isPointerType() && FromType2->isPointerType() && 4615 ToType1->isPointerType() && ToType2->isPointerType()) { 4616 QualType FromPointee1 = 4617 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4618 QualType ToPointee1 = 4619 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4620 QualType FromPointee2 = 4621 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4622 QualType ToPointee2 = 4623 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4624 4625 // -- conversion of C* to B* is better than conversion of C* to A*, 4626 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4627 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4628 return ImplicitConversionSequence::Better; 4629 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4630 return ImplicitConversionSequence::Worse; 4631 } 4632 4633 // -- conversion of B* to A* is better than conversion of C* to A*, 4634 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4635 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4636 return ImplicitConversionSequence::Better; 4637 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4638 return ImplicitConversionSequence::Worse; 4639 } 4640 } else if (SCS1.Second == ICK_Pointer_Conversion && 4641 SCS2.Second == ICK_Pointer_Conversion) { 4642 const ObjCObjectPointerType *FromPtr1 4643 = FromType1->getAs<ObjCObjectPointerType>(); 4644 const ObjCObjectPointerType *FromPtr2 4645 = FromType2->getAs<ObjCObjectPointerType>(); 4646 const ObjCObjectPointerType *ToPtr1 4647 = ToType1->getAs<ObjCObjectPointerType>(); 4648 const ObjCObjectPointerType *ToPtr2 4649 = ToType2->getAs<ObjCObjectPointerType>(); 4650 4651 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4652 // Apply the same conversion ranking rules for Objective-C pointer types 4653 // that we do for C++ pointers to class types. However, we employ the 4654 // Objective-C pseudo-subtyping relationship used for assignment of 4655 // Objective-C pointer types. 4656 bool FromAssignLeft 4657 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4658 bool FromAssignRight 4659 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4660 bool ToAssignLeft 4661 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4662 bool ToAssignRight 4663 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4664 4665 // A conversion to an a non-id object pointer type or qualified 'id' 4666 // type is better than a conversion to 'id'. 4667 if (ToPtr1->isObjCIdType() && 4668 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4669 return ImplicitConversionSequence::Worse; 4670 if (ToPtr2->isObjCIdType() && 4671 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4672 return ImplicitConversionSequence::Better; 4673 4674 // A conversion to a non-id object pointer type is better than a 4675 // conversion to a qualified 'id' type 4676 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4677 return ImplicitConversionSequence::Worse; 4678 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4679 return ImplicitConversionSequence::Better; 4680 4681 // A conversion to an a non-Class object pointer type or qualified 'Class' 4682 // type is better than a conversion to 'Class'. 4683 if (ToPtr1->isObjCClassType() && 4684 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4685 return ImplicitConversionSequence::Worse; 4686 if (ToPtr2->isObjCClassType() && 4687 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4688 return ImplicitConversionSequence::Better; 4689 4690 // A conversion to a non-Class object pointer type is better than a 4691 // conversion to a qualified 'Class' type. 4692 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4693 return ImplicitConversionSequence::Worse; 4694 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4695 return ImplicitConversionSequence::Better; 4696 4697 // -- "conversion of C* to B* is better than conversion of C* to A*," 4698 if (S.Context.hasSameType(FromType1, FromType2) && 4699 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4700 (ToAssignLeft != ToAssignRight)) { 4701 if (FromPtr1->isSpecialized()) { 4702 // "conversion of B<A> * to B * is better than conversion of B * to 4703 // C *. 4704 bool IsFirstSame = 4705 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4706 bool IsSecondSame = 4707 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4708 if (IsFirstSame) { 4709 if (!IsSecondSame) 4710 return ImplicitConversionSequence::Better; 4711 } else if (IsSecondSame) 4712 return ImplicitConversionSequence::Worse; 4713 } 4714 return ToAssignLeft? ImplicitConversionSequence::Worse 4715 : ImplicitConversionSequence::Better; 4716 } 4717 4718 // -- "conversion of B* to A* is better than conversion of C* to A*," 4719 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4720 (FromAssignLeft != FromAssignRight)) 4721 return FromAssignLeft? ImplicitConversionSequence::Better 4722 : ImplicitConversionSequence::Worse; 4723 } 4724 } 4725 4726 // Ranking of member-pointer types. 4727 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4728 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4729 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4730 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4731 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4732 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4733 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4734 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4735 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4736 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4737 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4738 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4739 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4740 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4741 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4742 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4743 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4744 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4745 return ImplicitConversionSequence::Worse; 4746 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4747 return ImplicitConversionSequence::Better; 4748 } 4749 // conversion of B::* to C::* is better than conversion of A::* to C::* 4750 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4751 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4752 return ImplicitConversionSequence::Better; 4753 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4754 return ImplicitConversionSequence::Worse; 4755 } 4756 } 4757 4758 if (SCS1.Second == ICK_Derived_To_Base) { 4759 // -- conversion of C to B is better than conversion of C to A, 4760 // -- binding of an expression of type C to a reference of type 4761 // B& is better than binding an expression of type C to a 4762 // reference of type A&, 4763 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4764 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4765 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4766 return ImplicitConversionSequence::Better; 4767 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4768 return ImplicitConversionSequence::Worse; 4769 } 4770 4771 // -- conversion of B to A is better than conversion of C to A. 4772 // -- binding of an expression of type B to a reference of type 4773 // A& is better than binding an expression of type C to a 4774 // reference of type A&, 4775 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4776 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4777 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4778 return ImplicitConversionSequence::Better; 4779 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4780 return ImplicitConversionSequence::Worse; 4781 } 4782 } 4783 4784 return ImplicitConversionSequence::Indistinguishable; 4785 } 4786 4787 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4788 if (!T.getQualifiers().hasUnaligned()) 4789 return T; 4790 4791 Qualifiers Q; 4792 T = Ctx.getUnqualifiedArrayType(T, Q); 4793 Q.removeUnaligned(); 4794 return Ctx.getQualifiedType(T, Q); 4795 } 4796 4797 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4798 /// determine whether they are reference-compatible, 4799 /// reference-related, or incompatible, for use in C++ initialization by 4800 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4801 /// type, and the first type (T1) is the pointee type of the reference 4802 /// type being initialized. 4803 Sema::ReferenceCompareResult 4804 Sema::CompareReferenceRelationship(SourceLocation Loc, 4805 QualType OrigT1, QualType OrigT2, 4806 ReferenceConversions *ConvOut) { 4807 assert(!OrigT1->isReferenceType() && 4808 "T1 must be the pointee type of the reference type"); 4809 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4810 4811 QualType T1 = Context.getCanonicalType(OrigT1); 4812 QualType T2 = Context.getCanonicalType(OrigT2); 4813 Qualifiers T1Quals, T2Quals; 4814 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4815 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4816 4817 ReferenceConversions ConvTmp; 4818 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4819 Conv = ReferenceConversions(); 4820 4821 // C++2a [dcl.init.ref]p4: 4822 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4823 // reference-related to "cv2 T2" if T1 is similar to T2, or 4824 // T1 is a base class of T2. 4825 // "cv1 T1" is reference-compatible with "cv2 T2" if 4826 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4827 // "pointer to cv1 T1" via a standard conversion sequence. 4828 4829 // Check for standard conversions we can apply to pointers: derived-to-base 4830 // conversions, ObjC pointer conversions, and function pointer conversions. 4831 // (Qualification conversions are checked last.) 4832 QualType ConvertedT2; 4833 if (UnqualT1 == UnqualT2) { 4834 // Nothing to do. 4835 } else if (isCompleteType(Loc, OrigT2) && 4836 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4837 Conv |= ReferenceConversions::DerivedToBase; 4838 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4839 UnqualT2->isObjCObjectOrInterfaceType() && 4840 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4841 Conv |= ReferenceConversions::ObjC; 4842 else if (UnqualT2->isFunctionType() && 4843 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4844 Conv |= ReferenceConversions::Function; 4845 // No need to check qualifiers; function types don't have them. 4846 return Ref_Compatible; 4847 } 4848 bool ConvertedReferent = Conv != 0; 4849 4850 // We can have a qualification conversion. Compute whether the types are 4851 // similar at the same time. 4852 bool PreviousToQualsIncludeConst = true; 4853 bool TopLevel = true; 4854 do { 4855 if (T1 == T2) 4856 break; 4857 4858 // We will need a qualification conversion. 4859 Conv |= ReferenceConversions::Qualification; 4860 4861 // Track whether we performed a qualification conversion anywhere other 4862 // than the top level. This matters for ranking reference bindings in 4863 // overload resolution. 4864 if (!TopLevel) 4865 Conv |= ReferenceConversions::NestedQualification; 4866 4867 // MS compiler ignores __unaligned qualifier for references; do the same. 4868 T1 = withoutUnaligned(Context, T1); 4869 T2 = withoutUnaligned(Context, T2); 4870 4871 // If we find a qualifier mismatch, the types are not reference-compatible, 4872 // but are still be reference-related if they're similar. 4873 bool ObjCLifetimeConversion = false; 4874 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4875 PreviousToQualsIncludeConst, 4876 ObjCLifetimeConversion)) 4877 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4878 ? Ref_Related 4879 : Ref_Incompatible; 4880 4881 // FIXME: Should we track this for any level other than the first? 4882 if (ObjCLifetimeConversion) 4883 Conv |= ReferenceConversions::ObjCLifetime; 4884 4885 TopLevel = false; 4886 } while (Context.UnwrapSimilarTypes(T1, T2)); 4887 4888 // At this point, if the types are reference-related, we must either have the 4889 // same inner type (ignoring qualifiers), or must have already worked out how 4890 // to convert the referent. 4891 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4892 ? Ref_Compatible 4893 : Ref_Incompatible; 4894 } 4895 4896 /// Look for a user-defined conversion to a value reference-compatible 4897 /// with DeclType. Return true if something definite is found. 4898 static bool 4899 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4900 QualType DeclType, SourceLocation DeclLoc, 4901 Expr *Init, QualType T2, bool AllowRvalues, 4902 bool AllowExplicit) { 4903 assert(T2->isRecordType() && "Can only find conversions of record types."); 4904 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4905 4906 OverloadCandidateSet CandidateSet( 4907 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4908 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4909 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4910 NamedDecl *D = *I; 4911 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4912 if (isa<UsingShadowDecl>(D)) 4913 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4914 4915 FunctionTemplateDecl *ConvTemplate 4916 = dyn_cast<FunctionTemplateDecl>(D); 4917 CXXConversionDecl *Conv; 4918 if (ConvTemplate) 4919 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4920 else 4921 Conv = cast<CXXConversionDecl>(D); 4922 4923 if (AllowRvalues) { 4924 // If we are initializing an rvalue reference, don't permit conversion 4925 // functions that return lvalues. 4926 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4927 const ReferenceType *RefType 4928 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4929 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4930 continue; 4931 } 4932 4933 if (!ConvTemplate && 4934 S.CompareReferenceRelationship( 4935 DeclLoc, 4936 Conv->getConversionType() 4937 .getNonReferenceType() 4938 .getUnqualifiedType(), 4939 DeclType.getNonReferenceType().getUnqualifiedType()) == 4940 Sema::Ref_Incompatible) 4941 continue; 4942 } else { 4943 // If the conversion function doesn't return a reference type, 4944 // it can't be considered for this conversion. An rvalue reference 4945 // is only acceptable if its referencee is a function type. 4946 4947 const ReferenceType *RefType = 4948 Conv->getConversionType()->getAs<ReferenceType>(); 4949 if (!RefType || 4950 (!RefType->isLValueReferenceType() && 4951 !RefType->getPointeeType()->isFunctionType())) 4952 continue; 4953 } 4954 4955 if (ConvTemplate) 4956 S.AddTemplateConversionCandidate( 4957 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4958 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4959 else 4960 S.AddConversionCandidate( 4961 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4962 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4963 } 4964 4965 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4966 4967 OverloadCandidateSet::iterator Best; 4968 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4969 case OR_Success: 4970 // C++ [over.ics.ref]p1: 4971 // 4972 // [...] If the parameter binds directly to the result of 4973 // applying a conversion function to the argument 4974 // expression, the implicit conversion sequence is a 4975 // user-defined conversion sequence (13.3.3.1.2), with the 4976 // second standard conversion sequence either an identity 4977 // conversion or, if the conversion function returns an 4978 // entity of a type that is a derived class of the parameter 4979 // type, a derived-to-base Conversion. 4980 if (!Best->FinalConversion.DirectBinding) 4981 return false; 4982 4983 ICS.setUserDefined(); 4984 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4985 ICS.UserDefined.After = Best->FinalConversion; 4986 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4987 ICS.UserDefined.ConversionFunction = Best->Function; 4988 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4989 ICS.UserDefined.EllipsisConversion = false; 4990 assert(ICS.UserDefined.After.ReferenceBinding && 4991 ICS.UserDefined.After.DirectBinding && 4992 "Expected a direct reference binding!"); 4993 return true; 4994 4995 case OR_Ambiguous: 4996 ICS.setAmbiguous(); 4997 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4998 Cand != CandidateSet.end(); ++Cand) 4999 if (Cand->Best) 5000 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 5001 return true; 5002 5003 case OR_No_Viable_Function: 5004 case OR_Deleted: 5005 // There was no suitable conversion, or we found a deleted 5006 // conversion; continue with other checks. 5007 return false; 5008 } 5009 5010 llvm_unreachable("Invalid OverloadResult!"); 5011 } 5012 5013 /// Compute an implicit conversion sequence for reference 5014 /// initialization. 5015 static ImplicitConversionSequence 5016 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 5017 SourceLocation DeclLoc, 5018 bool SuppressUserConversions, 5019 bool AllowExplicit) { 5020 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 5021 5022 // Most paths end in a failed conversion. 5023 ImplicitConversionSequence ICS; 5024 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5025 5026 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 5027 QualType T2 = Init->getType(); 5028 5029 // If the initializer is the address of an overloaded function, try 5030 // to resolve the overloaded function. If all goes well, T2 is the 5031 // type of the resulting function. 5032 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5033 DeclAccessPair Found; 5034 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 5035 false, Found)) 5036 T2 = Fn->getType(); 5037 } 5038 5039 // Compute some basic properties of the types and the initializer. 5040 bool isRValRef = DeclType->isRValueReferenceType(); 5041 Expr::Classification InitCategory = Init->Classify(S.Context); 5042 5043 Sema::ReferenceConversions RefConv; 5044 Sema::ReferenceCompareResult RefRelationship = 5045 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 5046 5047 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 5048 ICS.setStandard(); 5049 ICS.Standard.First = ICK_Identity; 5050 // FIXME: A reference binding can be a function conversion too. We should 5051 // consider that when ordering reference-to-function bindings. 5052 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 5053 ? ICK_Derived_To_Base 5054 : (RefConv & Sema::ReferenceConversions::ObjC) 5055 ? ICK_Compatible_Conversion 5056 : ICK_Identity; 5057 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 5058 // a reference binding that performs a non-top-level qualification 5059 // conversion as a qualification conversion, not as an identity conversion. 5060 ICS.Standard.Third = (RefConv & 5061 Sema::ReferenceConversions::NestedQualification) 5062 ? ICK_Qualification 5063 : ICK_Identity; 5064 ICS.Standard.setFromType(T2); 5065 ICS.Standard.setToType(0, T2); 5066 ICS.Standard.setToType(1, T1); 5067 ICS.Standard.setToType(2, T1); 5068 ICS.Standard.ReferenceBinding = true; 5069 ICS.Standard.DirectBinding = BindsDirectly; 5070 ICS.Standard.IsLvalueReference = !isRValRef; 5071 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 5072 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 5073 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5074 ICS.Standard.ObjCLifetimeConversionBinding = 5075 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 5076 ICS.Standard.CopyConstructor = nullptr; 5077 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 5078 }; 5079 5080 // C++0x [dcl.init.ref]p5: 5081 // A reference to type "cv1 T1" is initialized by an expression 5082 // of type "cv2 T2" as follows: 5083 5084 // -- If reference is an lvalue reference and the initializer expression 5085 if (!isRValRef) { 5086 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 5087 // reference-compatible with "cv2 T2," or 5088 // 5089 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 5090 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 5091 // C++ [over.ics.ref]p1: 5092 // When a parameter of reference type binds directly (8.5.3) 5093 // to an argument expression, the implicit conversion sequence 5094 // is the identity conversion, unless the argument expression 5095 // has a type that is a derived class of the parameter type, 5096 // in which case the implicit conversion sequence is a 5097 // derived-to-base Conversion (13.3.3.1). 5098 SetAsReferenceBinding(/*BindsDirectly=*/true); 5099 5100 // Nothing more to do: the inaccessibility/ambiguity check for 5101 // derived-to-base conversions is suppressed when we're 5102 // computing the implicit conversion sequence (C++ 5103 // [over.best.ics]p2). 5104 return ICS; 5105 } 5106 5107 // -- has a class type (i.e., T2 is a class type), where T1 is 5108 // not reference-related to T2, and can be implicitly 5109 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 5110 // is reference-compatible with "cv3 T3" 92) (this 5111 // conversion is selected by enumerating the applicable 5112 // conversion functions (13.3.1.6) and choosing the best 5113 // one through overload resolution (13.3)), 5114 if (!SuppressUserConversions && T2->isRecordType() && 5115 S.isCompleteType(DeclLoc, T2) && 5116 RefRelationship == Sema::Ref_Incompatible) { 5117 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 5118 Init, T2, /*AllowRvalues=*/false, 5119 AllowExplicit)) 5120 return ICS; 5121 } 5122 } 5123 5124 // -- Otherwise, the reference shall be an lvalue reference to a 5125 // non-volatile const type (i.e., cv1 shall be const), or the reference 5126 // shall be an rvalue reference. 5127 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) { 5128 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible) 5129 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 5130 return ICS; 5131 } 5132 5133 // -- If the initializer expression 5134 // 5135 // -- is an xvalue, class prvalue, array prvalue or function 5136 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 5137 if (RefRelationship == Sema::Ref_Compatible && 5138 (InitCategory.isXValue() || 5139 (InitCategory.isPRValue() && 5140 (T2->isRecordType() || T2->isArrayType())) || 5141 (InitCategory.isLValue() && T2->isFunctionType()))) { 5142 // In C++11, this is always a direct binding. In C++98/03, it's a direct 5143 // binding unless we're binding to a class prvalue. 5144 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 5145 // allow the use of rvalue references in C++98/03 for the benefit of 5146 // standard library implementors; therefore, we need the xvalue check here. 5147 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 5148 !(InitCategory.isPRValue() || T2->isRecordType())); 5149 return ICS; 5150 } 5151 5152 // -- has a class type (i.e., T2 is a class type), where T1 is not 5153 // reference-related to T2, and can be implicitly converted to 5154 // an xvalue, class prvalue, or function lvalue of type 5155 // "cv3 T3", where "cv1 T1" is reference-compatible with 5156 // "cv3 T3", 5157 // 5158 // then the reference is bound to the value of the initializer 5159 // expression in the first case and to the result of the conversion 5160 // in the second case (or, in either case, to an appropriate base 5161 // class subobject). 5162 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5163 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 5164 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 5165 Init, T2, /*AllowRvalues=*/true, 5166 AllowExplicit)) { 5167 // In the second case, if the reference is an rvalue reference 5168 // and the second standard conversion sequence of the 5169 // user-defined conversion sequence includes an lvalue-to-rvalue 5170 // conversion, the program is ill-formed. 5171 if (ICS.isUserDefined() && isRValRef && 5172 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 5173 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5174 5175 return ICS; 5176 } 5177 5178 // A temporary of function type cannot be created; don't even try. 5179 if (T1->isFunctionType()) 5180 return ICS; 5181 5182 // -- Otherwise, a temporary of type "cv1 T1" is created and 5183 // initialized from the initializer expression using the 5184 // rules for a non-reference copy initialization (8.5). The 5185 // reference is then bound to the temporary. If T1 is 5186 // reference-related to T2, cv1 must be the same 5187 // cv-qualification as, or greater cv-qualification than, 5188 // cv2; otherwise, the program is ill-formed. 5189 if (RefRelationship == Sema::Ref_Related) { 5190 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 5191 // we would be reference-compatible or reference-compatible with 5192 // added qualification. But that wasn't the case, so the reference 5193 // initialization fails. 5194 // 5195 // Note that we only want to check address spaces and cvr-qualifiers here. 5196 // ObjC GC, lifetime and unaligned qualifiers aren't important. 5197 Qualifiers T1Quals = T1.getQualifiers(); 5198 Qualifiers T2Quals = T2.getQualifiers(); 5199 T1Quals.removeObjCGCAttr(); 5200 T1Quals.removeObjCLifetime(); 5201 T2Quals.removeObjCGCAttr(); 5202 T2Quals.removeObjCLifetime(); 5203 // MS compiler ignores __unaligned qualifier for references; do the same. 5204 T1Quals.removeUnaligned(); 5205 T2Quals.removeUnaligned(); 5206 if (!T1Quals.compatiblyIncludes(T2Quals)) 5207 return ICS; 5208 } 5209 5210 // If at least one of the types is a class type, the types are not 5211 // related, and we aren't allowed any user conversions, the 5212 // reference binding fails. This case is important for breaking 5213 // recursion, since TryImplicitConversion below will attempt to 5214 // create a temporary through the use of a copy constructor. 5215 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 5216 (T1->isRecordType() || T2->isRecordType())) 5217 return ICS; 5218 5219 // If T1 is reference-related to T2 and the reference is an rvalue 5220 // reference, the initializer expression shall not be an lvalue. 5221 if (RefRelationship >= Sema::Ref_Related && isRValRef && 5222 Init->Classify(S.Context).isLValue()) { 5223 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType); 5224 return ICS; 5225 } 5226 5227 // C++ [over.ics.ref]p2: 5228 // When a parameter of reference type is not bound directly to 5229 // an argument expression, the conversion sequence is the one 5230 // required to convert the argument expression to the 5231 // underlying type of the reference according to 5232 // 13.3.3.1. Conceptually, this conversion sequence corresponds 5233 // to copy-initializing a temporary of the underlying type with 5234 // the argument expression. Any difference in top-level 5235 // cv-qualification is subsumed by the initialization itself 5236 // and does not constitute a conversion. 5237 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 5238 AllowedExplicit::None, 5239 /*InOverloadResolution=*/false, 5240 /*CStyle=*/false, 5241 /*AllowObjCWritebackConversion=*/false, 5242 /*AllowObjCConversionOnExplicit=*/false); 5243 5244 // Of course, that's still a reference binding. 5245 if (ICS.isStandard()) { 5246 ICS.Standard.ReferenceBinding = true; 5247 ICS.Standard.IsLvalueReference = !isRValRef; 5248 ICS.Standard.BindsToFunctionLvalue = false; 5249 ICS.Standard.BindsToRvalue = true; 5250 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5251 ICS.Standard.ObjCLifetimeConversionBinding = false; 5252 } else if (ICS.isUserDefined()) { 5253 const ReferenceType *LValRefType = 5254 ICS.UserDefined.ConversionFunction->getReturnType() 5255 ->getAs<LValueReferenceType>(); 5256 5257 // C++ [over.ics.ref]p3: 5258 // Except for an implicit object parameter, for which see 13.3.1, a 5259 // standard conversion sequence cannot be formed if it requires [...] 5260 // binding an rvalue reference to an lvalue other than a function 5261 // lvalue. 5262 // Note that the function case is not possible here. 5263 if (isRValRef && LValRefType) { 5264 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 5265 return ICS; 5266 } 5267 5268 ICS.UserDefined.After.ReferenceBinding = true; 5269 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 5270 ICS.UserDefined.After.BindsToFunctionLvalue = false; 5271 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 5272 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5273 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 5274 } 5275 5276 return ICS; 5277 } 5278 5279 static ImplicitConversionSequence 5280 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5281 bool SuppressUserConversions, 5282 bool InOverloadResolution, 5283 bool AllowObjCWritebackConversion, 5284 bool AllowExplicit = false); 5285 5286 /// TryListConversion - Try to copy-initialize a value of type ToType from the 5287 /// initializer list From. 5288 static ImplicitConversionSequence 5289 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 5290 bool SuppressUserConversions, 5291 bool InOverloadResolution, 5292 bool AllowObjCWritebackConversion) { 5293 // C++11 [over.ics.list]p1: 5294 // When an argument is an initializer list, it is not an expression and 5295 // special rules apply for converting it to a parameter type. 5296 5297 ImplicitConversionSequence Result; 5298 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 5299 5300 // We need a complete type for what follows. With one C++20 exception, 5301 // incomplete types can never be initialized from init lists. 5302 QualType InitTy = ToType; 5303 const ArrayType *AT = S.Context.getAsArrayType(ToType); 5304 if (AT && S.getLangOpts().CPlusPlus20) 5305 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) 5306 // C++20 allows list initialization of an incomplete array type. 5307 InitTy = IAT->getElementType(); 5308 if (!S.isCompleteType(From->getBeginLoc(), InitTy)) 5309 return Result; 5310 5311 // C++20 [over.ics.list]/2: 5312 // If the initializer list is a designated-initializer-list, a conversion 5313 // is only possible if the parameter has an aggregate type 5314 // 5315 // FIXME: The exception for reference initialization here is not part of the 5316 // language rules, but follow other compilers in adding it as a tentative DR 5317 // resolution. 5318 bool IsDesignatedInit = From->hasDesignatedInit(); 5319 if (!ToType->isAggregateType() && !ToType->isReferenceType() && 5320 IsDesignatedInit) 5321 return Result; 5322 5323 // Per DR1467: 5324 // If the parameter type is a class X and the initializer list has a single 5325 // element of type cv U, where U is X or a class derived from X, the 5326 // implicit conversion sequence is the one required to convert the element 5327 // to the parameter type. 5328 // 5329 // Otherwise, if the parameter type is a character array [... ] 5330 // and the initializer list has a single element that is an 5331 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 5332 // implicit conversion sequence is the identity conversion. 5333 if (From->getNumInits() == 1 && !IsDesignatedInit) { 5334 if (ToType->isRecordType()) { 5335 QualType InitType = From->getInit(0)->getType(); 5336 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 5337 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 5338 return TryCopyInitialization(S, From->getInit(0), ToType, 5339 SuppressUserConversions, 5340 InOverloadResolution, 5341 AllowObjCWritebackConversion); 5342 } 5343 5344 if (AT && S.IsStringInit(From->getInit(0), AT)) { 5345 InitializedEntity Entity = 5346 InitializedEntity::InitializeParameter(S.Context, ToType, 5347 /*Consumed=*/false); 5348 if (S.CanPerformCopyInitialization(Entity, From)) { 5349 Result.setStandard(); 5350 Result.Standard.setAsIdentityConversion(); 5351 Result.Standard.setFromType(ToType); 5352 Result.Standard.setAllToTypes(ToType); 5353 return Result; 5354 } 5355 } 5356 } 5357 5358 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 5359 // C++11 [over.ics.list]p2: 5360 // If the parameter type is std::initializer_list<X> or "array of X" and 5361 // all the elements can be implicitly converted to X, the implicit 5362 // conversion sequence is the worst conversion necessary to convert an 5363 // element of the list to X. 5364 // 5365 // C++14 [over.ics.list]p3: 5366 // Otherwise, if the parameter type is "array of N X", if the initializer 5367 // list has exactly N elements or if it has fewer than N elements and X is 5368 // default-constructible, and if all the elements of the initializer list 5369 // can be implicitly converted to X, the implicit conversion sequence is 5370 // the worst conversion necessary to convert an element of the list to X. 5371 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) { 5372 unsigned e = From->getNumInits(); 5373 ImplicitConversionSequence DfltElt; 5374 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(), 5375 QualType()); 5376 QualType ContTy = ToType; 5377 bool IsUnbounded = false; 5378 if (AT) { 5379 InitTy = AT->getElementType(); 5380 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) { 5381 if (CT->getSize().ult(e)) { 5382 // Too many inits, fatally bad 5383 Result.setBad(BadConversionSequence::too_many_initializers, From, 5384 ToType); 5385 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5386 return Result; 5387 } 5388 if (CT->getSize().ugt(e)) { 5389 // Need an init from empty {}, is there one? 5390 InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt, 5391 From->getEndLoc()); 5392 EmptyList.setType(S.Context.VoidTy); 5393 DfltElt = TryListConversion( 5394 S, &EmptyList, InitTy, SuppressUserConversions, 5395 InOverloadResolution, AllowObjCWritebackConversion); 5396 if (DfltElt.isBad()) { 5397 // No {} init, fatally bad 5398 Result.setBad(BadConversionSequence::too_few_initializers, From, 5399 ToType); 5400 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5401 return Result; 5402 } 5403 } 5404 } else { 5405 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array"); 5406 IsUnbounded = true; 5407 if (!e) { 5408 // Cannot convert to zero-sized. 5409 Result.setBad(BadConversionSequence::too_few_initializers, From, 5410 ToType); 5411 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5412 return Result; 5413 } 5414 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e); 5415 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr, 5416 ArraySizeModifier::Normal, 0); 5417 } 5418 } 5419 5420 Result.setStandard(); 5421 Result.Standard.setAsIdentityConversion(); 5422 Result.Standard.setFromType(InitTy); 5423 Result.Standard.setAllToTypes(InitTy); 5424 for (unsigned i = 0; i < e; ++i) { 5425 Expr *Init = From->getInit(i); 5426 ImplicitConversionSequence ICS = TryCopyInitialization( 5427 S, Init, InitTy, SuppressUserConversions, InOverloadResolution, 5428 AllowObjCWritebackConversion); 5429 5430 // Keep the worse conversion seen so far. 5431 // FIXME: Sequences are not totally ordered, so 'worse' can be 5432 // ambiguous. CWG has been informed. 5433 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS, 5434 Result) == 5435 ImplicitConversionSequence::Worse) { 5436 Result = ICS; 5437 // Bail as soon as we find something unconvertible. 5438 if (Result.isBad()) { 5439 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5440 return Result; 5441 } 5442 } 5443 } 5444 5445 // If we needed any implicit {} initialization, compare that now. 5446 // over.ics.list/6 indicates we should compare that conversion. Again CWG 5447 // has been informed that this might not be the best thing. 5448 if (!DfltElt.isBad() && CompareImplicitConversionSequences( 5449 S, From->getEndLoc(), DfltElt, Result) == 5450 ImplicitConversionSequence::Worse) 5451 Result = DfltElt; 5452 // Record the type being initialized so that we may compare sequences 5453 Result.setInitializerListContainerType(ContTy, IsUnbounded); 5454 return Result; 5455 } 5456 5457 // C++14 [over.ics.list]p4: 5458 // C++11 [over.ics.list]p3: 5459 // Otherwise, if the parameter is a non-aggregate class X and overload 5460 // resolution chooses a single best constructor [...] the implicit 5461 // conversion sequence is a user-defined conversion sequence. If multiple 5462 // constructors are viable but none is better than the others, the 5463 // implicit conversion sequence is a user-defined conversion sequence. 5464 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5465 // This function can deal with initializer lists. 5466 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5467 AllowedExplicit::None, 5468 InOverloadResolution, /*CStyle=*/false, 5469 AllowObjCWritebackConversion, 5470 /*AllowObjCConversionOnExplicit=*/false); 5471 } 5472 5473 // C++14 [over.ics.list]p5: 5474 // C++11 [over.ics.list]p4: 5475 // Otherwise, if the parameter has an aggregate type which can be 5476 // initialized from the initializer list [...] the implicit conversion 5477 // sequence is a user-defined conversion sequence. 5478 if (ToType->isAggregateType()) { 5479 // Type is an aggregate, argument is an init list. At this point it comes 5480 // down to checking whether the initialization works. 5481 // FIXME: Find out whether this parameter is consumed or not. 5482 InitializedEntity Entity = 5483 InitializedEntity::InitializeParameter(S.Context, ToType, 5484 /*Consumed=*/false); 5485 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5486 From)) { 5487 Result.setUserDefined(); 5488 Result.UserDefined.Before.setAsIdentityConversion(); 5489 // Initializer lists don't have a type. 5490 Result.UserDefined.Before.setFromType(QualType()); 5491 Result.UserDefined.Before.setAllToTypes(QualType()); 5492 5493 Result.UserDefined.After.setAsIdentityConversion(); 5494 Result.UserDefined.After.setFromType(ToType); 5495 Result.UserDefined.After.setAllToTypes(ToType); 5496 Result.UserDefined.ConversionFunction = nullptr; 5497 } 5498 return Result; 5499 } 5500 5501 // C++14 [over.ics.list]p6: 5502 // C++11 [over.ics.list]p5: 5503 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5504 if (ToType->isReferenceType()) { 5505 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5506 // mention initializer lists in any way. So we go by what list- 5507 // initialization would do and try to extrapolate from that. 5508 5509 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5510 5511 // If the initializer list has a single element that is reference-related 5512 // to the parameter type, we initialize the reference from that. 5513 if (From->getNumInits() == 1 && !IsDesignatedInit) { 5514 Expr *Init = From->getInit(0); 5515 5516 QualType T2 = Init->getType(); 5517 5518 // If the initializer is the address of an overloaded function, try 5519 // to resolve the overloaded function. If all goes well, T2 is the 5520 // type of the resulting function. 5521 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5522 DeclAccessPair Found; 5523 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5524 Init, ToType, false, Found)) 5525 T2 = Fn->getType(); 5526 } 5527 5528 // Compute some basic properties of the types and the initializer. 5529 Sema::ReferenceCompareResult RefRelationship = 5530 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5531 5532 if (RefRelationship >= Sema::Ref_Related) { 5533 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5534 SuppressUserConversions, 5535 /*AllowExplicit=*/false); 5536 } 5537 } 5538 5539 // Otherwise, we bind the reference to a temporary created from the 5540 // initializer list. 5541 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5542 InOverloadResolution, 5543 AllowObjCWritebackConversion); 5544 if (Result.isFailure()) 5545 return Result; 5546 assert(!Result.isEllipsis() && 5547 "Sub-initialization cannot result in ellipsis conversion."); 5548 5549 // Can we even bind to a temporary? 5550 if (ToType->isRValueReferenceType() || 5551 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5552 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5553 Result.UserDefined.After; 5554 SCS.ReferenceBinding = true; 5555 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5556 SCS.BindsToRvalue = true; 5557 SCS.BindsToFunctionLvalue = false; 5558 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5559 SCS.ObjCLifetimeConversionBinding = false; 5560 } else 5561 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5562 From, ToType); 5563 return Result; 5564 } 5565 5566 // C++14 [over.ics.list]p7: 5567 // C++11 [over.ics.list]p6: 5568 // Otherwise, if the parameter type is not a class: 5569 if (!ToType->isRecordType()) { 5570 // - if the initializer list has one element that is not itself an 5571 // initializer list, the implicit conversion sequence is the one 5572 // required to convert the element to the parameter type. 5573 unsigned NumInits = From->getNumInits(); 5574 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5575 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5576 SuppressUserConversions, 5577 InOverloadResolution, 5578 AllowObjCWritebackConversion); 5579 // - if the initializer list has no elements, the implicit conversion 5580 // sequence is the identity conversion. 5581 else if (NumInits == 0) { 5582 Result.setStandard(); 5583 Result.Standard.setAsIdentityConversion(); 5584 Result.Standard.setFromType(ToType); 5585 Result.Standard.setAllToTypes(ToType); 5586 } 5587 return Result; 5588 } 5589 5590 // C++14 [over.ics.list]p8: 5591 // C++11 [over.ics.list]p7: 5592 // In all cases other than those enumerated above, no conversion is possible 5593 return Result; 5594 } 5595 5596 /// TryCopyInitialization - Try to copy-initialize a value of type 5597 /// ToType from the expression From. Return the implicit conversion 5598 /// sequence required to pass this argument, which may be a bad 5599 /// conversion sequence (meaning that the argument cannot be passed to 5600 /// a parameter of this type). If @p SuppressUserConversions, then we 5601 /// do not permit any user-defined conversion sequences. 5602 static ImplicitConversionSequence 5603 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5604 bool SuppressUserConversions, 5605 bool InOverloadResolution, 5606 bool AllowObjCWritebackConversion, 5607 bool AllowExplicit) { 5608 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5609 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5610 InOverloadResolution,AllowObjCWritebackConversion); 5611 5612 if (ToType->isReferenceType()) 5613 return TryReferenceInit(S, From, ToType, 5614 /*FIXME:*/ From->getBeginLoc(), 5615 SuppressUserConversions, AllowExplicit); 5616 5617 return TryImplicitConversion(S, From, ToType, 5618 SuppressUserConversions, 5619 AllowedExplicit::None, 5620 InOverloadResolution, 5621 /*CStyle=*/false, 5622 AllowObjCWritebackConversion, 5623 /*AllowObjCConversionOnExplicit=*/false); 5624 } 5625 5626 static bool TryCopyInitialization(const CanQualType FromQTy, 5627 const CanQualType ToQTy, 5628 Sema &S, 5629 SourceLocation Loc, 5630 ExprValueKind FromVK) { 5631 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5632 ImplicitConversionSequence ICS = 5633 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5634 5635 return !ICS.isBad(); 5636 } 5637 5638 /// TryObjectArgumentInitialization - Try to initialize the object 5639 /// parameter of the given member function (@c Method) from the 5640 /// expression @p From. 5641 static ImplicitConversionSequence TryObjectArgumentInitialization( 5642 Sema &S, SourceLocation Loc, QualType FromType, 5643 Expr::Classification FromClassification, CXXMethodDecl *Method, 5644 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false, 5645 QualType ExplicitParameterType = QualType(), 5646 bool SuppressUserConversion = false) { 5647 5648 // We need to have an object of class type. 5649 if (const auto *PT = FromType->getAs<PointerType>()) { 5650 FromType = PT->getPointeeType(); 5651 5652 // When we had a pointer, it's implicitly dereferenced, so we 5653 // better have an lvalue. 5654 assert(FromClassification.isLValue()); 5655 } 5656 5657 auto ValueKindFromClassification = [](Expr::Classification C) { 5658 if (C.isPRValue()) 5659 return clang::VK_PRValue; 5660 if (C.isXValue()) 5661 return VK_XValue; 5662 return clang::VK_LValue; 5663 }; 5664 5665 if (Method->isExplicitObjectMemberFunction()) { 5666 if (ExplicitParameterType.isNull()) 5667 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType(); 5668 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(), 5669 ValueKindFromClassification(FromClassification)); 5670 ImplicitConversionSequence ICS = TryCopyInitialization( 5671 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion, 5672 /*InOverloadResolution=*/true, false); 5673 if (ICS.isBad()) 5674 ICS.Bad.FromExpr = nullptr; 5675 return ICS; 5676 } 5677 5678 assert(FromType->isRecordType()); 5679 5680 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5681 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5682 // const volatile object. 5683 Qualifiers Quals = Method->getMethodQualifiers(); 5684 if (isa<CXXDestructorDecl>(Method)) { 5685 Quals.addConst(); 5686 Quals.addVolatile(); 5687 } 5688 5689 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5690 5691 // Set up the conversion sequence as a "bad" conversion, to allow us 5692 // to exit early. 5693 ImplicitConversionSequence ICS; 5694 5695 // C++0x [over.match.funcs]p4: 5696 // For non-static member functions, the type of the implicit object 5697 // parameter is 5698 // 5699 // - "lvalue reference to cv X" for functions declared without a 5700 // ref-qualifier or with the & ref-qualifier 5701 // - "rvalue reference to cv X" for functions declared with the && 5702 // ref-qualifier 5703 // 5704 // where X is the class of which the function is a member and cv is the 5705 // cv-qualification on the member function declaration. 5706 // 5707 // However, when finding an implicit conversion sequence for the argument, we 5708 // are not allowed to perform user-defined conversions 5709 // (C++ [over.match.funcs]p5). We perform a simplified version of 5710 // reference binding here, that allows class rvalues to bind to 5711 // non-constant references. 5712 5713 // First check the qualifiers. 5714 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5715 // MSVC ignores __unaligned qualifier for overload candidates; do the same. 5716 if (ImplicitParamType.getCVRQualifiers() != 5717 FromTypeCanon.getLocalCVRQualifiers() && 5718 !ImplicitParamType.isAtLeastAsQualifiedAs( 5719 withoutUnaligned(S.Context, FromTypeCanon))) { 5720 ICS.setBad(BadConversionSequence::bad_qualifiers, 5721 FromType, ImplicitParamType); 5722 return ICS; 5723 } 5724 5725 if (FromTypeCanon.hasAddressSpace()) { 5726 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5727 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5728 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5729 ICS.setBad(BadConversionSequence::bad_qualifiers, 5730 FromType, ImplicitParamType); 5731 return ICS; 5732 } 5733 } 5734 5735 // Check that we have either the same type or a derived type. It 5736 // affects the conversion rank. 5737 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5738 ImplicitConversionKind SecondKind; 5739 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5740 SecondKind = ICK_Identity; 5741 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) { 5742 SecondKind = ICK_Derived_To_Base; 5743 } else if (!Method->isExplicitObjectMemberFunction()) { 5744 ICS.setBad(BadConversionSequence::unrelated_class, 5745 FromType, ImplicitParamType); 5746 return ICS; 5747 } 5748 5749 // Check the ref-qualifier. 5750 switch (Method->getRefQualifier()) { 5751 case RQ_None: 5752 // Do nothing; we don't care about lvalueness or rvalueness. 5753 break; 5754 5755 case RQ_LValue: 5756 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5757 // non-const lvalue reference cannot bind to an rvalue 5758 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5759 ImplicitParamType); 5760 return ICS; 5761 } 5762 break; 5763 5764 case RQ_RValue: 5765 if (!FromClassification.isRValue()) { 5766 // rvalue reference cannot bind to an lvalue 5767 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5768 ImplicitParamType); 5769 return ICS; 5770 } 5771 break; 5772 } 5773 5774 // Success. Mark this as a reference binding. 5775 ICS.setStandard(); 5776 ICS.Standard.setAsIdentityConversion(); 5777 ICS.Standard.Second = SecondKind; 5778 ICS.Standard.setFromType(FromType); 5779 ICS.Standard.setAllToTypes(ImplicitParamType); 5780 ICS.Standard.ReferenceBinding = true; 5781 ICS.Standard.DirectBinding = true; 5782 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5783 ICS.Standard.BindsToFunctionLvalue = false; 5784 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5785 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5786 = (Method->getRefQualifier() == RQ_None); 5787 return ICS; 5788 } 5789 5790 /// PerformObjectArgumentInitialization - Perform initialization of 5791 /// the implicit object parameter for the given Method with the given 5792 /// expression. 5793 ExprResult Sema::PerformImplicitObjectArgumentInitialization( 5794 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, 5795 CXXMethodDecl *Method) { 5796 QualType FromRecordType, DestType; 5797 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType(); 5798 5799 Expr::Classification FromClassification; 5800 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5801 FromRecordType = PT->getPointeeType(); 5802 DestType = Method->getThisType(); 5803 FromClassification = Expr::Classification::makeSimpleLValue(); 5804 } else { 5805 FromRecordType = From->getType(); 5806 DestType = ImplicitParamRecordType; 5807 FromClassification = From->Classify(Context); 5808 5809 // When performing member access on a prvalue, materialize a temporary. 5810 if (From->isPRValue()) { 5811 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5812 Method->getRefQualifier() != 5813 RefQualifierKind::RQ_RValue); 5814 } 5815 } 5816 5817 // Note that we always use the true parent context when performing 5818 // the actual argument initialization. 5819 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5820 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5821 Method->getParent()); 5822 if (ICS.isBad()) { 5823 switch (ICS.Bad.Kind) { 5824 case BadConversionSequence::bad_qualifiers: { 5825 Qualifiers FromQs = FromRecordType.getQualifiers(); 5826 Qualifiers ToQs = DestType.getQualifiers(); 5827 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5828 if (CVR) { 5829 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5830 << Method->getDeclName() << FromRecordType << (CVR - 1) 5831 << From->getSourceRange(); 5832 Diag(Method->getLocation(), diag::note_previous_decl) 5833 << Method->getDeclName(); 5834 return ExprError(); 5835 } 5836 break; 5837 } 5838 5839 case BadConversionSequence::lvalue_ref_to_rvalue: 5840 case BadConversionSequence::rvalue_ref_to_lvalue: { 5841 bool IsRValueQualified = 5842 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5843 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5844 << Method->getDeclName() << FromClassification.isRValue() 5845 << IsRValueQualified; 5846 Diag(Method->getLocation(), diag::note_previous_decl) 5847 << Method->getDeclName(); 5848 return ExprError(); 5849 } 5850 5851 case BadConversionSequence::no_conversion: 5852 case BadConversionSequence::unrelated_class: 5853 break; 5854 5855 case BadConversionSequence::too_few_initializers: 5856 case BadConversionSequence::too_many_initializers: 5857 llvm_unreachable("Lists are not objects"); 5858 } 5859 5860 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5861 << ImplicitParamRecordType << FromRecordType 5862 << From->getSourceRange(); 5863 } 5864 5865 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5866 ExprResult FromRes = 5867 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5868 if (FromRes.isInvalid()) 5869 return ExprError(); 5870 From = FromRes.get(); 5871 } 5872 5873 if (!Context.hasSameType(From->getType(), DestType)) { 5874 CastKind CK; 5875 QualType PteeTy = DestType->getPointeeType(); 5876 LangAS DestAS = 5877 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5878 if (FromRecordType.getAddressSpace() != DestAS) 5879 CK = CK_AddressSpaceConversion; 5880 else 5881 CK = CK_NoOp; 5882 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5883 } 5884 return From; 5885 } 5886 5887 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5888 /// expression From to bool (C++0x [conv]p3). 5889 static ImplicitConversionSequence 5890 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5891 // C++ [dcl.init]/17.8: 5892 // - Otherwise, if the initialization is direct-initialization, the source 5893 // type is std::nullptr_t, and the destination type is bool, the initial 5894 // value of the object being initialized is false. 5895 if (From->getType()->isNullPtrType()) 5896 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5897 S.Context.BoolTy, 5898 From->isGLValue()); 5899 5900 // All other direct-initialization of bool is equivalent to an implicit 5901 // conversion to bool in which explicit conversions are permitted. 5902 return TryImplicitConversion(S, From, S.Context.BoolTy, 5903 /*SuppressUserConversions=*/false, 5904 AllowedExplicit::Conversions, 5905 /*InOverloadResolution=*/false, 5906 /*CStyle=*/false, 5907 /*AllowObjCWritebackConversion=*/false, 5908 /*AllowObjCConversionOnExplicit=*/false); 5909 } 5910 5911 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5912 /// of the expression From to bool (C++0x [conv]p3). 5913 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5914 if (checkPlaceholderForOverload(*this, From)) 5915 return ExprError(); 5916 5917 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5918 if (!ICS.isBad()) 5919 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5920 5921 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5922 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5923 << From->getType() << From->getSourceRange(); 5924 return ExprError(); 5925 } 5926 5927 /// Check that the specified conversion is permitted in a converted constant 5928 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5929 /// is acceptable. 5930 static bool CheckConvertedConstantConversions(Sema &S, 5931 StandardConversionSequence &SCS) { 5932 // Since we know that the target type is an integral or unscoped enumeration 5933 // type, most conversion kinds are impossible. All possible First and Third 5934 // conversions are fine. 5935 switch (SCS.Second) { 5936 case ICK_Identity: 5937 case ICK_Integral_Promotion: 5938 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5939 case ICK_Zero_Queue_Conversion: 5940 return true; 5941 5942 case ICK_Boolean_Conversion: 5943 // Conversion from an integral or unscoped enumeration type to bool is 5944 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5945 // conversion, so we allow it in a converted constant expression. 5946 // 5947 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5948 // a lot of popular code. We should at least add a warning for this 5949 // (non-conforming) extension. 5950 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5951 SCS.getToType(2)->isBooleanType(); 5952 5953 case ICK_Pointer_Conversion: 5954 case ICK_Pointer_Member: 5955 // C++1z: null pointer conversions and null member pointer conversions are 5956 // only permitted if the source type is std::nullptr_t. 5957 return SCS.getFromType()->isNullPtrType(); 5958 5959 case ICK_Floating_Promotion: 5960 case ICK_Complex_Promotion: 5961 case ICK_Floating_Conversion: 5962 case ICK_Complex_Conversion: 5963 case ICK_Floating_Integral: 5964 case ICK_Compatible_Conversion: 5965 case ICK_Derived_To_Base: 5966 case ICK_Vector_Conversion: 5967 case ICK_SVE_Vector_Conversion: 5968 case ICK_RVV_Vector_Conversion: 5969 case ICK_Vector_Splat: 5970 case ICK_Complex_Real: 5971 case ICK_Block_Pointer_Conversion: 5972 case ICK_TransparentUnionConversion: 5973 case ICK_Writeback_Conversion: 5974 case ICK_Zero_Event_Conversion: 5975 case ICK_C_Only_Conversion: 5976 case ICK_Incompatible_Pointer_Conversion: 5977 case ICK_Fixed_Point_Conversion: 5978 return false; 5979 5980 case ICK_Lvalue_To_Rvalue: 5981 case ICK_Array_To_Pointer: 5982 case ICK_Function_To_Pointer: 5983 llvm_unreachable("found a first conversion kind in Second"); 5984 5985 case ICK_Function_Conversion: 5986 case ICK_Qualification: 5987 llvm_unreachable("found a third conversion kind in Second"); 5988 5989 case ICK_Num_Conversion_Kinds: 5990 break; 5991 } 5992 5993 llvm_unreachable("unknown conversion kind"); 5994 } 5995 5996 /// BuildConvertedConstantExpression - Check that the expression From is a 5997 /// converted constant expression of type T, perform the conversion but 5998 /// does not evaluate the expression 5999 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, 6000 QualType T, 6001 Sema::CCEKind CCE, 6002 NamedDecl *Dest, 6003 APValue &PreNarrowingValue) { 6004 assert(S.getLangOpts().CPlusPlus11 && 6005 "converted constant expression outside C++11"); 6006 6007 if (checkPlaceholderForOverload(S, From)) 6008 return ExprError(); 6009 6010 // C++1z [expr.const]p3: 6011 // A converted constant expression of type T is an expression, 6012 // implicitly converted to type T, where the converted 6013 // expression is a constant expression and the implicit conversion 6014 // sequence contains only [... list of conversions ...]. 6015 ImplicitConversionSequence ICS = 6016 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept) 6017 ? TryContextuallyConvertToBool(S, From) 6018 : TryCopyInitialization(S, From, T, 6019 /*SuppressUserConversions=*/false, 6020 /*InOverloadResolution=*/false, 6021 /*AllowObjCWritebackConversion=*/false, 6022 /*AllowExplicit=*/false); 6023 StandardConversionSequence *SCS = nullptr; 6024 switch (ICS.getKind()) { 6025 case ImplicitConversionSequence::StandardConversion: 6026 SCS = &ICS.Standard; 6027 break; 6028 case ImplicitConversionSequence::UserDefinedConversion: 6029 if (T->isRecordType()) 6030 SCS = &ICS.UserDefined.Before; 6031 else 6032 SCS = &ICS.UserDefined.After; 6033 break; 6034 case ImplicitConversionSequence::AmbiguousConversion: 6035 case ImplicitConversionSequence::BadConversion: 6036 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 6037 return S.Diag(From->getBeginLoc(), 6038 diag::err_typecheck_converted_constant_expression) 6039 << From->getType() << From->getSourceRange() << T; 6040 return ExprError(); 6041 6042 case ImplicitConversionSequence::EllipsisConversion: 6043 case ImplicitConversionSequence::StaticObjectArgumentConversion: 6044 llvm_unreachable("bad conversion in converted constant expression"); 6045 } 6046 6047 // Check that we would only use permitted conversions. 6048 if (!CheckConvertedConstantConversions(S, *SCS)) { 6049 return S.Diag(From->getBeginLoc(), 6050 diag::err_typecheck_converted_constant_expression_disallowed) 6051 << From->getType() << From->getSourceRange() << T; 6052 } 6053 // [...] and where the reference binding (if any) binds directly. 6054 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 6055 return S.Diag(From->getBeginLoc(), 6056 diag::err_typecheck_converted_constant_expression_indirect) 6057 << From->getType() << From->getSourceRange() << T; 6058 } 6059 // 'TryCopyInitialization' returns incorrect info for attempts to bind 6060 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely, 6061 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not 6062 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this 6063 // case explicitly. 6064 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) { 6065 return S.Diag(From->getBeginLoc(), 6066 diag::err_reference_bind_to_bitfield_in_cce) 6067 << From->getSourceRange(); 6068 } 6069 6070 // Usually we can simply apply the ImplicitConversionSequence we formed 6071 // earlier, but that's not guaranteed to work when initializing an object of 6072 // class type. 6073 ExprResult Result; 6074 if (T->isRecordType()) { 6075 assert(CCE == Sema::CCEK_TemplateArg && 6076 "unexpected class type converted constant expr"); 6077 Result = S.PerformCopyInitialization( 6078 InitializedEntity::InitializeTemplateParameter( 6079 T, cast<NonTypeTemplateParmDecl>(Dest)), 6080 SourceLocation(), From); 6081 } else { 6082 Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 6083 } 6084 if (Result.isInvalid()) 6085 return Result; 6086 6087 // C++2a [intro.execution]p5: 6088 // A full-expression is [...] a constant-expression [...] 6089 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 6090 /*DiscardedValue=*/false, /*IsConstexpr=*/true, 6091 CCE == Sema::CCEKind::CCEK_TemplateArg); 6092 if (Result.isInvalid()) 6093 return Result; 6094 6095 // Check for a narrowing implicit conversion. 6096 bool ReturnPreNarrowingValue = false; 6097 QualType PreNarrowingType; 6098 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 6099 PreNarrowingType)) { 6100 case NK_Dependent_Narrowing: 6101 // Implicit conversion to a narrower type, but the expression is 6102 // value-dependent so we can't tell whether it's actually narrowing. 6103 case NK_Variable_Narrowing: 6104 // Implicit conversion to a narrower type, and the value is not a constant 6105 // expression. We'll diagnose this in a moment. 6106 case NK_Not_Narrowing: 6107 break; 6108 6109 case NK_Constant_Narrowing: 6110 if (CCE == Sema::CCEK_ArrayBound && 6111 PreNarrowingType->isIntegralOrEnumerationType() && 6112 PreNarrowingValue.isInt()) { 6113 // Don't diagnose array bound narrowing here; we produce more precise 6114 // errors by allowing the un-narrowed value through. 6115 ReturnPreNarrowingValue = true; 6116 break; 6117 } 6118 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 6119 << CCE << /*Constant*/ 1 6120 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 6121 break; 6122 6123 case NK_Type_Narrowing: 6124 // FIXME: It would be better to diagnose that the expression is not a 6125 // constant expression. 6126 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 6127 << CCE << /*Constant*/ 0 << From->getType() << T; 6128 break; 6129 } 6130 if (!ReturnPreNarrowingValue) 6131 PreNarrowingValue = {}; 6132 6133 return Result; 6134 } 6135 6136 /// CheckConvertedConstantExpression - Check that the expression From is a 6137 /// converted constant expression of type T, perform the conversion and produce 6138 /// the converted expression, per C++11 [expr.const]p3. 6139 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 6140 QualType T, APValue &Value, 6141 Sema::CCEKind CCE, 6142 bool RequireInt, 6143 NamedDecl *Dest) { 6144 6145 APValue PreNarrowingValue; 6146 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest, 6147 PreNarrowingValue); 6148 if (Result.isInvalid() || Result.get()->isValueDependent()) { 6149 Value = APValue(); 6150 return Result; 6151 } 6152 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE, 6153 RequireInt, PreNarrowingValue); 6154 } 6155 6156 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T, 6157 CCEKind CCE, 6158 NamedDecl *Dest) { 6159 APValue PreNarrowingValue; 6160 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest, 6161 PreNarrowingValue); 6162 } 6163 6164 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 6165 APValue &Value, CCEKind CCE, 6166 NamedDecl *Dest) { 6167 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false, 6168 Dest); 6169 } 6170 6171 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 6172 llvm::APSInt &Value, 6173 CCEKind CCE) { 6174 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 6175 6176 APValue V; 6177 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true, 6178 /*Dest=*/nullptr); 6179 if (!R.isInvalid() && !R.get()->isValueDependent()) 6180 Value = V.getInt(); 6181 return R; 6182 } 6183 6184 /// EvaluateConvertedConstantExpression - Evaluate an Expression 6185 /// That is a converted constant expression 6186 /// (which was built with BuildConvertedConstantExpression) 6187 ExprResult 6188 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, 6189 Sema::CCEKind CCE, bool RequireInt, 6190 const APValue &PreNarrowingValue) { 6191 6192 ExprResult Result = E; 6193 // Check the expression is a constant expression. 6194 SmallVector<PartialDiagnosticAt, 8> Notes; 6195 Expr::EvalResult Eval; 6196 Eval.Diag = &Notes; 6197 6198 ConstantExprKind Kind; 6199 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType()) 6200 Kind = ConstantExprKind::ClassTemplateArgument; 6201 else if (CCE == Sema::CCEK_TemplateArg) 6202 Kind = ConstantExprKind::NonClassTemplateArgument; 6203 else 6204 Kind = ConstantExprKind::Normal; 6205 6206 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) || 6207 (RequireInt && !Eval.Val.isInt())) { 6208 // The expression can't be folded, so we can't keep it at this position in 6209 // the AST. 6210 Result = ExprError(); 6211 } else { 6212 Value = Eval.Val; 6213 6214 if (Notes.empty()) { 6215 // It's a constant expression. 6216 Expr *E = ConstantExpr::Create(Context, Result.get(), Value); 6217 if (!PreNarrowingValue.isAbsent()) 6218 Value = std::move(PreNarrowingValue); 6219 return E; 6220 } 6221 } 6222 6223 // It's not a constant expression. Produce an appropriate diagnostic. 6224 if (Notes.size() == 1 && 6225 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) { 6226 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 6227 } else if (!Notes.empty() && Notes[0].second.getDiagID() == 6228 diag::note_constexpr_invalid_template_arg) { 6229 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg); 6230 for (unsigned I = 0; I < Notes.size(); ++I) 6231 Diag(Notes[I].first, Notes[I].second); 6232 } else { 6233 Diag(E->getBeginLoc(), diag::err_expr_not_cce) 6234 << CCE << E->getSourceRange(); 6235 for (unsigned I = 0; I < Notes.size(); ++I) 6236 Diag(Notes[I].first, Notes[I].second); 6237 } 6238 return ExprError(); 6239 } 6240 6241 /// dropPointerConversions - If the given standard conversion sequence 6242 /// involves any pointer conversions, remove them. This may change 6243 /// the result type of the conversion sequence. 6244 static void dropPointerConversion(StandardConversionSequence &SCS) { 6245 if (SCS.Second == ICK_Pointer_Conversion) { 6246 SCS.Second = ICK_Identity; 6247 SCS.Third = ICK_Identity; 6248 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 6249 } 6250 } 6251 6252 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 6253 /// convert the expression From to an Objective-C pointer type. 6254 static ImplicitConversionSequence 6255 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 6256 // Do an implicit conversion to 'id'. 6257 QualType Ty = S.Context.getObjCIdType(); 6258 ImplicitConversionSequence ICS 6259 = TryImplicitConversion(S, From, Ty, 6260 // FIXME: Are these flags correct? 6261 /*SuppressUserConversions=*/false, 6262 AllowedExplicit::Conversions, 6263 /*InOverloadResolution=*/false, 6264 /*CStyle=*/false, 6265 /*AllowObjCWritebackConversion=*/false, 6266 /*AllowObjCConversionOnExplicit=*/true); 6267 6268 // Strip off any final conversions to 'id'. 6269 switch (ICS.getKind()) { 6270 case ImplicitConversionSequence::BadConversion: 6271 case ImplicitConversionSequence::AmbiguousConversion: 6272 case ImplicitConversionSequence::EllipsisConversion: 6273 case ImplicitConversionSequence::StaticObjectArgumentConversion: 6274 break; 6275 6276 case ImplicitConversionSequence::UserDefinedConversion: 6277 dropPointerConversion(ICS.UserDefined.After); 6278 break; 6279 6280 case ImplicitConversionSequence::StandardConversion: 6281 dropPointerConversion(ICS.Standard); 6282 break; 6283 } 6284 6285 return ICS; 6286 } 6287 6288 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 6289 /// conversion of the expression From to an Objective-C pointer type. 6290 /// Returns a valid but null ExprResult if no conversion sequence exists. 6291 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 6292 if (checkPlaceholderForOverload(*this, From)) 6293 return ExprError(); 6294 6295 QualType Ty = Context.getObjCIdType(); 6296 ImplicitConversionSequence ICS = 6297 TryContextuallyConvertToObjCPointer(*this, From); 6298 if (!ICS.isBad()) 6299 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 6300 return ExprResult(); 6301 } 6302 6303 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) { 6304 const Expr *Base = nullptr; 6305 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) && 6306 "expected a member expression"); 6307 6308 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE); 6309 M && !M->isImplicitAccess()) 6310 Base = M->getBase(); 6311 else if (const auto M = dyn_cast<MemberExpr>(MemExprE); 6312 M && !M->isImplicitAccess()) 6313 Base = M->getBase(); 6314 6315 QualType T = Base ? Base->getType() : S.getCurrentThisType(); 6316 6317 if (T->isPointerType()) 6318 T = T->getPointeeType(); 6319 6320 return T; 6321 } 6322 6323 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj, 6324 const FunctionDecl *Fun) { 6325 QualType ObjType = Obj->getType(); 6326 if (ObjType->isPointerType()) { 6327 ObjType = ObjType->getPointeeType(); 6328 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType, 6329 VK_LValue, OK_Ordinary, SourceLocation(), 6330 /*CanOverflow=*/false, FPOptionsOverride()); 6331 } 6332 if (Obj->Classify(S.getASTContext()).isPRValue()) { 6333 Obj = S.CreateMaterializeTemporaryExpr( 6334 ObjType, Obj, 6335 !Fun->getParamDecl(0)->getType()->isRValueReferenceType()); 6336 } 6337 return Obj; 6338 } 6339 6340 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj, 6341 FunctionDecl *Fun) { 6342 Obj = GetExplicitObjectExpr(S, Obj, Fun); 6343 return S.PerformCopyInitialization( 6344 InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)), 6345 Obj->getExprLoc(), Obj); 6346 } 6347 6348 static void PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, 6349 Expr *Object, MultiExprArg &Args, 6350 SmallVectorImpl<Expr *> &NewArgs) { 6351 assert(Method->isExplicitObjectMemberFunction() && 6352 "Method is not an explicit member function"); 6353 assert(NewArgs.empty() && "NewArgs should be empty"); 6354 NewArgs.reserve(Args.size() + 1); 6355 Expr *This = GetExplicitObjectExpr(S, Object, Method); 6356 NewArgs.push_back(This); 6357 NewArgs.append(Args.begin(), Args.end()); 6358 Args = NewArgs; 6359 } 6360 6361 /// Determine whether the provided type is an integral type, or an enumeration 6362 /// type of a permitted flavor. 6363 bool Sema::ICEConvertDiagnoser::match(QualType T) { 6364 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 6365 : T->isIntegralOrUnscopedEnumerationType(); 6366 } 6367 6368 static ExprResult 6369 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 6370 Sema::ContextualImplicitConverter &Converter, 6371 QualType T, UnresolvedSetImpl &ViableConversions) { 6372 6373 if (Converter.Suppress) 6374 return ExprError(); 6375 6376 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 6377 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6378 CXXConversionDecl *Conv = 6379 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 6380 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 6381 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 6382 } 6383 return From; 6384 } 6385 6386 static bool 6387 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6388 Sema::ContextualImplicitConverter &Converter, 6389 QualType T, bool HadMultipleCandidates, 6390 UnresolvedSetImpl &ExplicitConversions) { 6391 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 6392 DeclAccessPair Found = ExplicitConversions[0]; 6393 CXXConversionDecl *Conversion = 6394 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6395 6396 // The user probably meant to invoke the given explicit 6397 // conversion; use it. 6398 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 6399 std::string TypeStr; 6400 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 6401 6402 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 6403 << FixItHint::CreateInsertion(From->getBeginLoc(), 6404 "static_cast<" + TypeStr + ">(") 6405 << FixItHint::CreateInsertion( 6406 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 6407 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 6408 6409 // If we aren't in a SFINAE context, build a call to the 6410 // explicit conversion function. 6411 if (SemaRef.isSFINAEContext()) 6412 return true; 6413 6414 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6415 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6416 HadMultipleCandidates); 6417 if (Result.isInvalid()) 6418 return true; 6419 // Record usage of conversion in an implicit cast. 6420 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6421 CK_UserDefinedConversion, Result.get(), 6422 nullptr, Result.get()->getValueKind(), 6423 SemaRef.CurFPFeatureOverrides()); 6424 } 6425 return false; 6426 } 6427 6428 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 6429 Sema::ContextualImplicitConverter &Converter, 6430 QualType T, bool HadMultipleCandidates, 6431 DeclAccessPair &Found) { 6432 CXXConversionDecl *Conversion = 6433 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 6434 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 6435 6436 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 6437 if (!Converter.SuppressConversion) { 6438 if (SemaRef.isSFINAEContext()) 6439 return true; 6440 6441 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 6442 << From->getSourceRange(); 6443 } 6444 6445 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 6446 HadMultipleCandidates); 6447 if (Result.isInvalid()) 6448 return true; 6449 // Record usage of conversion in an implicit cast. 6450 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 6451 CK_UserDefinedConversion, Result.get(), 6452 nullptr, Result.get()->getValueKind(), 6453 SemaRef.CurFPFeatureOverrides()); 6454 return false; 6455 } 6456 6457 static ExprResult finishContextualImplicitConversion( 6458 Sema &SemaRef, SourceLocation Loc, Expr *From, 6459 Sema::ContextualImplicitConverter &Converter) { 6460 if (!Converter.match(From->getType()) && !Converter.Suppress) 6461 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 6462 << From->getSourceRange(); 6463 6464 return SemaRef.DefaultLvalueConversion(From); 6465 } 6466 6467 static void 6468 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 6469 UnresolvedSetImpl &ViableConversions, 6470 OverloadCandidateSet &CandidateSet) { 6471 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 6472 DeclAccessPair FoundDecl = ViableConversions[I]; 6473 NamedDecl *D = FoundDecl.getDecl(); 6474 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 6475 if (isa<UsingShadowDecl>(D)) 6476 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6477 6478 CXXConversionDecl *Conv; 6479 FunctionTemplateDecl *ConvTemplate; 6480 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 6481 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6482 else 6483 Conv = cast<CXXConversionDecl>(D); 6484 6485 if (ConvTemplate) 6486 SemaRef.AddTemplateConversionCandidate( 6487 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 6488 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 6489 else 6490 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 6491 ToType, CandidateSet, 6492 /*AllowObjCConversionOnExplicit=*/false, 6493 /*AllowExplicit*/ true); 6494 } 6495 } 6496 6497 /// Attempt to convert the given expression to a type which is accepted 6498 /// by the given converter. 6499 /// 6500 /// This routine will attempt to convert an expression of class type to a 6501 /// type accepted by the specified converter. In C++11 and before, the class 6502 /// must have a single non-explicit conversion function converting to a matching 6503 /// type. In C++1y, there can be multiple such conversion functions, but only 6504 /// one target type. 6505 /// 6506 /// \param Loc The source location of the construct that requires the 6507 /// conversion. 6508 /// 6509 /// \param From The expression we're converting from. 6510 /// 6511 /// \param Converter Used to control and diagnose the conversion process. 6512 /// 6513 /// \returns The expression, converted to an integral or enumeration type if 6514 /// successful. 6515 ExprResult Sema::PerformContextualImplicitConversion( 6516 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 6517 // We can't perform any more checking for type-dependent expressions. 6518 if (From->isTypeDependent()) 6519 return From; 6520 6521 // Process placeholders immediately. 6522 if (From->hasPlaceholderType()) { 6523 ExprResult result = CheckPlaceholderExpr(From); 6524 if (result.isInvalid()) 6525 return result; 6526 From = result.get(); 6527 } 6528 6529 // Try converting the expression to an Lvalue first, to get rid of qualifiers. 6530 ExprResult Converted = DefaultLvalueConversion(From); 6531 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType(); 6532 // If the expression already has a matching type, we're golden. 6533 if (Converter.match(T)) 6534 return Converted; 6535 6536 // FIXME: Check for missing '()' if T is a function type? 6537 6538 // We can only perform contextual implicit conversions on objects of class 6539 // type. 6540 const RecordType *RecordTy = T->getAs<RecordType>(); 6541 if (!RecordTy || !getLangOpts().CPlusPlus) { 6542 if (!Converter.Suppress) 6543 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 6544 return From; 6545 } 6546 6547 // We must have a complete class type. 6548 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 6549 ContextualImplicitConverter &Converter; 6550 Expr *From; 6551 6552 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 6553 : Converter(Converter), From(From) {} 6554 6555 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 6556 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 6557 } 6558 } IncompleteDiagnoser(Converter, From); 6559 6560 if (Converter.Suppress ? !isCompleteType(Loc, T) 6561 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 6562 return From; 6563 6564 // Look for a conversion to an integral or enumeration type. 6565 UnresolvedSet<4> 6566 ViableConversions; // These are *potentially* viable in C++1y. 6567 UnresolvedSet<4> ExplicitConversions; 6568 const auto &Conversions = 6569 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 6570 6571 bool HadMultipleCandidates = 6572 (std::distance(Conversions.begin(), Conversions.end()) > 1); 6573 6574 // To check that there is only one target type, in C++1y: 6575 QualType ToType; 6576 bool HasUniqueTargetType = true; 6577 6578 // Collect explicit or viable (potentially in C++1y) conversions. 6579 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6580 NamedDecl *D = (*I)->getUnderlyingDecl(); 6581 CXXConversionDecl *Conversion; 6582 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6583 if (ConvTemplate) { 6584 if (getLangOpts().CPlusPlus14) 6585 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6586 else 6587 continue; // C++11 does not consider conversion operator templates(?). 6588 } else 6589 Conversion = cast<CXXConversionDecl>(D); 6590 6591 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6592 "Conversion operator templates are considered potentially " 6593 "viable in C++1y"); 6594 6595 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6596 if (Converter.match(CurToType) || ConvTemplate) { 6597 6598 if (Conversion->isExplicit()) { 6599 // FIXME: For C++1y, do we need this restriction? 6600 // cf. diagnoseNoViableConversion() 6601 if (!ConvTemplate) 6602 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6603 } else { 6604 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6605 if (ToType.isNull()) 6606 ToType = CurToType.getUnqualifiedType(); 6607 else if (HasUniqueTargetType && 6608 (CurToType.getUnqualifiedType() != ToType)) 6609 HasUniqueTargetType = false; 6610 } 6611 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6612 } 6613 } 6614 } 6615 6616 if (getLangOpts().CPlusPlus14) { 6617 // C++1y [conv]p6: 6618 // ... An expression e of class type E appearing in such a context 6619 // is said to be contextually implicitly converted to a specified 6620 // type T and is well-formed if and only if e can be implicitly 6621 // converted to a type T that is determined as follows: E is searched 6622 // for conversion functions whose return type is cv T or reference to 6623 // cv T such that T is allowed by the context. There shall be 6624 // exactly one such T. 6625 6626 // If no unique T is found: 6627 if (ToType.isNull()) { 6628 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6629 HadMultipleCandidates, 6630 ExplicitConversions)) 6631 return ExprError(); 6632 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6633 } 6634 6635 // If more than one unique Ts are found: 6636 if (!HasUniqueTargetType) 6637 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6638 ViableConversions); 6639 6640 // If one unique T is found: 6641 // First, build a candidate set from the previously recorded 6642 // potentially viable conversions. 6643 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6644 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6645 CandidateSet); 6646 6647 // Then, perform overload resolution over the candidate set. 6648 OverloadCandidateSet::iterator Best; 6649 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6650 case OR_Success: { 6651 // Apply this conversion. 6652 DeclAccessPair Found = 6653 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6654 if (recordConversion(*this, Loc, From, Converter, T, 6655 HadMultipleCandidates, Found)) 6656 return ExprError(); 6657 break; 6658 } 6659 case OR_Ambiguous: 6660 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6661 ViableConversions); 6662 case OR_No_Viable_Function: 6663 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6664 HadMultipleCandidates, 6665 ExplicitConversions)) 6666 return ExprError(); 6667 [[fallthrough]]; 6668 case OR_Deleted: 6669 // We'll complain below about a non-integral condition type. 6670 break; 6671 } 6672 } else { 6673 switch (ViableConversions.size()) { 6674 case 0: { 6675 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6676 HadMultipleCandidates, 6677 ExplicitConversions)) 6678 return ExprError(); 6679 6680 // We'll complain below about a non-integral condition type. 6681 break; 6682 } 6683 case 1: { 6684 // Apply this conversion. 6685 DeclAccessPair Found = ViableConversions[0]; 6686 if (recordConversion(*this, Loc, From, Converter, T, 6687 HadMultipleCandidates, Found)) 6688 return ExprError(); 6689 break; 6690 } 6691 default: 6692 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6693 ViableConversions); 6694 } 6695 } 6696 6697 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6698 } 6699 6700 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6701 /// an acceptable non-member overloaded operator for a call whose 6702 /// arguments have types T1 (and, if non-empty, T2). This routine 6703 /// implements the check in C++ [over.match.oper]p3b2 concerning 6704 /// enumeration types. 6705 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6706 FunctionDecl *Fn, 6707 ArrayRef<Expr *> Args) { 6708 QualType T1 = Args[0]->getType(); 6709 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6710 6711 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6712 return true; 6713 6714 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6715 return true; 6716 6717 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6718 if (Proto->getNumParams() < 1) 6719 return false; 6720 6721 if (T1->isEnumeralType()) { 6722 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6723 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6724 return true; 6725 } 6726 6727 if (Proto->getNumParams() < 2) 6728 return false; 6729 6730 if (!T2.isNull() && T2->isEnumeralType()) { 6731 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6732 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6733 return true; 6734 } 6735 6736 return false; 6737 } 6738 6739 /// AddOverloadCandidate - Adds the given function to the set of 6740 /// candidate functions, using the given function call arguments. If 6741 /// @p SuppressUserConversions, then don't allow user-defined 6742 /// conversions via constructors or conversion operators. 6743 /// 6744 /// \param PartialOverloading true if we are performing "partial" overloading 6745 /// based on an incomplete set of function arguments. This feature is used by 6746 /// code completion. 6747 void Sema::AddOverloadCandidate( 6748 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6749 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6750 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6751 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6752 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { 6753 const FunctionProtoType *Proto 6754 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6755 assert(Proto && "Functions without a prototype cannot be overloaded"); 6756 assert(!Function->getDescribedFunctionTemplate() && 6757 "Use AddTemplateOverloadCandidate for function templates"); 6758 6759 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6760 if (!isa<CXXConstructorDecl>(Method)) { 6761 // If we get here, it's because we're calling a member function 6762 // that is named without a member access expression (e.g., 6763 // "this->f") that was either written explicitly or created 6764 // implicitly. This can happen with a qualified call to a member 6765 // function, e.g., X::f(). We use an empty type for the implied 6766 // object argument (C++ [over.call.func]p3), and the acting context 6767 // is irrelevant. 6768 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6769 Expr::Classification::makeSimpleLValue(), Args, 6770 CandidateSet, SuppressUserConversions, 6771 PartialOverloading, EarlyConversions, PO); 6772 return; 6773 } 6774 // We treat a constructor like a non-member function, since its object 6775 // argument doesn't participate in overload resolution. 6776 } 6777 6778 if (!CandidateSet.isNewCandidate(Function, PO)) 6779 return; 6780 6781 // C++11 [class.copy]p11: [DR1402] 6782 // A defaulted move constructor that is defined as deleted is ignored by 6783 // overload resolution. 6784 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6785 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6786 Constructor->isMoveConstructor()) 6787 return; 6788 6789 // Overload resolution is always an unevaluated context. 6790 EnterExpressionEvaluationContext Unevaluated( 6791 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6792 6793 // C++ [over.match.oper]p3: 6794 // if no operand has a class type, only those non-member functions in the 6795 // lookup set that have a first parameter of type T1 or "reference to 6796 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6797 // is a right operand) a second parameter of type T2 or "reference to 6798 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6799 // candidate functions. 6800 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6801 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6802 return; 6803 6804 // Add this candidate 6805 OverloadCandidate &Candidate = 6806 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6807 Candidate.FoundDecl = FoundDecl; 6808 Candidate.Function = Function; 6809 Candidate.Viable = true; 6810 Candidate.RewriteKind = 6811 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6812 Candidate.IsSurrogate = false; 6813 Candidate.IsADLCandidate = IsADLCandidate; 6814 Candidate.IgnoreObjectArgument = false; 6815 Candidate.ExplicitCallArguments = Args.size(); 6816 6817 // Explicit functions are not actually candidates at all if we're not 6818 // allowing them in this context, but keep them around so we can point 6819 // to them in diagnostics. 6820 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6821 Candidate.Viable = false; 6822 Candidate.FailureKind = ovl_fail_explicit; 6823 return; 6824 } 6825 6826 // Functions with internal linkage are only viable in the same module unit. 6827 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) { 6828 /// FIXME: Currently, the semantics of linkage in clang is slightly 6829 /// different from the semantics in C++ spec. In C++ spec, only names 6830 /// have linkage. So that all entities of the same should share one 6831 /// linkage. But in clang, different entities of the same could have 6832 /// different linkage. 6833 NamedDecl *ND = Function; 6834 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) 6835 ND = SpecInfo->getTemplate(); 6836 6837 if (ND->getFormalLinkage() == Linkage::Internal) { 6838 Candidate.Viable = false; 6839 Candidate.FailureKind = ovl_fail_module_mismatched; 6840 return; 6841 } 6842 } 6843 6844 if (Function->isMultiVersion() && 6845 ((Function->hasAttr<TargetAttr>() && 6846 !Function->getAttr<TargetAttr>()->isDefaultVersion()) || 6847 (Function->hasAttr<TargetVersionAttr>() && 6848 !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { 6849 Candidate.Viable = false; 6850 Candidate.FailureKind = ovl_non_default_multiversion_function; 6851 return; 6852 } 6853 6854 if (Constructor) { 6855 // C++ [class.copy]p3: 6856 // A member function template is never instantiated to perform the copy 6857 // of a class object to an object of its class type. 6858 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6859 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6860 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6861 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6862 ClassType))) { 6863 Candidate.Viable = false; 6864 Candidate.FailureKind = ovl_fail_illegal_constructor; 6865 return; 6866 } 6867 6868 // C++ [over.match.funcs]p8: (proposed DR resolution) 6869 // A constructor inherited from class type C that has a first parameter 6870 // of type "reference to P" (including such a constructor instantiated 6871 // from a template) is excluded from the set of candidate functions when 6872 // constructing an object of type cv D if the argument list has exactly 6873 // one argument and D is reference-related to P and P is reference-related 6874 // to C. 6875 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6876 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6877 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6878 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6879 QualType C = Context.getRecordType(Constructor->getParent()); 6880 QualType D = Context.getRecordType(Shadow->getParent()); 6881 SourceLocation Loc = Args.front()->getExprLoc(); 6882 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6883 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6884 Candidate.Viable = false; 6885 Candidate.FailureKind = ovl_fail_inhctor_slice; 6886 return; 6887 } 6888 } 6889 6890 // Check that the constructor is capable of constructing an object in the 6891 // destination address space. 6892 if (!Qualifiers::isAddressSpaceSupersetOf( 6893 Constructor->getMethodQualifiers().getAddressSpace(), 6894 CandidateSet.getDestAS())) { 6895 Candidate.Viable = false; 6896 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6897 } 6898 } 6899 6900 unsigned NumParams = Proto->getNumParams(); 6901 6902 // (C++ 13.3.2p2): A candidate function having fewer than m 6903 // parameters is viable only if it has an ellipsis in its parameter 6904 // list (8.3.5). 6905 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6906 !Proto->isVariadic() && 6907 shouldEnforceArgLimit(PartialOverloading, Function)) { 6908 Candidate.Viable = false; 6909 Candidate.FailureKind = ovl_fail_too_many_arguments; 6910 return; 6911 } 6912 6913 // (C++ 13.3.2p2): A candidate function having more than m parameters 6914 // is viable only if the (m+1)st parameter has a default argument 6915 // (8.3.6). For the purposes of overload resolution, the 6916 // parameter list is truncated on the right, so that there are 6917 // exactly m parameters. 6918 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6919 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs && 6920 !PartialOverloading) { 6921 // Not enough arguments. 6922 Candidate.Viable = false; 6923 Candidate.FailureKind = ovl_fail_too_few_arguments; 6924 return; 6925 } 6926 6927 // (CUDA B.1): Check for invalid calls between targets. 6928 if (getLangOpts().CUDA) { 6929 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 6930 // Skip the check for callers that are implicit members, because in this 6931 // case we may not yet know what the member's target is; the target is 6932 // inferred for the member automatically, based on the bases and fields of 6933 // the class. 6934 if (!(Caller && Caller->isImplicit()) && 6935 !IsAllowedCUDACall(Caller, Function)) { 6936 Candidate.Viable = false; 6937 Candidate.FailureKind = ovl_fail_bad_target; 6938 return; 6939 } 6940 } 6941 6942 if (Function->getTrailingRequiresClause()) { 6943 ConstraintSatisfaction Satisfaction; 6944 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {}, 6945 /*ForOverloadResolution*/ true) || 6946 !Satisfaction.IsSatisfied) { 6947 Candidate.Viable = false; 6948 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6949 return; 6950 } 6951 } 6952 6953 // Determine the implicit conversion sequences for each of the 6954 // arguments. 6955 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6956 unsigned ConvIdx = 6957 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6958 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6959 // We already formed a conversion sequence for this parameter during 6960 // template argument deduction. 6961 } else if (ArgIdx < NumParams) { 6962 // (C++ 13.3.2p3): for F to be a viable function, there shall 6963 // exist for each argument an implicit conversion sequence 6964 // (13.3.3.1) that converts that argument to the corresponding 6965 // parameter of F. 6966 QualType ParamType = Proto->getParamType(ArgIdx); 6967 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6968 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6969 /*InOverloadResolution=*/true, 6970 /*AllowObjCWritebackConversion=*/ 6971 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6972 if (Candidate.Conversions[ConvIdx].isBad()) { 6973 Candidate.Viable = false; 6974 Candidate.FailureKind = ovl_fail_bad_conversion; 6975 return; 6976 } 6977 } else { 6978 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6979 // argument for which there is no corresponding parameter is 6980 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6981 Candidate.Conversions[ConvIdx].setEllipsis(); 6982 } 6983 } 6984 6985 if (EnableIfAttr *FailedAttr = 6986 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6987 Candidate.Viable = false; 6988 Candidate.FailureKind = ovl_fail_enable_if; 6989 Candidate.DeductionFailure.Data = FailedAttr; 6990 return; 6991 } 6992 } 6993 6994 ObjCMethodDecl * 6995 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6996 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6997 if (Methods.size() <= 1) 6998 return nullptr; 6999 7000 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 7001 bool Match = true; 7002 ObjCMethodDecl *Method = Methods[b]; 7003 unsigned NumNamedArgs = Sel.getNumArgs(); 7004 // Method might have more arguments than selector indicates. This is due 7005 // to addition of c-style arguments in method. 7006 if (Method->param_size() > NumNamedArgs) 7007 NumNamedArgs = Method->param_size(); 7008 if (Args.size() < NumNamedArgs) 7009 continue; 7010 7011 for (unsigned i = 0; i < NumNamedArgs; i++) { 7012 // We can't do any type-checking on a type-dependent argument. 7013 if (Args[i]->isTypeDependent()) { 7014 Match = false; 7015 break; 7016 } 7017 7018 ParmVarDecl *param = Method->parameters()[i]; 7019 Expr *argExpr = Args[i]; 7020 assert(argExpr && "SelectBestMethod(): missing expression"); 7021 7022 // Strip the unbridged-cast placeholder expression off unless it's 7023 // a consumed argument. 7024 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 7025 !param->hasAttr<CFConsumedAttr>()) 7026 argExpr = stripARCUnbridgedCast(argExpr); 7027 7028 // If the parameter is __unknown_anytype, move on to the next method. 7029 if (param->getType() == Context.UnknownAnyTy) { 7030 Match = false; 7031 break; 7032 } 7033 7034 ImplicitConversionSequence ConversionState 7035 = TryCopyInitialization(*this, argExpr, param->getType(), 7036 /*SuppressUserConversions*/false, 7037 /*InOverloadResolution=*/true, 7038 /*AllowObjCWritebackConversion=*/ 7039 getLangOpts().ObjCAutoRefCount, 7040 /*AllowExplicit*/false); 7041 // This function looks for a reasonably-exact match, so we consider 7042 // incompatible pointer conversions to be a failure here. 7043 if (ConversionState.isBad() || 7044 (ConversionState.isStandard() && 7045 ConversionState.Standard.Second == 7046 ICK_Incompatible_Pointer_Conversion)) { 7047 Match = false; 7048 break; 7049 } 7050 } 7051 // Promote additional arguments to variadic methods. 7052 if (Match && Method->isVariadic()) { 7053 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 7054 if (Args[i]->isTypeDependent()) { 7055 Match = false; 7056 break; 7057 } 7058 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 7059 nullptr); 7060 if (Arg.isInvalid()) { 7061 Match = false; 7062 break; 7063 } 7064 } 7065 } else { 7066 // Check for extra arguments to non-variadic methods. 7067 if (Args.size() != NumNamedArgs) 7068 Match = false; 7069 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 7070 // Special case when selectors have no argument. In this case, select 7071 // one with the most general result type of 'id'. 7072 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 7073 QualType ReturnT = Methods[b]->getReturnType(); 7074 if (ReturnT->isObjCIdType()) 7075 return Methods[b]; 7076 } 7077 } 7078 } 7079 7080 if (Match) 7081 return Method; 7082 } 7083 return nullptr; 7084 } 7085 7086 static bool convertArgsForAvailabilityChecks( 7087 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 7088 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 7089 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 7090 if (ThisArg) { 7091 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 7092 assert(!isa<CXXConstructorDecl>(Method) && 7093 "Shouldn't have `this` for ctors!"); 7094 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 7095 ExprResult R = S.PerformImplicitObjectArgumentInitialization( 7096 ThisArg, /*Qualifier=*/nullptr, Method, Method); 7097 if (R.isInvalid()) 7098 return false; 7099 ConvertedThis = R.get(); 7100 } else { 7101 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 7102 (void)MD; 7103 assert((MissingImplicitThis || MD->isStatic() || 7104 isa<CXXConstructorDecl>(MD)) && 7105 "Expected `this` for non-ctor instance methods"); 7106 } 7107 ConvertedThis = nullptr; 7108 } 7109 7110 // Ignore any variadic arguments. Converting them is pointless, since the 7111 // user can't refer to them in the function condition. 7112 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 7113 7114 // Convert the arguments. 7115 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 7116 ExprResult R; 7117 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 7118 S.Context, Function->getParamDecl(I)), 7119 SourceLocation(), Args[I]); 7120 7121 if (R.isInvalid()) 7122 return false; 7123 7124 ConvertedArgs.push_back(R.get()); 7125 } 7126 7127 if (Trap.hasErrorOccurred()) 7128 return false; 7129 7130 // Push default arguments if needed. 7131 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 7132 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 7133 ParmVarDecl *P = Function->getParamDecl(i); 7134 if (!P->hasDefaultArg()) 7135 return false; 7136 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 7137 if (R.isInvalid()) 7138 return false; 7139 ConvertedArgs.push_back(R.get()); 7140 } 7141 7142 if (Trap.hasErrorOccurred()) 7143 return false; 7144 } 7145 return true; 7146 } 7147 7148 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 7149 SourceLocation CallLoc, 7150 ArrayRef<Expr *> Args, 7151 bool MissingImplicitThis) { 7152 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 7153 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 7154 return nullptr; 7155 7156 SFINAETrap Trap(*this); 7157 SmallVector<Expr *, 16> ConvertedArgs; 7158 // FIXME: We should look into making enable_if late-parsed. 7159 Expr *DiscardedThis; 7160 if (!convertArgsForAvailabilityChecks( 7161 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 7162 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 7163 return *EnableIfAttrs.begin(); 7164 7165 for (auto *EIA : EnableIfAttrs) { 7166 APValue Result; 7167 // FIXME: This doesn't consider value-dependent cases, because doing so is 7168 // very difficult. Ideally, we should handle them more gracefully. 7169 if (EIA->getCond()->isValueDependent() || 7170 !EIA->getCond()->EvaluateWithSubstitution( 7171 Result, Context, Function, llvm::ArrayRef(ConvertedArgs))) 7172 return EIA; 7173 7174 if (!Result.isInt() || !Result.getInt().getBoolValue()) 7175 return EIA; 7176 } 7177 return nullptr; 7178 } 7179 7180 template <typename CheckFn> 7181 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 7182 bool ArgDependent, SourceLocation Loc, 7183 CheckFn &&IsSuccessful) { 7184 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 7185 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 7186 if (ArgDependent == DIA->getArgDependent()) 7187 Attrs.push_back(DIA); 7188 } 7189 7190 // Common case: No diagnose_if attributes, so we can quit early. 7191 if (Attrs.empty()) 7192 return false; 7193 7194 auto WarningBegin = std::stable_partition( 7195 Attrs.begin(), Attrs.end(), 7196 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 7197 7198 // Note that diagnose_if attributes are late-parsed, so they appear in the 7199 // correct order (unlike enable_if attributes). 7200 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 7201 IsSuccessful); 7202 if (ErrAttr != WarningBegin) { 7203 const DiagnoseIfAttr *DIA = *ErrAttr; 7204 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 7205 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 7206 << DIA->getParent() << DIA->getCond()->getSourceRange(); 7207 return true; 7208 } 7209 7210 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 7211 if (IsSuccessful(DIA)) { 7212 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 7213 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 7214 << DIA->getParent() << DIA->getCond()->getSourceRange(); 7215 } 7216 7217 return false; 7218 } 7219 7220 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 7221 const Expr *ThisArg, 7222 ArrayRef<const Expr *> Args, 7223 SourceLocation Loc) { 7224 return diagnoseDiagnoseIfAttrsWith( 7225 *this, Function, /*ArgDependent=*/true, Loc, 7226 [&](const DiagnoseIfAttr *DIA) { 7227 APValue Result; 7228 // It's sane to use the same Args for any redecl of this function, since 7229 // EvaluateWithSubstitution only cares about the position of each 7230 // argument in the arg list, not the ParmVarDecl* it maps to. 7231 if (!DIA->getCond()->EvaluateWithSubstitution( 7232 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 7233 return false; 7234 return Result.isInt() && Result.getInt().getBoolValue(); 7235 }); 7236 } 7237 7238 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 7239 SourceLocation Loc) { 7240 return diagnoseDiagnoseIfAttrsWith( 7241 *this, ND, /*ArgDependent=*/false, Loc, 7242 [&](const DiagnoseIfAttr *DIA) { 7243 bool Result; 7244 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 7245 Result; 7246 }); 7247 } 7248 7249 /// Add all of the function declarations in the given function set to 7250 /// the overload candidate set. 7251 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 7252 ArrayRef<Expr *> Args, 7253 OverloadCandidateSet &CandidateSet, 7254 TemplateArgumentListInfo *ExplicitTemplateArgs, 7255 bool SuppressUserConversions, 7256 bool PartialOverloading, 7257 bool FirstArgumentIsBase) { 7258 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7259 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7260 ArrayRef<Expr *> FunctionArgs = Args; 7261 7262 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7263 FunctionDecl *FD = 7264 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7265 7266 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 7267 QualType ObjectType; 7268 Expr::Classification ObjectClassification; 7269 if (Args.size() > 0) { 7270 if (Expr *E = Args[0]) { 7271 // Use the explicit base to restrict the lookup: 7272 ObjectType = E->getType(); 7273 // Pointers in the object arguments are implicitly dereferenced, so we 7274 // always classify them as l-values. 7275 if (!ObjectType.isNull() && ObjectType->isPointerType()) 7276 ObjectClassification = Expr::Classification::makeSimpleLValue(); 7277 else 7278 ObjectClassification = E->Classify(Context); 7279 } // .. else there is an implicit base. 7280 FunctionArgs = Args.slice(1); 7281 } 7282 if (FunTmpl) { 7283 AddMethodTemplateCandidate( 7284 FunTmpl, F.getPair(), 7285 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 7286 ExplicitTemplateArgs, ObjectType, ObjectClassification, 7287 FunctionArgs, CandidateSet, SuppressUserConversions, 7288 PartialOverloading); 7289 } else { 7290 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 7291 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 7292 ObjectClassification, FunctionArgs, CandidateSet, 7293 SuppressUserConversions, PartialOverloading); 7294 } 7295 } else { 7296 // This branch handles both standalone functions and static methods. 7297 7298 // Slice the first argument (which is the base) when we access 7299 // static method as non-static. 7300 if (Args.size() > 0 && 7301 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 7302 !isa<CXXConstructorDecl>(FD)))) { 7303 assert(cast<CXXMethodDecl>(FD)->isStatic()); 7304 FunctionArgs = Args.slice(1); 7305 } 7306 if (FunTmpl) { 7307 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 7308 ExplicitTemplateArgs, FunctionArgs, 7309 CandidateSet, SuppressUserConversions, 7310 PartialOverloading); 7311 } else { 7312 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 7313 SuppressUserConversions, PartialOverloading); 7314 } 7315 } 7316 } 7317 } 7318 7319 /// AddMethodCandidate - Adds a named decl (which is some kind of 7320 /// method) as a method candidate to the given overload set. 7321 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 7322 Expr::Classification ObjectClassification, 7323 ArrayRef<Expr *> Args, 7324 OverloadCandidateSet &CandidateSet, 7325 bool SuppressUserConversions, 7326 OverloadCandidateParamOrder PO) { 7327 NamedDecl *Decl = FoundDecl.getDecl(); 7328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 7329 7330 if (isa<UsingShadowDecl>(Decl)) 7331 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 7332 7333 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 7334 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 7335 "Expected a member function template"); 7336 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 7337 /*ExplicitArgs*/ nullptr, ObjectType, 7338 ObjectClassification, Args, CandidateSet, 7339 SuppressUserConversions, false, PO); 7340 } else { 7341 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 7342 ObjectType, ObjectClassification, Args, CandidateSet, 7343 SuppressUserConversions, false, std::nullopt, PO); 7344 } 7345 } 7346 7347 /// AddMethodCandidate - Adds the given C++ member function to the set 7348 /// of candidate functions, using the given function call arguments 7349 /// and the object argument (@c Object). For example, in a call 7350 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 7351 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 7352 /// allow user-defined conversions via constructors or conversion 7353 /// operators. 7354 void 7355 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 7356 CXXRecordDecl *ActingContext, QualType ObjectType, 7357 Expr::Classification ObjectClassification, 7358 ArrayRef<Expr *> Args, 7359 OverloadCandidateSet &CandidateSet, 7360 bool SuppressUserConversions, 7361 bool PartialOverloading, 7362 ConversionSequenceList EarlyConversions, 7363 OverloadCandidateParamOrder PO) { 7364 const FunctionProtoType *Proto 7365 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 7366 assert(Proto && "Methods without a prototype cannot be overloaded"); 7367 assert(!isa<CXXConstructorDecl>(Method) && 7368 "Use AddOverloadCandidate for constructors"); 7369 7370 if (!CandidateSet.isNewCandidate(Method, PO)) 7371 return; 7372 7373 // C++11 [class.copy]p23: [DR1402] 7374 // A defaulted move assignment operator that is defined as deleted is 7375 // ignored by overload resolution. 7376 if (Method->isDefaulted() && Method->isDeleted() && 7377 Method->isMoveAssignmentOperator()) 7378 return; 7379 7380 // Overload resolution is always an unevaluated context. 7381 EnterExpressionEvaluationContext Unevaluated( 7382 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7383 7384 // Add this candidate 7385 OverloadCandidate &Candidate = 7386 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 7387 Candidate.FoundDecl = FoundDecl; 7388 Candidate.Function = Method; 7389 Candidate.RewriteKind = 7390 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 7391 Candidate.IsSurrogate = false; 7392 Candidate.IgnoreObjectArgument = false; 7393 Candidate.ExplicitCallArguments = Args.size(); 7394 7395 unsigned NumParams = Method->getNumExplicitParams(); 7396 unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0; 7397 7398 // (C++ 13.3.2p2): A candidate function having fewer than m 7399 // parameters is viable only if it has an ellipsis in its parameter 7400 // list (8.3.5). 7401 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 7402 !Proto->isVariadic() && 7403 shouldEnforceArgLimit(PartialOverloading, Method)) { 7404 Candidate.Viable = false; 7405 Candidate.FailureKind = ovl_fail_too_many_arguments; 7406 return; 7407 } 7408 7409 // (C++ 13.3.2p2): A candidate function having more than m parameters 7410 // is viable only if the (m+1)st parameter has a default argument 7411 // (8.3.6). For the purposes of overload resolution, the 7412 // parameter list is truncated on the right, so that there are 7413 // exactly m parameters. 7414 unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments(); 7415 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 7416 // Not enough arguments. 7417 Candidate.Viable = false; 7418 Candidate.FailureKind = ovl_fail_too_few_arguments; 7419 return; 7420 } 7421 7422 Candidate.Viable = true; 7423 7424 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7425 if (ObjectType.isNull()) 7426 Candidate.IgnoreObjectArgument = true; 7427 else if (Method->isStatic()) { 7428 // [over.best.ics.general]p8 7429 // When the parameter is the implicit object parameter of a static member 7430 // function, the implicit conversion sequence is a standard conversion 7431 // sequence that is neither better nor worse than any other standard 7432 // conversion sequence. 7433 // 7434 // This is a rule that was introduced in C++23 to support static lambdas. We 7435 // apply it retroactively because we want to support static lambdas as an 7436 // extension and it doesn't hurt previous code. 7437 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument(); 7438 } else { 7439 // Determine the implicit conversion sequence for the object 7440 // parameter. 7441 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization( 7442 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7443 Method, ActingContext, /*InOverloadResolution=*/true); 7444 if (Candidate.Conversions[FirstConvIdx].isBad()) { 7445 Candidate.Viable = false; 7446 Candidate.FailureKind = ovl_fail_bad_conversion; 7447 return; 7448 } 7449 } 7450 7451 // (CUDA B.1): Check for invalid calls between targets. 7452 if (getLangOpts().CUDA) 7453 if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method)) { 7454 Candidate.Viable = false; 7455 Candidate.FailureKind = ovl_fail_bad_target; 7456 return; 7457 } 7458 7459 if (Method->getTrailingRequiresClause()) { 7460 ConstraintSatisfaction Satisfaction; 7461 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {}, 7462 /*ForOverloadResolution*/ true) || 7463 !Satisfaction.IsSatisfied) { 7464 Candidate.Viable = false; 7465 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7466 return; 7467 } 7468 } 7469 7470 // Determine the implicit conversion sequences for each of the 7471 // arguments. 7472 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 7473 unsigned ConvIdx = 7474 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 7475 if (Candidate.Conversions[ConvIdx].isInitialized()) { 7476 // We already formed a conversion sequence for this parameter during 7477 // template argument deduction. 7478 } else if (ArgIdx < NumParams) { 7479 // (C++ 13.3.2p3): for F to be a viable function, there shall 7480 // exist for each argument an implicit conversion sequence 7481 // (13.3.3.1) that converts that argument to the corresponding 7482 // parameter of F. 7483 QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset); 7484 Candidate.Conversions[ConvIdx] 7485 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7486 SuppressUserConversions, 7487 /*InOverloadResolution=*/true, 7488 /*AllowObjCWritebackConversion=*/ 7489 getLangOpts().ObjCAutoRefCount); 7490 if (Candidate.Conversions[ConvIdx].isBad()) { 7491 Candidate.Viable = false; 7492 Candidate.FailureKind = ovl_fail_bad_conversion; 7493 return; 7494 } 7495 } else { 7496 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7497 // argument for which there is no corresponding parameter is 7498 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 7499 Candidate.Conversions[ConvIdx].setEllipsis(); 7500 } 7501 } 7502 7503 if (EnableIfAttr *FailedAttr = 7504 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 7505 Candidate.Viable = false; 7506 Candidate.FailureKind = ovl_fail_enable_if; 7507 Candidate.DeductionFailure.Data = FailedAttr; 7508 return; 7509 } 7510 7511 if (Method->isMultiVersion() && 7512 ((Method->hasAttr<TargetAttr>() && 7513 !Method->getAttr<TargetAttr>()->isDefaultVersion()) || 7514 (Method->hasAttr<TargetVersionAttr>() && 7515 !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { 7516 Candidate.Viable = false; 7517 Candidate.FailureKind = ovl_non_default_multiversion_function; 7518 } 7519 } 7520 7521 /// Add a C++ member function template as a candidate to the candidate 7522 /// set, using template argument deduction to produce an appropriate member 7523 /// function template specialization. 7524 void Sema::AddMethodTemplateCandidate( 7525 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 7526 CXXRecordDecl *ActingContext, 7527 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 7528 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 7529 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7530 bool PartialOverloading, OverloadCandidateParamOrder PO) { 7531 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 7532 return; 7533 7534 // C++ [over.match.funcs]p7: 7535 // In each case where a candidate is a function template, candidate 7536 // function template specializations are generated using template argument 7537 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7538 // candidate functions in the usual way.113) A given name can refer to one 7539 // or more function templates and also to a set of overloaded non-template 7540 // functions. In such a case, the candidate functions generated from each 7541 // function template are combined with the set of non-template candidate 7542 // functions. 7543 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7544 FunctionDecl *Specialization = nullptr; 7545 ConversionSequenceList Conversions; 7546 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7547 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 7548 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType, 7549 ObjectClassification, [&](ArrayRef<QualType> ParamTypes) { 7550 return CheckNonDependentConversions( 7551 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 7552 SuppressUserConversions, ActingContext, ObjectType, 7553 ObjectClassification, PO); 7554 })) { 7555 OverloadCandidate &Candidate = 7556 CandidateSet.addCandidate(Conversions.size(), Conversions); 7557 Candidate.FoundDecl = FoundDecl; 7558 Candidate.Function = MethodTmpl->getTemplatedDecl(); 7559 Candidate.Viable = false; 7560 Candidate.RewriteKind = 7561 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7562 Candidate.IsSurrogate = false; 7563 Candidate.IgnoreObjectArgument = 7564 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 7565 ObjectType.isNull(); 7566 Candidate.ExplicitCallArguments = Args.size(); 7567 if (Result == TDK_NonDependentConversionFailure) 7568 Candidate.FailureKind = ovl_fail_bad_conversion; 7569 else { 7570 Candidate.FailureKind = ovl_fail_bad_deduction; 7571 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7572 Info); 7573 } 7574 return; 7575 } 7576 7577 // Add the function template specialization produced by template argument 7578 // deduction as a candidate. 7579 assert(Specialization && "Missing member function template specialization?"); 7580 assert(isa<CXXMethodDecl>(Specialization) && 7581 "Specialization is not a member function?"); 7582 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 7583 ActingContext, ObjectType, ObjectClassification, Args, 7584 CandidateSet, SuppressUserConversions, PartialOverloading, 7585 Conversions, PO); 7586 } 7587 7588 /// Determine whether a given function template has a simple explicit specifier 7589 /// or a non-value-dependent explicit-specification that evaluates to true. 7590 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 7591 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 7592 } 7593 7594 /// Add a C++ function template specialization as a candidate 7595 /// in the candidate set, using template argument deduction to produce 7596 /// an appropriate function template specialization. 7597 void Sema::AddTemplateOverloadCandidate( 7598 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7599 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 7600 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 7601 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 7602 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) { 7603 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 7604 return; 7605 7606 // If the function template has a non-dependent explicit specification, 7607 // exclude it now if appropriate; we are not permitted to perform deduction 7608 // and substitution in this case. 7609 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7610 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7611 Candidate.FoundDecl = FoundDecl; 7612 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7613 Candidate.Viable = false; 7614 Candidate.FailureKind = ovl_fail_explicit; 7615 return; 7616 } 7617 7618 // C++ [over.match.funcs]p7: 7619 // In each case where a candidate is a function template, candidate 7620 // function template specializations are generated using template argument 7621 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7622 // candidate functions in the usual way.113) A given name can refer to one 7623 // or more function templates and also to a set of overloaded non-template 7624 // functions. In such a case, the candidate functions generated from each 7625 // function template are combined with the set of non-template candidate 7626 // functions. 7627 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7628 FunctionDecl *Specialization = nullptr; 7629 ConversionSequenceList Conversions; 7630 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7631 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7632 PartialOverloading, AggregateCandidateDeduction, 7633 /*ObjectType=*/QualType(), 7634 /*ObjectClassification=*/Expr::Classification(), 7635 [&](ArrayRef<QualType> ParamTypes) { 7636 return CheckNonDependentConversions( 7637 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7638 SuppressUserConversions, nullptr, QualType(), {}, PO); 7639 })) { 7640 OverloadCandidate &Candidate = 7641 CandidateSet.addCandidate(Conversions.size(), Conversions); 7642 Candidate.FoundDecl = FoundDecl; 7643 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7644 Candidate.Viable = false; 7645 Candidate.RewriteKind = 7646 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7647 Candidate.IsSurrogate = false; 7648 Candidate.IsADLCandidate = IsADLCandidate; 7649 // Ignore the object argument if there is one, since we don't have an object 7650 // type. 7651 Candidate.IgnoreObjectArgument = 7652 isa<CXXMethodDecl>(Candidate.Function) && 7653 !isa<CXXConstructorDecl>(Candidate.Function); 7654 Candidate.ExplicitCallArguments = Args.size(); 7655 if (Result == TDK_NonDependentConversionFailure) 7656 Candidate.FailureKind = ovl_fail_bad_conversion; 7657 else { 7658 Candidate.FailureKind = ovl_fail_bad_deduction; 7659 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7660 Info); 7661 } 7662 return; 7663 } 7664 7665 // Add the function template specialization produced by template argument 7666 // deduction as a candidate. 7667 assert(Specialization && "Missing function template specialization?"); 7668 AddOverloadCandidate( 7669 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7670 PartialOverloading, AllowExplicit, 7671 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO, 7672 Info.AggregateDeductionCandidateHasMismatchedArity); 7673 } 7674 7675 /// Check that implicit conversion sequences can be formed for each argument 7676 /// whose corresponding parameter has a non-dependent type, per DR1391's 7677 /// [temp.deduct.call]p10. 7678 bool Sema::CheckNonDependentConversions( 7679 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7680 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7681 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7682 CXXRecordDecl *ActingContext, QualType ObjectType, 7683 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7684 // FIXME: The cases in which we allow explicit conversions for constructor 7685 // arguments never consider calling a constructor template. It's not clear 7686 // that is correct. 7687 const bool AllowExplicit = false; 7688 7689 auto *FD = FunctionTemplate->getTemplatedDecl(); 7690 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7691 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7692 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7693 7694 Conversions = 7695 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7696 7697 // Overload resolution is always an unevaluated context. 7698 EnterExpressionEvaluationContext Unevaluated( 7699 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7700 7701 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7702 // require that, but this check should never result in a hard error, and 7703 // overload resolution is permitted to sidestep instantiations. 7704 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7705 !ObjectType.isNull()) { 7706 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7707 if (!FD->hasCXXExplicitFunctionObjectParameter() || 7708 !ParamTypes[0]->isDependentType()) { 7709 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7710 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7711 Method, ActingContext, /*InOverloadResolution=*/true, 7712 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0] 7713 : QualType()); 7714 if (Conversions[ConvIdx].isBad()) 7715 return true; 7716 } 7717 } 7718 7719 unsigned Offset = 7720 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0; 7721 7722 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7723 ++I) { 7724 QualType ParamType = ParamTypes[I + Offset]; 7725 if (!ParamType->isDependentType()) { 7726 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7727 ? 0 7728 : (ThisConversions + I); 7729 Conversions[ConvIdx] 7730 = TryCopyInitialization(*this, Args[I], ParamType, 7731 SuppressUserConversions, 7732 /*InOverloadResolution=*/true, 7733 /*AllowObjCWritebackConversion=*/ 7734 getLangOpts().ObjCAutoRefCount, 7735 AllowExplicit); 7736 if (Conversions[ConvIdx].isBad()) 7737 return true; 7738 } 7739 } 7740 7741 return false; 7742 } 7743 7744 /// Determine whether this is an allowable conversion from the result 7745 /// of an explicit conversion operator to the expected type, per C++ 7746 /// [over.match.conv]p1 and [over.match.ref]p1. 7747 /// 7748 /// \param ConvType The return type of the conversion function. 7749 /// 7750 /// \param ToType The type we are converting to. 7751 /// 7752 /// \param AllowObjCPointerConversion Allow a conversion from one 7753 /// Objective-C pointer to another. 7754 /// 7755 /// \returns true if the conversion is allowable, false otherwise. 7756 static bool isAllowableExplicitConversion(Sema &S, 7757 QualType ConvType, QualType ToType, 7758 bool AllowObjCPointerConversion) { 7759 QualType ToNonRefType = ToType.getNonReferenceType(); 7760 7761 // Easy case: the types are the same. 7762 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7763 return true; 7764 7765 // Allow qualification conversions. 7766 bool ObjCLifetimeConversion; 7767 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7768 ObjCLifetimeConversion)) 7769 return true; 7770 7771 // If we're not allowed to consider Objective-C pointer conversions, 7772 // we're done. 7773 if (!AllowObjCPointerConversion) 7774 return false; 7775 7776 // Is this an Objective-C pointer conversion? 7777 bool IncompatibleObjC = false; 7778 QualType ConvertedType; 7779 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7780 IncompatibleObjC); 7781 } 7782 7783 /// AddConversionCandidate - Add a C++ conversion function as a 7784 /// candidate in the candidate set (C++ [over.match.conv], 7785 /// C++ [over.match.copy]). From is the expression we're converting from, 7786 /// and ToType is the type that we're eventually trying to convert to 7787 /// (which may or may not be the same type as the type that the 7788 /// conversion function produces). 7789 void Sema::AddConversionCandidate( 7790 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7791 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7792 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7793 bool AllowExplicit, bool AllowResultConversion) { 7794 assert(!Conversion->getDescribedFunctionTemplate() && 7795 "Conversion function templates use AddTemplateConversionCandidate"); 7796 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7797 if (!CandidateSet.isNewCandidate(Conversion)) 7798 return; 7799 7800 // If the conversion function has an undeduced return type, trigger its 7801 // deduction now. 7802 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7803 if (DeduceReturnType(Conversion, From->getExprLoc())) 7804 return; 7805 ConvType = Conversion->getConversionType().getNonReferenceType(); 7806 } 7807 7808 // If we don't allow any conversion of the result type, ignore conversion 7809 // functions that don't convert to exactly (possibly cv-qualified) T. 7810 if (!AllowResultConversion && 7811 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7812 return; 7813 7814 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7815 // operator is only a candidate if its return type is the target type or 7816 // can be converted to the target type with a qualification conversion. 7817 // 7818 // FIXME: Include such functions in the candidate list and explain why we 7819 // can't select them. 7820 if (Conversion->isExplicit() && 7821 !isAllowableExplicitConversion(*this, ConvType, ToType, 7822 AllowObjCConversionOnExplicit)) 7823 return; 7824 7825 // Overload resolution is always an unevaluated context. 7826 EnterExpressionEvaluationContext Unevaluated( 7827 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7828 7829 // Add this candidate 7830 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7831 Candidate.FoundDecl = FoundDecl; 7832 Candidate.Function = Conversion; 7833 Candidate.IsSurrogate = false; 7834 Candidate.IgnoreObjectArgument = false; 7835 Candidate.FinalConversion.setAsIdentityConversion(); 7836 Candidate.FinalConversion.setFromType(ConvType); 7837 Candidate.FinalConversion.setAllToTypes(ToType); 7838 Candidate.Viable = true; 7839 Candidate.ExplicitCallArguments = 1; 7840 7841 // Explicit functions are not actually candidates at all if we're not 7842 // allowing them in this context, but keep them around so we can point 7843 // to them in diagnostics. 7844 if (!AllowExplicit && Conversion->isExplicit()) { 7845 Candidate.Viable = false; 7846 Candidate.FailureKind = ovl_fail_explicit; 7847 return; 7848 } 7849 7850 // C++ [over.match.funcs]p4: 7851 // For conversion functions, the function is considered to be a member of 7852 // the class of the implicit implied object argument for the purpose of 7853 // defining the type of the implicit object parameter. 7854 // 7855 // Determine the implicit conversion sequence for the implicit 7856 // object parameter. 7857 QualType ObjectType = From->getType(); 7858 if (const auto *FromPtrType = ObjectType->getAs<PointerType>()) 7859 ObjectType = FromPtrType->getPointeeType(); 7860 const auto *ConversionContext = 7861 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl()); 7862 7863 // C++23 [over.best.ics.general] 7864 // However, if the target is [...] 7865 // - the object parameter of a user-defined conversion function 7866 // [...] user-defined conversion sequences are not considered. 7867 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7868 *this, CandidateSet.getLocation(), From->getType(), 7869 From->Classify(Context), Conversion, ConversionContext, 7870 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(), 7871 /*SuppressUserConversion*/ true); 7872 7873 if (Candidate.Conversions[0].isBad()) { 7874 Candidate.Viable = false; 7875 Candidate.FailureKind = ovl_fail_bad_conversion; 7876 return; 7877 } 7878 7879 if (Conversion->getTrailingRequiresClause()) { 7880 ConstraintSatisfaction Satisfaction; 7881 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7882 !Satisfaction.IsSatisfied) { 7883 Candidate.Viable = false; 7884 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7885 return; 7886 } 7887 } 7888 7889 // We won't go through a user-defined type conversion function to convert a 7890 // derived to base as such conversions are given Conversion Rank. They only 7891 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7892 QualType FromCanon 7893 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7894 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7895 if (FromCanon == ToCanon || 7896 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7897 Candidate.Viable = false; 7898 Candidate.FailureKind = ovl_fail_trivial_conversion; 7899 return; 7900 } 7901 7902 // To determine what the conversion from the result of calling the 7903 // conversion function to the type we're eventually trying to 7904 // convert to (ToType), we need to synthesize a call to the 7905 // conversion function and attempt copy initialization from it. This 7906 // makes sure that we get the right semantics with respect to 7907 // lvalues/rvalues and the type. Fortunately, we can allocate this 7908 // call on the stack and we don't need its arguments to be 7909 // well-formed. 7910 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7911 VK_LValue, From->getBeginLoc()); 7912 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7913 Context.getPointerType(Conversion->getType()), 7914 CK_FunctionToPointerDecay, &ConversionRef, 7915 VK_PRValue, FPOptionsOverride()); 7916 7917 QualType ConversionType = Conversion->getConversionType(); 7918 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7919 Candidate.Viable = false; 7920 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7921 return; 7922 } 7923 7924 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7925 7926 // Note that it is safe to allocate CallExpr on the stack here because 7927 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7928 // allocator). 7929 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7930 7931 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7932 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7933 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7934 7935 ImplicitConversionSequence ICS = 7936 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7937 /*SuppressUserConversions=*/true, 7938 /*InOverloadResolution=*/false, 7939 /*AllowObjCWritebackConversion=*/false); 7940 7941 switch (ICS.getKind()) { 7942 case ImplicitConversionSequence::StandardConversion: 7943 Candidate.FinalConversion = ICS.Standard; 7944 7945 // C++ [over.ics.user]p3: 7946 // If the user-defined conversion is specified by a specialization of a 7947 // conversion function template, the second standard conversion sequence 7948 // shall have exact match rank. 7949 if (Conversion->getPrimaryTemplate() && 7950 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7951 Candidate.Viable = false; 7952 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7953 return; 7954 } 7955 7956 // C++0x [dcl.init.ref]p5: 7957 // In the second case, if the reference is an rvalue reference and 7958 // the second standard conversion sequence of the user-defined 7959 // conversion sequence includes an lvalue-to-rvalue conversion, the 7960 // program is ill-formed. 7961 if (ToType->isRValueReferenceType() && 7962 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7963 Candidate.Viable = false; 7964 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7965 return; 7966 } 7967 break; 7968 7969 case ImplicitConversionSequence::BadConversion: 7970 Candidate.Viable = false; 7971 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7972 return; 7973 7974 default: 7975 llvm_unreachable( 7976 "Can only end up with a standard conversion sequence or failure"); 7977 } 7978 7979 if (EnableIfAttr *FailedAttr = 7980 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { 7981 Candidate.Viable = false; 7982 Candidate.FailureKind = ovl_fail_enable_if; 7983 Candidate.DeductionFailure.Data = FailedAttr; 7984 return; 7985 } 7986 7987 if (Conversion->isMultiVersion() && 7988 ((Conversion->hasAttr<TargetAttr>() && 7989 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) || 7990 (Conversion->hasAttr<TargetVersionAttr>() && 7991 !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) { 7992 Candidate.Viable = false; 7993 Candidate.FailureKind = ovl_non_default_multiversion_function; 7994 } 7995 } 7996 7997 /// Adds a conversion function template specialization 7998 /// candidate to the overload set, using template argument deduction 7999 /// to deduce the template arguments of the conversion function 8000 /// template from the type that we are converting to (C++ 8001 /// [temp.deduct.conv]). 8002 void Sema::AddTemplateConversionCandidate( 8003 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 8004 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 8005 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 8006 bool AllowExplicit, bool AllowResultConversion) { 8007 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 8008 "Only conversion function templates permitted here"); 8009 8010 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 8011 return; 8012 8013 // If the function template has a non-dependent explicit specification, 8014 // exclude it now if appropriate; we are not permitted to perform deduction 8015 // and substitution in this case. 8016 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 8017 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 8018 Candidate.FoundDecl = FoundDecl; 8019 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 8020 Candidate.Viable = false; 8021 Candidate.FailureKind = ovl_fail_explicit; 8022 return; 8023 } 8024 8025 QualType ObjectType = From->getType(); 8026 Expr::Classification ObjectClassification = From->Classify(getASTContext()); 8027 8028 TemplateDeductionInfo Info(CandidateSet.getLocation()); 8029 CXXConversionDecl *Specialization = nullptr; 8030 if (TemplateDeductionResult Result = DeduceTemplateArguments( 8031 FunctionTemplate, ObjectType, ObjectClassification, ToType, 8032 Specialization, Info)) { 8033 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 8034 Candidate.FoundDecl = FoundDecl; 8035 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 8036 Candidate.Viable = false; 8037 Candidate.FailureKind = ovl_fail_bad_deduction; 8038 Candidate.IsSurrogate = false; 8039 Candidate.IgnoreObjectArgument = false; 8040 Candidate.ExplicitCallArguments = 1; 8041 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 8042 Info); 8043 return; 8044 } 8045 8046 // Add the conversion function template specialization produced by 8047 // template argument deduction as a candidate. 8048 assert(Specialization && "Missing function template specialization?"); 8049 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 8050 CandidateSet, AllowObjCConversionOnExplicit, 8051 AllowExplicit, AllowResultConversion); 8052 } 8053 8054 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 8055 /// converts the given @c Object to a function pointer via the 8056 /// conversion function @c Conversion, and then attempts to call it 8057 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 8058 /// the type of function that we'll eventually be calling. 8059 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 8060 DeclAccessPair FoundDecl, 8061 CXXRecordDecl *ActingContext, 8062 const FunctionProtoType *Proto, 8063 Expr *Object, 8064 ArrayRef<Expr *> Args, 8065 OverloadCandidateSet& CandidateSet) { 8066 if (!CandidateSet.isNewCandidate(Conversion)) 8067 return; 8068 8069 // Overload resolution is always an unevaluated context. 8070 EnterExpressionEvaluationContext Unevaluated( 8071 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8072 8073 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 8074 Candidate.FoundDecl = FoundDecl; 8075 Candidate.Function = nullptr; 8076 Candidate.Surrogate = Conversion; 8077 Candidate.Viable = true; 8078 Candidate.IsSurrogate = true; 8079 Candidate.IgnoreObjectArgument = false; 8080 Candidate.ExplicitCallArguments = Args.size(); 8081 8082 // Determine the implicit conversion sequence for the implicit 8083 // object parameter. 8084 ImplicitConversionSequence ObjectInit; 8085 if (Conversion->hasCXXExplicitFunctionObjectParameter()) { 8086 ObjectInit = TryCopyInitialization(*this, Object, 8087 Conversion->getParamDecl(0)->getType(), 8088 /*SuppressUserConversions=*/false, 8089 /*InOverloadResolution=*/true, false); 8090 } else { 8091 ObjectInit = TryObjectArgumentInitialization( 8092 *this, CandidateSet.getLocation(), Object->getType(), 8093 Object->Classify(Context), Conversion, ActingContext); 8094 } 8095 8096 if (ObjectInit.isBad()) { 8097 Candidate.Viable = false; 8098 Candidate.FailureKind = ovl_fail_bad_conversion; 8099 Candidate.Conversions[0] = ObjectInit; 8100 return; 8101 } 8102 8103 // The first conversion is actually a user-defined conversion whose 8104 // first conversion is ObjectInit's standard conversion (which is 8105 // effectively a reference binding). Record it as such. 8106 Candidate.Conversions[0].setUserDefined(); 8107 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 8108 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 8109 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 8110 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 8111 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 8112 Candidate.Conversions[0].UserDefined.After 8113 = Candidate.Conversions[0].UserDefined.Before; 8114 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 8115 8116 // Find the 8117 unsigned NumParams = Proto->getNumParams(); 8118 8119 // (C++ 13.3.2p2): A candidate function having fewer than m 8120 // parameters is viable only if it has an ellipsis in its parameter 8121 // list (8.3.5). 8122 if (Args.size() > NumParams && !Proto->isVariadic()) { 8123 Candidate.Viable = false; 8124 Candidate.FailureKind = ovl_fail_too_many_arguments; 8125 return; 8126 } 8127 8128 // Function types don't have any default arguments, so just check if 8129 // we have enough arguments. 8130 if (Args.size() < NumParams) { 8131 // Not enough arguments. 8132 Candidate.Viable = false; 8133 Candidate.FailureKind = ovl_fail_too_few_arguments; 8134 return; 8135 } 8136 8137 // Determine the implicit conversion sequences for each of the 8138 // arguments. 8139 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8140 if (ArgIdx < NumParams) { 8141 // (C++ 13.3.2p3): for F to be a viable function, there shall 8142 // exist for each argument an implicit conversion sequence 8143 // (13.3.3.1) that converts that argument to the corresponding 8144 // parameter of F. 8145 QualType ParamType = Proto->getParamType(ArgIdx); 8146 Candidate.Conversions[ArgIdx + 1] 8147 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 8148 /*SuppressUserConversions=*/false, 8149 /*InOverloadResolution=*/false, 8150 /*AllowObjCWritebackConversion=*/ 8151 getLangOpts().ObjCAutoRefCount); 8152 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 8153 Candidate.Viable = false; 8154 Candidate.FailureKind = ovl_fail_bad_conversion; 8155 return; 8156 } 8157 } else { 8158 // (C++ 13.3.2p2): For the purposes of overload resolution, any 8159 // argument for which there is no corresponding parameter is 8160 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 8161 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 8162 } 8163 } 8164 8165 if (Conversion->getTrailingRequiresClause()) { 8166 ConstraintSatisfaction Satisfaction; 8167 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {}, 8168 /*ForOverloadResolution*/ true) || 8169 !Satisfaction.IsSatisfied) { 8170 Candidate.Viable = false; 8171 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 8172 return; 8173 } 8174 } 8175 8176 if (EnableIfAttr *FailedAttr = 8177 CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) { 8178 Candidate.Viable = false; 8179 Candidate.FailureKind = ovl_fail_enable_if; 8180 Candidate.DeductionFailure.Data = FailedAttr; 8181 return; 8182 } 8183 } 8184 8185 /// Add all of the non-member operator function declarations in the given 8186 /// function set to the overload candidate set. 8187 void Sema::AddNonMemberOperatorCandidates( 8188 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 8189 OverloadCandidateSet &CandidateSet, 8190 TemplateArgumentListInfo *ExplicitTemplateArgs) { 8191 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 8192 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 8193 ArrayRef<Expr *> FunctionArgs = Args; 8194 8195 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 8196 FunctionDecl *FD = 8197 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 8198 8199 // Don't consider rewritten functions if we're not rewriting. 8200 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 8201 continue; 8202 8203 assert(!isa<CXXMethodDecl>(FD) && 8204 "unqualified operator lookup found a member function"); 8205 8206 if (FunTmpl) { 8207 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 8208 FunctionArgs, CandidateSet); 8209 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) 8210 AddTemplateOverloadCandidate( 8211 FunTmpl, F.getPair(), ExplicitTemplateArgs, 8212 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 8213 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 8214 } else { 8215 if (ExplicitTemplateArgs) 8216 continue; 8217 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 8218 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) 8219 AddOverloadCandidate( 8220 FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 8221 false, false, true, false, ADLCallKind::NotADL, std::nullopt, 8222 OverloadCandidateParamOrder::Reversed); 8223 } 8224 } 8225 } 8226 8227 /// Add overload candidates for overloaded operators that are 8228 /// member functions. 8229 /// 8230 /// Add the overloaded operator candidates that are member functions 8231 /// for the operator Op that was used in an operator expression such 8232 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 8233 /// CandidateSet will store the added overload candidates. (C++ 8234 /// [over.match.oper]). 8235 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 8236 SourceLocation OpLoc, 8237 ArrayRef<Expr *> Args, 8238 OverloadCandidateSet &CandidateSet, 8239 OverloadCandidateParamOrder PO) { 8240 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 8241 8242 // C++ [over.match.oper]p3: 8243 // For a unary operator @ with an operand of a type whose 8244 // cv-unqualified version is T1, and for a binary operator @ with 8245 // a left operand of a type whose cv-unqualified version is T1 and 8246 // a right operand of a type whose cv-unqualified version is T2, 8247 // three sets of candidate functions, designated member 8248 // candidates, non-member candidates and built-in candidates, are 8249 // constructed as follows: 8250 QualType T1 = Args[0]->getType(); 8251 8252 // -- If T1 is a complete class type or a class currently being 8253 // defined, the set of member candidates is the result of the 8254 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 8255 // the set of member candidates is empty. 8256 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 8257 // Complete the type if it can be completed. 8258 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 8259 return; 8260 // If the type is neither complete nor being defined, bail out now. 8261 if (!T1Rec->getDecl()->getDefinition()) 8262 return; 8263 8264 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 8265 LookupQualifiedName(Operators, T1Rec->getDecl()); 8266 Operators.suppressAccessDiagnostics(); 8267 8268 for (LookupResult::iterator Oper = Operators.begin(), 8269 OperEnd = Operators.end(); 8270 Oper != OperEnd; ++Oper) { 8271 if (Oper->getAsFunction() && 8272 PO == OverloadCandidateParamOrder::Reversed && 8273 !CandidateSet.getRewriteInfo().shouldAddReversed( 8274 *this, {Args[1], Args[0]}, Oper->getAsFunction())) 8275 continue; 8276 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 8277 Args[0]->Classify(Context), Args.slice(1), 8278 CandidateSet, /*SuppressUserConversion=*/false, PO); 8279 } 8280 } 8281 } 8282 8283 /// AddBuiltinCandidate - Add a candidate for a built-in 8284 /// operator. ResultTy and ParamTys are the result and parameter types 8285 /// of the built-in candidate, respectively. Args and NumArgs are the 8286 /// arguments being passed to the candidate. IsAssignmentOperator 8287 /// should be true when this built-in candidate is an assignment 8288 /// operator. NumContextualBoolArguments is the number of arguments 8289 /// (at the beginning of the argument list) that will be contextually 8290 /// converted to bool. 8291 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 8292 OverloadCandidateSet& CandidateSet, 8293 bool IsAssignmentOperator, 8294 unsigned NumContextualBoolArguments) { 8295 // Overload resolution is always an unevaluated context. 8296 EnterExpressionEvaluationContext Unevaluated( 8297 *this, Sema::ExpressionEvaluationContext::Unevaluated); 8298 8299 // Add this candidate 8300 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 8301 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 8302 Candidate.Function = nullptr; 8303 Candidate.IsSurrogate = false; 8304 Candidate.IgnoreObjectArgument = false; 8305 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 8306 8307 // Determine the implicit conversion sequences for each of the 8308 // arguments. 8309 Candidate.Viable = true; 8310 Candidate.ExplicitCallArguments = Args.size(); 8311 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8312 // C++ [over.match.oper]p4: 8313 // For the built-in assignment operators, conversions of the 8314 // left operand are restricted as follows: 8315 // -- no temporaries are introduced to hold the left operand, and 8316 // -- no user-defined conversions are applied to the left 8317 // operand to achieve a type match with the left-most 8318 // parameter of a built-in candidate. 8319 // 8320 // We block these conversions by turning off user-defined 8321 // conversions, since that is the only way that initialization of 8322 // a reference to a non-class type can occur from something that 8323 // is not of the same type. 8324 if (ArgIdx < NumContextualBoolArguments) { 8325 assert(ParamTys[ArgIdx] == Context.BoolTy && 8326 "Contextual conversion to bool requires bool type"); 8327 Candidate.Conversions[ArgIdx] 8328 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 8329 } else { 8330 Candidate.Conversions[ArgIdx] 8331 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 8332 ArgIdx == 0 && IsAssignmentOperator, 8333 /*InOverloadResolution=*/false, 8334 /*AllowObjCWritebackConversion=*/ 8335 getLangOpts().ObjCAutoRefCount); 8336 } 8337 if (Candidate.Conversions[ArgIdx].isBad()) { 8338 Candidate.Viable = false; 8339 Candidate.FailureKind = ovl_fail_bad_conversion; 8340 break; 8341 } 8342 } 8343 } 8344 8345 namespace { 8346 8347 /// BuiltinCandidateTypeSet - A set of types that will be used for the 8348 /// candidate operator functions for built-in operators (C++ 8349 /// [over.built]). The types are separated into pointer types and 8350 /// enumeration types. 8351 class BuiltinCandidateTypeSet { 8352 /// TypeSet - A set of types. 8353 typedef llvm::SmallSetVector<QualType, 8> TypeSet; 8354 8355 /// PointerTypes - The set of pointer types that will be used in the 8356 /// built-in candidates. 8357 TypeSet PointerTypes; 8358 8359 /// MemberPointerTypes - The set of member pointer types that will be 8360 /// used in the built-in candidates. 8361 TypeSet MemberPointerTypes; 8362 8363 /// EnumerationTypes - The set of enumeration types that will be 8364 /// used in the built-in candidates. 8365 TypeSet EnumerationTypes; 8366 8367 /// The set of vector types that will be used in the built-in 8368 /// candidates. 8369 TypeSet VectorTypes; 8370 8371 /// The set of matrix types that will be used in the built-in 8372 /// candidates. 8373 TypeSet MatrixTypes; 8374 8375 /// A flag indicating non-record types are viable candidates 8376 bool HasNonRecordTypes; 8377 8378 /// A flag indicating whether either arithmetic or enumeration types 8379 /// were present in the candidate set. 8380 bool HasArithmeticOrEnumeralTypes; 8381 8382 /// A flag indicating whether the nullptr type was present in the 8383 /// candidate set. 8384 bool HasNullPtrType; 8385 8386 /// Sema - The semantic analysis instance where we are building the 8387 /// candidate type set. 8388 Sema &SemaRef; 8389 8390 /// Context - The AST context in which we will build the type sets. 8391 ASTContext &Context; 8392 8393 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8394 const Qualifiers &VisibleQuals); 8395 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 8396 8397 public: 8398 /// iterator - Iterates through the types that are part of the set. 8399 typedef TypeSet::iterator iterator; 8400 8401 BuiltinCandidateTypeSet(Sema &SemaRef) 8402 : HasNonRecordTypes(false), 8403 HasArithmeticOrEnumeralTypes(false), 8404 HasNullPtrType(false), 8405 SemaRef(SemaRef), 8406 Context(SemaRef.Context) { } 8407 8408 void AddTypesConvertedFrom(QualType Ty, 8409 SourceLocation Loc, 8410 bool AllowUserConversions, 8411 bool AllowExplicitConversions, 8412 const Qualifiers &VisibleTypeConversionsQuals); 8413 8414 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; } 8415 llvm::iterator_range<iterator> member_pointer_types() { 8416 return MemberPointerTypes; 8417 } 8418 llvm::iterator_range<iterator> enumeration_types() { 8419 return EnumerationTypes; 8420 } 8421 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 8422 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 8423 8424 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 8425 bool hasNonRecordTypes() { return HasNonRecordTypes; } 8426 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 8427 bool hasNullPtrType() const { return HasNullPtrType; } 8428 }; 8429 8430 } // end anonymous namespace 8431 8432 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 8433 /// the set of pointer types along with any more-qualified variants of 8434 /// that type. For example, if @p Ty is "int const *", this routine 8435 /// will add "int const *", "int const volatile *", "int const 8436 /// restrict *", and "int const volatile restrict *" to the set of 8437 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8438 /// false otherwise. 8439 /// 8440 /// FIXME: what to do about extended qualifiers? 8441 bool 8442 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 8443 const Qualifiers &VisibleQuals) { 8444 8445 // Insert this type. 8446 if (!PointerTypes.insert(Ty)) 8447 return false; 8448 8449 QualType PointeeTy; 8450 const PointerType *PointerTy = Ty->getAs<PointerType>(); 8451 bool buildObjCPtr = false; 8452 if (!PointerTy) { 8453 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 8454 PointeeTy = PTy->getPointeeType(); 8455 buildObjCPtr = true; 8456 } else { 8457 PointeeTy = PointerTy->getPointeeType(); 8458 } 8459 8460 // Don't add qualified variants of arrays. For one, they're not allowed 8461 // (the qualifier would sink to the element type), and for another, the 8462 // only overload situation where it matters is subscript or pointer +- int, 8463 // and those shouldn't have qualifier variants anyway. 8464 if (PointeeTy->isArrayType()) 8465 return true; 8466 8467 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8468 bool hasVolatile = VisibleQuals.hasVolatile(); 8469 bool hasRestrict = VisibleQuals.hasRestrict(); 8470 8471 // Iterate through all strict supersets of BaseCVR. 8472 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8473 if ((CVR | BaseCVR) != CVR) continue; 8474 // Skip over volatile if no volatile found anywhere in the types. 8475 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 8476 8477 // Skip over restrict if no restrict found anywhere in the types, or if 8478 // the type cannot be restrict-qualified. 8479 if ((CVR & Qualifiers::Restrict) && 8480 (!hasRestrict || 8481 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 8482 continue; 8483 8484 // Build qualified pointee type. 8485 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8486 8487 // Build qualified pointer type. 8488 QualType QPointerTy; 8489 if (!buildObjCPtr) 8490 QPointerTy = Context.getPointerType(QPointeeTy); 8491 else 8492 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 8493 8494 // Insert qualified pointer type. 8495 PointerTypes.insert(QPointerTy); 8496 } 8497 8498 return true; 8499 } 8500 8501 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 8502 /// to the set of pointer types along with any more-qualified variants of 8503 /// that type. For example, if @p Ty is "int const *", this routine 8504 /// will add "int const *", "int const volatile *", "int const 8505 /// restrict *", and "int const volatile restrict *" to the set of 8506 /// pointer types. Returns true if the add of @p Ty itself succeeded, 8507 /// false otherwise. 8508 /// 8509 /// FIXME: what to do about extended qualifiers? 8510 bool 8511 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 8512 QualType Ty) { 8513 // Insert this type. 8514 if (!MemberPointerTypes.insert(Ty)) 8515 return false; 8516 8517 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 8518 assert(PointerTy && "type was not a member pointer type!"); 8519 8520 QualType PointeeTy = PointerTy->getPointeeType(); 8521 // Don't add qualified variants of arrays. For one, they're not allowed 8522 // (the qualifier would sink to the element type), and for another, the 8523 // only overload situation where it matters is subscript or pointer +- int, 8524 // and those shouldn't have qualifier variants anyway. 8525 if (PointeeTy->isArrayType()) 8526 return true; 8527 const Type *ClassTy = PointerTy->getClass(); 8528 8529 // Iterate through all strict supersets of the pointee type's CVR 8530 // qualifiers. 8531 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 8532 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 8533 if ((CVR | BaseCVR) != CVR) continue; 8534 8535 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 8536 MemberPointerTypes.insert( 8537 Context.getMemberPointerType(QPointeeTy, ClassTy)); 8538 } 8539 8540 return true; 8541 } 8542 8543 /// AddTypesConvertedFrom - Add each of the types to which the type @p 8544 /// Ty can be implicit converted to the given set of @p Types. We're 8545 /// primarily interested in pointer types and enumeration types. We also 8546 /// take member pointer types, for the conditional operator. 8547 /// AllowUserConversions is true if we should look at the conversion 8548 /// functions of a class type, and AllowExplicitConversions if we 8549 /// should also include the explicit conversion functions of a class 8550 /// type. 8551 void 8552 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 8553 SourceLocation Loc, 8554 bool AllowUserConversions, 8555 bool AllowExplicitConversions, 8556 const Qualifiers &VisibleQuals) { 8557 // Only deal with canonical types. 8558 Ty = Context.getCanonicalType(Ty); 8559 8560 // Look through reference types; they aren't part of the type of an 8561 // expression for the purposes of conversions. 8562 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 8563 Ty = RefTy->getPointeeType(); 8564 8565 // If we're dealing with an array type, decay to the pointer. 8566 if (Ty->isArrayType()) 8567 Ty = SemaRef.Context.getArrayDecayedType(Ty); 8568 8569 // Otherwise, we don't care about qualifiers on the type. 8570 Ty = Ty.getLocalUnqualifiedType(); 8571 8572 // Flag if we ever add a non-record type. 8573 const RecordType *TyRec = Ty->getAs<RecordType>(); 8574 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 8575 8576 // Flag if we encounter an arithmetic type. 8577 HasArithmeticOrEnumeralTypes = 8578 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 8579 8580 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 8581 PointerTypes.insert(Ty); 8582 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 8583 // Insert our type, and its more-qualified variants, into the set 8584 // of types. 8585 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 8586 return; 8587 } else if (Ty->isMemberPointerType()) { 8588 // Member pointers are far easier, since the pointee can't be converted. 8589 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 8590 return; 8591 } else if (Ty->isEnumeralType()) { 8592 HasArithmeticOrEnumeralTypes = true; 8593 EnumerationTypes.insert(Ty); 8594 } else if (Ty->isVectorType()) { 8595 // We treat vector types as arithmetic types in many contexts as an 8596 // extension. 8597 HasArithmeticOrEnumeralTypes = true; 8598 VectorTypes.insert(Ty); 8599 } else if (Ty->isMatrixType()) { 8600 // Similar to vector types, we treat vector types as arithmetic types in 8601 // many contexts as an extension. 8602 HasArithmeticOrEnumeralTypes = true; 8603 MatrixTypes.insert(Ty); 8604 } else if (Ty->isNullPtrType()) { 8605 HasNullPtrType = true; 8606 } else if (AllowUserConversions && TyRec) { 8607 // No conversion functions in incomplete types. 8608 if (!SemaRef.isCompleteType(Loc, Ty)) 8609 return; 8610 8611 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8612 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8613 if (isa<UsingShadowDecl>(D)) 8614 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8615 8616 // Skip conversion function templates; they don't tell us anything 8617 // about which builtin types we can convert to. 8618 if (isa<FunctionTemplateDecl>(D)) 8619 continue; 8620 8621 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 8622 if (AllowExplicitConversions || !Conv->isExplicit()) { 8623 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 8624 VisibleQuals); 8625 } 8626 } 8627 } 8628 } 8629 /// Helper function for adjusting address spaces for the pointer or reference 8630 /// operands of builtin operators depending on the argument. 8631 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 8632 Expr *Arg) { 8633 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 8634 } 8635 8636 /// Helper function for AddBuiltinOperatorCandidates() that adds 8637 /// the volatile- and non-volatile-qualified assignment operators for the 8638 /// given type to the candidate set. 8639 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 8640 QualType T, 8641 ArrayRef<Expr *> Args, 8642 OverloadCandidateSet &CandidateSet) { 8643 QualType ParamTypes[2]; 8644 8645 // T& operator=(T&, T) 8646 ParamTypes[0] = S.Context.getLValueReferenceType( 8647 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8648 ParamTypes[1] = T; 8649 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8650 /*IsAssignmentOperator=*/true); 8651 8652 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8653 // volatile T& operator=(volatile T&, T) 8654 ParamTypes[0] = S.Context.getLValueReferenceType( 8655 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8656 Args[0])); 8657 ParamTypes[1] = T; 8658 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8659 /*IsAssignmentOperator=*/true); 8660 } 8661 } 8662 8663 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8664 /// if any, found in visible type conversion functions found in ArgExpr's type. 8665 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8666 Qualifiers VRQuals; 8667 const RecordType *TyRec; 8668 if (const MemberPointerType *RHSMPType = 8669 ArgExpr->getType()->getAs<MemberPointerType>()) 8670 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8671 else 8672 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8673 if (!TyRec) { 8674 // Just to be safe, assume the worst case. 8675 VRQuals.addVolatile(); 8676 VRQuals.addRestrict(); 8677 return VRQuals; 8678 } 8679 8680 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8681 if (!ClassDecl->hasDefinition()) 8682 return VRQuals; 8683 8684 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8685 if (isa<UsingShadowDecl>(D)) 8686 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8687 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8688 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8689 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8690 CanTy = ResTypeRef->getPointeeType(); 8691 // Need to go down the pointer/mempointer chain and add qualifiers 8692 // as see them. 8693 bool done = false; 8694 while (!done) { 8695 if (CanTy.isRestrictQualified()) 8696 VRQuals.addRestrict(); 8697 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8698 CanTy = ResTypePtr->getPointeeType(); 8699 else if (const MemberPointerType *ResTypeMPtr = 8700 CanTy->getAs<MemberPointerType>()) 8701 CanTy = ResTypeMPtr->getPointeeType(); 8702 else 8703 done = true; 8704 if (CanTy.isVolatileQualified()) 8705 VRQuals.addVolatile(); 8706 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8707 return VRQuals; 8708 } 8709 } 8710 } 8711 return VRQuals; 8712 } 8713 8714 // Note: We're currently only handling qualifiers that are meaningful for the 8715 // LHS of compound assignment overloading. 8716 static void forAllQualifierCombinationsImpl( 8717 QualifiersAndAtomic Available, QualifiersAndAtomic Applied, 8718 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8719 // _Atomic 8720 if (Available.hasAtomic()) { 8721 Available.removeAtomic(); 8722 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback); 8723 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8724 return; 8725 } 8726 8727 // volatile 8728 if (Available.hasVolatile()) { 8729 Available.removeVolatile(); 8730 assert(!Applied.hasVolatile()); 8731 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(), 8732 Callback); 8733 forAllQualifierCombinationsImpl(Available, Applied, Callback); 8734 return; 8735 } 8736 8737 Callback(Applied); 8738 } 8739 8740 static void forAllQualifierCombinations( 8741 QualifiersAndAtomic Quals, 8742 llvm::function_ref<void(QualifiersAndAtomic)> Callback) { 8743 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(), 8744 Callback); 8745 } 8746 8747 static QualType makeQualifiedLValueReferenceType(QualType Base, 8748 QualifiersAndAtomic Quals, 8749 Sema &S) { 8750 if (Quals.hasAtomic()) 8751 Base = S.Context.getAtomicType(Base); 8752 if (Quals.hasVolatile()) 8753 Base = S.Context.getVolatileType(Base); 8754 return S.Context.getLValueReferenceType(Base); 8755 } 8756 8757 namespace { 8758 8759 /// Helper class to manage the addition of builtin operator overload 8760 /// candidates. It provides shared state and utility methods used throughout 8761 /// the process, as well as a helper method to add each group of builtin 8762 /// operator overloads from the standard to a candidate set. 8763 class BuiltinOperatorOverloadBuilder { 8764 // Common instance state available to all overload candidate addition methods. 8765 Sema &S; 8766 ArrayRef<Expr *> Args; 8767 QualifiersAndAtomic VisibleTypeConversionsQuals; 8768 bool HasArithmeticOrEnumeralCandidateType; 8769 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8770 OverloadCandidateSet &CandidateSet; 8771 8772 static constexpr int ArithmeticTypesCap = 24; 8773 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8774 8775 // Define some indices used to iterate over the arithmetic types in 8776 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8777 // types are that preserved by promotion (C++ [over.built]p2). 8778 unsigned FirstIntegralType, 8779 LastIntegralType; 8780 unsigned FirstPromotedIntegralType, 8781 LastPromotedIntegralType; 8782 unsigned FirstPromotedArithmeticType, 8783 LastPromotedArithmeticType; 8784 unsigned NumArithmeticTypes; 8785 8786 void InitArithmeticTypes() { 8787 // Start of promoted types. 8788 FirstPromotedArithmeticType = 0; 8789 ArithmeticTypes.push_back(S.Context.FloatTy); 8790 ArithmeticTypes.push_back(S.Context.DoubleTy); 8791 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8792 if (S.Context.getTargetInfo().hasFloat128Type()) 8793 ArithmeticTypes.push_back(S.Context.Float128Ty); 8794 if (S.Context.getTargetInfo().hasIbm128Type()) 8795 ArithmeticTypes.push_back(S.Context.Ibm128Ty); 8796 8797 // Start of integral types. 8798 FirstIntegralType = ArithmeticTypes.size(); 8799 FirstPromotedIntegralType = ArithmeticTypes.size(); 8800 ArithmeticTypes.push_back(S.Context.IntTy); 8801 ArithmeticTypes.push_back(S.Context.LongTy); 8802 ArithmeticTypes.push_back(S.Context.LongLongTy); 8803 if (S.Context.getTargetInfo().hasInt128Type() || 8804 (S.Context.getAuxTargetInfo() && 8805 S.Context.getAuxTargetInfo()->hasInt128Type())) 8806 ArithmeticTypes.push_back(S.Context.Int128Ty); 8807 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8808 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8809 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8810 if (S.Context.getTargetInfo().hasInt128Type() || 8811 (S.Context.getAuxTargetInfo() && 8812 S.Context.getAuxTargetInfo()->hasInt128Type())) 8813 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8814 LastPromotedIntegralType = ArithmeticTypes.size(); 8815 LastPromotedArithmeticType = ArithmeticTypes.size(); 8816 // End of promoted types. 8817 8818 ArithmeticTypes.push_back(S.Context.BoolTy); 8819 ArithmeticTypes.push_back(S.Context.CharTy); 8820 ArithmeticTypes.push_back(S.Context.WCharTy); 8821 if (S.Context.getLangOpts().Char8) 8822 ArithmeticTypes.push_back(S.Context.Char8Ty); 8823 ArithmeticTypes.push_back(S.Context.Char16Ty); 8824 ArithmeticTypes.push_back(S.Context.Char32Ty); 8825 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8826 ArithmeticTypes.push_back(S.Context.ShortTy); 8827 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8828 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8829 LastIntegralType = ArithmeticTypes.size(); 8830 NumArithmeticTypes = ArithmeticTypes.size(); 8831 // End of integral types. 8832 // FIXME: What about complex? What about half? 8833 8834 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8835 "Enough inline storage for all arithmetic types."); 8836 } 8837 8838 /// Helper method to factor out the common pattern of adding overloads 8839 /// for '++' and '--' builtin operators. 8840 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8841 bool HasVolatile, 8842 bool HasRestrict) { 8843 QualType ParamTypes[2] = { 8844 S.Context.getLValueReferenceType(CandidateTy), 8845 S.Context.IntTy 8846 }; 8847 8848 // Non-volatile version. 8849 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8850 8851 // Use a heuristic to reduce number of builtin candidates in the set: 8852 // add volatile version only if there are conversions to a volatile type. 8853 if (HasVolatile) { 8854 ParamTypes[0] = 8855 S.Context.getLValueReferenceType( 8856 S.Context.getVolatileType(CandidateTy)); 8857 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8858 } 8859 8860 // Add restrict version only if there are conversions to a restrict type 8861 // and our candidate type is a non-restrict-qualified pointer. 8862 if (HasRestrict && CandidateTy->isAnyPointerType() && 8863 !CandidateTy.isRestrictQualified()) { 8864 ParamTypes[0] 8865 = S.Context.getLValueReferenceType( 8866 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8867 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8868 8869 if (HasVolatile) { 8870 ParamTypes[0] 8871 = S.Context.getLValueReferenceType( 8872 S.Context.getCVRQualifiedType(CandidateTy, 8873 (Qualifiers::Volatile | 8874 Qualifiers::Restrict))); 8875 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8876 } 8877 } 8878 8879 } 8880 8881 /// Helper to add an overload candidate for a binary builtin with types \p L 8882 /// and \p R. 8883 void AddCandidate(QualType L, QualType R) { 8884 QualType LandR[2] = {L, R}; 8885 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8886 } 8887 8888 public: 8889 BuiltinOperatorOverloadBuilder( 8890 Sema &S, ArrayRef<Expr *> Args, 8891 QualifiersAndAtomic VisibleTypeConversionsQuals, 8892 bool HasArithmeticOrEnumeralCandidateType, 8893 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8894 OverloadCandidateSet &CandidateSet) 8895 : S(S), Args(Args), 8896 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8897 HasArithmeticOrEnumeralCandidateType( 8898 HasArithmeticOrEnumeralCandidateType), 8899 CandidateTypes(CandidateTypes), 8900 CandidateSet(CandidateSet) { 8901 8902 InitArithmeticTypes(); 8903 } 8904 8905 // Increment is deprecated for bool since C++17. 8906 // 8907 // C++ [over.built]p3: 8908 // 8909 // For every pair (T, VQ), where T is an arithmetic type other 8910 // than bool, and VQ is either volatile or empty, there exist 8911 // candidate operator functions of the form 8912 // 8913 // VQ T& operator++(VQ T&); 8914 // T operator++(VQ T&, int); 8915 // 8916 // C++ [over.built]p4: 8917 // 8918 // For every pair (T, VQ), where T is an arithmetic type other 8919 // than bool, and VQ is either volatile or empty, there exist 8920 // candidate operator functions of the form 8921 // 8922 // VQ T& operator--(VQ T&); 8923 // T operator--(VQ T&, int); 8924 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8925 if (!HasArithmeticOrEnumeralCandidateType) 8926 return; 8927 8928 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8929 const auto TypeOfT = ArithmeticTypes[Arith]; 8930 if (TypeOfT == S.Context.BoolTy) { 8931 if (Op == OO_MinusMinus) 8932 continue; 8933 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8934 continue; 8935 } 8936 addPlusPlusMinusMinusStyleOverloads( 8937 TypeOfT, 8938 VisibleTypeConversionsQuals.hasVolatile(), 8939 VisibleTypeConversionsQuals.hasRestrict()); 8940 } 8941 } 8942 8943 // C++ [over.built]p5: 8944 // 8945 // For every pair (T, VQ), where T is a cv-qualified or 8946 // cv-unqualified object type, and VQ is either volatile or 8947 // empty, there exist candidate operator functions of the form 8948 // 8949 // T*VQ& operator++(T*VQ&); 8950 // T*VQ& operator--(T*VQ&); 8951 // T* operator++(T*VQ&, int); 8952 // T* operator--(T*VQ&, int); 8953 void addPlusPlusMinusMinusPointerOverloads() { 8954 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 8955 // Skip pointer types that aren't pointers to object types. 8956 if (!PtrTy->getPointeeType()->isObjectType()) 8957 continue; 8958 8959 addPlusPlusMinusMinusStyleOverloads( 8960 PtrTy, 8961 (!PtrTy.isVolatileQualified() && 8962 VisibleTypeConversionsQuals.hasVolatile()), 8963 (!PtrTy.isRestrictQualified() && 8964 VisibleTypeConversionsQuals.hasRestrict())); 8965 } 8966 } 8967 8968 // C++ [over.built]p6: 8969 // For every cv-qualified or cv-unqualified object type T, there 8970 // exist candidate operator functions of the form 8971 // 8972 // T& operator*(T*); 8973 // 8974 // C++ [over.built]p7: 8975 // For every function type T that does not have cv-qualifiers or a 8976 // ref-qualifier, there exist candidate operator functions of the form 8977 // T& operator*(T*); 8978 void addUnaryStarPointerOverloads() { 8979 for (QualType ParamTy : CandidateTypes[0].pointer_types()) { 8980 QualType PointeeTy = ParamTy->getPointeeType(); 8981 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8982 continue; 8983 8984 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8985 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8986 continue; 8987 8988 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8989 } 8990 } 8991 8992 // C++ [over.built]p9: 8993 // For every promoted arithmetic type T, there exist candidate 8994 // operator functions of the form 8995 // 8996 // T operator+(T); 8997 // T operator-(T); 8998 void addUnaryPlusOrMinusArithmeticOverloads() { 8999 if (!HasArithmeticOrEnumeralCandidateType) 9000 return; 9001 9002 for (unsigned Arith = FirstPromotedArithmeticType; 9003 Arith < LastPromotedArithmeticType; ++Arith) { 9004 QualType ArithTy = ArithmeticTypes[Arith]; 9005 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 9006 } 9007 9008 // Extension: We also add these operators for vector types. 9009 for (QualType VecTy : CandidateTypes[0].vector_types()) 9010 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 9011 } 9012 9013 // C++ [over.built]p8: 9014 // For every type T, there exist candidate operator functions of 9015 // the form 9016 // 9017 // T* operator+(T*); 9018 void addUnaryPlusPointerOverloads() { 9019 for (QualType ParamTy : CandidateTypes[0].pointer_types()) 9020 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 9021 } 9022 9023 // C++ [over.built]p10: 9024 // For every promoted integral type T, there exist candidate 9025 // operator functions of the form 9026 // 9027 // T operator~(T); 9028 void addUnaryTildePromotedIntegralOverloads() { 9029 if (!HasArithmeticOrEnumeralCandidateType) 9030 return; 9031 9032 for (unsigned Int = FirstPromotedIntegralType; 9033 Int < LastPromotedIntegralType; ++Int) { 9034 QualType IntTy = ArithmeticTypes[Int]; 9035 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 9036 } 9037 9038 // Extension: We also add this operator for vector types. 9039 for (QualType VecTy : CandidateTypes[0].vector_types()) 9040 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 9041 } 9042 9043 // C++ [over.match.oper]p16: 9044 // For every pointer to member type T or type std::nullptr_t, there 9045 // exist candidate operator functions of the form 9046 // 9047 // bool operator==(T,T); 9048 // bool operator!=(T,T); 9049 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 9050 /// Set of (canonical) types that we've already handled. 9051 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9052 9053 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9054 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9055 // Don't add the same builtin candidate twice. 9056 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9057 continue; 9058 9059 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9060 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9061 } 9062 9063 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 9064 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 9065 if (AddedTypes.insert(NullPtrTy).second) { 9066 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 9067 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9068 } 9069 } 9070 } 9071 } 9072 9073 // C++ [over.built]p15: 9074 // 9075 // For every T, where T is an enumeration type or a pointer type, 9076 // there exist candidate operator functions of the form 9077 // 9078 // bool operator<(T, T); 9079 // bool operator>(T, T); 9080 // bool operator<=(T, T); 9081 // bool operator>=(T, T); 9082 // bool operator==(T, T); 9083 // bool operator!=(T, T); 9084 // R operator<=>(T, T) 9085 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) { 9086 // C++ [over.match.oper]p3: 9087 // [...]the built-in candidates include all of the candidate operator 9088 // functions defined in 13.6 that, compared to the given operator, [...] 9089 // do not have the same parameter-type-list as any non-template non-member 9090 // candidate. 9091 // 9092 // Note that in practice, this only affects enumeration types because there 9093 // aren't any built-in candidates of record type, and a user-defined operator 9094 // must have an operand of record or enumeration type. Also, the only other 9095 // overloaded operator with enumeration arguments, operator=, 9096 // cannot be overloaded for enumeration types, so this is the only place 9097 // where we must suppress candidates like this. 9098 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 9099 UserDefinedBinaryOperators; 9100 9101 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9102 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) { 9103 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 9104 CEnd = CandidateSet.end(); 9105 C != CEnd; ++C) { 9106 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 9107 continue; 9108 9109 if (C->Function->isFunctionTemplateSpecialization()) 9110 continue; 9111 9112 // We interpret "same parameter-type-list" as applying to the 9113 // "synthesized candidate, with the order of the two parameters 9114 // reversed", not to the original function. 9115 bool Reversed = C->isReversed(); 9116 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 9117 ->getType() 9118 .getUnqualifiedType(); 9119 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 9120 ->getType() 9121 .getUnqualifiedType(); 9122 9123 // Skip if either parameter isn't of enumeral type. 9124 if (!FirstParamType->isEnumeralType() || 9125 !SecondParamType->isEnumeralType()) 9126 continue; 9127 9128 // Add this operator to the set of known user-defined operators. 9129 UserDefinedBinaryOperators.insert( 9130 std::make_pair(S.Context.getCanonicalType(FirstParamType), 9131 S.Context.getCanonicalType(SecondParamType))); 9132 } 9133 } 9134 } 9135 9136 /// Set of (canonical) types that we've already handled. 9137 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9138 9139 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9140 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9141 // Don't add the same builtin candidate twice. 9142 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9143 continue; 9144 if (IsSpaceship && PtrTy->isFunctionPointerType()) 9145 continue; 9146 9147 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9148 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9149 } 9150 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9151 CanQualType CanonType = S.Context.getCanonicalType(EnumTy); 9152 9153 // Don't add the same builtin candidate twice, or if a user defined 9154 // candidate exists. 9155 if (!AddedTypes.insert(CanonType).second || 9156 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 9157 CanonType))) 9158 continue; 9159 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9160 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9161 } 9162 } 9163 } 9164 9165 // C++ [over.built]p13: 9166 // 9167 // For every cv-qualified or cv-unqualified object type T 9168 // there exist candidate operator functions of the form 9169 // 9170 // T* operator+(T*, ptrdiff_t); 9171 // T& operator[](T*, ptrdiff_t); [BELOW] 9172 // T* operator-(T*, ptrdiff_t); 9173 // T* operator+(ptrdiff_t, T*); 9174 // T& operator[](ptrdiff_t, T*); [BELOW] 9175 // 9176 // C++ [over.built]p14: 9177 // 9178 // For every T, where T is a pointer to object type, there 9179 // exist candidate operator functions of the form 9180 // 9181 // ptrdiff_t operator-(T, T); 9182 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 9183 /// Set of (canonical) types that we've already handled. 9184 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9185 9186 for (int Arg = 0; Arg < 2; ++Arg) { 9187 QualType AsymmetricParamTypes[2] = { 9188 S.Context.getPointerDiffType(), 9189 S.Context.getPointerDiffType(), 9190 }; 9191 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) { 9192 QualType PointeeTy = PtrTy->getPointeeType(); 9193 if (!PointeeTy->isObjectType()) 9194 continue; 9195 9196 AsymmetricParamTypes[Arg] = PtrTy; 9197 if (Arg == 0 || Op == OO_Plus) { 9198 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 9199 // T* operator+(ptrdiff_t, T*); 9200 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 9201 } 9202 if (Op == OO_Minus) { 9203 // ptrdiff_t operator-(T, T); 9204 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9205 continue; 9206 9207 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9208 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9209 } 9210 } 9211 } 9212 } 9213 9214 // C++ [over.built]p12: 9215 // 9216 // For every pair of promoted arithmetic types L and R, there 9217 // exist candidate operator functions of the form 9218 // 9219 // LR operator*(L, R); 9220 // LR operator/(L, R); 9221 // LR operator+(L, R); 9222 // LR operator-(L, R); 9223 // bool operator<(L, R); 9224 // bool operator>(L, R); 9225 // bool operator<=(L, R); 9226 // bool operator>=(L, R); 9227 // bool operator==(L, R); 9228 // bool operator!=(L, R); 9229 // 9230 // where LR is the result of the usual arithmetic conversions 9231 // between types L and R. 9232 // 9233 // C++ [over.built]p24: 9234 // 9235 // For every pair of promoted arithmetic types L and R, there exist 9236 // candidate operator functions of the form 9237 // 9238 // LR operator?(bool, L, R); 9239 // 9240 // where LR is the result of the usual arithmetic conversions 9241 // between types L and R. 9242 // Our candidates ignore the first parameter. 9243 void addGenericBinaryArithmeticOverloads() { 9244 if (!HasArithmeticOrEnumeralCandidateType) 9245 return; 9246 9247 for (unsigned Left = FirstPromotedArithmeticType; 9248 Left < LastPromotedArithmeticType; ++Left) { 9249 for (unsigned Right = FirstPromotedArithmeticType; 9250 Right < LastPromotedArithmeticType; ++Right) { 9251 QualType LandR[2] = { ArithmeticTypes[Left], 9252 ArithmeticTypes[Right] }; 9253 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9254 } 9255 } 9256 9257 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 9258 // conditional operator for vector types. 9259 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9260 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 9261 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 9262 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9263 } 9264 } 9265 9266 /// Add binary operator overloads for each candidate matrix type M1, M2: 9267 /// * (M1, M1) -> M1 9268 /// * (M1, M1.getElementType()) -> M1 9269 /// * (M2.getElementType(), M2) -> M2 9270 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 9271 void addMatrixBinaryArithmeticOverloads() { 9272 if (!HasArithmeticOrEnumeralCandidateType) 9273 return; 9274 9275 for (QualType M1 : CandidateTypes[0].matrix_types()) { 9276 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 9277 AddCandidate(M1, M1); 9278 } 9279 9280 for (QualType M2 : CandidateTypes[1].matrix_types()) { 9281 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 9282 if (!CandidateTypes[0].containsMatrixType(M2)) 9283 AddCandidate(M2, M2); 9284 } 9285 } 9286 9287 // C++2a [over.built]p14: 9288 // 9289 // For every integral type T there exists a candidate operator function 9290 // of the form 9291 // 9292 // std::strong_ordering operator<=>(T, T) 9293 // 9294 // C++2a [over.built]p15: 9295 // 9296 // For every pair of floating-point types L and R, there exists a candidate 9297 // operator function of the form 9298 // 9299 // std::partial_ordering operator<=>(L, R); 9300 // 9301 // FIXME: The current specification for integral types doesn't play nice with 9302 // the direction of p0946r0, which allows mixed integral and unscoped-enum 9303 // comparisons. Under the current spec this can lead to ambiguity during 9304 // overload resolution. For example: 9305 // 9306 // enum A : int {a}; 9307 // auto x = (a <=> (long)42); 9308 // 9309 // error: call is ambiguous for arguments 'A' and 'long'. 9310 // note: candidate operator<=>(int, int) 9311 // note: candidate operator<=>(long, long) 9312 // 9313 // To avoid this error, this function deviates from the specification and adds 9314 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 9315 // arithmetic types (the same as the generic relational overloads). 9316 // 9317 // For now this function acts as a placeholder. 9318 void addThreeWayArithmeticOverloads() { 9319 addGenericBinaryArithmeticOverloads(); 9320 } 9321 9322 // C++ [over.built]p17: 9323 // 9324 // For every pair of promoted integral types L and R, there 9325 // exist candidate operator functions of the form 9326 // 9327 // LR operator%(L, R); 9328 // LR operator&(L, R); 9329 // LR operator^(L, R); 9330 // LR operator|(L, R); 9331 // L operator<<(L, R); 9332 // L operator>>(L, R); 9333 // 9334 // where LR is the result of the usual arithmetic conversions 9335 // between types L and R. 9336 void addBinaryBitwiseArithmeticOverloads() { 9337 if (!HasArithmeticOrEnumeralCandidateType) 9338 return; 9339 9340 for (unsigned Left = FirstPromotedIntegralType; 9341 Left < LastPromotedIntegralType; ++Left) { 9342 for (unsigned Right = FirstPromotedIntegralType; 9343 Right < LastPromotedIntegralType; ++Right) { 9344 QualType LandR[2] = { ArithmeticTypes[Left], 9345 ArithmeticTypes[Right] }; 9346 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 9347 } 9348 } 9349 } 9350 9351 // C++ [over.built]p20: 9352 // 9353 // For every pair (T, VQ), where T is an enumeration or 9354 // pointer to member type and VQ is either volatile or 9355 // empty, there exist candidate operator functions of the form 9356 // 9357 // VQ T& operator=(VQ T&, T); 9358 void addAssignmentMemberPointerOrEnumeralOverloads() { 9359 /// Set of (canonical) types that we've already handled. 9360 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9361 9362 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9363 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9364 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9365 continue; 9366 9367 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet); 9368 } 9369 9370 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9371 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9372 continue; 9373 9374 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet); 9375 } 9376 } 9377 } 9378 9379 // C++ [over.built]p19: 9380 // 9381 // For every pair (T, VQ), where T is any type and VQ is either 9382 // volatile or empty, there exist candidate operator functions 9383 // of the form 9384 // 9385 // T*VQ& operator=(T*VQ&, T*); 9386 // 9387 // C++ [over.built]p21: 9388 // 9389 // For every pair (T, VQ), where T is a cv-qualified or 9390 // cv-unqualified object type and VQ is either volatile or 9391 // empty, there exist candidate operator functions of the form 9392 // 9393 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 9394 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 9395 void addAssignmentPointerOverloads(bool isEqualOp) { 9396 /// Set of (canonical) types that we've already handled. 9397 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9398 9399 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9400 // If this is operator=, keep track of the builtin candidates we added. 9401 if (isEqualOp) 9402 AddedTypes.insert(S.Context.getCanonicalType(PtrTy)); 9403 else if (!PtrTy->getPointeeType()->isObjectType()) 9404 continue; 9405 9406 // non-volatile version 9407 QualType ParamTypes[2] = { 9408 S.Context.getLValueReferenceType(PtrTy), 9409 isEqualOp ? PtrTy : S.Context.getPointerDiffType(), 9410 }; 9411 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9412 /*IsAssignmentOperator=*/ isEqualOp); 9413 9414 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9415 VisibleTypeConversionsQuals.hasVolatile(); 9416 if (NeedVolatile) { 9417 // volatile version 9418 ParamTypes[0] = 9419 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy)); 9420 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9421 /*IsAssignmentOperator=*/isEqualOp); 9422 } 9423 9424 if (!PtrTy.isRestrictQualified() && 9425 VisibleTypeConversionsQuals.hasRestrict()) { 9426 // restrict version 9427 ParamTypes[0] = 9428 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy)); 9429 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9430 /*IsAssignmentOperator=*/isEqualOp); 9431 9432 if (NeedVolatile) { 9433 // volatile restrict version 9434 ParamTypes[0] = 9435 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9436 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9437 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9438 /*IsAssignmentOperator=*/isEqualOp); 9439 } 9440 } 9441 } 9442 9443 if (isEqualOp) { 9444 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9445 // Make sure we don't add the same candidate twice. 9446 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9447 continue; 9448 9449 QualType ParamTypes[2] = { 9450 S.Context.getLValueReferenceType(PtrTy), 9451 PtrTy, 9452 }; 9453 9454 // non-volatile version 9455 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9456 /*IsAssignmentOperator=*/true); 9457 9458 bool NeedVolatile = !PtrTy.isVolatileQualified() && 9459 VisibleTypeConversionsQuals.hasVolatile(); 9460 if (NeedVolatile) { 9461 // volatile version 9462 ParamTypes[0] = S.Context.getLValueReferenceType( 9463 S.Context.getVolatileType(PtrTy)); 9464 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9465 /*IsAssignmentOperator=*/true); 9466 } 9467 9468 if (!PtrTy.isRestrictQualified() && 9469 VisibleTypeConversionsQuals.hasRestrict()) { 9470 // restrict version 9471 ParamTypes[0] = S.Context.getLValueReferenceType( 9472 S.Context.getRestrictType(PtrTy)); 9473 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9474 /*IsAssignmentOperator=*/true); 9475 9476 if (NeedVolatile) { 9477 // volatile restrict version 9478 ParamTypes[0] = 9479 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType( 9480 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict))); 9481 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9482 /*IsAssignmentOperator=*/true); 9483 } 9484 } 9485 } 9486 } 9487 } 9488 9489 // C++ [over.built]p18: 9490 // 9491 // For every triple (L, VQ, R), where L is an arithmetic type, 9492 // VQ is either volatile or empty, and R is a promoted 9493 // arithmetic type, there exist candidate operator functions of 9494 // the form 9495 // 9496 // VQ L& operator=(VQ L&, R); 9497 // VQ L& operator*=(VQ L&, R); 9498 // VQ L& operator/=(VQ L&, R); 9499 // VQ L& operator+=(VQ L&, R); 9500 // VQ L& operator-=(VQ L&, R); 9501 void addAssignmentArithmeticOverloads(bool isEqualOp) { 9502 if (!HasArithmeticOrEnumeralCandidateType) 9503 return; 9504 9505 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 9506 for (unsigned Right = FirstPromotedArithmeticType; 9507 Right < LastPromotedArithmeticType; ++Right) { 9508 QualType ParamTypes[2]; 9509 ParamTypes[1] = ArithmeticTypes[Right]; 9510 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9511 S, ArithmeticTypes[Left], Args[0]); 9512 9513 forAllQualifierCombinations( 9514 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9515 ParamTypes[0] = 9516 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9517 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9518 /*IsAssignmentOperator=*/isEqualOp); 9519 }); 9520 } 9521 } 9522 9523 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 9524 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 9525 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 9526 QualType ParamTypes[2]; 9527 ParamTypes[1] = Vec2Ty; 9528 // Add this built-in operator as a candidate (VQ is empty). 9529 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 9530 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9531 /*IsAssignmentOperator=*/isEqualOp); 9532 9533 // Add this built-in operator as a candidate (VQ is 'volatile'). 9534 if (VisibleTypeConversionsQuals.hasVolatile()) { 9535 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 9536 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 9537 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9538 /*IsAssignmentOperator=*/isEqualOp); 9539 } 9540 } 9541 } 9542 9543 // C++ [over.built]p22: 9544 // 9545 // For every triple (L, VQ, R), where L is an integral type, VQ 9546 // is either volatile or empty, and R is a promoted integral 9547 // type, there exist candidate operator functions of the form 9548 // 9549 // VQ L& operator%=(VQ L&, R); 9550 // VQ L& operator<<=(VQ L&, R); 9551 // VQ L& operator>>=(VQ L&, R); 9552 // VQ L& operator&=(VQ L&, R); 9553 // VQ L& operator^=(VQ L&, R); 9554 // VQ L& operator|=(VQ L&, R); 9555 void addAssignmentIntegralOverloads() { 9556 if (!HasArithmeticOrEnumeralCandidateType) 9557 return; 9558 9559 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 9560 for (unsigned Right = FirstPromotedIntegralType; 9561 Right < LastPromotedIntegralType; ++Right) { 9562 QualType ParamTypes[2]; 9563 ParamTypes[1] = ArithmeticTypes[Right]; 9564 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 9565 S, ArithmeticTypes[Left], Args[0]); 9566 9567 forAllQualifierCombinations( 9568 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) { 9569 ParamTypes[0] = 9570 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S); 9571 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9572 }); 9573 } 9574 } 9575 } 9576 9577 // C++ [over.operator]p23: 9578 // 9579 // There also exist candidate operator functions of the form 9580 // 9581 // bool operator!(bool); 9582 // bool operator&&(bool, bool); 9583 // bool operator||(bool, bool); 9584 void addExclaimOverload() { 9585 QualType ParamTy = S.Context.BoolTy; 9586 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 9587 /*IsAssignmentOperator=*/false, 9588 /*NumContextualBoolArguments=*/1); 9589 } 9590 void addAmpAmpOrPipePipeOverload() { 9591 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 9592 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 9593 /*IsAssignmentOperator=*/false, 9594 /*NumContextualBoolArguments=*/2); 9595 } 9596 9597 // C++ [over.built]p13: 9598 // 9599 // For every cv-qualified or cv-unqualified object type T there 9600 // exist candidate operator functions of the form 9601 // 9602 // T* operator+(T*, ptrdiff_t); [ABOVE] 9603 // T& operator[](T*, ptrdiff_t); 9604 // T* operator-(T*, ptrdiff_t); [ABOVE] 9605 // T* operator+(ptrdiff_t, T*); [ABOVE] 9606 // T& operator[](ptrdiff_t, T*); 9607 void addSubscriptOverloads() { 9608 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9609 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()}; 9610 QualType PointeeType = PtrTy->getPointeeType(); 9611 if (!PointeeType->isObjectType()) 9612 continue; 9613 9614 // T& operator[](T*, ptrdiff_t) 9615 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9616 } 9617 9618 for (QualType PtrTy : CandidateTypes[1].pointer_types()) { 9619 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy}; 9620 QualType PointeeType = PtrTy->getPointeeType(); 9621 if (!PointeeType->isObjectType()) 9622 continue; 9623 9624 // T& operator[](ptrdiff_t, T*) 9625 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9626 } 9627 } 9628 9629 // C++ [over.built]p11: 9630 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 9631 // C1 is the same type as C2 or is a derived class of C2, T is an object 9632 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 9633 // there exist candidate operator functions of the form 9634 // 9635 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 9636 // 9637 // where CV12 is the union of CV1 and CV2. 9638 void addArrowStarOverloads() { 9639 for (QualType PtrTy : CandidateTypes[0].pointer_types()) { 9640 QualType C1Ty = PtrTy; 9641 QualType C1; 9642 QualifierCollector Q1; 9643 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9644 if (!isa<RecordType>(C1)) 9645 continue; 9646 // heuristic to reduce number of builtin candidates in the set. 9647 // Add volatile/restrict version only if there are conversions to a 9648 // volatile/restrict type. 9649 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9650 continue; 9651 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9652 continue; 9653 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) { 9654 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy); 9655 QualType C2 = QualType(mptr->getClass(), 0); 9656 C2 = C2.getUnqualifiedType(); 9657 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9658 break; 9659 QualType ParamTypes[2] = {PtrTy, MemPtrTy}; 9660 // build CV12 T& 9661 QualType T = mptr->getPointeeType(); 9662 if (!VisibleTypeConversionsQuals.hasVolatile() && 9663 T.isVolatileQualified()) 9664 continue; 9665 if (!VisibleTypeConversionsQuals.hasRestrict() && 9666 T.isRestrictQualified()) 9667 continue; 9668 T = Q1.apply(S.Context, T); 9669 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9670 } 9671 } 9672 } 9673 9674 // Note that we don't consider the first argument, since it has been 9675 // contextually converted to bool long ago. The candidates below are 9676 // therefore added as binary. 9677 // 9678 // C++ [over.built]p25: 9679 // For every type T, where T is a pointer, pointer-to-member, or scoped 9680 // enumeration type, there exist candidate operator functions of the form 9681 // 9682 // T operator?(bool, T, T); 9683 // 9684 void addConditionalOperatorOverloads() { 9685 /// Set of (canonical) types that we've already handled. 9686 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9687 9688 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9689 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) { 9690 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second) 9691 continue; 9692 9693 QualType ParamTypes[2] = {PtrTy, PtrTy}; 9694 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9695 } 9696 9697 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) { 9698 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second) 9699 continue; 9700 9701 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy}; 9702 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9703 } 9704 9705 if (S.getLangOpts().CPlusPlus11) { 9706 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) { 9707 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped()) 9708 continue; 9709 9710 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second) 9711 continue; 9712 9713 QualType ParamTypes[2] = {EnumTy, EnumTy}; 9714 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9715 } 9716 } 9717 } 9718 } 9719 }; 9720 9721 } // end anonymous namespace 9722 9723 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9724 /// operator overloads to the candidate set (C++ [over.built]), based 9725 /// on the operator @p Op and the arguments given. For example, if the 9726 /// operator is a binary '+', this routine might add "int 9727 /// operator+(int, int)" to cover integer addition. 9728 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9729 SourceLocation OpLoc, 9730 ArrayRef<Expr *> Args, 9731 OverloadCandidateSet &CandidateSet) { 9732 // Find all of the types that the arguments can convert to, but only 9733 // if the operator we're looking at has built-in operator candidates 9734 // that make use of these types. Also record whether we encounter non-record 9735 // candidate types or either arithmetic or enumeral candidate types. 9736 QualifiersAndAtomic VisibleTypeConversionsQuals; 9737 VisibleTypeConversionsQuals.addConst(); 9738 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9739 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9740 if (Args[ArgIdx]->getType()->isAtomicType()) 9741 VisibleTypeConversionsQuals.addAtomic(); 9742 } 9743 9744 bool HasNonRecordCandidateType = false; 9745 bool HasArithmeticOrEnumeralCandidateType = false; 9746 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9747 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9748 CandidateTypes.emplace_back(*this); 9749 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9750 OpLoc, 9751 true, 9752 (Op == OO_Exclaim || 9753 Op == OO_AmpAmp || 9754 Op == OO_PipePipe), 9755 VisibleTypeConversionsQuals); 9756 HasNonRecordCandidateType = HasNonRecordCandidateType || 9757 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9758 HasArithmeticOrEnumeralCandidateType = 9759 HasArithmeticOrEnumeralCandidateType || 9760 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9761 } 9762 9763 // Exit early when no non-record types have been added to the candidate set 9764 // for any of the arguments to the operator. 9765 // 9766 // We can't exit early for !, ||, or &&, since there we have always have 9767 // 'bool' overloads. 9768 if (!HasNonRecordCandidateType && 9769 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9770 return; 9771 9772 // Setup an object to manage the common state for building overloads. 9773 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9774 VisibleTypeConversionsQuals, 9775 HasArithmeticOrEnumeralCandidateType, 9776 CandidateTypes, CandidateSet); 9777 9778 // Dispatch over the operation to add in only those overloads which apply. 9779 switch (Op) { 9780 case OO_None: 9781 case NUM_OVERLOADED_OPERATORS: 9782 llvm_unreachable("Expected an overloaded operator"); 9783 9784 case OO_New: 9785 case OO_Delete: 9786 case OO_Array_New: 9787 case OO_Array_Delete: 9788 case OO_Call: 9789 llvm_unreachable( 9790 "Special operators don't use AddBuiltinOperatorCandidates"); 9791 9792 case OO_Comma: 9793 case OO_Arrow: 9794 case OO_Coawait: 9795 // C++ [over.match.oper]p3: 9796 // -- For the operator ',', the unary operator '&', the 9797 // operator '->', or the operator 'co_await', the 9798 // built-in candidates set is empty. 9799 break; 9800 9801 case OO_Plus: // '+' is either unary or binary 9802 if (Args.size() == 1) 9803 OpBuilder.addUnaryPlusPointerOverloads(); 9804 [[fallthrough]]; 9805 9806 case OO_Minus: // '-' is either unary or binary 9807 if (Args.size() == 1) { 9808 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9809 } else { 9810 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9811 OpBuilder.addGenericBinaryArithmeticOverloads(); 9812 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9813 } 9814 break; 9815 9816 case OO_Star: // '*' is either unary or binary 9817 if (Args.size() == 1) 9818 OpBuilder.addUnaryStarPointerOverloads(); 9819 else { 9820 OpBuilder.addGenericBinaryArithmeticOverloads(); 9821 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9822 } 9823 break; 9824 9825 case OO_Slash: 9826 OpBuilder.addGenericBinaryArithmeticOverloads(); 9827 break; 9828 9829 case OO_PlusPlus: 9830 case OO_MinusMinus: 9831 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9832 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9833 break; 9834 9835 case OO_EqualEqual: 9836 case OO_ExclaimEqual: 9837 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9838 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9839 OpBuilder.addGenericBinaryArithmeticOverloads(); 9840 break; 9841 9842 case OO_Less: 9843 case OO_Greater: 9844 case OO_LessEqual: 9845 case OO_GreaterEqual: 9846 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false); 9847 OpBuilder.addGenericBinaryArithmeticOverloads(); 9848 break; 9849 9850 case OO_Spaceship: 9851 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true); 9852 OpBuilder.addThreeWayArithmeticOverloads(); 9853 break; 9854 9855 case OO_Percent: 9856 case OO_Caret: 9857 case OO_Pipe: 9858 case OO_LessLess: 9859 case OO_GreaterGreater: 9860 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9861 break; 9862 9863 case OO_Amp: // '&' is either unary or binary 9864 if (Args.size() == 1) 9865 // C++ [over.match.oper]p3: 9866 // -- For the operator ',', the unary operator '&', or the 9867 // operator '->', the built-in candidates set is empty. 9868 break; 9869 9870 OpBuilder.addBinaryBitwiseArithmeticOverloads(); 9871 break; 9872 9873 case OO_Tilde: 9874 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9875 break; 9876 9877 case OO_Equal: 9878 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9879 [[fallthrough]]; 9880 9881 case OO_PlusEqual: 9882 case OO_MinusEqual: 9883 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9884 [[fallthrough]]; 9885 9886 case OO_StarEqual: 9887 case OO_SlashEqual: 9888 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9889 break; 9890 9891 case OO_PercentEqual: 9892 case OO_LessLessEqual: 9893 case OO_GreaterGreaterEqual: 9894 case OO_AmpEqual: 9895 case OO_CaretEqual: 9896 case OO_PipeEqual: 9897 OpBuilder.addAssignmentIntegralOverloads(); 9898 break; 9899 9900 case OO_Exclaim: 9901 OpBuilder.addExclaimOverload(); 9902 break; 9903 9904 case OO_AmpAmp: 9905 case OO_PipePipe: 9906 OpBuilder.addAmpAmpOrPipePipeOverload(); 9907 break; 9908 9909 case OO_Subscript: 9910 if (Args.size() == 2) 9911 OpBuilder.addSubscriptOverloads(); 9912 break; 9913 9914 case OO_ArrowStar: 9915 OpBuilder.addArrowStarOverloads(); 9916 break; 9917 9918 case OO_Conditional: 9919 OpBuilder.addConditionalOperatorOverloads(); 9920 OpBuilder.addGenericBinaryArithmeticOverloads(); 9921 break; 9922 } 9923 } 9924 9925 /// Add function candidates found via argument-dependent lookup 9926 /// to the set of overloading candidates. 9927 /// 9928 /// This routine performs argument-dependent name lookup based on the 9929 /// given function name (which may also be an operator name) and adds 9930 /// all of the overload candidates found by ADL to the overload 9931 /// candidate set (C++ [basic.lookup.argdep]). 9932 void 9933 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9934 SourceLocation Loc, 9935 ArrayRef<Expr *> Args, 9936 TemplateArgumentListInfo *ExplicitTemplateArgs, 9937 OverloadCandidateSet& CandidateSet, 9938 bool PartialOverloading) { 9939 ADLResult Fns; 9940 9941 // FIXME: This approach for uniquing ADL results (and removing 9942 // redundant candidates from the set) relies on pointer-equality, 9943 // which means we need to key off the canonical decl. However, 9944 // always going back to the canonical decl might not get us the 9945 // right set of default arguments. What default arguments are 9946 // we supposed to consider on ADL candidates, anyway? 9947 9948 // FIXME: Pass in the explicit template arguments? 9949 ArgumentDependentLookup(Name, Loc, Args, Fns); 9950 9951 // Erase all of the candidates we already knew about. 9952 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9953 CandEnd = CandidateSet.end(); 9954 Cand != CandEnd; ++Cand) 9955 if (Cand->Function) { 9956 Fns.erase(Cand->Function); 9957 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9958 Fns.erase(FunTmpl); 9959 } 9960 9961 // For each of the ADL candidates we found, add it to the overload 9962 // set. 9963 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9964 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9965 9966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9967 if (ExplicitTemplateArgs) 9968 continue; 9969 9970 AddOverloadCandidate( 9971 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9972 PartialOverloading, /*AllowExplicit=*/true, 9973 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL); 9974 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) { 9975 AddOverloadCandidate( 9976 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9977 /*SuppressUserConversions=*/false, PartialOverloading, 9978 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false, 9979 ADLCallKind::UsesADL, std::nullopt, 9980 OverloadCandidateParamOrder::Reversed); 9981 } 9982 } else { 9983 auto *FTD = cast<FunctionTemplateDecl>(*I); 9984 AddTemplateOverloadCandidate( 9985 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9986 /*SuppressUserConversions=*/false, PartialOverloading, 9987 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9988 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9989 *this, Args, FTD->getTemplatedDecl())) { 9990 AddTemplateOverloadCandidate( 9991 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9992 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9993 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9994 OverloadCandidateParamOrder::Reversed); 9995 } 9996 } 9997 } 9998 } 9999 10000 namespace { 10001 enum class Comparison { Equal, Better, Worse }; 10002 } 10003 10004 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 10005 /// overload resolution. 10006 /// 10007 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 10008 /// Cand1's first N enable_if attributes have precisely the same conditions as 10009 /// Cand2's first N enable_if attributes (where N = the number of enable_if 10010 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 10011 /// 10012 /// Note that you can have a pair of candidates such that Cand1's enable_if 10013 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 10014 /// worse than Cand1's. 10015 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 10016 const FunctionDecl *Cand2) { 10017 // Common case: One (or both) decls don't have enable_if attrs. 10018 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 10019 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 10020 if (!Cand1Attr || !Cand2Attr) { 10021 if (Cand1Attr == Cand2Attr) 10022 return Comparison::Equal; 10023 return Cand1Attr ? Comparison::Better : Comparison::Worse; 10024 } 10025 10026 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 10027 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 10028 10029 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 10030 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 10031 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 10032 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 10033 10034 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 10035 // has fewer enable_if attributes than Cand2, and vice versa. 10036 if (!Cand1A) 10037 return Comparison::Worse; 10038 if (!Cand2A) 10039 return Comparison::Better; 10040 10041 Cand1ID.clear(); 10042 Cand2ID.clear(); 10043 10044 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 10045 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 10046 if (Cand1ID != Cand2ID) 10047 return Comparison::Worse; 10048 } 10049 10050 return Comparison::Equal; 10051 } 10052 10053 static Comparison 10054 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 10055 const OverloadCandidate &Cand2) { 10056 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 10057 !Cand2.Function->isMultiVersion()) 10058 return Comparison::Equal; 10059 10060 // If both are invalid, they are equal. If one of them is invalid, the other 10061 // is better. 10062 if (Cand1.Function->isInvalidDecl()) { 10063 if (Cand2.Function->isInvalidDecl()) 10064 return Comparison::Equal; 10065 return Comparison::Worse; 10066 } 10067 if (Cand2.Function->isInvalidDecl()) 10068 return Comparison::Better; 10069 10070 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 10071 // cpu_dispatch, else arbitrarily based on the identifiers. 10072 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 10073 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 10074 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 10075 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 10076 10077 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 10078 return Comparison::Equal; 10079 10080 if (Cand1CPUDisp && !Cand2CPUDisp) 10081 return Comparison::Better; 10082 if (Cand2CPUDisp && !Cand1CPUDisp) 10083 return Comparison::Worse; 10084 10085 if (Cand1CPUSpec && Cand2CPUSpec) { 10086 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 10087 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 10088 ? Comparison::Better 10089 : Comparison::Worse; 10090 10091 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 10092 FirstDiff = std::mismatch( 10093 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 10094 Cand2CPUSpec->cpus_begin(), 10095 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 10096 return LHS->getName() == RHS->getName(); 10097 }); 10098 10099 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 10100 "Two different cpu-specific versions should not have the same " 10101 "identifier list, otherwise they'd be the same decl!"); 10102 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 10103 ? Comparison::Better 10104 : Comparison::Worse; 10105 } 10106 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 10107 } 10108 10109 /// Compute the type of the implicit object parameter for the given function, 10110 /// if any. Returns std::nullopt if there is no implicit object parameter, and a 10111 /// null QualType if there is a 'matches anything' implicit object parameter. 10112 static std::optional<QualType> 10113 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) { 10114 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 10115 return std::nullopt; 10116 10117 auto *M = cast<CXXMethodDecl>(F); 10118 // Static member functions' object parameters match all types. 10119 if (M->isStatic()) 10120 return QualType(); 10121 return M->getFunctionObjectParameterReferenceType(); 10122 } 10123 10124 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 10125 const FunctionDecl *F2) { 10126 if (declaresSameEntity(F1, F2)) 10127 return true; 10128 10129 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 10130 if (First) { 10131 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F)) 10132 return *T; 10133 } 10134 assert(I < F->getNumParams()); 10135 return F->getParamDecl(I++)->getType(); 10136 }; 10137 10138 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1); 10139 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2); 10140 10141 if (F1NumParams != F2NumParams) 10142 return false; 10143 10144 unsigned I1 = 0, I2 = 0; 10145 for (unsigned I = 0; I != F1NumParams; ++I) { 10146 QualType T1 = NextParam(F1, I1, I == 0); 10147 QualType T2 = NextParam(F2, I2, I == 0); 10148 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types"); 10149 if (!Context.hasSameUnqualifiedType(T1, T2)) 10150 return false; 10151 } 10152 return true; 10153 } 10154 10155 /// We're allowed to use constraints partial ordering only if the candidates 10156 /// have the same parameter types: 10157 /// [over.match.best.general]p2.6 10158 /// F1 and F2 are non-template functions with the same 10159 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...] 10160 static bool sameFunctionParameterTypeLists(Sema &S, 10161 const OverloadCandidate &Cand1, 10162 const OverloadCandidate &Cand2) { 10163 if (!Cand1.Function || !Cand2.Function) 10164 return false; 10165 10166 FunctionDecl *Fn1 = Cand1.Function; 10167 FunctionDecl *Fn2 = Cand2.Function; 10168 10169 if (Fn1->isVariadic() != Fn1->isVariadic()) 10170 return false; 10171 10172 if (!S.FunctionNonObjectParamTypesAreEqual( 10173 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed())) 10174 return false; 10175 10176 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1); 10177 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2); 10178 if (Mem1 && Mem2) { 10179 // if they are member functions, both are direct members of the same class, 10180 // and 10181 if (Mem1->getParent() != Mem2->getParent()) 10182 return false; 10183 // if both are non-static member functions, they have the same types for 10184 // their object parameters 10185 if (Mem1->isInstance() && Mem2->isInstance() && 10186 !S.getASTContext().hasSameType( 10187 Mem1->getFunctionObjectParameterReferenceType(), 10188 Mem1->getFunctionObjectParameterReferenceType())) 10189 return false; 10190 } 10191 return true; 10192 } 10193 10194 /// isBetterOverloadCandidate - Determines whether the first overload 10195 /// candidate is a better candidate than the second (C++ 13.3.3p1). 10196 bool clang::isBetterOverloadCandidate( 10197 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 10198 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 10199 // Define viable functions to be better candidates than non-viable 10200 // functions. 10201 if (!Cand2.Viable) 10202 return Cand1.Viable; 10203 else if (!Cand1.Viable) 10204 return false; 10205 10206 // [CUDA] A function with 'never' preference is marked not viable, therefore 10207 // is never shown up here. The worst preference shown up here is 'wrong side', 10208 // e.g. an H function called by a HD function in device compilation. This is 10209 // valid AST as long as the HD function is not emitted, e.g. it is an inline 10210 // function which is called only by an H function. A deferred diagnostic will 10211 // be triggered if it is emitted. However a wrong-sided function is still 10212 // a viable candidate here. 10213 // 10214 // If Cand1 can be emitted and Cand2 cannot be emitted in the current 10215 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2 10216 // can be emitted, Cand1 is not better than Cand2. This rule should have 10217 // precedence over other rules. 10218 // 10219 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then 10220 // other rules should be used to determine which is better. This is because 10221 // host/device based overloading resolution is mostly for determining 10222 // viability of a function. If two functions are both viable, other factors 10223 // should take precedence in preference, e.g. the standard-defined preferences 10224 // like argument conversion ranks or enable_if partial-ordering. The 10225 // preference for pass-object-size parameters is probably most similar to a 10226 // type-based-overloading decision and so should take priority. 10227 // 10228 // If other rules cannot determine which is better, CUDA preference will be 10229 // used again to determine which is better. 10230 // 10231 // TODO: Currently IdentifyCUDAPreference does not return correct values 10232 // for functions called in global variable initializers due to missing 10233 // correct context about device/host. Therefore we can only enforce this 10234 // rule when there is a caller. We should enforce this rule for functions 10235 // in global variable initializers once proper context is added. 10236 // 10237 // TODO: We can only enable the hostness based overloading resolution when 10238 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring 10239 // overloading resolution diagnostics. 10240 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function && 10241 S.getLangOpts().GPUExcludeWrongSideOverloads) { 10242 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) { 10243 bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller); 10244 bool IsCand1ImplicitHD = 10245 Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function); 10246 bool IsCand2ImplicitHD = 10247 Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function); 10248 auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function); 10249 auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function); 10250 assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never); 10251 // The implicit HD function may be a function in a system header which 10252 // is forced by pragma. In device compilation, if we prefer HD candidates 10253 // over wrong-sided candidates, overloading resolution may change, which 10254 // may result in non-deferrable diagnostics. As a workaround, we let 10255 // implicit HD candidates take equal preference as wrong-sided candidates. 10256 // This will preserve the overloading resolution. 10257 // TODO: We still need special handling of implicit HD functions since 10258 // they may incur other diagnostics to be deferred. We should make all 10259 // host/device related diagnostics deferrable and remove special handling 10260 // of implicit HD functions. 10261 auto EmitThreshold = 10262 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD && 10263 (IsCand1ImplicitHD || IsCand2ImplicitHD)) 10264 ? Sema::CFP_Never 10265 : Sema::CFP_WrongSide; 10266 auto Cand1Emittable = P1 > EmitThreshold; 10267 auto Cand2Emittable = P2 > EmitThreshold; 10268 if (Cand1Emittable && !Cand2Emittable) 10269 return true; 10270 if (!Cand1Emittable && Cand2Emittable) 10271 return false; 10272 } 10273 } 10274 10275 // C++ [over.match.best]p1: (Changed in C++23) 10276 // 10277 // -- if F is a static member function, ICS1(F) is defined such 10278 // that ICS1(F) is neither better nor worse than ICS1(G) for 10279 // any function G, and, symmetrically, ICS1(G) is neither 10280 // better nor worse than ICS1(F). 10281 unsigned StartArg = 0; 10282 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 10283 StartArg = 1; 10284 10285 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 10286 // We don't allow incompatible pointer conversions in C++. 10287 if (!S.getLangOpts().CPlusPlus) 10288 return ICS.isStandard() && 10289 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 10290 10291 // The only ill-formed conversion we allow in C++ is the string literal to 10292 // char* conversion, which is only considered ill-formed after C++11. 10293 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 10294 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 10295 }; 10296 10297 // Define functions that don't require ill-formed conversions for a given 10298 // argument to be better candidates than functions that do. 10299 unsigned NumArgs = Cand1.Conversions.size(); 10300 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 10301 bool HasBetterConversion = false; 10302 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 10303 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 10304 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 10305 if (Cand1Bad != Cand2Bad) { 10306 if (Cand1Bad) 10307 return false; 10308 HasBetterConversion = true; 10309 } 10310 } 10311 10312 if (HasBetterConversion) 10313 return true; 10314 10315 // C++ [over.match.best]p1: 10316 // A viable function F1 is defined to be a better function than another 10317 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 10318 // conversion sequence than ICSi(F2), and then... 10319 bool HasWorseConversion = false; 10320 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 10321 switch (CompareImplicitConversionSequences(S, Loc, 10322 Cand1.Conversions[ArgIdx], 10323 Cand2.Conversions[ArgIdx])) { 10324 case ImplicitConversionSequence::Better: 10325 // Cand1 has a better conversion sequence. 10326 HasBetterConversion = true; 10327 break; 10328 10329 case ImplicitConversionSequence::Worse: 10330 if (Cand1.Function && Cand2.Function && 10331 Cand1.isReversed() != Cand2.isReversed() && 10332 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function)) { 10333 // Work around large-scale breakage caused by considering reversed 10334 // forms of operator== in C++20: 10335 // 10336 // When comparing a function against a reversed function with the same 10337 // parameter types, if we have a better conversion for one argument and 10338 // a worse conversion for the other, the implicit conversion sequences 10339 // are treated as being equally good. 10340 // 10341 // This prevents a comparison function from being considered ambiguous 10342 // with a reversed form that is written in the same way. 10343 // 10344 // We diagnose this as an extension from CreateOverloadedBinOp. 10345 HasWorseConversion = true; 10346 break; 10347 } 10348 10349 // Cand1 can't be better than Cand2. 10350 return false; 10351 10352 case ImplicitConversionSequence::Indistinguishable: 10353 // Do nothing. 10354 break; 10355 } 10356 } 10357 10358 // -- for some argument j, ICSj(F1) is a better conversion sequence than 10359 // ICSj(F2), or, if not that, 10360 if (HasBetterConversion && !HasWorseConversion) 10361 return true; 10362 10363 // -- the context is an initialization by user-defined conversion 10364 // (see 8.5, 13.3.1.5) and the standard conversion sequence 10365 // from the return type of F1 to the destination type (i.e., 10366 // the type of the entity being initialized) is a better 10367 // conversion sequence than the standard conversion sequence 10368 // from the return type of F2 to the destination type. 10369 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 10370 Cand1.Function && Cand2.Function && 10371 isa<CXXConversionDecl>(Cand1.Function) && 10372 isa<CXXConversionDecl>(Cand2.Function)) { 10373 // First check whether we prefer one of the conversion functions over the 10374 // other. This only distinguishes the results in non-standard, extension 10375 // cases such as the conversion from a lambda closure type to a function 10376 // pointer or block. 10377 ImplicitConversionSequence::CompareKind Result = 10378 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 10379 if (Result == ImplicitConversionSequence::Indistinguishable) 10380 Result = CompareStandardConversionSequences(S, Loc, 10381 Cand1.FinalConversion, 10382 Cand2.FinalConversion); 10383 10384 if (Result != ImplicitConversionSequence::Indistinguishable) 10385 return Result == ImplicitConversionSequence::Better; 10386 10387 // FIXME: Compare kind of reference binding if conversion functions 10388 // convert to a reference type used in direct reference binding, per 10389 // C++14 [over.match.best]p1 section 2 bullet 3. 10390 } 10391 10392 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 10393 // as combined with the resolution to CWG issue 243. 10394 // 10395 // When the context is initialization by constructor ([over.match.ctor] or 10396 // either phase of [over.match.list]), a constructor is preferred over 10397 // a conversion function. 10398 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 10399 Cand1.Function && Cand2.Function && 10400 isa<CXXConstructorDecl>(Cand1.Function) != 10401 isa<CXXConstructorDecl>(Cand2.Function)) 10402 return isa<CXXConstructorDecl>(Cand1.Function); 10403 10404 // -- F1 is a non-template function and F2 is a function template 10405 // specialization, or, if not that, 10406 bool Cand1IsSpecialization = Cand1.Function && 10407 Cand1.Function->getPrimaryTemplate(); 10408 bool Cand2IsSpecialization = Cand2.Function && 10409 Cand2.Function->getPrimaryTemplate(); 10410 if (Cand1IsSpecialization != Cand2IsSpecialization) 10411 return Cand2IsSpecialization; 10412 10413 // -- F1 and F2 are function template specializations, and the function 10414 // template for F1 is more specialized than the template for F2 10415 // according to the partial ordering rules described in 14.5.5.2, or, 10416 // if not that, 10417 if (Cand1IsSpecialization && Cand2IsSpecialization) { 10418 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 10419 Cand1.Function->getPrimaryTemplate(), 10420 Cand2.Function->getPrimaryTemplate(), Loc, 10421 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 10422 : TPOC_Call, 10423 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 10424 Cand1.isReversed() ^ Cand2.isReversed())) 10425 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 10426 } 10427 10428 // -— F1 and F2 are non-template functions with the same 10429 // parameter-type-lists, and F1 is more constrained than F2 [...], 10430 if (!Cand1IsSpecialization && !Cand2IsSpecialization && 10431 sameFunctionParameterTypeLists(S, Cand1, Cand2)) { 10432 FunctionDecl *Function1 = Cand1.Function; 10433 FunctionDecl *Function2 = Cand2.Function; 10434 if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction()) 10435 Function1 = MF; 10436 if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction()) 10437 Function2 = MF; 10438 10439 const Expr *RC1 = Function1->getTrailingRequiresClause(); 10440 const Expr *RC2 = Function2->getTrailingRequiresClause(); 10441 if (RC1 && RC2) { 10442 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 10443 if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2, 10444 AtLeastAsConstrained1) || 10445 S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1, 10446 AtLeastAsConstrained2)) 10447 return false; 10448 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 10449 return AtLeastAsConstrained1; 10450 } else if (RC1 || RC2) { 10451 return RC1 != nullptr; 10452 } 10453 } 10454 10455 // -- F1 is a constructor for a class D, F2 is a constructor for a base 10456 // class B of D, and for all arguments the corresponding parameters of 10457 // F1 and F2 have the same type. 10458 // FIXME: Implement the "all parameters have the same type" check. 10459 bool Cand1IsInherited = 10460 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 10461 bool Cand2IsInherited = 10462 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 10463 if (Cand1IsInherited != Cand2IsInherited) 10464 return Cand2IsInherited; 10465 else if (Cand1IsInherited) { 10466 assert(Cand2IsInherited); 10467 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 10468 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 10469 if (Cand1Class->isDerivedFrom(Cand2Class)) 10470 return true; 10471 if (Cand2Class->isDerivedFrom(Cand1Class)) 10472 return false; 10473 // Inherited from sibling base classes: still ambiguous. 10474 } 10475 10476 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 10477 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 10478 // with reversed order of parameters and F1 is not 10479 // 10480 // We rank reversed + different operator as worse than just reversed, but 10481 // that comparison can never happen, because we only consider reversing for 10482 // the maximally-rewritten operator (== or <=>). 10483 if (Cand1.RewriteKind != Cand2.RewriteKind) 10484 return Cand1.RewriteKind < Cand2.RewriteKind; 10485 10486 // Check C++17 tie-breakers for deduction guides. 10487 { 10488 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 10489 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 10490 if (Guide1 && Guide2) { 10491 // -- F1 is generated from a deduction-guide and F2 is not 10492 if (Guide1->isImplicit() != Guide2->isImplicit()) 10493 return Guide2->isImplicit(); 10494 10495 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 10496 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy) 10497 return true; 10498 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy) 10499 return false; 10500 10501 // --F1 is generated from a non-template constructor and F2 is generated 10502 // from a constructor template 10503 const auto *Constructor1 = Guide1->getCorrespondingConstructor(); 10504 const auto *Constructor2 = Guide2->getCorrespondingConstructor(); 10505 if (Constructor1 && Constructor2) { 10506 bool isC1Templated = Constructor1->getTemplatedKind() != 10507 FunctionDecl::TemplatedKind::TK_NonTemplate; 10508 bool isC2Templated = Constructor2->getTemplatedKind() != 10509 FunctionDecl::TemplatedKind::TK_NonTemplate; 10510 if (isC1Templated != isC2Templated) 10511 return isC2Templated; 10512 } 10513 } 10514 } 10515 10516 // Check for enable_if value-based overload resolution. 10517 if (Cand1.Function && Cand2.Function) { 10518 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 10519 if (Cmp != Comparison::Equal) 10520 return Cmp == Comparison::Better; 10521 } 10522 10523 bool HasPS1 = Cand1.Function != nullptr && 10524 functionHasPassObjectSizeParams(Cand1.Function); 10525 bool HasPS2 = Cand2.Function != nullptr && 10526 functionHasPassObjectSizeParams(Cand2.Function); 10527 if (HasPS1 != HasPS2 && HasPS1) 10528 return true; 10529 10530 auto MV = isBetterMultiversionCandidate(Cand1, Cand2); 10531 if (MV == Comparison::Better) 10532 return true; 10533 if (MV == Comparison::Worse) 10534 return false; 10535 10536 // If other rules cannot determine which is better, CUDA preference is used 10537 // to determine which is better. 10538 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 10539 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10540 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 10541 S.IdentifyCUDAPreference(Caller, Cand2.Function); 10542 } 10543 10544 // General member function overloading is handled above, so this only handles 10545 // constructors with address spaces. 10546 // This only handles address spaces since C++ has no other 10547 // qualifier that can be used with constructors. 10548 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function); 10549 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function); 10550 if (CD1 && CD2) { 10551 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace(); 10552 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace(); 10553 if (AS1 != AS2) { 10554 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1)) 10555 return true; 10556 if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2)) 10557 return false; 10558 } 10559 } 10560 10561 return false; 10562 } 10563 10564 /// Determine whether two declarations are "equivalent" for the purposes of 10565 /// name lookup and overload resolution. This applies when the same internal/no 10566 /// linkage entity is defined by two modules (probably by textually including 10567 /// the same header). In such a case, we don't consider the declarations to 10568 /// declare the same entity, but we also don't want lookups with both 10569 /// declarations visible to be ambiguous in some cases (this happens when using 10570 /// a modularized libstdc++). 10571 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10572 const NamedDecl *B) { 10573 auto *VA = dyn_cast_or_null<ValueDecl>(A); 10574 auto *VB = dyn_cast_or_null<ValueDecl>(B); 10575 if (!VA || !VB) 10576 return false; 10577 10578 // The declarations must be declaring the same name as an internal linkage 10579 // entity in different modules. 10580 if (!VA->getDeclContext()->getRedeclContext()->Equals( 10581 VB->getDeclContext()->getRedeclContext()) || 10582 getOwningModule(VA) == getOwningModule(VB) || 10583 VA->isExternallyVisible() || VB->isExternallyVisible()) 10584 return false; 10585 10586 // Check that the declarations appear to be equivalent. 10587 // 10588 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 10589 // For constants and functions, we should check the initializer or body is 10590 // the same. For non-constant variables, we shouldn't allow it at all. 10591 if (Context.hasSameType(VA->getType(), VB->getType())) 10592 return true; 10593 10594 // Enum constants within unnamed enumerations will have different types, but 10595 // may still be similar enough to be interchangeable for our purposes. 10596 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 10597 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 10598 // Only handle anonymous enums. If the enumerations were named and 10599 // equivalent, they would have been merged to the same type. 10600 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 10601 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 10602 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 10603 !Context.hasSameType(EnumA->getIntegerType(), 10604 EnumB->getIntegerType())) 10605 return false; 10606 // Allow this only if the value is the same for both enumerators. 10607 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 10608 } 10609 } 10610 10611 // Nothing else is sufficiently similar. 10612 return false; 10613 } 10614 10615 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 10616 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 10617 assert(D && "Unknown declaration"); 10618 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 10619 10620 Module *M = getOwningModule(D); 10621 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 10622 << !M << (M ? M->getFullModuleName() : ""); 10623 10624 for (auto *E : Equiv) { 10625 Module *M = getOwningModule(E); 10626 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 10627 << !M << (M ? M->getFullModuleName() : ""); 10628 } 10629 } 10630 10631 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const { 10632 return FailureKind == ovl_fail_bad_deduction && 10633 DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied && 10634 static_cast<CNSInfo *>(DeductionFailure.Data) 10635 ->Satisfaction.ContainsErrors; 10636 } 10637 10638 /// Computes the best viable function (C++ 13.3.3) 10639 /// within an overload candidate set. 10640 /// 10641 /// \param Loc The location of the function name (or operator symbol) for 10642 /// which overload resolution occurs. 10643 /// 10644 /// \param Best If overload resolution was successful or found a deleted 10645 /// function, \p Best points to the candidate function found. 10646 /// 10647 /// \returns The result of overload resolution. 10648 OverloadingResult 10649 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 10650 iterator &Best) { 10651 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 10652 std::transform(begin(), end(), std::back_inserter(Candidates), 10653 [](OverloadCandidate &Cand) { return &Cand; }); 10654 10655 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 10656 // are accepted by both clang and NVCC. However, during a particular 10657 // compilation mode only one call variant is viable. We need to 10658 // exclude non-viable overload candidates from consideration based 10659 // only on their host/device attributes. Specifically, if one 10660 // candidate call is WrongSide and the other is SameSide, we ignore 10661 // the WrongSide candidate. 10662 // We only need to remove wrong-sided candidates here if 10663 // -fgpu-exclude-wrong-side-overloads is off. When 10664 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared 10665 // uniformly in isBetterOverloadCandidate. 10666 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) { 10667 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 10668 bool ContainsSameSideCandidate = 10669 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 10670 // Check viable function only. 10671 return Cand->Viable && Cand->Function && 10672 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10673 Sema::CFP_SameSide; 10674 }); 10675 if (ContainsSameSideCandidate) { 10676 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 10677 // Check viable function only to avoid unnecessary data copying/moving. 10678 return Cand->Viable && Cand->Function && 10679 S.IdentifyCUDAPreference(Caller, Cand->Function) == 10680 Sema::CFP_WrongSide; 10681 }; 10682 llvm::erase_if(Candidates, IsWrongSideCandidate); 10683 } 10684 } 10685 10686 // Find the best viable function. 10687 Best = end(); 10688 for (auto *Cand : Candidates) { 10689 Cand->Best = false; 10690 if (Cand->Viable) { 10691 if (Best == end() || 10692 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 10693 Best = Cand; 10694 } else if (Cand->NotValidBecauseConstraintExprHasError()) { 10695 // This candidate has constraint that we were unable to evaluate because 10696 // it referenced an expression that contained an error. Rather than fall 10697 // back onto a potentially unintended candidate (made worse by 10698 // subsuming constraints), treat this as 'no viable candidate'. 10699 Best = end(); 10700 return OR_No_Viable_Function; 10701 } 10702 } 10703 10704 // If we didn't find any viable functions, abort. 10705 if (Best == end()) 10706 return OR_No_Viable_Function; 10707 10708 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 10709 10710 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 10711 PendingBest.push_back(&*Best); 10712 Best->Best = true; 10713 10714 // Make sure that this function is better than every other viable 10715 // function. If not, we have an ambiguity. 10716 while (!PendingBest.empty()) { 10717 auto *Curr = PendingBest.pop_back_val(); 10718 for (auto *Cand : Candidates) { 10719 if (Cand->Viable && !Cand->Best && 10720 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 10721 PendingBest.push_back(Cand); 10722 Cand->Best = true; 10723 10724 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 10725 Curr->Function)) 10726 EquivalentCands.push_back(Cand->Function); 10727 else 10728 Best = end(); 10729 } 10730 } 10731 } 10732 10733 // If we found more than one best candidate, this is ambiguous. 10734 if (Best == end()) 10735 return OR_Ambiguous; 10736 10737 // Best is the best viable function. 10738 if (Best->Function && Best->Function->isDeleted()) 10739 return OR_Deleted; 10740 10741 if (!EquivalentCands.empty()) 10742 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 10743 EquivalentCands); 10744 10745 return OR_Success; 10746 } 10747 10748 namespace { 10749 10750 enum OverloadCandidateKind { 10751 oc_function, 10752 oc_method, 10753 oc_reversed_binary_operator, 10754 oc_constructor, 10755 oc_implicit_default_constructor, 10756 oc_implicit_copy_constructor, 10757 oc_implicit_move_constructor, 10758 oc_implicit_copy_assignment, 10759 oc_implicit_move_assignment, 10760 oc_implicit_equality_comparison, 10761 oc_inherited_constructor 10762 }; 10763 10764 enum OverloadCandidateSelect { 10765 ocs_non_template, 10766 ocs_template, 10767 ocs_described_template, 10768 }; 10769 10770 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 10771 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found, 10772 const FunctionDecl *Fn, 10773 OverloadCandidateRewriteKind CRK, 10774 std::string &Description) { 10775 10776 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 10777 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 10778 isTemplate = true; 10779 Description = S.getTemplateArgumentBindingsText( 10780 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 10781 } 10782 10783 OverloadCandidateSelect Select = [&]() { 10784 if (!Description.empty()) 10785 return ocs_described_template; 10786 return isTemplate ? ocs_template : ocs_non_template; 10787 }(); 10788 10789 OverloadCandidateKind Kind = [&]() { 10790 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 10791 return oc_implicit_equality_comparison; 10792 10793 if (CRK & CRK_Reversed) 10794 return oc_reversed_binary_operator; 10795 10796 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 10797 if (!Ctor->isImplicit()) { 10798 if (isa<ConstructorUsingShadowDecl>(Found)) 10799 return oc_inherited_constructor; 10800 else 10801 return oc_constructor; 10802 } 10803 10804 if (Ctor->isDefaultConstructor()) 10805 return oc_implicit_default_constructor; 10806 10807 if (Ctor->isMoveConstructor()) 10808 return oc_implicit_move_constructor; 10809 10810 assert(Ctor->isCopyConstructor() && 10811 "unexpected sort of implicit constructor"); 10812 return oc_implicit_copy_constructor; 10813 } 10814 10815 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10816 // This actually gets spelled 'candidate function' for now, but 10817 // it doesn't hurt to split it out. 10818 if (!Meth->isImplicit()) 10819 return oc_method; 10820 10821 if (Meth->isMoveAssignmentOperator()) 10822 return oc_implicit_move_assignment; 10823 10824 if (Meth->isCopyAssignmentOperator()) 10825 return oc_implicit_copy_assignment; 10826 10827 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10828 return oc_method; 10829 } 10830 10831 return oc_function; 10832 }(); 10833 10834 return std::make_pair(Kind, Select); 10835 } 10836 10837 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) { 10838 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10839 // set. 10840 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10841 S.Diag(FoundDecl->getLocation(), 10842 diag::note_ovl_candidate_inherited_constructor) 10843 << Shadow->getNominatedBaseClass(); 10844 } 10845 10846 } // end anonymous namespace 10847 10848 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10849 const FunctionDecl *FD) { 10850 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10851 bool AlwaysTrue; 10852 if (EnableIf->getCond()->isValueDependent() || 10853 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10854 return false; 10855 if (!AlwaysTrue) 10856 return false; 10857 } 10858 return true; 10859 } 10860 10861 /// Returns true if we can take the address of the function. 10862 /// 10863 /// \param Complain - If true, we'll emit a diagnostic 10864 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10865 /// we in overload resolution? 10866 /// \param Loc - The location of the statement we're complaining about. Ignored 10867 /// if we're not complaining, or if we're in overload resolution. 10868 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10869 bool Complain, 10870 bool InOverloadResolution, 10871 SourceLocation Loc) { 10872 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10873 if (Complain) { 10874 if (InOverloadResolution) 10875 S.Diag(FD->getBeginLoc(), 10876 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10877 else 10878 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10879 } 10880 return false; 10881 } 10882 10883 if (FD->getTrailingRequiresClause()) { 10884 ConstraintSatisfaction Satisfaction; 10885 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10886 return false; 10887 if (!Satisfaction.IsSatisfied) { 10888 if (Complain) { 10889 if (InOverloadResolution) { 10890 SmallString<128> TemplateArgString; 10891 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) { 10892 TemplateArgString += " "; 10893 TemplateArgString += S.getTemplateArgumentBindingsText( 10894 FunTmpl->getTemplateParameters(), 10895 *FD->getTemplateSpecializationArgs()); 10896 } 10897 10898 S.Diag(FD->getBeginLoc(), 10899 diag::note_ovl_candidate_unsatisfied_constraints) 10900 << TemplateArgString; 10901 } else 10902 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10903 << FD; 10904 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10905 } 10906 return false; 10907 } 10908 } 10909 10910 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10911 return P->hasAttr<PassObjectSizeAttr>(); 10912 }); 10913 if (I == FD->param_end()) 10914 return true; 10915 10916 if (Complain) { 10917 // Add one to ParamNo because it's user-facing 10918 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10919 if (InOverloadResolution) 10920 S.Diag(FD->getLocation(), 10921 diag::note_ovl_candidate_has_pass_object_size_params) 10922 << ParamNo; 10923 else 10924 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10925 << FD << ParamNo; 10926 } 10927 return false; 10928 } 10929 10930 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10931 const FunctionDecl *FD) { 10932 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10933 /*InOverloadResolution=*/true, 10934 /*Loc=*/SourceLocation()); 10935 } 10936 10937 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10938 bool Complain, 10939 SourceLocation Loc) { 10940 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10941 /*InOverloadResolution=*/false, 10942 Loc); 10943 } 10944 10945 // Don't print candidates other than the one that matches the calling 10946 // convention of the call operator, since that is guaranteed to exist. 10947 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) { 10948 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn); 10949 10950 if (!ConvD) 10951 return false; 10952 const auto *RD = cast<CXXRecordDecl>(Fn->getParent()); 10953 if (!RD->isLambda()) 10954 return false; 10955 10956 CXXMethodDecl *CallOp = RD->getLambdaCallOperator(); 10957 CallingConv CallOpCC = 10958 CallOp->getType()->castAs<FunctionType>()->getCallConv(); 10959 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType(); 10960 CallingConv ConvToCC = 10961 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv(); 10962 10963 return ConvToCC != CallOpCC; 10964 } 10965 10966 // Notes the location of an overload candidate. 10967 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, 10968 OverloadCandidateRewriteKind RewriteKind, 10969 QualType DestType, bool TakingAddress) { 10970 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10971 return; 10972 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10973 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10974 return; 10975 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() && 10976 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion()) 10977 return; 10978 if (shouldSkipNotingLambdaConversionDecl(Fn)) 10979 return; 10980 10981 std::string FnDesc; 10982 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10983 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10984 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10985 << (unsigned)KSPair.first << (unsigned)KSPair.second 10986 << Fn << FnDesc; 10987 10988 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10989 Diag(Fn->getLocation(), PD); 10990 MaybeEmitInheritedConstructorNote(*this, Found); 10991 } 10992 10993 static void 10994 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10995 // Perhaps the ambiguity was caused by two atomic constraints that are 10996 // 'identical' but not equivalent: 10997 // 10998 // void foo() requires (sizeof(T) > 4) { } // #1 10999 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 11000 // 11001 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 11002 // #2 to subsume #1, but these constraint are not considered equivalent 11003 // according to the subsumption rules because they are not the same 11004 // source-level construct. This behavior is quite confusing and we should try 11005 // to help the user figure out what happened. 11006 11007 SmallVector<const Expr *, 3> FirstAC, SecondAC; 11008 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 11009 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11010 if (!I->Function) 11011 continue; 11012 SmallVector<const Expr *, 3> AC; 11013 if (auto *Template = I->Function->getPrimaryTemplate()) 11014 Template->getAssociatedConstraints(AC); 11015 else 11016 I->Function->getAssociatedConstraints(AC); 11017 if (AC.empty()) 11018 continue; 11019 if (FirstCand == nullptr) { 11020 FirstCand = I->Function; 11021 FirstAC = AC; 11022 } else if (SecondCand == nullptr) { 11023 SecondCand = I->Function; 11024 SecondAC = AC; 11025 } else { 11026 // We have more than one pair of constrained functions - this check is 11027 // expensive and we'd rather not try to diagnose it. 11028 return; 11029 } 11030 } 11031 if (!SecondCand) 11032 return; 11033 // The diagnostic can only happen if there are associated constraints on 11034 // both sides (there needs to be some identical atomic constraint). 11035 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 11036 SecondCand, SecondAC)) 11037 // Just show the user one diagnostic, they'll probably figure it out 11038 // from here. 11039 return; 11040 } 11041 11042 // Notes the location of all overload candidates designated through 11043 // OverloadedExpr 11044 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 11045 bool TakingAddress) { 11046 assert(OverloadedExpr->getType() == Context.OverloadTy); 11047 11048 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 11049 OverloadExpr *OvlExpr = Ovl.Expression; 11050 11051 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11052 IEnd = OvlExpr->decls_end(); 11053 I != IEnd; ++I) { 11054 if (FunctionTemplateDecl *FunTmpl = 11055 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 11056 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 11057 TakingAddress); 11058 } else if (FunctionDecl *Fun 11059 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 11060 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 11061 } 11062 } 11063 } 11064 11065 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 11066 /// "lead" diagnostic; it will be given two arguments, the source and 11067 /// target types of the conversion. 11068 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 11069 Sema &S, 11070 SourceLocation CaretLoc, 11071 const PartialDiagnostic &PDiag) const { 11072 S.Diag(CaretLoc, PDiag) 11073 << Ambiguous.getFromType() << Ambiguous.getToType(); 11074 unsigned CandsShown = 0; 11075 AmbiguousConversionSequence::const_iterator I, E; 11076 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 11077 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow()) 11078 break; 11079 ++CandsShown; 11080 S.NoteOverloadCandidate(I->first, I->second); 11081 } 11082 S.Diags.overloadCandidatesShown(CandsShown); 11083 if (I != E) 11084 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 11085 } 11086 11087 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 11088 unsigned I, bool TakingCandidateAddress) { 11089 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 11090 assert(Conv.isBad()); 11091 assert(Cand->Function && "for now, candidate must be a function"); 11092 FunctionDecl *Fn = Cand->Function; 11093 11094 // There's a conversion slot for the object argument if this is a 11095 // non-constructor method. Note that 'I' corresponds the 11096 // conversion-slot index. 11097 bool isObjectArgument = false; 11098 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 11099 if (I == 0) 11100 isObjectArgument = true; 11101 else 11102 I--; 11103 } 11104 11105 std::string FnDesc; 11106 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11107 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 11108 FnDesc); 11109 11110 Expr *FromExpr = Conv.Bad.FromExpr; 11111 QualType FromTy = Conv.Bad.getFromType(); 11112 QualType ToTy = Conv.Bad.getToType(); 11113 SourceRange ToParamRange = 11114 !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange(); 11115 11116 if (FromTy == S.Context.OverloadTy) { 11117 assert(FromExpr && "overload set argument came from implicit argument?"); 11118 Expr *E = FromExpr->IgnoreParens(); 11119 if (isa<UnaryOperator>(E)) 11120 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 11121 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 11122 11123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 11124 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11125 << ToParamRange << ToTy << Name << I + 1; 11126 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11127 return; 11128 } 11129 11130 // Do some hand-waving analysis to see if the non-viability is due 11131 // to a qualifier mismatch. 11132 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 11133 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 11134 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 11135 CToTy = RT->getPointeeType(); 11136 else { 11137 // TODO: detect and diagnose the full richness of const mismatches. 11138 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 11139 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 11140 CFromTy = FromPT->getPointeeType(); 11141 CToTy = ToPT->getPointeeType(); 11142 } 11143 } 11144 11145 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 11146 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 11147 Qualifiers FromQs = CFromTy.getQualifiers(); 11148 Qualifiers ToQs = CToTy.getQualifiers(); 11149 11150 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 11151 if (isObjectArgument) 11152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 11153 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11154 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 11155 else 11156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 11157 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11158 << FnDesc << ToParamRange << FromQs.getAddressSpace() 11159 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1; 11160 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11161 return; 11162 } 11163 11164 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 11165 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 11166 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11167 << ToParamRange << FromTy << FromQs.getObjCLifetime() 11168 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1; 11169 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11170 return; 11171 } 11172 11173 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 11174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 11175 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11176 << ToParamRange << FromTy << FromQs.getObjCGCAttr() 11177 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1; 11178 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11179 return; 11180 } 11181 11182 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 11183 assert(CVR && "expected qualifiers mismatch"); 11184 11185 if (isObjectArgument) { 11186 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 11187 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11188 << FromTy << (CVR - 1); 11189 } else { 11190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 11191 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11192 << ToParamRange << FromTy << (CVR - 1) << I + 1; 11193 } 11194 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11195 return; 11196 } 11197 11198 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue || 11199 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) { 11200 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category) 11201 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11202 << (unsigned)isObjectArgument << I + 1 11203 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) 11204 << ToParamRange; 11205 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11206 return; 11207 } 11208 11209 // Special diagnostic for failure to convert an initializer list, since 11210 // telling the user that it has type void is not useful. 11211 if (FromExpr && isa<InitListExpr>(FromExpr)) { 11212 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 11213 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11214 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11215 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1 11216 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers 11217 ? 2 11218 : 0); 11219 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11220 return; 11221 } 11222 11223 // Diagnose references or pointers to incomplete types differently, 11224 // since it's far from impossible that the incompleteness triggered 11225 // the failure. 11226 QualType TempFromTy = FromTy.getNonReferenceType(); 11227 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 11228 TempFromTy = PTy->getPointeeType(); 11229 if (TempFromTy->isIncompleteType()) { 11230 // Emit the generic diagnostic and, optionally, add the hints to it. 11231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 11232 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11233 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11234 << (unsigned)(Cand->Fix.Kind); 11235 11236 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11237 return; 11238 } 11239 11240 // Diagnose base -> derived pointer conversions. 11241 unsigned BaseToDerivedConversion = 0; 11242 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 11243 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 11244 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 11245 FromPtrTy->getPointeeType()) && 11246 !FromPtrTy->getPointeeType()->isIncompleteType() && 11247 !ToPtrTy->getPointeeType()->isIncompleteType() && 11248 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 11249 FromPtrTy->getPointeeType())) 11250 BaseToDerivedConversion = 1; 11251 } 11252 } else if (const ObjCObjectPointerType *FromPtrTy 11253 = FromTy->getAs<ObjCObjectPointerType>()) { 11254 if (const ObjCObjectPointerType *ToPtrTy 11255 = ToTy->getAs<ObjCObjectPointerType>()) 11256 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 11257 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 11258 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 11259 FromPtrTy->getPointeeType()) && 11260 FromIface->isSuperClassOf(ToIface)) 11261 BaseToDerivedConversion = 2; 11262 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 11263 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 11264 !FromTy->isIncompleteType() && 11265 !ToRefTy->getPointeeType()->isIncompleteType() && 11266 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 11267 BaseToDerivedConversion = 3; 11268 } 11269 } 11270 11271 if (BaseToDerivedConversion) { 11272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 11273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11274 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy 11275 << I + 1; 11276 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11277 return; 11278 } 11279 11280 if (isa<ObjCObjectPointerType>(CFromTy) && 11281 isa<PointerType>(CToTy)) { 11282 Qualifiers FromQs = CFromTy.getQualifiers(); 11283 Qualifiers ToQs = CToTy.getQualifiers(); 11284 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 11285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 11286 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11287 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument 11288 << I + 1; 11289 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11290 return; 11291 } 11292 } 11293 11294 if (TakingCandidateAddress && 11295 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 11296 return; 11297 11298 // Emit the generic diagnostic and, optionally, add the hints to it. 11299 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 11300 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11301 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1 11302 << (unsigned)(Cand->Fix.Kind); 11303 11304 // Check that location of Fn is not in system header. 11305 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) { 11306 // If we can fix the conversion, suggest the FixIts. 11307 for (const FixItHint &HI : Cand->Fix.Hints) 11308 FDiag << HI; 11309 } 11310 11311 S.Diag(Fn->getLocation(), FDiag); 11312 11313 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11314 } 11315 11316 /// Additional arity mismatch diagnosis specific to a function overload 11317 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 11318 /// over a candidate in any candidate set. 11319 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 11320 unsigned NumArgs) { 11321 FunctionDecl *Fn = Cand->Function; 11322 unsigned MinParams = Fn->getMinRequiredArguments(); 11323 11324 // With invalid overloaded operators, it's possible that we think we 11325 // have an arity mismatch when in fact it looks like we have the 11326 // right number of arguments, because only overloaded operators have 11327 // the weird behavior of overloading member and non-member functions. 11328 // Just don't report anything. 11329 if (Fn->isInvalidDecl() && 11330 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 11331 return true; 11332 11333 if (NumArgs < MinParams) { 11334 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 11335 (Cand->FailureKind == ovl_fail_bad_deduction && 11336 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 11337 } else { 11338 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 11339 (Cand->FailureKind == ovl_fail_bad_deduction && 11340 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 11341 } 11342 11343 return false; 11344 } 11345 11346 /// General arity mismatch diagnosis over a candidate in a candidate set. 11347 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 11348 unsigned NumFormalArgs) { 11349 assert(isa<FunctionDecl>(D) && 11350 "The templated declaration should at least be a function" 11351 " when diagnosing bad template argument deduction due to too many" 11352 " or too few arguments"); 11353 11354 FunctionDecl *Fn = cast<FunctionDecl>(D); 11355 11356 // TODO: treat calls to a missing default constructor as a special case 11357 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 11358 unsigned MinParams = Fn->getMinRequiredExplicitArguments(); 11359 11360 // at least / at most / exactly 11361 bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter(); 11362 unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0); 11363 unsigned mode, modeCount; 11364 if (NumFormalArgs < MinParams) { 11365 if (MinParams != ParamCount || FnTy->isVariadic() || 11366 FnTy->isTemplateVariadic()) 11367 mode = 0; // "at least" 11368 else 11369 mode = 2; // "exactly" 11370 modeCount = MinParams; 11371 } else { 11372 if (MinParams != ParamCount) 11373 mode = 1; // "at most" 11374 else 11375 mode = 2; // "exactly" 11376 modeCount = ParamCount; 11377 } 11378 11379 std::string Description; 11380 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11381 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 11382 11383 if (modeCount == 1 && 11384 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName()) 11385 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 11386 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11387 << Description << mode 11388 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs 11389 << HasExplicitObjectParam << Fn->getParametersSourceRange(); 11390 else 11391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 11392 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 11393 << Description << mode << modeCount << NumFormalArgs 11394 << HasExplicitObjectParam << Fn->getParametersSourceRange(); 11395 11396 MaybeEmitInheritedConstructorNote(S, Found); 11397 } 11398 11399 /// Arity mismatch diagnosis specific to a function overload candidate. 11400 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 11401 unsigned NumFormalArgs) { 11402 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 11403 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 11404 } 11405 11406 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 11407 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 11408 return TD; 11409 llvm_unreachable("Unsupported: Getting the described template declaration" 11410 " for bad deduction diagnosis"); 11411 } 11412 11413 /// Diagnose a failed template-argument deduction. 11414 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 11415 DeductionFailureInfo &DeductionFailure, 11416 unsigned NumArgs, 11417 bool TakingCandidateAddress) { 11418 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 11419 NamedDecl *ParamD; 11420 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 11421 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 11422 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 11423 switch (DeductionFailure.Result) { 11424 case Sema::TDK_Success: 11425 llvm_unreachable("TDK_success while diagnosing bad deduction"); 11426 11427 case Sema::TDK_Incomplete: { 11428 assert(ParamD && "no parameter found for incomplete deduction result"); 11429 S.Diag(Templated->getLocation(), 11430 diag::note_ovl_candidate_incomplete_deduction) 11431 << ParamD->getDeclName(); 11432 MaybeEmitInheritedConstructorNote(S, Found); 11433 return; 11434 } 11435 11436 case Sema::TDK_IncompletePack: { 11437 assert(ParamD && "no parameter found for incomplete deduction result"); 11438 S.Diag(Templated->getLocation(), 11439 diag::note_ovl_candidate_incomplete_deduction_pack) 11440 << ParamD->getDeclName() 11441 << (DeductionFailure.getFirstArg()->pack_size() + 1) 11442 << *DeductionFailure.getFirstArg(); 11443 MaybeEmitInheritedConstructorNote(S, Found); 11444 return; 11445 } 11446 11447 case Sema::TDK_Underqualified: { 11448 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 11449 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 11450 11451 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 11452 11453 // Param will have been canonicalized, but it should just be a 11454 // qualified version of ParamD, so move the qualifiers to that. 11455 QualifierCollector Qs; 11456 Qs.strip(Param); 11457 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 11458 assert(S.Context.hasSameType(Param, NonCanonParam)); 11459 11460 // Arg has also been canonicalized, but there's nothing we can do 11461 // about that. It also doesn't matter as much, because it won't 11462 // have any template parameters in it (because deduction isn't 11463 // done on dependent types). 11464 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 11465 11466 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 11467 << ParamD->getDeclName() << Arg << NonCanonParam; 11468 MaybeEmitInheritedConstructorNote(S, Found); 11469 return; 11470 } 11471 11472 case Sema::TDK_Inconsistent: { 11473 assert(ParamD && "no parameter found for inconsistent deduction result"); 11474 int which = 0; 11475 if (isa<TemplateTypeParmDecl>(ParamD)) 11476 which = 0; 11477 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 11478 // Deduction might have failed because we deduced arguments of two 11479 // different types for a non-type template parameter. 11480 // FIXME: Use a different TDK value for this. 11481 QualType T1 = 11482 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 11483 QualType T2 = 11484 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 11485 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 11486 S.Diag(Templated->getLocation(), 11487 diag::note_ovl_candidate_inconsistent_deduction_types) 11488 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 11489 << *DeductionFailure.getSecondArg() << T2; 11490 MaybeEmitInheritedConstructorNote(S, Found); 11491 return; 11492 } 11493 11494 which = 1; 11495 } else { 11496 which = 2; 11497 } 11498 11499 // Tweak the diagnostic if the problem is that we deduced packs of 11500 // different arities. We'll print the actual packs anyway in case that 11501 // includes additional useful information. 11502 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 11503 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 11504 DeductionFailure.getFirstArg()->pack_size() != 11505 DeductionFailure.getSecondArg()->pack_size()) { 11506 which = 3; 11507 } 11508 11509 S.Diag(Templated->getLocation(), 11510 diag::note_ovl_candidate_inconsistent_deduction) 11511 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 11512 << *DeductionFailure.getSecondArg(); 11513 MaybeEmitInheritedConstructorNote(S, Found); 11514 return; 11515 } 11516 11517 case Sema::TDK_InvalidExplicitArguments: 11518 assert(ParamD && "no parameter found for invalid explicit arguments"); 11519 if (ParamD->getDeclName()) 11520 S.Diag(Templated->getLocation(), 11521 diag::note_ovl_candidate_explicit_arg_mismatch_named) 11522 << ParamD->getDeclName(); 11523 else { 11524 int index = 0; 11525 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 11526 index = TTP->getIndex(); 11527 else if (NonTypeTemplateParmDecl *NTTP 11528 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 11529 index = NTTP->getIndex(); 11530 else 11531 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 11532 S.Diag(Templated->getLocation(), 11533 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 11534 << (index + 1); 11535 } 11536 MaybeEmitInheritedConstructorNote(S, Found); 11537 return; 11538 11539 case Sema::TDK_ConstraintsNotSatisfied: { 11540 // Format the template argument list into the argument string. 11541 SmallString<128> TemplateArgString; 11542 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 11543 TemplateArgString = " "; 11544 TemplateArgString += S.getTemplateArgumentBindingsText( 11545 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11546 if (TemplateArgString.size() == 1) 11547 TemplateArgString.clear(); 11548 S.Diag(Templated->getLocation(), 11549 diag::note_ovl_candidate_unsatisfied_constraints) 11550 << TemplateArgString; 11551 11552 S.DiagnoseUnsatisfiedConstraint( 11553 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 11554 return; 11555 } 11556 case Sema::TDK_TooManyArguments: 11557 case Sema::TDK_TooFewArguments: 11558 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 11559 return; 11560 11561 case Sema::TDK_InstantiationDepth: 11562 S.Diag(Templated->getLocation(), 11563 diag::note_ovl_candidate_instantiation_depth); 11564 MaybeEmitInheritedConstructorNote(S, Found); 11565 return; 11566 11567 case Sema::TDK_SubstitutionFailure: { 11568 // Format the template argument list into the argument string. 11569 SmallString<128> TemplateArgString; 11570 if (TemplateArgumentList *Args = 11571 DeductionFailure.getTemplateArgumentList()) { 11572 TemplateArgString = " "; 11573 TemplateArgString += S.getTemplateArgumentBindingsText( 11574 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11575 if (TemplateArgString.size() == 1) 11576 TemplateArgString.clear(); 11577 } 11578 11579 // If this candidate was disabled by enable_if, say so. 11580 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 11581 if (PDiag && PDiag->second.getDiagID() == 11582 diag::err_typename_nested_not_found_enable_if) { 11583 // FIXME: Use the source range of the condition, and the fully-qualified 11584 // name of the enable_if template. These are both present in PDiag. 11585 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 11586 << "'enable_if'" << TemplateArgString; 11587 return; 11588 } 11589 11590 // We found a specific requirement that disabled the enable_if. 11591 if (PDiag && PDiag->second.getDiagID() == 11592 diag::err_typename_nested_not_found_requirement) { 11593 S.Diag(Templated->getLocation(), 11594 diag::note_ovl_candidate_disabled_by_requirement) 11595 << PDiag->second.getStringArg(0) << TemplateArgString; 11596 return; 11597 } 11598 11599 // Format the SFINAE diagnostic into the argument string. 11600 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 11601 // formatted message in another diagnostic. 11602 SmallString<128> SFINAEArgString; 11603 SourceRange R; 11604 if (PDiag) { 11605 SFINAEArgString = ": "; 11606 R = SourceRange(PDiag->first, PDiag->first); 11607 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 11608 } 11609 11610 S.Diag(Templated->getLocation(), 11611 diag::note_ovl_candidate_substitution_failure) 11612 << TemplateArgString << SFINAEArgString << R; 11613 MaybeEmitInheritedConstructorNote(S, Found); 11614 return; 11615 } 11616 11617 case Sema::TDK_DeducedMismatch: 11618 case Sema::TDK_DeducedMismatchNested: { 11619 // Format the template argument list into the argument string. 11620 SmallString<128> TemplateArgString; 11621 if (TemplateArgumentList *Args = 11622 DeductionFailure.getTemplateArgumentList()) { 11623 TemplateArgString = " "; 11624 TemplateArgString += S.getTemplateArgumentBindingsText( 11625 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 11626 if (TemplateArgString.size() == 1) 11627 TemplateArgString.clear(); 11628 } 11629 11630 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 11631 << (*DeductionFailure.getCallArgIndex() + 1) 11632 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 11633 << TemplateArgString 11634 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 11635 break; 11636 } 11637 11638 case Sema::TDK_NonDeducedMismatch: { 11639 // FIXME: Provide a source location to indicate what we couldn't match. 11640 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 11641 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 11642 if (FirstTA.getKind() == TemplateArgument::Template && 11643 SecondTA.getKind() == TemplateArgument::Template) { 11644 TemplateName FirstTN = FirstTA.getAsTemplate(); 11645 TemplateName SecondTN = SecondTA.getAsTemplate(); 11646 if (FirstTN.getKind() == TemplateName::Template && 11647 SecondTN.getKind() == TemplateName::Template) { 11648 if (FirstTN.getAsTemplateDecl()->getName() == 11649 SecondTN.getAsTemplateDecl()->getName()) { 11650 // FIXME: This fixes a bad diagnostic where both templates are named 11651 // the same. This particular case is a bit difficult since: 11652 // 1) It is passed as a string to the diagnostic printer. 11653 // 2) The diagnostic printer only attempts to find a better 11654 // name for types, not decls. 11655 // Ideally, this should folded into the diagnostic printer. 11656 S.Diag(Templated->getLocation(), 11657 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 11658 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 11659 return; 11660 } 11661 } 11662 } 11663 11664 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 11665 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 11666 return; 11667 11668 // FIXME: For generic lambda parameters, check if the function is a lambda 11669 // call operator, and if so, emit a prettier and more informative 11670 // diagnostic that mentions 'auto' and lambda in addition to 11671 // (or instead of?) the canonical template type parameters. 11672 S.Diag(Templated->getLocation(), 11673 diag::note_ovl_candidate_non_deduced_mismatch) 11674 << FirstTA << SecondTA; 11675 return; 11676 } 11677 // TODO: diagnose these individually, then kill off 11678 // note_ovl_candidate_bad_deduction, which is uselessly vague. 11679 case Sema::TDK_MiscellaneousDeductionFailure: 11680 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 11681 MaybeEmitInheritedConstructorNote(S, Found); 11682 return; 11683 case Sema::TDK_CUDATargetMismatch: 11684 S.Diag(Templated->getLocation(), 11685 diag::note_cuda_ovl_candidate_target_mismatch); 11686 return; 11687 } 11688 } 11689 11690 /// Diagnose a failed template-argument deduction, for function calls. 11691 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 11692 unsigned NumArgs, 11693 bool TakingCandidateAddress) { 11694 unsigned TDK = Cand->DeductionFailure.Result; 11695 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 11696 if (CheckArityMismatch(S, Cand, NumArgs)) 11697 return; 11698 } 11699 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 11700 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 11701 } 11702 11703 /// CUDA: diagnose an invalid call across targets. 11704 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 11705 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 11706 FunctionDecl *Callee = Cand->Function; 11707 11708 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 11709 CalleeTarget = S.IdentifyCUDATarget(Callee); 11710 11711 std::string FnDesc; 11712 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11713 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 11714 Cand->getRewriteKind(), FnDesc); 11715 11716 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 11717 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11718 << FnDesc /* Ignored */ 11719 << CalleeTarget << CallerTarget; 11720 11721 // This could be an implicit constructor for which we could not infer the 11722 // target due to a collsion. Diagnose that case. 11723 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 11724 if (Meth != nullptr && Meth->isImplicit()) { 11725 CXXRecordDecl *ParentClass = Meth->getParent(); 11726 Sema::CXXSpecialMember CSM; 11727 11728 switch (FnKindPair.first) { 11729 default: 11730 return; 11731 case oc_implicit_default_constructor: 11732 CSM = Sema::CXXDefaultConstructor; 11733 break; 11734 case oc_implicit_copy_constructor: 11735 CSM = Sema::CXXCopyConstructor; 11736 break; 11737 case oc_implicit_move_constructor: 11738 CSM = Sema::CXXMoveConstructor; 11739 break; 11740 case oc_implicit_copy_assignment: 11741 CSM = Sema::CXXCopyAssignment; 11742 break; 11743 case oc_implicit_move_assignment: 11744 CSM = Sema::CXXMoveAssignment; 11745 break; 11746 }; 11747 11748 bool ConstRHS = false; 11749 if (Meth->getNumParams()) { 11750 if (const ReferenceType *RT = 11751 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 11752 ConstRHS = RT->getPointeeType().isConstQualified(); 11753 } 11754 } 11755 11756 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 11757 /* ConstRHS */ ConstRHS, 11758 /* Diagnose */ true); 11759 } 11760 } 11761 11762 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 11763 FunctionDecl *Callee = Cand->Function; 11764 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 11765 11766 S.Diag(Callee->getLocation(), 11767 diag::note_ovl_candidate_disabled_by_function_cond_attr) 11768 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 11769 } 11770 11771 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 11772 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 11773 assert(ES.isExplicit() && "not an explicit candidate"); 11774 11775 unsigned Kind; 11776 switch (Cand->Function->getDeclKind()) { 11777 case Decl::Kind::CXXConstructor: 11778 Kind = 0; 11779 break; 11780 case Decl::Kind::CXXConversion: 11781 Kind = 1; 11782 break; 11783 case Decl::Kind::CXXDeductionGuide: 11784 Kind = Cand->Function->isImplicit() ? 0 : 2; 11785 break; 11786 default: 11787 llvm_unreachable("invalid Decl"); 11788 } 11789 11790 // Note the location of the first (in-class) declaration; a redeclaration 11791 // (particularly an out-of-class definition) will typically lack the 11792 // 'explicit' specifier. 11793 // FIXME: This is probably a good thing to do for all 'candidate' notes. 11794 FunctionDecl *First = Cand->Function->getFirstDecl(); 11795 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 11796 First = Pattern->getFirstDecl(); 11797 11798 S.Diag(First->getLocation(), 11799 diag::note_ovl_candidate_explicit) 11800 << Kind << (ES.getExpr() ? 1 : 0) 11801 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 11802 } 11803 11804 /// Generates a 'note' diagnostic for an overload candidate. We've 11805 /// already generated a primary error at the call site. 11806 /// 11807 /// It really does need to be a single diagnostic with its caret 11808 /// pointed at the candidate declaration. Yes, this creates some 11809 /// major challenges of technical writing. Yes, this makes pointing 11810 /// out problems with specific arguments quite awkward. It's still 11811 /// better than generating twenty screens of text for every failed 11812 /// overload. 11813 /// 11814 /// It would be great to be able to express per-candidate problems 11815 /// more richly for those diagnostic clients that cared, but we'd 11816 /// still have to be just as careful with the default diagnostics. 11817 /// \param CtorDestAS Addr space of object being constructed (for ctor 11818 /// candidates only). 11819 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 11820 unsigned NumArgs, 11821 bool TakingCandidateAddress, 11822 LangAS CtorDestAS = LangAS::Default) { 11823 FunctionDecl *Fn = Cand->Function; 11824 if (shouldSkipNotingLambdaConversionDecl(Fn)) 11825 return; 11826 11827 // There is no physical candidate declaration to point to for OpenCL builtins. 11828 // Except for failed conversions, the notes are identical for each candidate, 11829 // so do not generate such notes. 11830 if (S.getLangOpts().OpenCL && Fn->isImplicit() && 11831 Cand->FailureKind != ovl_fail_bad_conversion) 11832 return; 11833 11834 // Note deleted candidates, but only if they're viable. 11835 if (Cand->Viable) { 11836 if (Fn->isDeleted()) { 11837 std::string FnDesc; 11838 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11839 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11840 Cand->getRewriteKind(), FnDesc); 11841 11842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11843 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11844 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11845 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11846 return; 11847 } 11848 11849 // We don't really have anything else to say about viable candidates. 11850 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11851 return; 11852 } 11853 11854 switch (Cand->FailureKind) { 11855 case ovl_fail_too_many_arguments: 11856 case ovl_fail_too_few_arguments: 11857 return DiagnoseArityMismatch(S, Cand, NumArgs); 11858 11859 case ovl_fail_bad_deduction: 11860 return DiagnoseBadDeduction(S, Cand, NumArgs, 11861 TakingCandidateAddress); 11862 11863 case ovl_fail_illegal_constructor: { 11864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11865 << (Fn->getPrimaryTemplate() ? 1 : 0); 11866 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11867 return; 11868 } 11869 11870 case ovl_fail_object_addrspace_mismatch: { 11871 Qualifiers QualsForPrinting; 11872 QualsForPrinting.setAddressSpace(CtorDestAS); 11873 S.Diag(Fn->getLocation(), 11874 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11875 << QualsForPrinting; 11876 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11877 return; 11878 } 11879 11880 case ovl_fail_trivial_conversion: 11881 case ovl_fail_bad_final_conversion: 11882 case ovl_fail_final_conversion_not_exact: 11883 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11884 11885 case ovl_fail_bad_conversion: { 11886 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11887 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11888 if (Cand->Conversions[I].isBad()) 11889 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11890 11891 // FIXME: this currently happens when we're called from SemaInit 11892 // when user-conversion overload fails. Figure out how to handle 11893 // those conditions and diagnose them well. 11894 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11895 } 11896 11897 case ovl_fail_bad_target: 11898 return DiagnoseBadTarget(S, Cand); 11899 11900 case ovl_fail_enable_if: 11901 return DiagnoseFailedEnableIfAttr(S, Cand); 11902 11903 case ovl_fail_explicit: 11904 return DiagnoseFailedExplicitSpec(S, Cand); 11905 11906 case ovl_fail_inhctor_slice: 11907 // It's generally not interesting to note copy/move constructors here. 11908 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11909 return; 11910 S.Diag(Fn->getLocation(), 11911 diag::note_ovl_candidate_inherited_constructor_slice) 11912 << (Fn->getPrimaryTemplate() ? 1 : 0) 11913 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11914 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11915 return; 11916 11917 case ovl_fail_addr_not_available: { 11918 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11919 (void)Available; 11920 assert(!Available); 11921 break; 11922 } 11923 case ovl_non_default_multiversion_function: 11924 // Do nothing, these should simply be ignored. 11925 break; 11926 11927 case ovl_fail_constraints_not_satisfied: { 11928 std::string FnDesc; 11929 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11930 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11931 Cand->getRewriteKind(), FnDesc); 11932 11933 S.Diag(Fn->getLocation(), 11934 diag::note_ovl_candidate_constraints_not_satisfied) 11935 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11936 << FnDesc /* Ignored */; 11937 ConstraintSatisfaction Satisfaction; 11938 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11939 break; 11940 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11941 } 11942 } 11943 } 11944 11945 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11946 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate)) 11947 return; 11948 11949 // Desugar the type of the surrogate down to a function type, 11950 // retaining as many typedefs as possible while still showing 11951 // the function type (and, therefore, its parameter types). 11952 QualType FnType = Cand->Surrogate->getConversionType(); 11953 bool isLValueReference = false; 11954 bool isRValueReference = false; 11955 bool isPointer = false; 11956 if (const LValueReferenceType *FnTypeRef = 11957 FnType->getAs<LValueReferenceType>()) { 11958 FnType = FnTypeRef->getPointeeType(); 11959 isLValueReference = true; 11960 } else if (const RValueReferenceType *FnTypeRef = 11961 FnType->getAs<RValueReferenceType>()) { 11962 FnType = FnTypeRef->getPointeeType(); 11963 isRValueReference = true; 11964 } 11965 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11966 FnType = FnTypePtr->getPointeeType(); 11967 isPointer = true; 11968 } 11969 // Desugar down to a function type. 11970 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11971 // Reconstruct the pointer/reference as appropriate. 11972 if (isPointer) FnType = S.Context.getPointerType(FnType); 11973 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11974 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11975 11976 if (!Cand->Viable && 11977 Cand->FailureKind == ovl_fail_constraints_not_satisfied) { 11978 S.Diag(Cand->Surrogate->getLocation(), 11979 diag::note_ovl_surrogate_constraints_not_satisfied) 11980 << Cand->Surrogate; 11981 ConstraintSatisfaction Satisfaction; 11982 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction)) 11983 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11984 } else { 11985 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11986 << FnType; 11987 } 11988 } 11989 11990 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11991 SourceLocation OpLoc, 11992 OverloadCandidate *Cand) { 11993 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11994 std::string TypeStr("operator"); 11995 TypeStr += Opc; 11996 TypeStr += "("; 11997 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11998 if (Cand->Conversions.size() == 1) { 11999 TypeStr += ")"; 12000 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 12001 } else { 12002 TypeStr += ", "; 12003 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 12004 TypeStr += ")"; 12005 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 12006 } 12007 } 12008 12009 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 12010 OverloadCandidate *Cand) { 12011 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 12012 if (ICS.isBad()) break; // all meaningless after first invalid 12013 if (!ICS.isAmbiguous()) continue; 12014 12015 ICS.DiagnoseAmbiguousConversion( 12016 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 12017 } 12018 } 12019 12020 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 12021 if (Cand->Function) 12022 return Cand->Function->getLocation(); 12023 if (Cand->IsSurrogate) 12024 return Cand->Surrogate->getLocation(); 12025 return SourceLocation(); 12026 } 12027 12028 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 12029 switch ((Sema::TemplateDeductionResult)DFI.Result) { 12030 case Sema::TDK_Success: 12031 case Sema::TDK_NonDependentConversionFailure: 12032 case Sema::TDK_AlreadyDiagnosed: 12033 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 12034 12035 case Sema::TDK_Invalid: 12036 case Sema::TDK_Incomplete: 12037 case Sema::TDK_IncompletePack: 12038 return 1; 12039 12040 case Sema::TDK_Underqualified: 12041 case Sema::TDK_Inconsistent: 12042 return 2; 12043 12044 case Sema::TDK_SubstitutionFailure: 12045 case Sema::TDK_DeducedMismatch: 12046 case Sema::TDK_ConstraintsNotSatisfied: 12047 case Sema::TDK_DeducedMismatchNested: 12048 case Sema::TDK_NonDeducedMismatch: 12049 case Sema::TDK_MiscellaneousDeductionFailure: 12050 case Sema::TDK_CUDATargetMismatch: 12051 return 3; 12052 12053 case Sema::TDK_InstantiationDepth: 12054 return 4; 12055 12056 case Sema::TDK_InvalidExplicitArguments: 12057 return 5; 12058 12059 case Sema::TDK_TooManyArguments: 12060 case Sema::TDK_TooFewArguments: 12061 return 6; 12062 } 12063 llvm_unreachable("Unhandled deduction result"); 12064 } 12065 12066 namespace { 12067 12068 struct CompareOverloadCandidatesForDisplay { 12069 Sema &S; 12070 SourceLocation Loc; 12071 size_t NumArgs; 12072 OverloadCandidateSet::CandidateSetKind CSK; 12073 12074 CompareOverloadCandidatesForDisplay( 12075 Sema &S, SourceLocation Loc, size_t NArgs, 12076 OverloadCandidateSet::CandidateSetKind CSK) 12077 : S(S), NumArgs(NArgs), CSK(CSK) {} 12078 12079 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 12080 // If there are too many or too few arguments, that's the high-order bit we 12081 // want to sort by, even if the immediate failure kind was something else. 12082 if (C->FailureKind == ovl_fail_too_many_arguments || 12083 C->FailureKind == ovl_fail_too_few_arguments) 12084 return static_cast<OverloadFailureKind>(C->FailureKind); 12085 12086 if (C->Function) { 12087 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 12088 return ovl_fail_too_many_arguments; 12089 if (NumArgs < C->Function->getMinRequiredArguments()) 12090 return ovl_fail_too_few_arguments; 12091 } 12092 12093 return static_cast<OverloadFailureKind>(C->FailureKind); 12094 } 12095 12096 bool operator()(const OverloadCandidate *L, 12097 const OverloadCandidate *R) { 12098 // Fast-path this check. 12099 if (L == R) return false; 12100 12101 // Order first by viability. 12102 if (L->Viable) { 12103 if (!R->Viable) return true; 12104 12105 if (int Ord = CompareConversions(*L, *R)) 12106 return Ord < 0; 12107 // Use other tie breakers. 12108 } else if (R->Viable) 12109 return false; 12110 12111 assert(L->Viable == R->Viable); 12112 12113 // Criteria by which we can sort non-viable candidates: 12114 if (!L->Viable) { 12115 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 12116 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 12117 12118 // 1. Arity mismatches come after other candidates. 12119 if (LFailureKind == ovl_fail_too_many_arguments || 12120 LFailureKind == ovl_fail_too_few_arguments) { 12121 if (RFailureKind == ovl_fail_too_many_arguments || 12122 RFailureKind == ovl_fail_too_few_arguments) { 12123 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 12124 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 12125 if (LDist == RDist) { 12126 if (LFailureKind == RFailureKind) 12127 // Sort non-surrogates before surrogates. 12128 return !L->IsSurrogate && R->IsSurrogate; 12129 // Sort candidates requiring fewer parameters than there were 12130 // arguments given after candidates requiring more parameters 12131 // than there were arguments given. 12132 return LFailureKind == ovl_fail_too_many_arguments; 12133 } 12134 return LDist < RDist; 12135 } 12136 return false; 12137 } 12138 if (RFailureKind == ovl_fail_too_many_arguments || 12139 RFailureKind == ovl_fail_too_few_arguments) 12140 return true; 12141 12142 // 2. Bad conversions come first and are ordered by the number 12143 // of bad conversions and quality of good conversions. 12144 if (LFailureKind == ovl_fail_bad_conversion) { 12145 if (RFailureKind != ovl_fail_bad_conversion) 12146 return true; 12147 12148 // The conversion that can be fixed with a smaller number of changes, 12149 // comes first. 12150 unsigned numLFixes = L->Fix.NumConversionsFixed; 12151 unsigned numRFixes = R->Fix.NumConversionsFixed; 12152 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 12153 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 12154 if (numLFixes != numRFixes) { 12155 return numLFixes < numRFixes; 12156 } 12157 12158 // If there's any ordering between the defined conversions... 12159 if (int Ord = CompareConversions(*L, *R)) 12160 return Ord < 0; 12161 } else if (RFailureKind == ovl_fail_bad_conversion) 12162 return false; 12163 12164 if (LFailureKind == ovl_fail_bad_deduction) { 12165 if (RFailureKind != ovl_fail_bad_deduction) 12166 return true; 12167 12168 if (L->DeductionFailure.Result != R->DeductionFailure.Result) { 12169 unsigned LRank = RankDeductionFailure(L->DeductionFailure); 12170 unsigned RRank = RankDeductionFailure(R->DeductionFailure); 12171 if (LRank != RRank) 12172 return LRank < RRank; 12173 } 12174 } else if (RFailureKind == ovl_fail_bad_deduction) 12175 return false; 12176 12177 // TODO: others? 12178 } 12179 12180 // Sort everything else by location. 12181 SourceLocation LLoc = GetLocationForCandidate(L); 12182 SourceLocation RLoc = GetLocationForCandidate(R); 12183 12184 // Put candidates without locations (e.g. builtins) at the end. 12185 if (LLoc.isValid() && RLoc.isValid()) 12186 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 12187 if (LLoc.isValid() && !RLoc.isValid()) 12188 return true; 12189 if (RLoc.isValid() && !LLoc.isValid()) 12190 return false; 12191 assert(!LLoc.isValid() && !RLoc.isValid()); 12192 // For builtins and other functions without locations, fallback to the order 12193 // in which they were added into the candidate set. 12194 return L < R; 12195 } 12196 12197 private: 12198 struct ConversionSignals { 12199 unsigned KindRank = 0; 12200 ImplicitConversionRank Rank = ICR_Exact_Match; 12201 12202 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) { 12203 ConversionSignals Sig; 12204 Sig.KindRank = Seq.getKindRank(); 12205 if (Seq.isStandard()) 12206 Sig.Rank = Seq.Standard.getRank(); 12207 else if (Seq.isUserDefined()) 12208 Sig.Rank = Seq.UserDefined.After.getRank(); 12209 // We intend StaticObjectArgumentConversion to compare the same as 12210 // StandardConversion with ICR_ExactMatch rank. 12211 return Sig; 12212 } 12213 12214 static ConversionSignals ForObjectArgument() { 12215 // We intend StaticObjectArgumentConversion to compare the same as 12216 // StandardConversion with ICR_ExactMatch rank. Default give us that. 12217 return {}; 12218 } 12219 }; 12220 12221 // Returns -1 if conversions in L are considered better. 12222 // 0 if they are considered indistinguishable. 12223 // 1 if conversions in R are better. 12224 int CompareConversions(const OverloadCandidate &L, 12225 const OverloadCandidate &R) { 12226 // We cannot use `isBetterOverloadCandidate` because it is defined 12227 // according to the C++ standard and provides a partial order, but we need 12228 // a total order as this function is used in sort. 12229 assert(L.Conversions.size() == R.Conversions.size()); 12230 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) { 12231 auto LS = L.IgnoreObjectArgument && I == 0 12232 ? ConversionSignals::ForObjectArgument() 12233 : ConversionSignals::ForSequence(L.Conversions[I]); 12234 auto RS = R.IgnoreObjectArgument 12235 ? ConversionSignals::ForObjectArgument() 12236 : ConversionSignals::ForSequence(R.Conversions[I]); 12237 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank)) 12238 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank) 12239 ? -1 12240 : 1; 12241 } 12242 // FIXME: find a way to compare templates for being more or less 12243 // specialized that provides a strict weak ordering. 12244 return 0; 12245 } 12246 }; 12247 } 12248 12249 /// CompleteNonViableCandidate - Normally, overload resolution only 12250 /// computes up to the first bad conversion. Produces the FixIt set if 12251 /// possible. 12252 static void 12253 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 12254 ArrayRef<Expr *> Args, 12255 OverloadCandidateSet::CandidateSetKind CSK) { 12256 assert(!Cand->Viable); 12257 12258 // Don't do anything on failures other than bad conversion. 12259 if (Cand->FailureKind != ovl_fail_bad_conversion) 12260 return; 12261 12262 // We only want the FixIts if all the arguments can be corrected. 12263 bool Unfixable = false; 12264 // Use a implicit copy initialization to check conversion fixes. 12265 Cand->Fix.setConversionChecker(TryCopyInitialization); 12266 12267 // Attempt to fix the bad conversion. 12268 unsigned ConvCount = Cand->Conversions.size(); 12269 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 12270 ++ConvIdx) { 12271 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 12272 if (Cand->Conversions[ConvIdx].isInitialized() && 12273 Cand->Conversions[ConvIdx].isBad()) { 12274 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 12275 break; 12276 } 12277 } 12278 12279 // FIXME: this should probably be preserved from the overload 12280 // operation somehow. 12281 bool SuppressUserConversions = false; 12282 12283 unsigned ConvIdx = 0; 12284 unsigned ArgIdx = 0; 12285 ArrayRef<QualType> ParamTypes; 12286 bool Reversed = Cand->isReversed(); 12287 12288 if (Cand->IsSurrogate) { 12289 QualType ConvType 12290 = Cand->Surrogate->getConversionType().getNonReferenceType(); 12291 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12292 ConvType = ConvPtrType->getPointeeType(); 12293 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 12294 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 12295 ConvIdx = 1; 12296 } else if (Cand->Function) { 12297 ParamTypes = 12298 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 12299 if (isa<CXXMethodDecl>(Cand->Function) && 12300 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 12301 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 12302 ConvIdx = 1; 12303 if (CSK == OverloadCandidateSet::CSK_Operator && 12304 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call && 12305 Cand->Function->getDeclName().getCXXOverloadedOperator() != 12306 OO_Subscript) 12307 // Argument 0 is 'this', which doesn't have a corresponding parameter. 12308 ArgIdx = 1; 12309 } 12310 } else { 12311 // Builtin operator. 12312 assert(ConvCount <= 3); 12313 ParamTypes = Cand->BuiltinParamTypes; 12314 } 12315 12316 // Fill in the rest of the conversions. 12317 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 12318 ConvIdx != ConvCount; 12319 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 12320 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 12321 if (Cand->Conversions[ConvIdx].isInitialized()) { 12322 // We've already checked this conversion. 12323 } else if (ParamIdx < ParamTypes.size()) { 12324 if (ParamTypes[ParamIdx]->isDependentType()) 12325 Cand->Conversions[ConvIdx].setAsIdentityConversion( 12326 Args[ArgIdx]->getType()); 12327 else { 12328 Cand->Conversions[ConvIdx] = 12329 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 12330 SuppressUserConversions, 12331 /*InOverloadResolution=*/true, 12332 /*AllowObjCWritebackConversion=*/ 12333 S.getLangOpts().ObjCAutoRefCount); 12334 // Store the FixIt in the candidate if it exists. 12335 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 12336 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 12337 } 12338 } else 12339 Cand->Conversions[ConvIdx].setEllipsis(); 12340 } 12341 } 12342 12343 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 12344 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 12345 SourceLocation OpLoc, 12346 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 12347 // Sort the candidates by viability and position. Sorting directly would 12348 // be prohibitive, so we make a set of pointers and sort those. 12349 SmallVector<OverloadCandidate*, 32> Cands; 12350 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 12351 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12352 if (!Filter(*Cand)) 12353 continue; 12354 switch (OCD) { 12355 case OCD_AllCandidates: 12356 if (!Cand->Viable) { 12357 if (!Cand->Function && !Cand->IsSurrogate) { 12358 // This a non-viable builtin candidate. We do not, in general, 12359 // want to list every possible builtin candidate. 12360 continue; 12361 } 12362 CompleteNonViableCandidate(S, Cand, Args, Kind); 12363 } 12364 break; 12365 12366 case OCD_ViableCandidates: 12367 if (!Cand->Viable) 12368 continue; 12369 break; 12370 12371 case OCD_AmbiguousCandidates: 12372 if (!Cand->Best) 12373 continue; 12374 break; 12375 } 12376 12377 Cands.push_back(Cand); 12378 } 12379 12380 llvm::stable_sort( 12381 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 12382 12383 return Cands; 12384 } 12385 12386 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args, 12387 SourceLocation OpLoc) { 12388 bool DeferHint = false; 12389 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) { 12390 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or 12391 // host device candidates. 12392 auto WrongSidedCands = 12393 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) { 12394 return (Cand.Viable == false && 12395 Cand.FailureKind == ovl_fail_bad_target) || 12396 (Cand.Function && 12397 Cand.Function->template hasAttr<CUDAHostAttr>() && 12398 Cand.Function->template hasAttr<CUDADeviceAttr>()); 12399 }); 12400 DeferHint = !WrongSidedCands.empty(); 12401 } 12402 return DeferHint; 12403 } 12404 12405 /// When overload resolution fails, prints diagnostic messages containing the 12406 /// candidates in the candidate set. 12407 void OverloadCandidateSet::NoteCandidates( 12408 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD, 12409 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc, 12410 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 12411 12412 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 12413 12414 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc)); 12415 12416 // In WebAssembly we don't want to emit further diagnostics if a table is 12417 // passed as an argument to a function. 12418 bool NoteCands = true; 12419 for (const Expr *Arg : Args) { 12420 if (Arg->getType()->isWebAssemblyTableType()) 12421 NoteCands = false; 12422 } 12423 12424 if (NoteCands) 12425 NoteCandidates(S, Args, Cands, Opc, OpLoc); 12426 12427 if (OCD == OCD_AmbiguousCandidates) 12428 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 12429 } 12430 12431 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 12432 ArrayRef<OverloadCandidate *> Cands, 12433 StringRef Opc, SourceLocation OpLoc) { 12434 bool ReportedAmbiguousConversions = false; 12435 12436 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12437 unsigned CandsShown = 0; 12438 auto I = Cands.begin(), E = Cands.end(); 12439 for (; I != E; ++I) { 12440 OverloadCandidate *Cand = *I; 12441 12442 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() && 12443 ShowOverloads == Ovl_Best) { 12444 break; 12445 } 12446 ++CandsShown; 12447 12448 if (Cand->Function) 12449 NoteFunctionCandidate(S, Cand, Args.size(), 12450 /*TakingCandidateAddress=*/false, DestAS); 12451 else if (Cand->IsSurrogate) 12452 NoteSurrogateCandidate(S, Cand); 12453 else { 12454 assert(Cand->Viable && 12455 "Non-viable built-in candidates are not added to Cands."); 12456 // Generally we only see ambiguities including viable builtin 12457 // operators if overload resolution got screwed up by an 12458 // ambiguous user-defined conversion. 12459 // 12460 // FIXME: It's quite possible for different conversions to see 12461 // different ambiguities, though. 12462 if (!ReportedAmbiguousConversions) { 12463 NoteAmbiguousUserConversions(S, OpLoc, Cand); 12464 ReportedAmbiguousConversions = true; 12465 } 12466 12467 // If this is a viable builtin, print it. 12468 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 12469 } 12470 } 12471 12472 // Inform S.Diags that we've shown an overload set with N elements. This may 12473 // inform the future value of S.Diags.getNumOverloadCandidatesToShow(). 12474 S.Diags.overloadCandidatesShown(CandsShown); 12475 12476 if (I != E) 12477 S.Diag(OpLoc, diag::note_ovl_too_many_candidates, 12478 shouldDeferDiags(S, Args, OpLoc)) 12479 << int(E - I); 12480 } 12481 12482 static SourceLocation 12483 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 12484 return Cand->Specialization ? Cand->Specialization->getLocation() 12485 : SourceLocation(); 12486 } 12487 12488 namespace { 12489 struct CompareTemplateSpecCandidatesForDisplay { 12490 Sema &S; 12491 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 12492 12493 bool operator()(const TemplateSpecCandidate *L, 12494 const TemplateSpecCandidate *R) { 12495 // Fast-path this check. 12496 if (L == R) 12497 return false; 12498 12499 // Assuming that both candidates are not matches... 12500 12501 // Sort by the ranking of deduction failures. 12502 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 12503 return RankDeductionFailure(L->DeductionFailure) < 12504 RankDeductionFailure(R->DeductionFailure); 12505 12506 // Sort everything else by location. 12507 SourceLocation LLoc = GetLocationForCandidate(L); 12508 SourceLocation RLoc = GetLocationForCandidate(R); 12509 12510 // Put candidates without locations (e.g. builtins) at the end. 12511 if (LLoc.isInvalid()) 12512 return false; 12513 if (RLoc.isInvalid()) 12514 return true; 12515 12516 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 12517 } 12518 }; 12519 } 12520 12521 /// Diagnose a template argument deduction failure. 12522 /// We are treating these failures as overload failures due to bad 12523 /// deductions. 12524 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 12525 bool ForTakingAddress) { 12526 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 12527 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 12528 } 12529 12530 void TemplateSpecCandidateSet::destroyCandidates() { 12531 for (iterator i = begin(), e = end(); i != e; ++i) { 12532 i->DeductionFailure.Destroy(); 12533 } 12534 } 12535 12536 void TemplateSpecCandidateSet::clear() { 12537 destroyCandidates(); 12538 Candidates.clear(); 12539 } 12540 12541 /// NoteCandidates - When no template specialization match is found, prints 12542 /// diagnostic messages containing the non-matching specializations that form 12543 /// the candidate set. 12544 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 12545 /// OCD == OCD_AllCandidates and Cand->Viable == false. 12546 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 12547 // Sort the candidates by position (assuming no candidate is a match). 12548 // Sorting directly would be prohibitive, so we make a set of pointers 12549 // and sort those. 12550 SmallVector<TemplateSpecCandidate *, 32> Cands; 12551 Cands.reserve(size()); 12552 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 12553 if (Cand->Specialization) 12554 Cands.push_back(Cand); 12555 // Otherwise, this is a non-matching builtin candidate. We do not, 12556 // in general, want to list every possible builtin candidate. 12557 } 12558 12559 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 12560 12561 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 12562 // for generalization purposes (?). 12563 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 12564 12565 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 12566 unsigned CandsShown = 0; 12567 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 12568 TemplateSpecCandidate *Cand = *I; 12569 12570 // Set an arbitrary limit on the number of candidates we'll spam 12571 // the user with. FIXME: This limit should depend on details of the 12572 // candidate list. 12573 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 12574 break; 12575 ++CandsShown; 12576 12577 assert(Cand->Specialization && 12578 "Non-matching built-in candidates are not added to Cands."); 12579 Cand->NoteDeductionFailure(S, ForTakingAddress); 12580 } 12581 12582 if (I != E) 12583 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 12584 } 12585 12586 // [PossiblyAFunctionType] --> [Return] 12587 // NonFunctionType --> NonFunctionType 12588 // R (A) --> R(A) 12589 // R (*)(A) --> R (A) 12590 // R (&)(A) --> R (A) 12591 // R (S::*)(A) --> R (A) 12592 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 12593 QualType Ret = PossiblyAFunctionType; 12594 if (const PointerType *ToTypePtr = 12595 PossiblyAFunctionType->getAs<PointerType>()) 12596 Ret = ToTypePtr->getPointeeType(); 12597 else if (const ReferenceType *ToTypeRef = 12598 PossiblyAFunctionType->getAs<ReferenceType>()) 12599 Ret = ToTypeRef->getPointeeType(); 12600 else if (const MemberPointerType *MemTypePtr = 12601 PossiblyAFunctionType->getAs<MemberPointerType>()) 12602 Ret = MemTypePtr->getPointeeType(); 12603 Ret = 12604 Context.getCanonicalType(Ret).getUnqualifiedType(); 12605 return Ret; 12606 } 12607 12608 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 12609 bool Complain = true) { 12610 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 12611 S.DeduceReturnType(FD, Loc, Complain)) 12612 return true; 12613 12614 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 12615 if (S.getLangOpts().CPlusPlus17 && 12616 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 12617 !S.ResolveExceptionSpec(Loc, FPT)) 12618 return true; 12619 12620 return false; 12621 } 12622 12623 namespace { 12624 // A helper class to help with address of function resolution 12625 // - allows us to avoid passing around all those ugly parameters 12626 class AddressOfFunctionResolver { 12627 Sema& S; 12628 Expr* SourceExpr; 12629 const QualType& TargetType; 12630 QualType TargetFunctionType; // Extracted function type from target type 12631 12632 bool Complain; 12633 //DeclAccessPair& ResultFunctionAccessPair; 12634 ASTContext& Context; 12635 12636 bool TargetTypeIsNonStaticMemberFunction; 12637 bool FoundNonTemplateFunction; 12638 bool StaticMemberFunctionFromBoundPointer; 12639 bool HasComplained; 12640 12641 OverloadExpr::FindResult OvlExprInfo; 12642 OverloadExpr *OvlExpr; 12643 TemplateArgumentListInfo OvlExplicitTemplateArgs; 12644 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 12645 TemplateSpecCandidateSet FailedCandidates; 12646 12647 public: 12648 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 12649 const QualType &TargetType, bool Complain) 12650 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 12651 Complain(Complain), Context(S.getASTContext()), 12652 TargetTypeIsNonStaticMemberFunction( 12653 !!TargetType->getAs<MemberPointerType>()), 12654 FoundNonTemplateFunction(false), 12655 StaticMemberFunctionFromBoundPointer(false), 12656 HasComplained(false), 12657 OvlExprInfo(OverloadExpr::find(SourceExpr)), 12658 OvlExpr(OvlExprInfo.Expression), 12659 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 12660 ExtractUnqualifiedFunctionTypeFromTargetType(); 12661 12662 if (TargetFunctionType->isFunctionType()) { 12663 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 12664 if (!UME->isImplicitAccess() && 12665 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 12666 StaticMemberFunctionFromBoundPointer = true; 12667 } else if (OvlExpr->hasExplicitTemplateArgs()) { 12668 DeclAccessPair dap; 12669 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 12670 OvlExpr, false, &dap)) { 12671 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 12672 if (!Method->isStatic()) { 12673 // If the target type is a non-function type and the function found 12674 // is a non-static member function, pretend as if that was the 12675 // target, it's the only possible type to end up with. 12676 TargetTypeIsNonStaticMemberFunction = true; 12677 12678 // And skip adding the function if its not in the proper form. 12679 // We'll diagnose this due to an empty set of functions. 12680 if (!OvlExprInfo.HasFormOfMemberPointer) 12681 return; 12682 } 12683 12684 Matches.push_back(std::make_pair(dap, Fn)); 12685 } 12686 return; 12687 } 12688 12689 if (OvlExpr->hasExplicitTemplateArgs()) 12690 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 12691 12692 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 12693 // C++ [over.over]p4: 12694 // If more than one function is selected, [...] 12695 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 12696 if (FoundNonTemplateFunction) 12697 EliminateAllTemplateMatches(); 12698 else 12699 EliminateAllExceptMostSpecializedTemplate(); 12700 } 12701 } 12702 12703 if (S.getLangOpts().CUDA && Matches.size() > 1) 12704 EliminateSuboptimalCudaMatches(); 12705 } 12706 12707 bool hasComplained() const { return HasComplained; } 12708 12709 private: 12710 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 12711 QualType Discard; 12712 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 12713 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 12714 } 12715 12716 /// \return true if A is considered a better overload candidate for the 12717 /// desired type than B. 12718 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 12719 // If A doesn't have exactly the correct type, we don't want to classify it 12720 // as "better" than anything else. This way, the user is required to 12721 // disambiguate for us if there are multiple candidates and no exact match. 12722 return candidateHasExactlyCorrectType(A) && 12723 (!candidateHasExactlyCorrectType(B) || 12724 compareEnableIfAttrs(S, A, B) == Comparison::Better); 12725 } 12726 12727 /// \return true if we were able to eliminate all but one overload candidate, 12728 /// false otherwise. 12729 bool eliminiateSuboptimalOverloadCandidates() { 12730 // Same algorithm as overload resolution -- one pass to pick the "best", 12731 // another pass to be sure that nothing is better than the best. 12732 auto Best = Matches.begin(); 12733 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 12734 if (isBetterCandidate(I->second, Best->second)) 12735 Best = I; 12736 12737 const FunctionDecl *BestFn = Best->second; 12738 auto IsBestOrInferiorToBest = [this, BestFn]( 12739 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 12740 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 12741 }; 12742 12743 // Note: We explicitly leave Matches unmodified if there isn't a clear best 12744 // option, so we can potentially give the user a better error 12745 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 12746 return false; 12747 Matches[0] = *Best; 12748 Matches.resize(1); 12749 return true; 12750 } 12751 12752 bool isTargetTypeAFunction() const { 12753 return TargetFunctionType->isFunctionType(); 12754 } 12755 12756 // [ToType] [Return] 12757 12758 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 12759 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 12760 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 12761 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 12762 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 12763 } 12764 12765 // return true if any matching specializations were found 12766 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 12767 const DeclAccessPair& CurAccessFunPair) { 12768 if (CXXMethodDecl *Method 12769 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 12770 // Skip non-static function templates when converting to pointer, and 12771 // static when converting to member pointer. 12772 bool CanConvertToFunctionPointer = 12773 Method->isStatic() || Method->isExplicitObjectMemberFunction(); 12774 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) 12775 return false; 12776 } 12777 else if (TargetTypeIsNonStaticMemberFunction) 12778 return false; 12779 12780 // C++ [over.over]p2: 12781 // If the name is a function template, template argument deduction is 12782 // done (14.8.2.2), and if the argument deduction succeeds, the 12783 // resulting template argument list is used to generate a single 12784 // function template specialization, which is added to the set of 12785 // overloaded functions considered. 12786 FunctionDecl *Specialization = nullptr; 12787 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12788 if (Sema::TemplateDeductionResult Result 12789 = S.DeduceTemplateArguments(FunctionTemplate, 12790 &OvlExplicitTemplateArgs, 12791 TargetFunctionType, Specialization, 12792 Info, /*IsAddressOfFunction*/true)) { 12793 // Make a note of the failed deduction for diagnostics. 12794 FailedCandidates.addCandidate() 12795 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 12796 MakeDeductionFailureInfo(Context, Result, Info)); 12797 return false; 12798 } 12799 12800 // Template argument deduction ensures that we have an exact match or 12801 // compatible pointer-to-function arguments that would be adjusted by ICS. 12802 // This function template specicalization works. 12803 assert(S.isSameOrCompatibleFunctionType( 12804 Context.getCanonicalType(Specialization->getType()), 12805 Context.getCanonicalType(TargetFunctionType))); 12806 12807 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 12808 return false; 12809 12810 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 12811 return true; 12812 } 12813 12814 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 12815 const DeclAccessPair& CurAccessFunPair) { 12816 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12817 // Skip non-static functions when converting to pointer, and static 12818 // when converting to member pointer. 12819 bool CanConvertToFunctionPointer = 12820 Method->isStatic() || Method->isExplicitObjectMemberFunction(); 12821 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction) 12822 return false; 12823 } 12824 else if (TargetTypeIsNonStaticMemberFunction) 12825 return false; 12826 12827 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 12828 if (S.getLangOpts().CUDA) { 12829 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true); 12830 if (!(Caller && Caller->isImplicit()) && 12831 !S.IsAllowedCUDACall(Caller, FunDecl)) 12832 return false; 12833 } 12834 if (FunDecl->isMultiVersion()) { 12835 const auto *TA = FunDecl->getAttr<TargetAttr>(); 12836 if (TA && !TA->isDefaultVersion()) 12837 return false; 12838 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>(); 12839 if (TVA && !TVA->isDefaultVersion()) 12840 return false; 12841 } 12842 12843 // If any candidate has a placeholder return type, trigger its deduction 12844 // now. 12845 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 12846 Complain)) { 12847 HasComplained |= Complain; 12848 return false; 12849 } 12850 12851 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 12852 return false; 12853 12854 // If we're in C, we need to support types that aren't exactly identical. 12855 if (!S.getLangOpts().CPlusPlus || 12856 candidateHasExactlyCorrectType(FunDecl)) { 12857 Matches.push_back(std::make_pair( 12858 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 12859 FoundNonTemplateFunction = true; 12860 return true; 12861 } 12862 } 12863 12864 return false; 12865 } 12866 12867 bool FindAllFunctionsThatMatchTargetTypeExactly() { 12868 bool Ret = false; 12869 12870 // If the overload expression doesn't have the form of a pointer to 12871 // member, don't try to convert it to a pointer-to-member type. 12872 if (IsInvalidFormOfPointerToMemberFunction()) 12873 return false; 12874 12875 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12876 E = OvlExpr->decls_end(); 12877 I != E; ++I) { 12878 // Look through any using declarations to find the underlying function. 12879 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 12880 12881 // C++ [over.over]p3: 12882 // Non-member functions and static member functions match 12883 // targets of type "pointer-to-function" or "reference-to-function." 12884 // Nonstatic member functions match targets of 12885 // type "pointer-to-member-function." 12886 // Note that according to DR 247, the containing class does not matter. 12887 if (FunctionTemplateDecl *FunctionTemplate 12888 = dyn_cast<FunctionTemplateDecl>(Fn)) { 12889 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 12890 Ret = true; 12891 } 12892 // If we have explicit template arguments supplied, skip non-templates. 12893 else if (!OvlExpr->hasExplicitTemplateArgs() && 12894 AddMatchingNonTemplateFunction(Fn, I.getPair())) 12895 Ret = true; 12896 } 12897 assert(Ret || Matches.empty()); 12898 return Ret; 12899 } 12900 12901 void EliminateAllExceptMostSpecializedTemplate() { 12902 // [...] and any given function template specialization F1 is 12903 // eliminated if the set contains a second function template 12904 // specialization whose function template is more specialized 12905 // than the function template of F1 according to the partial 12906 // ordering rules of 14.5.5.2. 12907 12908 // The algorithm specified above is quadratic. We instead use a 12909 // two-pass algorithm (similar to the one used to identify the 12910 // best viable function in an overload set) that identifies the 12911 // best function template (if it exists). 12912 12913 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 12914 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 12915 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 12916 12917 // TODO: It looks like FailedCandidates does not serve much purpose 12918 // here, since the no_viable diagnostic has index 0. 12919 UnresolvedSetIterator Result = S.getMostSpecialized( 12920 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 12921 SourceExpr->getBeginLoc(), S.PDiag(), 12922 S.PDiag(diag::err_addr_ovl_ambiguous) 12923 << Matches[0].second->getDeclName(), 12924 S.PDiag(diag::note_ovl_candidate) 12925 << (unsigned)oc_function << (unsigned)ocs_described_template, 12926 Complain, TargetFunctionType); 12927 12928 if (Result != MatchesCopy.end()) { 12929 // Make it the first and only element 12930 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12931 Matches[0].second = cast<FunctionDecl>(*Result); 12932 Matches.resize(1); 12933 } else 12934 HasComplained |= Complain; 12935 } 12936 12937 void EliminateAllTemplateMatches() { 12938 // [...] any function template specializations in the set are 12939 // eliminated if the set also contains a non-template function, [...] 12940 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12941 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12942 ++I; 12943 else { 12944 Matches[I] = Matches[--N]; 12945 Matches.resize(N); 12946 } 12947 } 12948 } 12949 12950 void EliminateSuboptimalCudaMatches() { 12951 S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true), 12952 Matches); 12953 } 12954 12955 public: 12956 void ComplainNoMatchesFound() const { 12957 assert(Matches.empty()); 12958 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12959 << OvlExpr->getName() << TargetFunctionType 12960 << OvlExpr->getSourceRange(); 12961 if (FailedCandidates.empty()) 12962 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12963 /*TakingAddress=*/true); 12964 else { 12965 // We have some deduction failure messages. Use them to diagnose 12966 // the function templates, and diagnose the non-template candidates 12967 // normally. 12968 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12969 IEnd = OvlExpr->decls_end(); 12970 I != IEnd; ++I) 12971 if (FunctionDecl *Fun = 12972 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12973 if (!functionHasPassObjectSizeParams(Fun)) 12974 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12975 /*TakingAddress=*/true); 12976 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12977 } 12978 } 12979 12980 bool IsInvalidFormOfPointerToMemberFunction() const { 12981 return TargetTypeIsNonStaticMemberFunction && 12982 !OvlExprInfo.HasFormOfMemberPointer; 12983 } 12984 12985 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12986 // TODO: Should we condition this on whether any functions might 12987 // have matched, or is it more appropriate to do that in callers? 12988 // TODO: a fixit wouldn't hurt. 12989 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12990 << TargetType << OvlExpr->getSourceRange(); 12991 } 12992 12993 bool IsStaticMemberFunctionFromBoundPointer() const { 12994 return StaticMemberFunctionFromBoundPointer; 12995 } 12996 12997 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12998 S.Diag(OvlExpr->getBeginLoc(), 12999 diag::err_invalid_form_pointer_member_function) 13000 << OvlExpr->getSourceRange(); 13001 } 13002 13003 void ComplainOfInvalidConversion() const { 13004 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 13005 << OvlExpr->getName() << TargetType; 13006 } 13007 13008 void ComplainMultipleMatchesFound() const { 13009 assert(Matches.size() > 1); 13010 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 13011 << OvlExpr->getName() << OvlExpr->getSourceRange(); 13012 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 13013 /*TakingAddress=*/true); 13014 } 13015 13016 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 13017 13018 int getNumMatches() const { return Matches.size(); } 13019 13020 FunctionDecl* getMatchingFunctionDecl() const { 13021 if (Matches.size() != 1) return nullptr; 13022 return Matches[0].second; 13023 } 13024 13025 const DeclAccessPair* getMatchingFunctionAccessPair() const { 13026 if (Matches.size() != 1) return nullptr; 13027 return &Matches[0].first; 13028 } 13029 }; 13030 } 13031 13032 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 13033 /// an overloaded function (C++ [over.over]), where @p From is an 13034 /// expression with overloaded function type and @p ToType is the type 13035 /// we're trying to resolve to. For example: 13036 /// 13037 /// @code 13038 /// int f(double); 13039 /// int f(int); 13040 /// 13041 /// int (*pfd)(double) = f; // selects f(double) 13042 /// @endcode 13043 /// 13044 /// This routine returns the resulting FunctionDecl if it could be 13045 /// resolved, and NULL otherwise. When @p Complain is true, this 13046 /// routine will emit diagnostics if there is an error. 13047 FunctionDecl * 13048 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 13049 QualType TargetType, 13050 bool Complain, 13051 DeclAccessPair &FoundResult, 13052 bool *pHadMultipleCandidates) { 13053 assert(AddressOfExpr->getType() == Context.OverloadTy); 13054 13055 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 13056 Complain); 13057 int NumMatches = Resolver.getNumMatches(); 13058 FunctionDecl *Fn = nullptr; 13059 bool ShouldComplain = Complain && !Resolver.hasComplained(); 13060 if (NumMatches == 0 && ShouldComplain) { 13061 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 13062 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 13063 else 13064 Resolver.ComplainNoMatchesFound(); 13065 } 13066 else if (NumMatches > 1 && ShouldComplain) 13067 Resolver.ComplainMultipleMatchesFound(); 13068 else if (NumMatches == 1) { 13069 Fn = Resolver.getMatchingFunctionDecl(); 13070 assert(Fn); 13071 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13072 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 13073 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 13074 if (Complain) { 13075 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 13076 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 13077 else 13078 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 13079 } 13080 } 13081 13082 if (pHadMultipleCandidates) 13083 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 13084 return Fn; 13085 } 13086 13087 /// Given an expression that refers to an overloaded function, try to 13088 /// resolve that function to a single function that can have its address taken. 13089 /// This will modify `Pair` iff it returns non-null. 13090 /// 13091 /// This routine can only succeed if from all of the candidates in the overload 13092 /// set for SrcExpr that can have their addresses taken, there is one candidate 13093 /// that is more constrained than the rest. 13094 FunctionDecl * 13095 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 13096 OverloadExpr::FindResult R = OverloadExpr::find(E); 13097 OverloadExpr *Ovl = R.Expression; 13098 bool IsResultAmbiguous = false; 13099 FunctionDecl *Result = nullptr; 13100 DeclAccessPair DAP; 13101 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 13102 13103 // Return positive for better, negative for worse, 0 for equal preference. 13104 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) { 13105 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 13106 return static_cast<int>(IdentifyCUDAPreference(Caller, FD1)) - 13107 static_cast<int>(IdentifyCUDAPreference(Caller, FD2)); 13108 }; 13109 13110 auto CheckMoreConstrained = [&](FunctionDecl *FD1, 13111 FunctionDecl *FD2) -> std::optional<bool> { 13112 if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction()) 13113 FD1 = MF; 13114 if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction()) 13115 FD2 = MF; 13116 SmallVector<const Expr *, 1> AC1, AC2; 13117 FD1->getAssociatedConstraints(AC1); 13118 FD2->getAssociatedConstraints(AC2); 13119 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 13120 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 13121 return std::nullopt; 13122 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 13123 return std::nullopt; 13124 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 13125 return std::nullopt; 13126 return AtLeastAsConstrained1; 13127 }; 13128 13129 // Don't use the AddressOfResolver because we're specifically looking for 13130 // cases where we have one overload candidate that lacks 13131 // enable_if/pass_object_size/... 13132 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 13133 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 13134 if (!FD) 13135 return nullptr; 13136 13137 if (!checkAddressOfFunctionIsAvailable(FD)) 13138 continue; 13139 13140 // If we found a better result, update Result. 13141 auto FoundBetter = [&]() { 13142 IsResultAmbiguous = false; 13143 DAP = I.getPair(); 13144 Result = FD; 13145 }; 13146 13147 // We have more than one result - see if it is more constrained than the 13148 // previous one. 13149 if (Result) { 13150 // Check CUDA preference first. If the candidates have differennt CUDA 13151 // preference, choose the one with higher CUDA preference. Otherwise, 13152 // choose the one with more constraints. 13153 if (getLangOpts().CUDA) { 13154 int PreferenceByCUDA = CheckCUDAPreference(FD, Result); 13155 // FD has different preference than Result. 13156 if (PreferenceByCUDA != 0) { 13157 // FD is more preferable than Result. 13158 if (PreferenceByCUDA > 0) 13159 FoundBetter(); 13160 continue; 13161 } 13162 } 13163 // FD has the same CUDA prefernece than Result. Continue check 13164 // constraints. 13165 std::optional<bool> MoreConstrainedThanPrevious = 13166 CheckMoreConstrained(FD, Result); 13167 if (!MoreConstrainedThanPrevious) { 13168 IsResultAmbiguous = true; 13169 AmbiguousDecls.push_back(FD); 13170 continue; 13171 } 13172 if (!*MoreConstrainedThanPrevious) 13173 continue; 13174 // FD is more constrained - replace Result with it. 13175 } 13176 FoundBetter(); 13177 } 13178 13179 if (IsResultAmbiguous) 13180 return nullptr; 13181 13182 if (Result) { 13183 SmallVector<const Expr *, 1> ResultAC; 13184 // We skipped over some ambiguous declarations which might be ambiguous with 13185 // the selected result. 13186 for (FunctionDecl *Skipped : AmbiguousDecls) { 13187 // If skipped candidate has different CUDA preference than the result, 13188 // there is no ambiguity. Otherwise check whether they have different 13189 // constraints. 13190 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0) 13191 continue; 13192 if (!CheckMoreConstrained(Skipped, Result)) 13193 return nullptr; 13194 } 13195 Pair = DAP; 13196 } 13197 return Result; 13198 } 13199 13200 /// Given an overloaded function, tries to turn it into a non-overloaded 13201 /// function reference using resolveAddressOfSingleOverloadCandidate. This 13202 /// will perform access checks, diagnose the use of the resultant decl, and, if 13203 /// requested, potentially perform a function-to-pointer decay. 13204 /// 13205 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 13206 /// Otherwise, returns true. This may emit diagnostics and return true. 13207 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 13208 ExprResult &SrcExpr, bool DoFunctionPointerConversion) { 13209 Expr *E = SrcExpr.get(); 13210 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 13211 13212 DeclAccessPair DAP; 13213 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 13214 if (!Found || Found->isCPUDispatchMultiVersion() || 13215 Found->isCPUSpecificMultiVersion()) 13216 return false; 13217 13218 // Emitting multiple diagnostics for a function that is both inaccessible and 13219 // unavailable is consistent with our behavior elsewhere. So, always check 13220 // for both. 13221 DiagnoseUseOfDecl(Found, E->getExprLoc()); 13222 CheckAddressOfMemberAccess(E, DAP); 13223 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found); 13224 if (Res.isInvalid()) 13225 return false; 13226 Expr *Fixed = Res.get(); 13227 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType()) 13228 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 13229 else 13230 SrcExpr = Fixed; 13231 return true; 13232 } 13233 13234 /// Given an expression that refers to an overloaded function, try to 13235 /// resolve that overloaded function expression down to a single function. 13236 /// 13237 /// This routine can only resolve template-ids that refer to a single function 13238 /// template, where that template-id refers to a single template whose template 13239 /// arguments are either provided by the template-id or have defaults, 13240 /// as described in C++0x [temp.arg.explicit]p3. 13241 /// 13242 /// If no template-ids are found, no diagnostics are emitted and NULL is 13243 /// returned. 13244 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization( 13245 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult, 13246 TemplateSpecCandidateSet *FailedTSC) { 13247 // C++ [over.over]p1: 13248 // [...] [Note: any redundant set of parentheses surrounding the 13249 // overloaded function name is ignored (5.1). ] 13250 // C++ [over.over]p1: 13251 // [...] The overloaded function name can be preceded by the & 13252 // operator. 13253 13254 // If we didn't actually find any template-ids, we're done. 13255 if (!ovl->hasExplicitTemplateArgs()) 13256 return nullptr; 13257 13258 TemplateArgumentListInfo ExplicitTemplateArgs; 13259 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 13260 13261 // Look through all of the overloaded functions, searching for one 13262 // whose type matches exactly. 13263 FunctionDecl *Matched = nullptr; 13264 for (UnresolvedSetIterator I = ovl->decls_begin(), 13265 E = ovl->decls_end(); I != E; ++I) { 13266 // C++0x [temp.arg.explicit]p3: 13267 // [...] In contexts where deduction is done and fails, or in contexts 13268 // where deduction is not done, if a template argument list is 13269 // specified and it, along with any default template arguments, 13270 // identifies a single function template specialization, then the 13271 // template-id is an lvalue for the function template specialization. 13272 FunctionTemplateDecl *FunctionTemplate 13273 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 13274 13275 // C++ [over.over]p2: 13276 // If the name is a function template, template argument deduction is 13277 // done (14.8.2.2), and if the argument deduction succeeds, the 13278 // resulting template argument list is used to generate a single 13279 // function template specialization, which is added to the set of 13280 // overloaded functions considered. 13281 FunctionDecl *Specialization = nullptr; 13282 TemplateDeductionInfo Info(ovl->getNameLoc()); 13283 if (TemplateDeductionResult Result 13284 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 13285 Specialization, Info, 13286 /*IsAddressOfFunction*/true)) { 13287 // Make a note of the failed deduction for diagnostics. 13288 if (FailedTSC) 13289 FailedTSC->addCandidate().set( 13290 I.getPair(), FunctionTemplate->getTemplatedDecl(), 13291 MakeDeductionFailureInfo(Context, Result, Info)); 13292 continue; 13293 } 13294 13295 assert(Specialization && "no specialization and no error?"); 13296 13297 // Multiple matches; we can't resolve to a single declaration. 13298 if (Matched) { 13299 if (Complain) { 13300 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 13301 << ovl->getName(); 13302 NoteAllOverloadCandidates(ovl); 13303 } 13304 return nullptr; 13305 } 13306 13307 Matched = Specialization; 13308 if (FoundResult) *FoundResult = I.getPair(); 13309 } 13310 13311 if (Matched && 13312 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 13313 return nullptr; 13314 13315 return Matched; 13316 } 13317 13318 // Resolve and fix an overloaded expression that can be resolved 13319 // because it identifies a single function template specialization. 13320 // 13321 // Last three arguments should only be supplied if Complain = true 13322 // 13323 // Return true if it was logically possible to so resolve the 13324 // expression, regardless of whether or not it succeeded. Always 13325 // returns true if 'complain' is set. 13326 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 13327 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain, 13328 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining, 13329 unsigned DiagIDForComplaining) { 13330 assert(SrcExpr.get()->getType() == Context.OverloadTy); 13331 13332 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 13333 13334 DeclAccessPair found; 13335 ExprResult SingleFunctionExpression; 13336 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 13337 ovl.Expression, /*complain*/ false, &found)) { 13338 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 13339 SrcExpr = ExprError(); 13340 return true; 13341 } 13342 13343 // It is only correct to resolve to an instance method if we're 13344 // resolving a form that's permitted to be a pointer to member. 13345 // Otherwise we'll end up making a bound member expression, which 13346 // is illegal in all the contexts we resolve like this. 13347 if (!ovl.HasFormOfMemberPointer && 13348 isa<CXXMethodDecl>(fn) && 13349 cast<CXXMethodDecl>(fn)->isInstance()) { 13350 if (!complain) return false; 13351 13352 Diag(ovl.Expression->getExprLoc(), 13353 diag::err_bound_member_function) 13354 << 0 << ovl.Expression->getSourceRange(); 13355 13356 // TODO: I believe we only end up here if there's a mix of 13357 // static and non-static candidates (otherwise the expression 13358 // would have 'bound member' type, not 'overload' type). 13359 // Ideally we would note which candidate was chosen and why 13360 // the static candidates were rejected. 13361 SrcExpr = ExprError(); 13362 return true; 13363 } 13364 13365 // Fix the expression to refer to 'fn'. 13366 SingleFunctionExpression = 13367 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 13368 13369 // If desired, do function-to-pointer decay. 13370 if (doFunctionPointerConversion) { 13371 SingleFunctionExpression = 13372 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 13373 if (SingleFunctionExpression.isInvalid()) { 13374 SrcExpr = ExprError(); 13375 return true; 13376 } 13377 } 13378 } 13379 13380 if (!SingleFunctionExpression.isUsable()) { 13381 if (complain) { 13382 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 13383 << ovl.Expression->getName() 13384 << DestTypeForComplaining 13385 << OpRangeForComplaining 13386 << ovl.Expression->getQualifierLoc().getSourceRange(); 13387 NoteAllOverloadCandidates(SrcExpr.get()); 13388 13389 SrcExpr = ExprError(); 13390 return true; 13391 } 13392 13393 return false; 13394 } 13395 13396 SrcExpr = SingleFunctionExpression; 13397 return true; 13398 } 13399 13400 /// Add a single candidate to the overload set. 13401 static void AddOverloadedCallCandidate(Sema &S, 13402 DeclAccessPair FoundDecl, 13403 TemplateArgumentListInfo *ExplicitTemplateArgs, 13404 ArrayRef<Expr *> Args, 13405 OverloadCandidateSet &CandidateSet, 13406 bool PartialOverloading, 13407 bool KnownValid) { 13408 NamedDecl *Callee = FoundDecl.getDecl(); 13409 if (isa<UsingShadowDecl>(Callee)) 13410 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 13411 13412 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 13413 if (ExplicitTemplateArgs) { 13414 assert(!KnownValid && "Explicit template arguments?"); 13415 return; 13416 } 13417 // Prevent ill-formed function decls to be added as overload candidates. 13418 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 13419 return; 13420 13421 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 13422 /*SuppressUserConversions=*/false, 13423 PartialOverloading); 13424 return; 13425 } 13426 13427 if (FunctionTemplateDecl *FuncTemplate 13428 = dyn_cast<FunctionTemplateDecl>(Callee)) { 13429 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 13430 ExplicitTemplateArgs, Args, CandidateSet, 13431 /*SuppressUserConversions=*/false, 13432 PartialOverloading); 13433 return; 13434 } 13435 13436 assert(!KnownValid && "unhandled case in overloaded call candidate"); 13437 } 13438 13439 /// Add the overload candidates named by callee and/or found by argument 13440 /// dependent lookup to the given overload set. 13441 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 13442 ArrayRef<Expr *> Args, 13443 OverloadCandidateSet &CandidateSet, 13444 bool PartialOverloading) { 13445 13446 #ifndef NDEBUG 13447 // Verify that ArgumentDependentLookup is consistent with the rules 13448 // in C++0x [basic.lookup.argdep]p3: 13449 // 13450 // Let X be the lookup set produced by unqualified lookup (3.4.1) 13451 // and let Y be the lookup set produced by argument dependent 13452 // lookup (defined as follows). If X contains 13453 // 13454 // -- a declaration of a class member, or 13455 // 13456 // -- a block-scope function declaration that is not a 13457 // using-declaration, or 13458 // 13459 // -- a declaration that is neither a function or a function 13460 // template 13461 // 13462 // then Y is empty. 13463 13464 if (ULE->requiresADL()) { 13465 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 13466 E = ULE->decls_end(); I != E; ++I) { 13467 assert(!(*I)->getDeclContext()->isRecord()); 13468 assert(isa<UsingShadowDecl>(*I) || 13469 !(*I)->getDeclContext()->isFunctionOrMethod()); 13470 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 13471 } 13472 } 13473 #endif 13474 13475 // It would be nice to avoid this copy. 13476 TemplateArgumentListInfo TABuffer; 13477 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13478 if (ULE->hasExplicitTemplateArgs()) { 13479 ULE->copyTemplateArgumentsInto(TABuffer); 13480 ExplicitTemplateArgs = &TABuffer; 13481 } 13482 13483 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 13484 E = ULE->decls_end(); I != E; ++I) 13485 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 13486 CandidateSet, PartialOverloading, 13487 /*KnownValid*/ true); 13488 13489 if (ULE->requiresADL()) 13490 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 13491 Args, ExplicitTemplateArgs, 13492 CandidateSet, PartialOverloading); 13493 } 13494 13495 /// Add the call candidates from the given set of lookup results to the given 13496 /// overload set. Non-function lookup results are ignored. 13497 void Sema::AddOverloadedCallCandidates( 13498 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 13499 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) { 13500 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 13501 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 13502 CandidateSet, false, /*KnownValid*/ false); 13503 } 13504 13505 /// Determine whether a declaration with the specified name could be moved into 13506 /// a different namespace. 13507 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 13508 switch (Name.getCXXOverloadedOperator()) { 13509 case OO_New: case OO_Array_New: 13510 case OO_Delete: case OO_Array_Delete: 13511 return false; 13512 13513 default: 13514 return true; 13515 } 13516 } 13517 13518 /// Attempt to recover from an ill-formed use of a non-dependent name in a 13519 /// template, where the non-dependent name was declared after the template 13520 /// was defined. This is common in code written for a compilers which do not 13521 /// correctly implement two-stage name lookup. 13522 /// 13523 /// Returns true if a viable candidate was found and a diagnostic was issued. 13524 static bool DiagnoseTwoPhaseLookup( 13525 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, 13526 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, 13527 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 13528 CXXRecordDecl **FoundInClass = nullptr) { 13529 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 13530 return false; 13531 13532 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 13533 if (DC->isTransparentContext()) 13534 continue; 13535 13536 SemaRef.LookupQualifiedName(R, DC); 13537 13538 if (!R.empty()) { 13539 R.suppressDiagnostics(); 13540 13541 OverloadCandidateSet Candidates(FnLoc, CSK); 13542 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, 13543 Candidates); 13544 13545 OverloadCandidateSet::iterator Best; 13546 OverloadingResult OR = 13547 Candidates.BestViableFunction(SemaRef, FnLoc, Best); 13548 13549 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) { 13550 // We either found non-function declarations or a best viable function 13551 // at class scope. A class-scope lookup result disables ADL. Don't 13552 // look past this, but let the caller know that we found something that 13553 // either is, or might be, usable in this class. 13554 if (FoundInClass) { 13555 *FoundInClass = RD; 13556 if (OR == OR_Success) { 13557 R.clear(); 13558 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 13559 R.resolveKind(); 13560 } 13561 } 13562 return false; 13563 } 13564 13565 if (OR != OR_Success) { 13566 // There wasn't a unique best function or function template. 13567 return false; 13568 } 13569 13570 // Find the namespaces where ADL would have looked, and suggest 13571 // declaring the function there instead. 13572 Sema::AssociatedNamespaceSet AssociatedNamespaces; 13573 Sema::AssociatedClassSet AssociatedClasses; 13574 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 13575 AssociatedNamespaces, 13576 AssociatedClasses); 13577 Sema::AssociatedNamespaceSet SuggestedNamespaces; 13578 if (canBeDeclaredInNamespace(R.getLookupName())) { 13579 DeclContext *Std = SemaRef.getStdNamespace(); 13580 for (Sema::AssociatedNamespaceSet::iterator 13581 it = AssociatedNamespaces.begin(), 13582 end = AssociatedNamespaces.end(); it != end; ++it) { 13583 // Never suggest declaring a function within namespace 'std'. 13584 if (Std && Std->Encloses(*it)) 13585 continue; 13586 13587 // Never suggest declaring a function within a namespace with a 13588 // reserved name, like __gnu_cxx. 13589 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 13590 if (NS && 13591 NS->getQualifiedNameAsString().find("__") != std::string::npos) 13592 continue; 13593 13594 SuggestedNamespaces.insert(*it); 13595 } 13596 } 13597 13598 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 13599 << R.getLookupName(); 13600 if (SuggestedNamespaces.empty()) { 13601 SemaRef.Diag(Best->Function->getLocation(), 13602 diag::note_not_found_by_two_phase_lookup) 13603 << R.getLookupName() << 0; 13604 } else if (SuggestedNamespaces.size() == 1) { 13605 SemaRef.Diag(Best->Function->getLocation(), 13606 diag::note_not_found_by_two_phase_lookup) 13607 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 13608 } else { 13609 // FIXME: It would be useful to list the associated namespaces here, 13610 // but the diagnostics infrastructure doesn't provide a way to produce 13611 // a localized representation of a list of items. 13612 SemaRef.Diag(Best->Function->getLocation(), 13613 diag::note_not_found_by_two_phase_lookup) 13614 << R.getLookupName() << 2; 13615 } 13616 13617 // Try to recover by calling this function. 13618 return true; 13619 } 13620 13621 R.clear(); 13622 } 13623 13624 return false; 13625 } 13626 13627 /// Attempt to recover from ill-formed use of a non-dependent operator in a 13628 /// template, where the non-dependent operator was declared after the template 13629 /// was defined. 13630 /// 13631 /// Returns true if a viable candidate was found and a diagnostic was issued. 13632 static bool 13633 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 13634 SourceLocation OpLoc, 13635 ArrayRef<Expr *> Args) { 13636 DeclarationName OpName = 13637 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 13638 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 13639 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 13640 OverloadCandidateSet::CSK_Operator, 13641 /*ExplicitTemplateArgs=*/nullptr, Args); 13642 } 13643 13644 namespace { 13645 class BuildRecoveryCallExprRAII { 13646 Sema &SemaRef; 13647 Sema::SatisfactionStackResetRAII SatStack; 13648 13649 public: 13650 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) { 13651 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 13652 SemaRef.IsBuildingRecoveryCallExpr = true; 13653 } 13654 13655 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; } 13656 }; 13657 } 13658 13659 /// Attempts to recover from a call where no functions were found. 13660 /// 13661 /// This function will do one of three things: 13662 /// * Diagnose, recover, and return a recovery expression. 13663 /// * Diagnose, fail to recover, and return ExprError(). 13664 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is 13665 /// expected to diagnose as appropriate. 13666 static ExprResult 13667 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13668 UnresolvedLookupExpr *ULE, 13669 SourceLocation LParenLoc, 13670 MutableArrayRef<Expr *> Args, 13671 SourceLocation RParenLoc, 13672 bool EmptyLookup, bool AllowTypoCorrection) { 13673 // Do not try to recover if it is already building a recovery call. 13674 // This stops infinite loops for template instantiations like 13675 // 13676 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 13677 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 13678 if (SemaRef.IsBuildingRecoveryCallExpr) 13679 return ExprResult(); 13680 BuildRecoveryCallExprRAII RCE(SemaRef); 13681 13682 CXXScopeSpec SS; 13683 SS.Adopt(ULE->getQualifierLoc()); 13684 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 13685 13686 TemplateArgumentListInfo TABuffer; 13687 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 13688 if (ULE->hasExplicitTemplateArgs()) { 13689 ULE->copyTemplateArgumentsInto(TABuffer); 13690 ExplicitTemplateArgs = &TABuffer; 13691 } 13692 13693 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 13694 Sema::LookupOrdinaryName); 13695 CXXRecordDecl *FoundInClass = nullptr; 13696 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 13697 OverloadCandidateSet::CSK_Normal, 13698 ExplicitTemplateArgs, Args, &FoundInClass)) { 13699 // OK, diagnosed a two-phase lookup issue. 13700 } else if (EmptyLookup) { 13701 // Try to recover from an empty lookup with typo correction. 13702 R.clear(); 13703 NoTypoCorrectionCCC NoTypoValidator{}; 13704 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 13705 ExplicitTemplateArgs != nullptr, 13706 dyn_cast<MemberExpr>(Fn)); 13707 CorrectionCandidateCallback &Validator = 13708 AllowTypoCorrection 13709 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 13710 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 13711 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 13712 Args)) 13713 return ExprError(); 13714 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) { 13715 // We found a usable declaration of the name in a dependent base of some 13716 // enclosing class. 13717 // FIXME: We should also explain why the candidates found by name lookup 13718 // were not viable. 13719 if (SemaRef.DiagnoseDependentMemberLookup(R)) 13720 return ExprError(); 13721 } else { 13722 // We had viable candidates and couldn't recover; let the caller diagnose 13723 // this. 13724 return ExprResult(); 13725 } 13726 13727 // If we get here, we should have issued a diagnostic and formed a recovery 13728 // lookup result. 13729 assert(!R.empty() && "lookup results empty despite recovery"); 13730 13731 // If recovery created an ambiguity, just bail out. 13732 if (R.isAmbiguous()) { 13733 R.suppressDiagnostics(); 13734 return ExprError(); 13735 } 13736 13737 // Build an implicit member call if appropriate. Just drop the 13738 // casts and such from the call, we don't really care. 13739 ExprResult NewFn = ExprError(); 13740 if ((*R.begin())->isCXXClassMember()) 13741 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 13742 ExplicitTemplateArgs, S); 13743 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 13744 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 13745 ExplicitTemplateArgs); 13746 else 13747 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 13748 13749 if (NewFn.isInvalid()) 13750 return ExprError(); 13751 13752 // This shouldn't cause an infinite loop because we're giving it 13753 // an expression with viable lookup results, which should never 13754 // end up here. 13755 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 13756 MultiExprArg(Args.data(), Args.size()), 13757 RParenLoc); 13758 } 13759 13760 /// Constructs and populates an OverloadedCandidateSet from 13761 /// the given function. 13762 /// \returns true when an the ExprResult output parameter has been set. 13763 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 13764 UnresolvedLookupExpr *ULE, 13765 MultiExprArg Args, 13766 SourceLocation RParenLoc, 13767 OverloadCandidateSet *CandidateSet, 13768 ExprResult *Result) { 13769 #ifndef NDEBUG 13770 if (ULE->requiresADL()) { 13771 // To do ADL, we must have found an unqualified name. 13772 assert(!ULE->getQualifier() && "qualified name with ADL"); 13773 13774 // We don't perform ADL for implicit declarations of builtins. 13775 // Verify that this was correctly set up. 13776 FunctionDecl *F; 13777 if (ULE->decls_begin() != ULE->decls_end() && 13778 ULE->decls_begin() + 1 == ULE->decls_end() && 13779 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 13780 F->getBuiltinID() && F->isImplicit()) 13781 llvm_unreachable("performing ADL for builtin"); 13782 13783 // We don't perform ADL in C. 13784 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 13785 } 13786 #endif 13787 13788 UnbridgedCastsSet UnbridgedCasts; 13789 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 13790 *Result = ExprError(); 13791 return true; 13792 } 13793 13794 // Add the functions denoted by the callee to the set of candidate 13795 // functions, including those from argument-dependent lookup. 13796 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 13797 13798 if (getLangOpts().MSVCCompat && 13799 CurContext->isDependentContext() && !isSFINAEContext() && 13800 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 13801 13802 OverloadCandidateSet::iterator Best; 13803 if (CandidateSet->empty() || 13804 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 13805 OR_No_Viable_Function) { 13806 // In Microsoft mode, if we are inside a template class member function 13807 // then create a type dependent CallExpr. The goal is to postpone name 13808 // lookup to instantiation time to be able to search into type dependent 13809 // base classes. 13810 CallExpr *CE = 13811 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue, 13812 RParenLoc, CurFPFeatureOverrides()); 13813 CE->markDependentForPostponedNameLookup(); 13814 *Result = CE; 13815 return true; 13816 } 13817 } 13818 13819 if (CandidateSet->empty()) 13820 return false; 13821 13822 UnbridgedCasts.restore(); 13823 return false; 13824 } 13825 13826 // Guess at what the return type for an unresolvable overload should be. 13827 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 13828 OverloadCandidateSet::iterator *Best) { 13829 std::optional<QualType> Result; 13830 // Adjust Type after seeing a candidate. 13831 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 13832 if (!Candidate.Function) 13833 return; 13834 if (Candidate.Function->isInvalidDecl()) 13835 return; 13836 QualType T = Candidate.Function->getReturnType(); 13837 if (T.isNull()) 13838 return; 13839 if (!Result) 13840 Result = T; 13841 else if (Result != T) 13842 Result = QualType(); 13843 }; 13844 13845 // Look for an unambiguous type from a progressively larger subset. 13846 // e.g. if types disagree, but all *viable* overloads return int, choose int. 13847 // 13848 // First, consider only the best candidate. 13849 if (Best && *Best != CS.end()) 13850 ConsiderCandidate(**Best); 13851 // Next, consider only viable candidates. 13852 if (!Result) 13853 for (const auto &C : CS) 13854 if (C.Viable) 13855 ConsiderCandidate(C); 13856 // Finally, consider all candidates. 13857 if (!Result) 13858 for (const auto &C : CS) 13859 ConsiderCandidate(C); 13860 13861 if (!Result) 13862 return QualType(); 13863 auto Value = *Result; 13864 if (Value.isNull() || Value->isUndeducedType()) 13865 return QualType(); 13866 return Value; 13867 } 13868 13869 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 13870 /// the completed call expression. If overload resolution fails, emits 13871 /// diagnostics and returns ExprError() 13872 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 13873 UnresolvedLookupExpr *ULE, 13874 SourceLocation LParenLoc, 13875 MultiExprArg Args, 13876 SourceLocation RParenLoc, 13877 Expr *ExecConfig, 13878 OverloadCandidateSet *CandidateSet, 13879 OverloadCandidateSet::iterator *Best, 13880 OverloadingResult OverloadResult, 13881 bool AllowTypoCorrection) { 13882 switch (OverloadResult) { 13883 case OR_Success: { 13884 FunctionDecl *FDecl = (*Best)->Function; 13885 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 13886 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 13887 return ExprError(); 13888 ExprResult Res = 13889 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13890 if (Res.isInvalid()) 13891 return ExprError(); 13892 return SemaRef.BuildResolvedCallExpr( 13893 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, 13894 /*IsExecConfig=*/false, (*Best)->IsADLCandidate); 13895 } 13896 13897 case OR_No_Viable_Function: { 13898 // Try to recover by looking for viable functions which the user might 13899 // have meant to call. 13900 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 13901 Args, RParenLoc, 13902 CandidateSet->empty(), 13903 AllowTypoCorrection); 13904 if (Recovery.isInvalid() || Recovery.isUsable()) 13905 return Recovery; 13906 13907 // If the user passes in a function that we can't take the address of, we 13908 // generally end up emitting really bad error messages. Here, we attempt to 13909 // emit better ones. 13910 for (const Expr *Arg : Args) { 13911 if (!Arg->getType()->isFunctionType()) 13912 continue; 13913 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 13914 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13915 if (FD && 13916 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13917 Arg->getExprLoc())) 13918 return ExprError(); 13919 } 13920 } 13921 13922 CandidateSet->NoteCandidates( 13923 PartialDiagnosticAt( 13924 Fn->getBeginLoc(), 13925 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 13926 << ULE->getName() << Fn->getSourceRange()), 13927 SemaRef, OCD_AllCandidates, Args); 13928 break; 13929 } 13930 13931 case OR_Ambiguous: 13932 CandidateSet->NoteCandidates( 13933 PartialDiagnosticAt(Fn->getBeginLoc(), 13934 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 13935 << ULE->getName() << Fn->getSourceRange()), 13936 SemaRef, OCD_AmbiguousCandidates, Args); 13937 break; 13938 13939 case OR_Deleted: { 13940 CandidateSet->NoteCandidates( 13941 PartialDiagnosticAt(Fn->getBeginLoc(), 13942 SemaRef.PDiag(diag::err_ovl_deleted_call) 13943 << ULE->getName() << Fn->getSourceRange()), 13944 SemaRef, OCD_AllCandidates, Args); 13945 13946 // We emitted an error for the unavailable/deleted function call but keep 13947 // the call in the AST. 13948 FunctionDecl *FDecl = (*Best)->Function; 13949 ExprResult Res = 13950 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 13951 if (Res.isInvalid()) 13952 return ExprError(); 13953 return SemaRef.BuildResolvedCallExpr( 13954 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig, 13955 /*IsExecConfig=*/false, (*Best)->IsADLCandidate); 13956 } 13957 } 13958 13959 // Overload resolution failed, try to recover. 13960 SmallVector<Expr *, 8> SubExprs = {Fn}; 13961 SubExprs.append(Args.begin(), Args.end()); 13962 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 13963 chooseRecoveryType(*CandidateSet, Best)); 13964 } 13965 13966 static void markUnaddressableCandidatesUnviable(Sema &S, 13967 OverloadCandidateSet &CS) { 13968 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 13969 if (I->Viable && 13970 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 13971 I->Viable = false; 13972 I->FailureKind = ovl_fail_addr_not_available; 13973 } 13974 } 13975 } 13976 13977 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 13978 /// (which eventually refers to the declaration Func) and the call 13979 /// arguments Args/NumArgs, attempt to resolve the function call down 13980 /// to a specific function. If overload resolution succeeds, returns 13981 /// the call expression produced by overload resolution. 13982 /// Otherwise, emits diagnostics and returns ExprError. 13983 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 13984 UnresolvedLookupExpr *ULE, 13985 SourceLocation LParenLoc, 13986 MultiExprArg Args, 13987 SourceLocation RParenLoc, 13988 Expr *ExecConfig, 13989 bool AllowTypoCorrection, 13990 bool CalleesAddressIsTaken) { 13991 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 13992 OverloadCandidateSet::CSK_Normal); 13993 ExprResult result; 13994 13995 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 13996 &result)) 13997 return result; 13998 13999 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 14000 // functions that aren't addressible are considered unviable. 14001 if (CalleesAddressIsTaken) 14002 markUnaddressableCandidatesUnviable(*this, CandidateSet); 14003 14004 OverloadCandidateSet::iterator Best; 14005 OverloadingResult OverloadResult = 14006 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 14007 14008 // Model the case with a call to a templated function whose definition 14009 // encloses the call and whose return type contains a placeholder type as if 14010 // the UnresolvedLookupExpr was type-dependent. 14011 if (OverloadResult == OR_Success) { 14012 const FunctionDecl *FDecl = Best->Function; 14013 if (FDecl && FDecl->isTemplateInstantiation() && 14014 FDecl->getReturnType()->isUndeducedType()) { 14015 if (const auto *TP = 14016 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false); 14017 TP && TP->willHaveBody()) { 14018 return CallExpr::Create(Context, Fn, Args, Context.DependentTy, 14019 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 14020 } 14021 } 14022 } 14023 14024 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 14025 ExecConfig, &CandidateSet, &Best, 14026 OverloadResult, AllowTypoCorrection); 14027 } 14028 14029 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 14030 return Functions.size() > 1 || 14031 (Functions.size() == 1 && 14032 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 14033 } 14034 14035 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 14036 NestedNameSpecifierLoc NNSLoc, 14037 DeclarationNameInfo DNI, 14038 const UnresolvedSetImpl &Fns, 14039 bool PerformADL) { 14040 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 14041 PerformADL, IsOverloaded(Fns), 14042 Fns.begin(), Fns.end()); 14043 } 14044 14045 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 14046 CXXConversionDecl *Method, 14047 bool HadMultipleCandidates) { 14048 // Convert the expression to match the conversion function's implicit object 14049 // parameter. 14050 ExprResult Exp; 14051 if (Method->isExplicitObjectMemberFunction()) 14052 Exp = InitializeExplicitObjectArgument(*this, E, Method); 14053 else 14054 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 14055 FoundDecl, Method); 14056 if (Exp.isInvalid()) 14057 return true; 14058 14059 if (Method->getParent()->isLambda() && 14060 Method->getConversionType()->isBlockPointerType()) { 14061 // This is a lambda conversion to block pointer; check if the argument 14062 // was a LambdaExpr. 14063 Expr *SubE = E; 14064 auto *CE = dyn_cast<CastExpr>(SubE); 14065 if (CE && CE->getCastKind() == CK_NoOp) 14066 SubE = CE->getSubExpr(); 14067 SubE = SubE->IgnoreParens(); 14068 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 14069 SubE = BE->getSubExpr(); 14070 if (isa<LambdaExpr>(SubE)) { 14071 // For the conversion to block pointer on a lambda expression, we 14072 // construct a special BlockLiteral instead; this doesn't really make 14073 // a difference in ARC, but outside of ARC the resulting block literal 14074 // follows the normal lifetime rules for block literals instead of being 14075 // autoreleased. 14076 PushExpressionEvaluationContext( 14077 ExpressionEvaluationContext::PotentiallyEvaluated); 14078 ExprResult BlockExp = BuildBlockForLambdaConversion( 14079 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 14080 PopExpressionEvaluationContext(); 14081 14082 // FIXME: This note should be produced by a CodeSynthesisContext. 14083 if (BlockExp.isInvalid()) 14084 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 14085 return BlockExp; 14086 } 14087 } 14088 CallExpr *CE; 14089 QualType ResultType = Method->getReturnType(); 14090 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14091 ResultType = ResultType.getNonLValueExprType(Context); 14092 if (Method->isExplicitObjectMemberFunction()) { 14093 ExprResult FnExpr = 14094 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(), 14095 HadMultipleCandidates, E->getBeginLoc()); 14096 if (FnExpr.isInvalid()) 14097 return ExprError(); 14098 Expr *ObjectParam = Exp.get(); 14099 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1), 14100 ResultType, VK, Exp.get()->getEndLoc(), 14101 CurFPFeatureOverrides()); 14102 } else { 14103 MemberExpr *ME = 14104 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 14105 NestedNameSpecifierLoc(), SourceLocation(), Method, 14106 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 14107 HadMultipleCandidates, DeclarationNameInfo(), 14108 Context.BoundMemberTy, VK_PRValue, OK_Ordinary); 14109 14110 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK, 14111 Exp.get()->getEndLoc(), 14112 CurFPFeatureOverrides()); 14113 } 14114 14115 if (CheckFunctionCall(Method, CE, 14116 Method->getType()->castAs<FunctionProtoType>())) 14117 return ExprError(); 14118 14119 return CheckForImmediateInvocation(CE, CE->getDirectCallee()); 14120 } 14121 14122 /// Create a unary operation that may resolve to an overloaded 14123 /// operator. 14124 /// 14125 /// \param OpLoc The location of the operator itself (e.g., '*'). 14126 /// 14127 /// \param Opc The UnaryOperatorKind that describes this operator. 14128 /// 14129 /// \param Fns The set of non-member functions that will be 14130 /// considered by overload resolution. The caller needs to build this 14131 /// set based on the context using, e.g., 14132 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 14133 /// set should not contain any member functions; those will be added 14134 /// by CreateOverloadedUnaryOp(). 14135 /// 14136 /// \param Input The input argument. 14137 ExprResult 14138 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 14139 const UnresolvedSetImpl &Fns, 14140 Expr *Input, bool PerformADL) { 14141 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 14142 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 14143 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14144 // TODO: provide better source location info. 14145 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 14146 14147 if (checkPlaceholderForOverload(*this, Input)) 14148 return ExprError(); 14149 14150 Expr *Args[2] = { Input, nullptr }; 14151 unsigned NumArgs = 1; 14152 14153 // For post-increment and post-decrement, add the implicit '0' as 14154 // the second argument, so that we know this is a post-increment or 14155 // post-decrement. 14156 if (Opc == UO_PostInc || Opc == UO_PostDec) { 14157 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 14158 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 14159 SourceLocation()); 14160 NumArgs = 2; 14161 } 14162 14163 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 14164 14165 if (Input->isTypeDependent()) { 14166 if (Fns.empty()) 14167 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 14168 VK_PRValue, OK_Ordinary, OpLoc, false, 14169 CurFPFeatureOverrides()); 14170 14171 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14172 ExprResult Fn = CreateUnresolvedLookupExpr( 14173 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 14174 if (Fn.isInvalid()) 14175 return ExprError(); 14176 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 14177 Context.DependentTy, VK_PRValue, OpLoc, 14178 CurFPFeatureOverrides()); 14179 } 14180 14181 // Build an empty overload set. 14182 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 14183 14184 // Add the candidates from the given function set. 14185 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 14186 14187 // Add operator candidates that are member functions. 14188 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 14189 14190 // Add candidates from ADL. 14191 if (PerformADL) { 14192 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 14193 /*ExplicitTemplateArgs*/nullptr, 14194 CandidateSet); 14195 } 14196 14197 // Add builtin operator candidates. 14198 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 14199 14200 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14201 14202 // Perform overload resolution. 14203 OverloadCandidateSet::iterator Best; 14204 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14205 case OR_Success: { 14206 // We found a built-in operator or an overloaded operator. 14207 FunctionDecl *FnDecl = Best->Function; 14208 14209 if (FnDecl) { 14210 Expr *Base = nullptr; 14211 // We matched an overloaded operator. Build a call to that 14212 // operator. 14213 14214 // Convert the arguments. 14215 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 14216 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl); 14217 14218 ExprResult InputInit; 14219 if (Method->isExplicitObjectMemberFunction()) 14220 InputInit = InitializeExplicitObjectArgument(*this, Input, Method); 14221 else 14222 InputInit = PerformImplicitObjectArgumentInitialization( 14223 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14224 if (InputInit.isInvalid()) 14225 return ExprError(); 14226 Base = Input = InputInit.get(); 14227 } else { 14228 // Convert the arguments. 14229 ExprResult InputInit 14230 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14231 Context, 14232 FnDecl->getParamDecl(0)), 14233 SourceLocation(), 14234 Input); 14235 if (InputInit.isInvalid()) 14236 return ExprError(); 14237 Input = InputInit.get(); 14238 } 14239 14240 // Build the actual expression node. 14241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 14242 Base, HadMultipleCandidates, 14243 OpLoc); 14244 if (FnExpr.isInvalid()) 14245 return ExprError(); 14246 14247 // Determine the result type. 14248 QualType ResultTy = FnDecl->getReturnType(); 14249 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14250 ResultTy = ResultTy.getNonLValueExprType(Context); 14251 14252 Args[0] = Input; 14253 CallExpr *TheCall = CXXOperatorCallExpr::Create( 14254 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 14255 CurFPFeatureOverrides(), Best->IsADLCandidate); 14256 14257 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 14258 return ExprError(); 14259 14260 if (CheckFunctionCall(FnDecl, TheCall, 14261 FnDecl->getType()->castAs<FunctionProtoType>())) 14262 return ExprError(); 14263 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 14264 } else { 14265 // We matched a built-in operator. Convert the arguments, then 14266 // break out so that we will build the appropriate built-in 14267 // operator node. 14268 ExprResult InputRes = PerformImplicitConversion( 14269 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 14270 CCK_ForBuiltinOverloadedOp); 14271 if (InputRes.isInvalid()) 14272 return ExprError(); 14273 Input = InputRes.get(); 14274 break; 14275 } 14276 } 14277 14278 case OR_No_Viable_Function: 14279 // This is an erroneous use of an operator which can be overloaded by 14280 // a non-member function. Check for non-member operators which were 14281 // defined too late to be candidates. 14282 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 14283 // FIXME: Recover by calling the found function. 14284 return ExprError(); 14285 14286 // No viable function; fall through to handling this as a 14287 // built-in operator, which will produce an error message for us. 14288 break; 14289 14290 case OR_Ambiguous: 14291 CandidateSet.NoteCandidates( 14292 PartialDiagnosticAt(OpLoc, 14293 PDiag(diag::err_ovl_ambiguous_oper_unary) 14294 << UnaryOperator::getOpcodeStr(Opc) 14295 << Input->getType() << Input->getSourceRange()), 14296 *this, OCD_AmbiguousCandidates, ArgsArray, 14297 UnaryOperator::getOpcodeStr(Opc), OpLoc); 14298 return ExprError(); 14299 14300 case OR_Deleted: 14301 CandidateSet.NoteCandidates( 14302 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14303 << UnaryOperator::getOpcodeStr(Opc) 14304 << Input->getSourceRange()), 14305 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 14306 OpLoc); 14307 return ExprError(); 14308 } 14309 14310 // Either we found no viable overloaded operator or we matched a 14311 // built-in operator. In either case, fall through to trying to 14312 // build a built-in operation. 14313 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14314 } 14315 14316 /// Perform lookup for an overloaded binary operator. 14317 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 14318 OverloadedOperatorKind Op, 14319 const UnresolvedSetImpl &Fns, 14320 ArrayRef<Expr *> Args, bool PerformADL) { 14321 SourceLocation OpLoc = CandidateSet.getLocation(); 14322 14323 OverloadedOperatorKind ExtraOp = 14324 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 14325 ? getRewrittenOverloadedOperator(Op) 14326 : OO_None; 14327 14328 // Add the candidates from the given function set. This also adds the 14329 // rewritten candidates using these functions if necessary. 14330 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 14331 14332 // Add operator candidates that are member functions. 14333 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 14334 if (CandidateSet.getRewriteInfo().allowsReversed(Op)) 14335 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 14336 OverloadCandidateParamOrder::Reversed); 14337 14338 // In C++20, also add any rewritten member candidates. 14339 if (ExtraOp) { 14340 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 14341 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp)) 14342 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 14343 CandidateSet, 14344 OverloadCandidateParamOrder::Reversed); 14345 } 14346 14347 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 14348 // performed for an assignment operator (nor for operator[] nor operator->, 14349 // which don't get here). 14350 if (Op != OO_Equal && PerformADL) { 14351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14352 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 14353 /*ExplicitTemplateArgs*/ nullptr, 14354 CandidateSet); 14355 if (ExtraOp) { 14356 DeclarationName ExtraOpName = 14357 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 14358 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 14359 /*ExplicitTemplateArgs*/ nullptr, 14360 CandidateSet); 14361 } 14362 } 14363 14364 // Add builtin operator candidates. 14365 // 14366 // FIXME: We don't add any rewritten candidates here. This is strictly 14367 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 14368 // resulting in our selecting a rewritten builtin candidate. For example: 14369 // 14370 // enum class E { e }; 14371 // bool operator!=(E, E) requires false; 14372 // bool k = E::e != E::e; 14373 // 14374 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 14375 // it seems unreasonable to consider rewritten builtin candidates. A core 14376 // issue has been filed proposing to removed this requirement. 14377 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 14378 } 14379 14380 /// Create a binary operation that may resolve to an overloaded 14381 /// operator. 14382 /// 14383 /// \param OpLoc The location of the operator itself (e.g., '+'). 14384 /// 14385 /// \param Opc The BinaryOperatorKind that describes this operator. 14386 /// 14387 /// \param Fns The set of non-member functions that will be 14388 /// considered by overload resolution. The caller needs to build this 14389 /// set based on the context using, e.g., 14390 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 14391 /// set should not contain any member functions; those will be added 14392 /// by CreateOverloadedBinOp(). 14393 /// 14394 /// \param LHS Left-hand argument. 14395 /// \param RHS Right-hand argument. 14396 /// \param PerformADL Whether to consider operator candidates found by ADL. 14397 /// \param AllowRewrittenCandidates Whether to consider candidates found by 14398 /// C++20 operator rewrites. 14399 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 14400 /// the function in question. Such a function is never a candidate in 14401 /// our overload resolution. This also enables synthesizing a three-way 14402 /// comparison from < and == as described in C++20 [class.spaceship]p1. 14403 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 14404 BinaryOperatorKind Opc, 14405 const UnresolvedSetImpl &Fns, Expr *LHS, 14406 Expr *RHS, bool PerformADL, 14407 bool AllowRewrittenCandidates, 14408 FunctionDecl *DefaultedFn) { 14409 Expr *Args[2] = { LHS, RHS }; 14410 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 14411 14412 if (!getLangOpts().CPlusPlus20) 14413 AllowRewrittenCandidates = false; 14414 14415 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 14416 14417 // If either side is type-dependent, create an appropriate dependent 14418 // expression. 14419 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 14420 if (Fns.empty()) { 14421 // If there are no functions to store, just build a dependent 14422 // BinaryOperator or CompoundAssignment. 14423 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14424 return CompoundAssignOperator::Create( 14425 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 14426 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 14427 Context.DependentTy); 14428 return BinaryOperator::Create( 14429 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue, 14430 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 14431 } 14432 14433 // FIXME: save results of ADL from here? 14434 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14435 // TODO: provide better source location info in DNLoc component. 14436 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 14437 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 14438 ExprResult Fn = CreateUnresolvedLookupExpr( 14439 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 14440 if (Fn.isInvalid()) 14441 return ExprError(); 14442 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 14443 Context.DependentTy, VK_PRValue, OpLoc, 14444 CurFPFeatureOverrides()); 14445 } 14446 14447 // Always do placeholder-like conversions on the RHS. 14448 if (checkPlaceholderForOverload(*this, Args[1])) 14449 return ExprError(); 14450 14451 // Do placeholder-like conversion on the LHS; note that we should 14452 // not get here with a PseudoObject LHS. 14453 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 14454 if (checkPlaceholderForOverload(*this, Args[0])) 14455 return ExprError(); 14456 14457 // If this is the assignment operator, we only perform overload resolution 14458 // if the left-hand side is a class or enumeration type. This is actually 14459 // a hack. The standard requires that we do overload resolution between the 14460 // various built-in candidates, but as DR507 points out, this can lead to 14461 // problems. So we do it this way, which pretty much follows what GCC does. 14462 // Note that we go the traditional code path for compound assignment forms. 14463 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 14464 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14465 14466 // If this is the .* operator, which is not overloadable, just 14467 // create a built-in binary operator. 14468 if (Opc == BO_PtrMemD) 14469 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14470 14471 // Build the overload set. 14472 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator, 14473 OverloadCandidateSet::OperatorRewriteInfo( 14474 Op, OpLoc, AllowRewrittenCandidates)); 14475 if (DefaultedFn) 14476 CandidateSet.exclude(DefaultedFn); 14477 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 14478 14479 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14480 14481 // Perform overload resolution. 14482 OverloadCandidateSet::iterator Best; 14483 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14484 case OR_Success: { 14485 // We found a built-in operator or an overloaded operator. 14486 FunctionDecl *FnDecl = Best->Function; 14487 14488 bool IsReversed = Best->isReversed(); 14489 if (IsReversed) 14490 std::swap(Args[0], Args[1]); 14491 14492 if (FnDecl) { 14493 14494 if (FnDecl->isInvalidDecl()) 14495 return ExprError(); 14496 14497 Expr *Base = nullptr; 14498 // We matched an overloaded operator. Build a call to that 14499 // operator. 14500 14501 OverloadedOperatorKind ChosenOp = 14502 FnDecl->getDeclName().getCXXOverloadedOperator(); 14503 14504 // C++2a [over.match.oper]p9: 14505 // If a rewritten operator== candidate is selected by overload 14506 // resolution for an operator@, its return type shall be cv bool 14507 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 14508 !FnDecl->getReturnType()->isBooleanType()) { 14509 bool IsExtension = 14510 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 14511 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 14512 : diag::err_ovl_rewrite_equalequal_not_bool) 14513 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 14514 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14515 Diag(FnDecl->getLocation(), diag::note_declared_at); 14516 if (!IsExtension) 14517 return ExprError(); 14518 } 14519 14520 if (AllowRewrittenCandidates && !IsReversed && 14521 CandidateSet.getRewriteInfo().isReversible()) { 14522 // We could have reversed this operator, but didn't. Check if some 14523 // reversed form was a viable candidate, and if so, if it had a 14524 // better conversion for either parameter. If so, this call is 14525 // formally ambiguous, and allowing it is an extension. 14526 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 14527 for (OverloadCandidate &Cand : CandidateSet) { 14528 if (Cand.Viable && Cand.Function && Cand.isReversed() && 14529 haveSameParameterTypes(Context, Cand.Function, FnDecl)) { 14530 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 14531 if (CompareImplicitConversionSequences( 14532 *this, OpLoc, Cand.Conversions[ArgIdx], 14533 Best->Conversions[ArgIdx]) == 14534 ImplicitConversionSequence::Better) { 14535 AmbiguousWith.push_back(Cand.Function); 14536 break; 14537 } 14538 } 14539 } 14540 } 14541 14542 if (!AmbiguousWith.empty()) { 14543 bool AmbiguousWithSelf = 14544 AmbiguousWith.size() == 1 && 14545 declaresSameEntity(AmbiguousWith.front(), FnDecl); 14546 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 14547 << BinaryOperator::getOpcodeStr(Opc) 14548 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 14549 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14550 if (AmbiguousWithSelf) { 14551 Diag(FnDecl->getLocation(), 14552 diag::note_ovl_ambiguous_oper_binary_reversed_self); 14553 // Mark member== const or provide matching != to disallow reversed 14554 // args. Eg. 14555 // struct S { bool operator==(const S&); }; 14556 // S()==S(); 14557 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl)) 14558 if (Op == OverloadedOperatorKind::OO_EqualEqual && 14559 !MD->isConst() && 14560 !MD->hasCXXExplicitFunctionObjectParameter() && 14561 Context.hasSameUnqualifiedType( 14562 MD->getFunctionObjectParameterType(), 14563 MD->getParamDecl(0)->getType().getNonReferenceType()) && 14564 Context.hasSameUnqualifiedType( 14565 MD->getFunctionObjectParameterType(), 14566 Args[0]->getType()) && 14567 Context.hasSameUnqualifiedType( 14568 MD->getFunctionObjectParameterType(), 14569 Args[1]->getType())) 14570 Diag(FnDecl->getLocation(), 14571 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const); 14572 } else { 14573 Diag(FnDecl->getLocation(), 14574 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 14575 for (auto *F : AmbiguousWith) 14576 Diag(F->getLocation(), 14577 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 14578 } 14579 } 14580 } 14581 14582 // Convert the arguments. 14583 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 14584 // Best->Access is only meaningful for class members. 14585 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 14586 14587 ExprResult Arg0, Arg1; 14588 unsigned ParamIdx = 0; 14589 if (Method->isExplicitObjectMemberFunction()) { 14590 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl); 14591 ParamIdx = 1; 14592 } else { 14593 Arg0 = PerformImplicitObjectArgumentInitialization( 14594 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 14595 } 14596 Arg1 = PerformCopyInitialization( 14597 InitializedEntity::InitializeParameter( 14598 Context, FnDecl->getParamDecl(ParamIdx)), 14599 SourceLocation(), Args[1]); 14600 if (Arg0.isInvalid() || Arg1.isInvalid()) 14601 return ExprError(); 14602 14603 Base = Args[0] = Arg0.getAs<Expr>(); 14604 Args[1] = RHS = Arg1.getAs<Expr>(); 14605 } else { 14606 // Convert the arguments. 14607 ExprResult Arg0 = PerformCopyInitialization( 14608 InitializedEntity::InitializeParameter(Context, 14609 FnDecl->getParamDecl(0)), 14610 SourceLocation(), Args[0]); 14611 if (Arg0.isInvalid()) 14612 return ExprError(); 14613 14614 ExprResult Arg1 = 14615 PerformCopyInitialization( 14616 InitializedEntity::InitializeParameter(Context, 14617 FnDecl->getParamDecl(1)), 14618 SourceLocation(), Args[1]); 14619 if (Arg1.isInvalid()) 14620 return ExprError(); 14621 Args[0] = LHS = Arg0.getAs<Expr>(); 14622 Args[1] = RHS = Arg1.getAs<Expr>(); 14623 } 14624 14625 // Build the actual expression node. 14626 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 14627 Best->FoundDecl, Base, 14628 HadMultipleCandidates, OpLoc); 14629 if (FnExpr.isInvalid()) 14630 return ExprError(); 14631 14632 // Determine the result type. 14633 QualType ResultTy = FnDecl->getReturnType(); 14634 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14635 ResultTy = ResultTy.getNonLValueExprType(Context); 14636 14637 CallExpr *TheCall; 14638 ArrayRef<const Expr *> ArgsArray(Args, 2); 14639 const Expr *ImplicitThis = nullptr; 14640 14641 // We always create a CXXOperatorCallExpr, even for explicit object 14642 // members; CodeGen should take care not to emit the this pointer. 14643 TheCall = CXXOperatorCallExpr::Create( 14644 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 14645 CurFPFeatureOverrides(), Best->IsADLCandidate); 14646 14647 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl); 14648 Method && Method->isImplicitObjectMemberFunction()) { 14649 // Cut off the implicit 'this'. 14650 ImplicitThis = ArgsArray[0]; 14651 ArgsArray = ArgsArray.slice(1); 14652 } 14653 14654 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 14655 FnDecl)) 14656 return ExprError(); 14657 14658 // Check for a self move. 14659 if (Op == OO_Equal) 14660 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 14661 14662 if (ImplicitThis) { 14663 QualType ThisType = Context.getPointerType(ImplicitThis->getType()); 14664 QualType ThisTypeFromDecl = Context.getPointerType( 14665 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType()); 14666 14667 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType, 14668 ThisTypeFromDecl); 14669 } 14670 14671 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 14672 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 14673 VariadicDoesNotApply); 14674 14675 ExprResult R = MaybeBindToTemporary(TheCall); 14676 if (R.isInvalid()) 14677 return ExprError(); 14678 14679 R = CheckForImmediateInvocation(R, FnDecl); 14680 if (R.isInvalid()) 14681 return ExprError(); 14682 14683 // For a rewritten candidate, we've already reversed the arguments 14684 // if needed. Perform the rest of the rewrite now. 14685 if ((Best->RewriteKind & CRK_DifferentOperator) || 14686 (Op == OO_Spaceship && IsReversed)) { 14687 if (Op == OO_ExclaimEqual) { 14688 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 14689 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 14690 } else { 14691 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 14692 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 14693 Expr *ZeroLiteral = 14694 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 14695 14696 Sema::CodeSynthesisContext Ctx; 14697 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 14698 Ctx.Entity = FnDecl; 14699 pushCodeSynthesisContext(Ctx); 14700 14701 R = CreateOverloadedBinOp( 14702 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 14703 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true, 14704 /*AllowRewrittenCandidates=*/false); 14705 14706 popCodeSynthesisContext(); 14707 } 14708 if (R.isInvalid()) 14709 return ExprError(); 14710 } else { 14711 assert(ChosenOp == Op && "unexpected operator name"); 14712 } 14713 14714 // Make a note in the AST if we did any rewriting. 14715 if (Best->RewriteKind != CRK_None) 14716 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 14717 14718 return R; 14719 } else { 14720 // We matched a built-in operator. Convert the arguments, then 14721 // break out so that we will build the appropriate built-in 14722 // operator node. 14723 ExprResult ArgsRes0 = PerformImplicitConversion( 14724 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 14725 AA_Passing, CCK_ForBuiltinOverloadedOp); 14726 if (ArgsRes0.isInvalid()) 14727 return ExprError(); 14728 Args[0] = ArgsRes0.get(); 14729 14730 ExprResult ArgsRes1 = PerformImplicitConversion( 14731 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 14732 AA_Passing, CCK_ForBuiltinOverloadedOp); 14733 if (ArgsRes1.isInvalid()) 14734 return ExprError(); 14735 Args[1] = ArgsRes1.get(); 14736 break; 14737 } 14738 } 14739 14740 case OR_No_Viable_Function: { 14741 // C++ [over.match.oper]p9: 14742 // If the operator is the operator , [...] and there are no 14743 // viable functions, then the operator is assumed to be the 14744 // built-in operator and interpreted according to clause 5. 14745 if (Opc == BO_Comma) 14746 break; 14747 14748 // When defaulting an 'operator<=>', we can try to synthesize a three-way 14749 // compare result using '==' and '<'. 14750 if (DefaultedFn && Opc == BO_Cmp) { 14751 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 14752 Args[1], DefaultedFn); 14753 if (E.isInvalid() || E.isUsable()) 14754 return E; 14755 } 14756 14757 // For class as left operand for assignment or compound assignment 14758 // operator do not fall through to handling in built-in, but report that 14759 // no overloaded assignment operator found 14760 ExprResult Result = ExprError(); 14761 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 14762 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 14763 Args, OpLoc); 14764 DeferDiagsRAII DDR(*this, 14765 CandidateSet.shouldDeferDiags(*this, Args, OpLoc)); 14766 if (Args[0]->getType()->isRecordType() && 14767 Opc >= BO_Assign && Opc <= BO_OrAssign) { 14768 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14769 << BinaryOperator::getOpcodeStr(Opc) 14770 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14771 if (Args[0]->getType()->isIncompleteType()) { 14772 Diag(OpLoc, diag::note_assign_lhs_incomplete) 14773 << Args[0]->getType() 14774 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 14775 } 14776 } else { 14777 // This is an erroneous use of an operator which can be overloaded by 14778 // a non-member function. Check for non-member operators which were 14779 // defined too late to be candidates. 14780 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 14781 // FIXME: Recover by calling the found function. 14782 return ExprError(); 14783 14784 // No viable function; try to create a built-in operation, which will 14785 // produce an error. Then, show the non-viable candidates. 14786 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14787 } 14788 assert(Result.isInvalid() && 14789 "C++ binary operator overloading is missing candidates!"); 14790 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 14791 return Result; 14792 } 14793 14794 case OR_Ambiguous: 14795 CandidateSet.NoteCandidates( 14796 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 14797 << BinaryOperator::getOpcodeStr(Opc) 14798 << Args[0]->getType() 14799 << Args[1]->getType() 14800 << Args[0]->getSourceRange() 14801 << Args[1]->getSourceRange()), 14802 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14803 OpLoc); 14804 return ExprError(); 14805 14806 case OR_Deleted: 14807 if (isImplicitlyDeleted(Best->Function)) { 14808 FunctionDecl *DeletedFD = Best->Function; 14809 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 14810 if (DFK.isSpecialMember()) { 14811 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 14812 << Args[0]->getType() << DFK.asSpecialMember(); 14813 } else { 14814 assert(DFK.isComparison()); 14815 Diag(OpLoc, diag::err_ovl_deleted_comparison) 14816 << Args[0]->getType() << DeletedFD; 14817 } 14818 14819 // The user probably meant to call this special member. Just 14820 // explain why it's deleted. 14821 NoteDeletedFunction(DeletedFD); 14822 return ExprError(); 14823 } 14824 CandidateSet.NoteCandidates( 14825 PartialDiagnosticAt( 14826 OpLoc, PDiag(diag::err_ovl_deleted_oper) 14827 << getOperatorSpelling(Best->Function->getDeclName() 14828 .getCXXOverloadedOperator()) 14829 << Args[0]->getSourceRange() 14830 << Args[1]->getSourceRange()), 14831 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 14832 OpLoc); 14833 return ExprError(); 14834 } 14835 14836 // We matched a built-in operator; build it. 14837 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 14838 } 14839 14840 ExprResult Sema::BuildSynthesizedThreeWayComparison( 14841 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 14842 FunctionDecl *DefaultedFn) { 14843 const ComparisonCategoryInfo *Info = 14844 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 14845 // If we're not producing a known comparison category type, we can't 14846 // synthesize a three-way comparison. Let the caller diagnose this. 14847 if (!Info) 14848 return ExprResult((Expr*)nullptr); 14849 14850 // If we ever want to perform this synthesis more generally, we will need to 14851 // apply the temporary materialization conversion to the operands. 14852 assert(LHS->isGLValue() && RHS->isGLValue() && 14853 "cannot use prvalue expressions more than once"); 14854 Expr *OrigLHS = LHS; 14855 Expr *OrigRHS = RHS; 14856 14857 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 14858 // each of them multiple times below. 14859 LHS = new (Context) 14860 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 14861 LHS->getObjectKind(), LHS); 14862 RHS = new (Context) 14863 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 14864 RHS->getObjectKind(), RHS); 14865 14866 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 14867 DefaultedFn); 14868 if (Eq.isInvalid()) 14869 return ExprError(); 14870 14871 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 14872 true, DefaultedFn); 14873 if (Less.isInvalid()) 14874 return ExprError(); 14875 14876 ExprResult Greater; 14877 if (Info->isPartial()) { 14878 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 14879 DefaultedFn); 14880 if (Greater.isInvalid()) 14881 return ExprError(); 14882 } 14883 14884 // Form the list of comparisons we're going to perform. 14885 struct Comparison { 14886 ExprResult Cmp; 14887 ComparisonCategoryResult Result; 14888 } Comparisons[4] = 14889 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 14890 : ComparisonCategoryResult::Equivalent}, 14891 {Less, ComparisonCategoryResult::Less}, 14892 {Greater, ComparisonCategoryResult::Greater}, 14893 {ExprResult(), ComparisonCategoryResult::Unordered}, 14894 }; 14895 14896 int I = Info->isPartial() ? 3 : 2; 14897 14898 // Combine the comparisons with suitable conditional expressions. 14899 ExprResult Result; 14900 for (; I >= 0; --I) { 14901 // Build a reference to the comparison category constant. 14902 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 14903 // FIXME: Missing a constant for a comparison category. Diagnose this? 14904 if (!VI) 14905 return ExprResult((Expr*)nullptr); 14906 ExprResult ThisResult = 14907 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 14908 if (ThisResult.isInvalid()) 14909 return ExprError(); 14910 14911 // Build a conditional unless this is the final case. 14912 if (Result.get()) { 14913 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 14914 ThisResult.get(), Result.get()); 14915 if (Result.isInvalid()) 14916 return ExprError(); 14917 } else { 14918 Result = ThisResult; 14919 } 14920 } 14921 14922 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 14923 // bind the OpaqueValueExprs before they're (repeatedly) used. 14924 Expr *SyntacticForm = BinaryOperator::Create( 14925 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 14926 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 14927 CurFPFeatureOverrides()); 14928 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 14929 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 14930 } 14931 14932 static bool PrepareArgumentsForCallToObjectOfClassType( 14933 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method, 14934 MultiExprArg Args, SourceLocation LParenLoc) { 14935 14936 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14937 unsigned NumParams = Proto->getNumParams(); 14938 unsigned NumArgsSlots = 14939 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams); 14940 // Build the full argument list for the method call (the implicit object 14941 // parameter is placed at the beginning of the list). 14942 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots); 14943 bool IsError = false; 14944 // Initialize the implicit object parameter. 14945 // Check the argument types. 14946 for (unsigned i = 0; i != NumParams; i++) { 14947 Expr *Arg; 14948 if (i < Args.size()) { 14949 Arg = Args[i]; 14950 ExprResult InputInit = 14951 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 14952 S.Context, Method->getParamDecl(i)), 14953 SourceLocation(), Arg); 14954 IsError |= InputInit.isInvalid(); 14955 Arg = InputInit.getAs<Expr>(); 14956 } else { 14957 ExprResult DefArg = 14958 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14959 if (DefArg.isInvalid()) { 14960 IsError = true; 14961 break; 14962 } 14963 Arg = DefArg.getAs<Expr>(); 14964 } 14965 14966 MethodArgs.push_back(Arg); 14967 } 14968 return IsError; 14969 } 14970 14971 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 14972 SourceLocation RLoc, 14973 Expr *Base, 14974 MultiExprArg ArgExpr) { 14975 SmallVector<Expr *, 2> Args; 14976 Args.push_back(Base); 14977 for (auto *e : ArgExpr) { 14978 Args.push_back(e); 14979 } 14980 DeclarationName OpName = 14981 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 14982 14983 SourceRange Range = ArgExpr.empty() 14984 ? SourceRange{} 14985 : SourceRange(ArgExpr.front()->getBeginLoc(), 14986 ArgExpr.back()->getEndLoc()); 14987 14988 // If either side is type-dependent, create an appropriate dependent 14989 // expression. 14990 if (Expr::hasAnyTypeDependentArguments(Args)) { 14991 14992 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 14993 // CHECKME: no 'operator' keyword? 14994 DeclarationNameInfo OpNameInfo(OpName, LLoc); 14995 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 14996 ExprResult Fn = CreateUnresolvedLookupExpr( 14997 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 14998 if (Fn.isInvalid()) 14999 return ExprError(); 15000 // Can't add any actual overloads yet 15001 15002 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 15003 Context.DependentTy, VK_PRValue, RLoc, 15004 CurFPFeatureOverrides()); 15005 } 15006 15007 // Handle placeholders 15008 UnbridgedCastsSet UnbridgedCasts; 15009 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 15010 return ExprError(); 15011 } 15012 // Build an empty overload set. 15013 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 15014 15015 // Subscript can only be overloaded as a member function. 15016 15017 // Add operator candidates that are member functions. 15018 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 15019 15020 // Add builtin operator candidates. 15021 if (Args.size() == 2) 15022 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 15023 15024 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15025 15026 // Perform overload resolution. 15027 OverloadCandidateSet::iterator Best; 15028 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 15029 case OR_Success: { 15030 // We found a built-in operator or an overloaded operator. 15031 FunctionDecl *FnDecl = Best->Function; 15032 15033 if (FnDecl) { 15034 // We matched an overloaded operator. Build a call to that 15035 // operator. 15036 15037 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl); 15038 15039 // Convert the arguments. 15040 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 15041 SmallVector<Expr *, 2> MethodArgs; 15042 15043 // Handle 'this' parameter if the selected function is not static. 15044 if (Method->isExplicitObjectMemberFunction()) { 15045 ExprResult Res = 15046 InitializeExplicitObjectArgument(*this, Args[0], Method); 15047 if (Res.isInvalid()) 15048 return ExprError(); 15049 Args[0] = Res.get(); 15050 ArgExpr = Args; 15051 } else if (Method->isInstance()) { 15052 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization( 15053 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15054 if (Arg0.isInvalid()) 15055 return ExprError(); 15056 15057 MethodArgs.push_back(Arg0.get()); 15058 } 15059 15060 bool IsError = PrepareArgumentsForCallToObjectOfClassType( 15061 *this, MethodArgs, Method, ArgExpr, LLoc); 15062 if (IsError) 15063 return ExprError(); 15064 15065 // Build the actual expression node. 15066 DeclarationNameInfo OpLocInfo(OpName, LLoc); 15067 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 15068 ExprResult FnExpr = CreateFunctionRefExpr( 15069 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates, 15070 OpLocInfo.getLoc(), OpLocInfo.getInfo()); 15071 if (FnExpr.isInvalid()) 15072 return ExprError(); 15073 15074 // Determine the result type 15075 QualType ResultTy = FnDecl->getReturnType(); 15076 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15077 ResultTy = ResultTy.getNonLValueExprType(Context); 15078 15079 CallExpr *TheCall; 15080 if (Method->isInstance()) 15081 TheCall = CXXOperatorCallExpr::Create( 15082 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, 15083 RLoc, CurFPFeatureOverrides()); 15084 else 15085 TheCall = 15086 CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK, 15087 RLoc, CurFPFeatureOverrides()); 15088 15089 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 15090 return ExprError(); 15091 15092 if (CheckFunctionCall(Method, TheCall, 15093 Method->getType()->castAs<FunctionProtoType>())) 15094 return ExprError(); 15095 15096 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 15097 FnDecl); 15098 } else { 15099 // We matched a built-in operator. Convert the arguments, then 15100 // break out so that we will build the appropriate built-in 15101 // operator node. 15102 ExprResult ArgsRes0 = PerformImplicitConversion( 15103 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 15104 AA_Passing, CCK_ForBuiltinOverloadedOp); 15105 if (ArgsRes0.isInvalid()) 15106 return ExprError(); 15107 Args[0] = ArgsRes0.get(); 15108 15109 ExprResult ArgsRes1 = PerformImplicitConversion( 15110 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 15111 AA_Passing, CCK_ForBuiltinOverloadedOp); 15112 if (ArgsRes1.isInvalid()) 15113 return ExprError(); 15114 Args[1] = ArgsRes1.get(); 15115 15116 break; 15117 } 15118 } 15119 15120 case OR_No_Viable_Function: { 15121 PartialDiagnostic PD = 15122 CandidateSet.empty() 15123 ? (PDiag(diag::err_ovl_no_oper) 15124 << Args[0]->getType() << /*subscript*/ 0 15125 << Args[0]->getSourceRange() << Range) 15126 : (PDiag(diag::err_ovl_no_viable_subscript) 15127 << Args[0]->getType() << Args[0]->getSourceRange() << Range); 15128 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 15129 OCD_AllCandidates, ArgExpr, "[]", LLoc); 15130 return ExprError(); 15131 } 15132 15133 case OR_Ambiguous: 15134 if (Args.size() == 2) { 15135 CandidateSet.NoteCandidates( 15136 PartialDiagnosticAt( 15137 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 15138 << "[]" << Args[0]->getType() << Args[1]->getType() 15139 << Args[0]->getSourceRange() << Range), 15140 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 15141 } else { 15142 CandidateSet.NoteCandidates( 15143 PartialDiagnosticAt(LLoc, 15144 PDiag(diag::err_ovl_ambiguous_subscript_call) 15145 << Args[0]->getType() 15146 << Args[0]->getSourceRange() << Range), 15147 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 15148 } 15149 return ExprError(); 15150 15151 case OR_Deleted: 15152 CandidateSet.NoteCandidates( 15153 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 15154 << "[]" << Args[0]->getSourceRange() 15155 << Range), 15156 *this, OCD_AllCandidates, Args, "[]", LLoc); 15157 return ExprError(); 15158 } 15159 15160 // We matched a built-in operator; build it. 15161 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 15162 } 15163 15164 /// BuildCallToMemberFunction - Build a call to a member 15165 /// function. MemExpr is the expression that refers to the member 15166 /// function (and includes the object parameter), Args/NumArgs are the 15167 /// arguments to the function call (not including the object 15168 /// parameter). The caller needs to validate that the member 15169 /// expression refers to a non-static member function or an overloaded 15170 /// member function. 15171 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 15172 SourceLocation LParenLoc, 15173 MultiExprArg Args, 15174 SourceLocation RParenLoc, 15175 Expr *ExecConfig, bool IsExecConfig, 15176 bool AllowRecovery) { 15177 assert(MemExprE->getType() == Context.BoundMemberTy || 15178 MemExprE->getType() == Context.OverloadTy); 15179 15180 // Dig out the member expression. This holds both the object 15181 // argument and the member function we're referring to. 15182 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 15183 15184 // Determine whether this is a call to a pointer-to-member function. 15185 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 15186 assert(op->getType() == Context.BoundMemberTy); 15187 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 15188 15189 QualType fnType = 15190 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 15191 15192 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 15193 QualType resultType = proto->getCallResultType(Context); 15194 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 15195 15196 // Check that the object type isn't more qualified than the 15197 // member function we're calling. 15198 Qualifiers funcQuals = proto->getMethodQuals(); 15199 15200 QualType objectType = op->getLHS()->getType(); 15201 if (op->getOpcode() == BO_PtrMemI) 15202 objectType = objectType->castAs<PointerType>()->getPointeeType(); 15203 Qualifiers objectQuals = objectType.getQualifiers(); 15204 15205 Qualifiers difference = objectQuals - funcQuals; 15206 difference.removeObjCGCAttr(); 15207 difference.removeAddressSpace(); 15208 if (difference) { 15209 std::string qualsString = difference.getAsString(); 15210 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 15211 << fnType.getUnqualifiedType() 15212 << qualsString 15213 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 15214 } 15215 15216 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 15217 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 15218 CurFPFeatureOverrides(), proto->getNumParams()); 15219 15220 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 15221 call, nullptr)) 15222 return ExprError(); 15223 15224 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 15225 return ExprError(); 15226 15227 if (CheckOtherCall(call, proto)) 15228 return ExprError(); 15229 15230 return MaybeBindToTemporary(call); 15231 } 15232 15233 // We only try to build a recovery expr at this level if we can preserve 15234 // the return type, otherwise we return ExprError() and let the caller 15235 // recover. 15236 auto BuildRecoveryExpr = [&](QualType Type) { 15237 if (!AllowRecovery) 15238 return ExprError(); 15239 std::vector<Expr *> SubExprs = {MemExprE}; 15240 llvm::append_range(SubExprs, Args); 15241 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs, 15242 Type); 15243 }; 15244 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 15245 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue, 15246 RParenLoc, CurFPFeatureOverrides()); 15247 15248 UnbridgedCastsSet UnbridgedCasts; 15249 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 15250 return ExprError(); 15251 15252 MemberExpr *MemExpr; 15253 CXXMethodDecl *Method = nullptr; 15254 bool HadMultipleCandidates = false; 15255 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 15256 NestedNameSpecifier *Qualifier = nullptr; 15257 if (isa<MemberExpr>(NakedMemExpr)) { 15258 MemExpr = cast<MemberExpr>(NakedMemExpr); 15259 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 15260 FoundDecl = MemExpr->getFoundDecl(); 15261 Qualifier = MemExpr->getQualifier(); 15262 UnbridgedCasts.restore(); 15263 } else { 15264 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 15265 Qualifier = UnresExpr->getQualifier(); 15266 15267 QualType ObjectType = UnresExpr->getBaseType(); 15268 Expr::Classification ObjectClassification 15269 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 15270 : UnresExpr->getBase()->Classify(Context); 15271 15272 // Add overload candidates 15273 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 15274 OverloadCandidateSet::CSK_Normal); 15275 15276 // FIXME: avoid copy. 15277 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 15278 if (UnresExpr->hasExplicitTemplateArgs()) { 15279 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 15280 TemplateArgs = &TemplateArgsBuffer; 15281 } 15282 15283 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 15284 E = UnresExpr->decls_end(); I != E; ++I) { 15285 15286 QualType ExplicitObjectType = ObjectType; 15287 15288 NamedDecl *Func = *I; 15289 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 15290 if (isa<UsingShadowDecl>(Func)) 15291 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 15292 15293 bool HasExplicitParameter = false; 15294 if (const auto *M = dyn_cast<FunctionDecl>(Func); 15295 M && M->hasCXXExplicitFunctionObjectParameter()) 15296 HasExplicitParameter = true; 15297 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func); 15298 M && 15299 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter()) 15300 HasExplicitParameter = true; 15301 15302 if (HasExplicitParameter) 15303 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr); 15304 15305 // Microsoft supports direct constructor calls. 15306 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 15307 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 15308 CandidateSet, 15309 /*SuppressUserConversions*/ false); 15310 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 15311 // If explicit template arguments were provided, we can't call a 15312 // non-template member function. 15313 if (TemplateArgs) 15314 continue; 15315 15316 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType, 15317 ObjectClassification, Args, CandidateSet, 15318 /*SuppressUserConversions=*/false); 15319 } else { 15320 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 15321 I.getPair(), ActingDC, TemplateArgs, 15322 ExplicitObjectType, ObjectClassification, 15323 Args, CandidateSet, 15324 /*SuppressUserConversions=*/false); 15325 } 15326 } 15327 15328 HadMultipleCandidates = (CandidateSet.size() > 1); 15329 15330 DeclarationName DeclName = UnresExpr->getMemberName(); 15331 15332 UnbridgedCasts.restore(); 15333 15334 OverloadCandidateSet::iterator Best; 15335 bool Succeeded = false; 15336 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 15337 Best)) { 15338 case OR_Success: 15339 Method = cast<CXXMethodDecl>(Best->Function); 15340 FoundDecl = Best->FoundDecl; 15341 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 15342 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 15343 break; 15344 // If FoundDecl is different from Method (such as if one is a template 15345 // and the other a specialization), make sure DiagnoseUseOfDecl is 15346 // called on both. 15347 // FIXME: This would be more comprehensively addressed by modifying 15348 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 15349 // being used. 15350 if (Method != FoundDecl.getDecl() && 15351 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc())) 15352 break; 15353 Succeeded = true; 15354 break; 15355 15356 case OR_No_Viable_Function: 15357 CandidateSet.NoteCandidates( 15358 PartialDiagnosticAt( 15359 UnresExpr->getMemberLoc(), 15360 PDiag(diag::err_ovl_no_viable_member_function_in_call) 15361 << DeclName << MemExprE->getSourceRange()), 15362 *this, OCD_AllCandidates, Args); 15363 break; 15364 case OR_Ambiguous: 15365 CandidateSet.NoteCandidates( 15366 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 15367 PDiag(diag::err_ovl_ambiguous_member_call) 15368 << DeclName << MemExprE->getSourceRange()), 15369 *this, OCD_AmbiguousCandidates, Args); 15370 break; 15371 case OR_Deleted: 15372 CandidateSet.NoteCandidates( 15373 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 15374 PDiag(diag::err_ovl_deleted_member_call) 15375 << DeclName << MemExprE->getSourceRange()), 15376 *this, OCD_AllCandidates, Args); 15377 break; 15378 } 15379 // Overload resolution fails, try to recover. 15380 if (!Succeeded) 15381 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best)); 15382 15383 ExprResult Res = 15384 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 15385 if (Res.isInvalid()) 15386 return ExprError(); 15387 MemExprE = Res.get(); 15388 15389 // If overload resolution picked a static member 15390 // build a non-member call based on that function. 15391 if (Method->isStatic()) { 15392 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc, 15393 ExecConfig, IsExecConfig); 15394 } 15395 15396 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 15397 } 15398 15399 QualType ResultType = Method->getReturnType(); 15400 ExprValueKind VK = Expr::getValueKindForType(ResultType); 15401 ResultType = ResultType.getNonLValueExprType(Context); 15402 15403 assert(Method && "Member call to something that isn't a method?"); 15404 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15405 15406 CallExpr *TheCall = nullptr; 15407 llvm::SmallVector<Expr *, 8> NewArgs; 15408 if (Method->isExplicitObjectMemberFunction()) { 15409 PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args, 15410 NewArgs); 15411 // Build the actual expression node. 15412 ExprResult FnExpr = 15413 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr, 15414 HadMultipleCandidates, MemExpr->getExprLoc()); 15415 if (FnExpr.isInvalid()) 15416 return ExprError(); 15417 15418 TheCall = 15419 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc, 15420 CurFPFeatureOverrides(), Proto->getNumParams()); 15421 } else { 15422 // Convert the object argument (for a non-static member function call). 15423 // We only need to do this if there was actually an overload; otherwise 15424 // it was done at lookup. 15425 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization( 15426 MemExpr->getBase(), Qualifier, FoundDecl, Method); 15427 if (ObjectArg.isInvalid()) 15428 return ExprError(); 15429 MemExpr->setBase(ObjectArg.get()); 15430 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 15431 RParenLoc, CurFPFeatureOverrides(), 15432 Proto->getNumParams()); 15433 } 15434 15435 // Check for a valid return type. 15436 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 15437 TheCall, Method)) 15438 return BuildRecoveryExpr(ResultType); 15439 15440 // Convert the rest of the arguments 15441 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 15442 RParenLoc)) 15443 return BuildRecoveryExpr(ResultType); 15444 15445 DiagnoseSentinelCalls(Method, LParenLoc, Args); 15446 15447 if (CheckFunctionCall(Method, TheCall, Proto)) 15448 return ExprError(); 15449 15450 // In the case the method to call was not selected by the overloading 15451 // resolution process, we still need to handle the enable_if attribute. Do 15452 // that here, so it will not hide previous -- and more relevant -- errors. 15453 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 15454 if (const EnableIfAttr *Attr = 15455 CheckEnableIf(Method, LParenLoc, Args, true)) { 15456 Diag(MemE->getMemberLoc(), 15457 diag::err_ovl_no_viable_member_function_in_call) 15458 << Method << Method->getSourceRange(); 15459 Diag(Method->getLocation(), 15460 diag::note_ovl_candidate_disabled_by_function_cond_attr) 15461 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 15462 return ExprError(); 15463 } 15464 } 15465 15466 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) && 15467 TheCall->getDirectCallee()->isPure()) { 15468 const FunctionDecl *MD = TheCall->getDirectCallee(); 15469 15470 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 15471 MemExpr->performsVirtualDispatch(getLangOpts())) { 15472 Diag(MemExpr->getBeginLoc(), 15473 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 15474 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 15475 << MD->getParent(); 15476 15477 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 15478 if (getLangOpts().AppleKext) 15479 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 15480 << MD->getParent() << MD->getDeclName(); 15481 } 15482 } 15483 15484 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) { 15485 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 15486 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 15487 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 15488 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 15489 MemExpr->getMemberLoc()); 15490 } 15491 15492 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 15493 TheCall->getDirectCallee()); 15494 } 15495 15496 /// BuildCallToObjectOfClassType - Build a call to an object of class 15497 /// type (C++ [over.call.object]), which can end up invoking an 15498 /// overloaded function call operator (@c operator()) or performing a 15499 /// user-defined conversion on the object argument. 15500 ExprResult 15501 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 15502 SourceLocation LParenLoc, 15503 MultiExprArg Args, 15504 SourceLocation RParenLoc) { 15505 if (checkPlaceholderForOverload(*this, Obj)) 15506 return ExprError(); 15507 ExprResult Object = Obj; 15508 15509 UnbridgedCastsSet UnbridgedCasts; 15510 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 15511 return ExprError(); 15512 15513 assert(Object.get()->getType()->isRecordType() && 15514 "Requires object type argument"); 15515 15516 // C++ [over.call.object]p1: 15517 // If the primary-expression E in the function call syntax 15518 // evaluates to a class object of type "cv T", then the set of 15519 // candidate functions includes at least the function call 15520 // operators of T. The function call operators of T are obtained by 15521 // ordinary lookup of the name operator() in the context of 15522 // (E).operator(). 15523 OverloadCandidateSet CandidateSet(LParenLoc, 15524 OverloadCandidateSet::CSK_Operator); 15525 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 15526 15527 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 15528 diag::err_incomplete_object_call, Object.get())) 15529 return true; 15530 15531 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 15532 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 15533 LookupQualifiedName(R, Record->getDecl()); 15534 R.suppressAccessDiagnostics(); 15535 15536 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 15537 Oper != OperEnd; ++Oper) { 15538 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 15539 Object.get()->Classify(Context), Args, CandidateSet, 15540 /*SuppressUserConversion=*/false); 15541 } 15542 15543 // When calling a lambda, both the call operator, and 15544 // the conversion operator to function pointer 15545 // are considered. But when constraint checking 15546 // on the call operator fails, it will also fail on the 15547 // conversion operator as the constraints are always the same. 15548 // As the user probably does not intend to perform a surrogate call, 15549 // we filter them out to produce better error diagnostics, ie to avoid 15550 // showing 2 failed overloads instead of one. 15551 bool IgnoreSurrogateFunctions = false; 15552 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) { 15553 const OverloadCandidate &Candidate = *CandidateSet.begin(); 15554 if (!Candidate.Viable && 15555 Candidate.FailureKind == ovl_fail_constraints_not_satisfied) 15556 IgnoreSurrogateFunctions = true; 15557 } 15558 15559 // C++ [over.call.object]p2: 15560 // In addition, for each (non-explicit in C++0x) conversion function 15561 // declared in T of the form 15562 // 15563 // operator conversion-type-id () cv-qualifier; 15564 // 15565 // where cv-qualifier is the same cv-qualification as, or a 15566 // greater cv-qualification than, cv, and where conversion-type-id 15567 // denotes the type "pointer to function of (P1,...,Pn) returning 15568 // R", or the type "reference to pointer to function of 15569 // (P1,...,Pn) returning R", or the type "reference to function 15570 // of (P1,...,Pn) returning R", a surrogate call function [...] 15571 // is also considered as a candidate function. Similarly, 15572 // surrogate call functions are added to the set of candidate 15573 // functions for each conversion function declared in an 15574 // accessible base class provided the function is not hidden 15575 // within T by another intervening declaration. 15576 const auto &Conversions = 15577 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 15578 for (auto I = Conversions.begin(), E = Conversions.end(); 15579 !IgnoreSurrogateFunctions && I != E; ++I) { 15580 NamedDecl *D = *I; 15581 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 15582 if (isa<UsingShadowDecl>(D)) 15583 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 15584 15585 // Skip over templated conversion functions; they aren't 15586 // surrogates. 15587 if (isa<FunctionTemplateDecl>(D)) 15588 continue; 15589 15590 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 15591 if (!Conv->isExplicit()) { 15592 // Strip the reference type (if any) and then the pointer type (if 15593 // any) to get down to what might be a function type. 15594 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 15595 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 15596 ConvType = ConvPtrType->getPointeeType(); 15597 15598 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 15599 { 15600 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 15601 Object.get(), Args, CandidateSet); 15602 } 15603 } 15604 } 15605 15606 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15607 15608 // Perform overload resolution. 15609 OverloadCandidateSet::iterator Best; 15610 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 15611 Best)) { 15612 case OR_Success: 15613 // Overload resolution succeeded; we'll build the appropriate call 15614 // below. 15615 break; 15616 15617 case OR_No_Viable_Function: { 15618 PartialDiagnostic PD = 15619 CandidateSet.empty() 15620 ? (PDiag(diag::err_ovl_no_oper) 15621 << Object.get()->getType() << /*call*/ 1 15622 << Object.get()->getSourceRange()) 15623 : (PDiag(diag::err_ovl_no_viable_object_call) 15624 << Object.get()->getType() << Object.get()->getSourceRange()); 15625 CandidateSet.NoteCandidates( 15626 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 15627 OCD_AllCandidates, Args); 15628 break; 15629 } 15630 case OR_Ambiguous: 15631 if (!R.isAmbiguous()) 15632 CandidateSet.NoteCandidates( 15633 PartialDiagnosticAt(Object.get()->getBeginLoc(), 15634 PDiag(diag::err_ovl_ambiguous_object_call) 15635 << Object.get()->getType() 15636 << Object.get()->getSourceRange()), 15637 *this, OCD_AmbiguousCandidates, Args); 15638 break; 15639 15640 case OR_Deleted: 15641 CandidateSet.NoteCandidates( 15642 PartialDiagnosticAt(Object.get()->getBeginLoc(), 15643 PDiag(diag::err_ovl_deleted_object_call) 15644 << Object.get()->getType() 15645 << Object.get()->getSourceRange()), 15646 *this, OCD_AllCandidates, Args); 15647 break; 15648 } 15649 15650 if (Best == CandidateSet.end()) 15651 return true; 15652 15653 UnbridgedCasts.restore(); 15654 15655 if (Best->Function == nullptr) { 15656 // Since there is no function declaration, this is one of the 15657 // surrogate candidates. Dig out the conversion function. 15658 CXXConversionDecl *Conv 15659 = cast<CXXConversionDecl>( 15660 Best->Conversions[0].UserDefined.ConversionFunction); 15661 15662 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 15663 Best->FoundDecl); 15664 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 15665 return ExprError(); 15666 assert(Conv == Best->FoundDecl.getDecl() && 15667 "Found Decl & conversion-to-functionptr should be same, right?!"); 15668 // We selected one of the surrogate functions that converts the 15669 // object parameter to a function pointer. Perform the conversion 15670 // on the object argument, then let BuildCallExpr finish the job. 15671 15672 // Create an implicit member expr to refer to the conversion operator. 15673 // and then call it. 15674 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 15675 Conv, HadMultipleCandidates); 15676 if (Call.isInvalid()) 15677 return ExprError(); 15678 // Record usage of conversion in an implicit cast. 15679 Call = ImplicitCastExpr::Create( 15680 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(), 15681 nullptr, VK_PRValue, CurFPFeatureOverrides()); 15682 15683 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 15684 } 15685 15686 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 15687 15688 // We found an overloaded operator(). Build a CXXOperatorCallExpr 15689 // that calls this method, using Object for the implicit object 15690 // parameter and passing along the remaining arguments. 15691 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15692 15693 // An error diagnostic has already been printed when parsing the declaration. 15694 if (Method->isInvalidDecl()) 15695 return ExprError(); 15696 15697 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 15698 unsigned NumParams = Proto->getNumParams(); 15699 15700 DeclarationNameInfo OpLocInfo( 15701 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 15702 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 15703 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15704 Obj, HadMultipleCandidates, 15705 OpLocInfo.getLoc(), 15706 OpLocInfo.getInfo()); 15707 if (NewFn.isInvalid()) 15708 return true; 15709 15710 SmallVector<Expr *, 8> MethodArgs; 15711 MethodArgs.reserve(NumParams + 1); 15712 15713 bool IsError = false; 15714 15715 // Initialize the implicit object parameter if needed. 15716 // Since C++23, this could also be a call to a static call operator 15717 // which we emit as a regular CallExpr. 15718 llvm::SmallVector<Expr *, 8> NewArgs; 15719 if (Method->isExplicitObjectMemberFunction()) { 15720 // FIXME: we should do that during the definition of the lambda when we can. 15721 DiagnoseInvalidExplicitObjectParameterInLambda(Method); 15722 PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs); 15723 } else if (Method->isInstance()) { 15724 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization( 15725 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15726 if (ObjRes.isInvalid()) 15727 IsError = true; 15728 else 15729 Object = ObjRes; 15730 MethodArgs.push_back(Object.get()); 15731 } 15732 15733 IsError |= PrepareArgumentsForCallToObjectOfClassType( 15734 *this, MethodArgs, Method, Args, LParenLoc); 15735 15736 // If this is a variadic call, handle args passed through "...". 15737 if (Proto->isVariadic()) { 15738 // Promote the arguments (C99 6.5.2.2p7). 15739 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 15740 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 15741 nullptr); 15742 IsError |= Arg.isInvalid(); 15743 MethodArgs.push_back(Arg.get()); 15744 } 15745 } 15746 15747 if (IsError) 15748 return true; 15749 15750 DiagnoseSentinelCalls(Method, LParenLoc, Args); 15751 15752 // Once we've built TheCall, all of the expressions are properly owned. 15753 QualType ResultTy = Method->getReturnType(); 15754 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15755 ResultTy = ResultTy.getNonLValueExprType(Context); 15756 15757 CallExpr *TheCall; 15758 if (Method->isInstance()) 15759 TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), 15760 MethodArgs, ResultTy, VK, RParenLoc, 15761 CurFPFeatureOverrides()); 15762 else 15763 TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK, 15764 RParenLoc, CurFPFeatureOverrides()); 15765 15766 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 15767 return true; 15768 15769 if (CheckFunctionCall(Method, TheCall, Proto)) 15770 return true; 15771 15772 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15773 } 15774 15775 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 15776 /// (if one exists), where @c Base is an expression of class type and 15777 /// @c Member is the name of the member we're trying to find. 15778 ExprResult 15779 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 15780 bool *NoArrowOperatorFound) { 15781 assert(Base->getType()->isRecordType() && 15782 "left-hand side must have class type"); 15783 15784 if (checkPlaceholderForOverload(*this, Base)) 15785 return ExprError(); 15786 15787 SourceLocation Loc = Base->getExprLoc(); 15788 15789 // C++ [over.ref]p1: 15790 // 15791 // [...] An expression x->m is interpreted as (x.operator->())->m 15792 // for a class object x of type T if T::operator->() exists and if 15793 // the operator is selected as the best match function by the 15794 // overload resolution mechanism (13.3). 15795 DeclarationName OpName = 15796 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 15797 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 15798 15799 if (RequireCompleteType(Loc, Base->getType(), 15800 diag::err_typecheck_incomplete_tag, Base)) 15801 return ExprError(); 15802 15803 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 15804 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 15805 R.suppressAccessDiagnostics(); 15806 15807 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 15808 Oper != OperEnd; ++Oper) { 15809 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 15810 std::nullopt, CandidateSet, 15811 /*SuppressUserConversion=*/false); 15812 } 15813 15814 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15815 15816 // Perform overload resolution. 15817 OverloadCandidateSet::iterator Best; 15818 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 15819 case OR_Success: 15820 // Overload resolution succeeded; we'll build the call below. 15821 break; 15822 15823 case OR_No_Viable_Function: { 15824 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 15825 if (CandidateSet.empty()) { 15826 QualType BaseType = Base->getType(); 15827 if (NoArrowOperatorFound) { 15828 // Report this specific error to the caller instead of emitting a 15829 // diagnostic, as requested. 15830 *NoArrowOperatorFound = true; 15831 return ExprError(); 15832 } 15833 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 15834 << BaseType << Base->getSourceRange(); 15835 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 15836 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 15837 << FixItHint::CreateReplacement(OpLoc, "."); 15838 } 15839 } else 15840 Diag(OpLoc, diag::err_ovl_no_viable_oper) 15841 << "operator->" << Base->getSourceRange(); 15842 CandidateSet.NoteCandidates(*this, Base, Cands); 15843 return ExprError(); 15844 } 15845 case OR_Ambiguous: 15846 if (!R.isAmbiguous()) 15847 CandidateSet.NoteCandidates( 15848 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 15849 << "->" << Base->getType() 15850 << Base->getSourceRange()), 15851 *this, OCD_AmbiguousCandidates, Base); 15852 return ExprError(); 15853 15854 case OR_Deleted: 15855 CandidateSet.NoteCandidates( 15856 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 15857 << "->" << Base->getSourceRange()), 15858 *this, OCD_AllCandidates, Base); 15859 return ExprError(); 15860 } 15861 15862 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 15863 15864 // Convert the object parameter. 15865 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 15866 15867 if (Method->isExplicitObjectMemberFunction()) { 15868 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method); 15869 if (R.isInvalid()) 15870 return ExprError(); 15871 Base = R.get(); 15872 } else { 15873 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization( 15874 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method); 15875 if (BaseResult.isInvalid()) 15876 return ExprError(); 15877 Base = BaseResult.get(); 15878 } 15879 15880 // Build the operator call. 15881 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 15882 Base, HadMultipleCandidates, OpLoc); 15883 if (FnExpr.isInvalid()) 15884 return ExprError(); 15885 15886 QualType ResultTy = Method->getReturnType(); 15887 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15888 ResultTy = ResultTy.getNonLValueExprType(Context); 15889 15890 CallExpr *TheCall = 15891 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 15892 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 15893 15894 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 15895 return ExprError(); 15896 15897 if (CheckFunctionCall(Method, TheCall, 15898 Method->getType()->castAs<FunctionProtoType>())) 15899 return ExprError(); 15900 15901 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 15902 } 15903 15904 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 15905 /// a literal operator described by the provided lookup results. 15906 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 15907 DeclarationNameInfo &SuffixInfo, 15908 ArrayRef<Expr*> Args, 15909 SourceLocation LitEndLoc, 15910 TemplateArgumentListInfo *TemplateArgs) { 15911 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 15912 15913 OverloadCandidateSet CandidateSet(UDSuffixLoc, 15914 OverloadCandidateSet::CSK_Normal); 15915 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 15916 TemplateArgs); 15917 15918 bool HadMultipleCandidates = (CandidateSet.size() > 1); 15919 15920 // Perform overload resolution. This will usually be trivial, but might need 15921 // to perform substitutions for a literal operator template. 15922 OverloadCandidateSet::iterator Best; 15923 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 15924 case OR_Success: 15925 case OR_Deleted: 15926 break; 15927 15928 case OR_No_Viable_Function: 15929 CandidateSet.NoteCandidates( 15930 PartialDiagnosticAt(UDSuffixLoc, 15931 PDiag(diag::err_ovl_no_viable_function_in_call) 15932 << R.getLookupName()), 15933 *this, OCD_AllCandidates, Args); 15934 return ExprError(); 15935 15936 case OR_Ambiguous: 15937 CandidateSet.NoteCandidates( 15938 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 15939 << R.getLookupName()), 15940 *this, OCD_AmbiguousCandidates, Args); 15941 return ExprError(); 15942 } 15943 15944 FunctionDecl *FD = Best->Function; 15945 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 15946 nullptr, HadMultipleCandidates, 15947 SuffixInfo.getLoc(), 15948 SuffixInfo.getInfo()); 15949 if (Fn.isInvalid()) 15950 return true; 15951 15952 // Check the argument types. This should almost always be a no-op, except 15953 // that array-to-pointer decay is applied to string literals. 15954 Expr *ConvArgs[2]; 15955 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 15956 ExprResult InputInit = PerformCopyInitialization( 15957 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 15958 SourceLocation(), Args[ArgIdx]); 15959 if (InputInit.isInvalid()) 15960 return true; 15961 ConvArgs[ArgIdx] = InputInit.get(); 15962 } 15963 15964 QualType ResultTy = FD->getReturnType(); 15965 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 15966 ResultTy = ResultTy.getNonLValueExprType(Context); 15967 15968 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 15969 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK, 15970 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 15971 15972 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 15973 return ExprError(); 15974 15975 if (CheckFunctionCall(FD, UDL, nullptr)) 15976 return ExprError(); 15977 15978 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 15979 } 15980 15981 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 15982 /// given LookupResult is non-empty, it is assumed to describe a member which 15983 /// will be invoked. Otherwise, the function will be found via argument 15984 /// dependent lookup. 15985 /// CallExpr is set to a valid expression and FRS_Success returned on success, 15986 /// otherwise CallExpr is set to ExprError() and some non-success value 15987 /// is returned. 15988 Sema::ForRangeStatus 15989 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 15990 SourceLocation RangeLoc, 15991 const DeclarationNameInfo &NameInfo, 15992 LookupResult &MemberLookup, 15993 OverloadCandidateSet *CandidateSet, 15994 Expr *Range, ExprResult *CallExpr) { 15995 Scope *S = nullptr; 15996 15997 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 15998 if (!MemberLookup.empty()) { 15999 ExprResult MemberRef = 16000 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 16001 /*IsPtr=*/false, CXXScopeSpec(), 16002 /*TemplateKWLoc=*/SourceLocation(), 16003 /*FirstQualifierInScope=*/nullptr, 16004 MemberLookup, 16005 /*TemplateArgs=*/nullptr, S); 16006 if (MemberRef.isInvalid()) { 16007 *CallExpr = ExprError(); 16008 return FRS_DiagnosticIssued; 16009 } 16010 *CallExpr = 16011 BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr); 16012 if (CallExpr->isInvalid()) { 16013 *CallExpr = ExprError(); 16014 return FRS_DiagnosticIssued; 16015 } 16016 } else { 16017 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 16018 NestedNameSpecifierLoc(), 16019 NameInfo, UnresolvedSet<0>()); 16020 if (FnR.isInvalid()) 16021 return FRS_DiagnosticIssued; 16022 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 16023 16024 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 16025 CandidateSet, CallExpr); 16026 if (CandidateSet->empty() || CandidateSetError) { 16027 *CallExpr = ExprError(); 16028 return FRS_NoViableFunction; 16029 } 16030 OverloadCandidateSet::iterator Best; 16031 OverloadingResult OverloadResult = 16032 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 16033 16034 if (OverloadResult == OR_No_Viable_Function) { 16035 *CallExpr = ExprError(); 16036 return FRS_NoViableFunction; 16037 } 16038 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 16039 Loc, nullptr, CandidateSet, &Best, 16040 OverloadResult, 16041 /*AllowTypoCorrection=*/false); 16042 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 16043 *CallExpr = ExprError(); 16044 return FRS_DiagnosticIssued; 16045 } 16046 } 16047 return FRS_Success; 16048 } 16049 16050 16051 /// FixOverloadedFunctionReference - E is an expression that refers to 16052 /// a C++ overloaded function (possibly with some parentheses and 16053 /// perhaps a '&' around it). We have resolved the overloaded function 16054 /// to the function declaration Fn, so patch up the expression E to 16055 /// refer (possibly indirectly) to Fn. Returns the new expr. 16056 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 16057 FunctionDecl *Fn) { 16058 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 16059 ExprResult SubExpr = 16060 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn); 16061 if (SubExpr.isInvalid()) 16062 return ExprError(); 16063 if (SubExpr.get() == PE->getSubExpr()) 16064 return PE; 16065 16066 return new (Context) 16067 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 16068 } 16069 16070 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 16071 ExprResult SubExpr = 16072 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn); 16073 if (SubExpr.isInvalid()) 16074 return ExprError(); 16075 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 16076 SubExpr.get()->getType()) && 16077 "Implicit cast type cannot be determined from overload"); 16078 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 16079 if (SubExpr.get() == ICE->getSubExpr()) 16080 return ICE; 16081 16082 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(), 16083 SubExpr.get(), nullptr, ICE->getValueKind(), 16084 CurFPFeatureOverrides()); 16085 } 16086 16087 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 16088 if (!GSE->isResultDependent()) { 16089 ExprResult SubExpr = 16090 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 16091 if (SubExpr.isInvalid()) 16092 return ExprError(); 16093 if (SubExpr.get() == GSE->getResultExpr()) 16094 return GSE; 16095 16096 // Replace the resulting type information before rebuilding the generic 16097 // selection expression. 16098 ArrayRef<Expr *> A = GSE->getAssocExprs(); 16099 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 16100 unsigned ResultIdx = GSE->getResultIndex(); 16101 AssocExprs[ResultIdx] = SubExpr.get(); 16102 16103 if (GSE->isExprPredicate()) 16104 return GenericSelectionExpr::Create( 16105 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 16106 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 16107 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 16108 ResultIdx); 16109 return GenericSelectionExpr::Create( 16110 Context, GSE->getGenericLoc(), GSE->getControllingType(), 16111 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 16112 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 16113 ResultIdx); 16114 } 16115 // Rather than fall through to the unreachable, return the original generic 16116 // selection expression. 16117 return GSE; 16118 } 16119 16120 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 16121 assert(UnOp->getOpcode() == UO_AddrOf && 16122 "Can only take the address of an overloaded function"); 16123 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 16124 if (Method->isStatic()) { 16125 // Do nothing: static member functions aren't any different 16126 // from non-member functions. 16127 } else { 16128 // Fix the subexpression, which really has to be an 16129 // UnresolvedLookupExpr holding an overloaded member function 16130 // or template. 16131 ExprResult SubExpr = 16132 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); 16133 if (SubExpr.isInvalid()) 16134 return ExprError(); 16135 if (SubExpr.get() == UnOp->getSubExpr()) 16136 return UnOp; 16137 16138 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(), 16139 SubExpr.get(), Method)) 16140 return ExprError(); 16141 16142 assert(isa<DeclRefExpr>(SubExpr.get()) && 16143 "fixed to something other than a decl ref"); 16144 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() && 16145 "fixed to a member ref with no nested name qualifier"); 16146 16147 // We have taken the address of a pointer to member 16148 // function. Perform the computation here so that we get the 16149 // appropriate pointer to member type. 16150 QualType ClassType 16151 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 16152 QualType MemPtrType 16153 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 16154 // Under the MS ABI, lock down the inheritance model now. 16155 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 16156 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 16157 16158 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf, 16159 MemPtrType, VK_PRValue, OK_Ordinary, 16160 UnOp->getOperatorLoc(), false, 16161 CurFPFeatureOverrides()); 16162 } 16163 } 16164 ExprResult SubExpr = 16165 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn); 16166 if (SubExpr.isInvalid()) 16167 return ExprError(); 16168 if (SubExpr.get() == UnOp->getSubExpr()) 16169 return UnOp; 16170 16171 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, 16172 SubExpr.get()); 16173 } 16174 16175 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 16176 // FIXME: avoid copy. 16177 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 16178 if (ULE->hasExplicitTemplateArgs()) { 16179 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 16180 TemplateArgs = &TemplateArgsBuffer; 16181 } 16182 16183 QualType Type = Fn->getType(); 16184 ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue; 16185 16186 // FIXME: Duplicated from BuildDeclarationNameExpr. 16187 if (unsigned BID = Fn->getBuiltinID()) { 16188 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 16189 Type = Context.BuiltinFnTy; 16190 ValueKind = VK_PRValue; 16191 } 16192 } 16193 16194 DeclRefExpr *DRE = BuildDeclRefExpr( 16195 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(), 16196 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs); 16197 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 16198 return DRE; 16199 } 16200 16201 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 16202 // FIXME: avoid copy. 16203 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 16204 if (MemExpr->hasExplicitTemplateArgs()) { 16205 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 16206 TemplateArgs = &TemplateArgsBuffer; 16207 } 16208 16209 Expr *Base; 16210 16211 // If we're filling in a static method where we used to have an 16212 // implicit member access, rewrite to a simple decl ref. 16213 if (MemExpr->isImplicitAccess()) { 16214 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 16215 DeclRefExpr *DRE = BuildDeclRefExpr( 16216 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 16217 MemExpr->getQualifierLoc(), Found.getDecl(), 16218 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 16219 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 16220 return DRE; 16221 } else { 16222 SourceLocation Loc = MemExpr->getMemberLoc(); 16223 if (MemExpr->getQualifier()) 16224 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 16225 Base = 16226 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 16227 } 16228 } else 16229 Base = MemExpr->getBase(); 16230 16231 ExprValueKind valueKind; 16232 QualType type; 16233 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 16234 valueKind = VK_LValue; 16235 type = Fn->getType(); 16236 } else { 16237 valueKind = VK_PRValue; 16238 type = Context.BoundMemberTy; 16239 } 16240 16241 return BuildMemberExpr( 16242 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 16243 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 16244 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 16245 type, valueKind, OK_Ordinary, TemplateArgs); 16246 } 16247 16248 llvm_unreachable("Invalid reference to overloaded function"); 16249 } 16250 16251 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 16252 DeclAccessPair Found, 16253 FunctionDecl *Fn) { 16254 return FixOverloadedFunctionReference(E.get(), Found, Fn); 16255 } 16256 16257 bool clang::shouldEnforceArgLimit(bool PartialOverloading, 16258 FunctionDecl *Function) { 16259 if (!PartialOverloading || !Function) 16260 return true; 16261 if (Function->isVariadic()) 16262 return false; 16263 if (const auto *Proto = 16264 dyn_cast<FunctionProtoType>(Function->getFunctionType())) 16265 if (Proto->isTemplateVariadic()) 16266 return false; 16267 if (auto *Pattern = Function->getTemplateInstantiationPattern()) 16268 if (const auto *Proto = 16269 dyn_cast<FunctionProtoType>(Pattern->getFunctionType())) 16270 if (Proto->isTemplateVariadic()) 16271 return false; 16272 return true; 16273 } 16274