1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/CXXInheritance.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DependenceFlags.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Overload.h" 29 #include "clang/Sema/SemaInternal.h" 30 #include "clang/Sema/Template.h" 31 #include "clang/Sema/TemplateDeduction.h" 32 #include "llvm/ADT/DenseSet.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallString.h" 37 #include <algorithm> 38 #include <cstdlib> 39 40 using namespace clang; 41 using namespace sema; 42 43 using AllowedExplicit = Sema::AllowedExplicit; 44 45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 46 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 47 return P->hasAttr<PassObjectSizeAttr>(); 48 }); 49 } 50 51 /// A convenience routine for creating a decayed reference to a function. 52 static ExprResult 53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 54 const Expr *Base, bool HadMultipleCandidates, 55 SourceLocation Loc = SourceLocation(), 56 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 57 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 58 return ExprError(); 59 // If FoundDecl is different from Fn (such as if one is a template 60 // and the other a specialization), make sure DiagnoseUseOfDecl is 61 // called on both. 62 // FIXME: This would be more comprehensively addressed by modifying 63 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 64 // being used. 65 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 66 return ExprError(); 67 DeclRefExpr *DRE = new (S.Context) 68 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 69 if (HadMultipleCandidates) 70 DRE->setHadMultipleCandidates(true); 71 72 S.MarkDeclRefReferenced(DRE, Base); 73 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) { 74 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 75 S.ResolveExceptionSpec(Loc, FPT); 76 DRE->setType(Fn->getType()); 77 } 78 } 79 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 80 CK_FunctionToPointerDecay); 81 } 82 83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 84 bool InOverloadResolution, 85 StandardConversionSequence &SCS, 86 bool CStyle, 87 bool AllowObjCWritebackConversion); 88 89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 90 QualType &ToType, 91 bool InOverloadResolution, 92 StandardConversionSequence &SCS, 93 bool CStyle); 94 static OverloadingResult 95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 96 UserDefinedConversionSequence& User, 97 OverloadCandidateSet& Conversions, 98 AllowedExplicit AllowExplicit, 99 bool AllowObjCConversionOnExplicit); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 static ImplicitConversionSequence::CompareKind 107 CompareQualificationConversions(Sema &S, 108 const StandardConversionSequence& SCS1, 109 const StandardConversionSequence& SCS2); 110 111 static ImplicitConversionSequence::CompareKind 112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 113 const StandardConversionSequence& SCS1, 114 const StandardConversionSequence& SCS2); 115 116 /// GetConversionRank - Retrieve the implicit conversion rank 117 /// corresponding to the given implicit conversion kind. 118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 119 static const ImplicitConversionRank 120 Rank[(int)ICK_Num_Conversion_Kinds] = { 121 ICR_Exact_Match, 122 ICR_Exact_Match, 123 ICR_Exact_Match, 124 ICR_Exact_Match, 125 ICR_Exact_Match, 126 ICR_Exact_Match, 127 ICR_Promotion, 128 ICR_Promotion, 129 ICR_Promotion, 130 ICR_Conversion, 131 ICR_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_OCL_Scalar_Widening, 141 ICR_Complex_Real_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Writeback_Conversion, 145 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 146 // it was omitted by the patch that added 147 // ICK_Zero_Event_Conversion 148 ICR_C_Conversion, 149 ICR_C_Conversion_Extension 150 }; 151 return Rank[(int)Kind]; 152 } 153 154 /// GetImplicitConversionName - Return the name of this kind of 155 /// implicit conversion. 156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 158 "No conversion", 159 "Lvalue-to-rvalue", 160 "Array-to-pointer", 161 "Function-to-pointer", 162 "Function pointer conversion", 163 "Qualification", 164 "Integral promotion", 165 "Floating point promotion", 166 "Complex promotion", 167 "Integral conversion", 168 "Floating conversion", 169 "Complex conversion", 170 "Floating-integral conversion", 171 "Pointer conversion", 172 "Pointer-to-member conversion", 173 "Boolean conversion", 174 "Compatible-types conversion", 175 "Derived-to-base conversion", 176 "Vector conversion", 177 "Vector splat", 178 "Complex-real conversion", 179 "Block Pointer conversion", 180 "Transparent Union Conversion", 181 "Writeback conversion", 182 "OpenCL Zero Event Conversion", 183 "C specific type conversion", 184 "Incompatible pointer conversion" 185 }; 186 return Name[Kind]; 187 } 188 189 /// StandardConversionSequence - Set the standard conversion 190 /// sequence to the identity conversion. 191 void StandardConversionSequence::setAsIdentityConversion() { 192 First = ICK_Identity; 193 Second = ICK_Identity; 194 Third = ICK_Identity; 195 DeprecatedStringLiteralToCharPtr = false; 196 QualificationIncludesObjCLifetime = false; 197 ReferenceBinding = false; 198 DirectBinding = false; 199 IsLvalueReference = true; 200 BindsToFunctionLvalue = false; 201 BindsToRvalue = false; 202 BindsImplicitObjectArgumentWithoutRefQualifier = false; 203 ObjCLifetimeConversionBinding = false; 204 CopyConstructor = nullptr; 205 } 206 207 /// getRank - Retrieve the rank of this standard conversion sequence 208 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 209 /// implicit conversions. 210 ImplicitConversionRank StandardConversionSequence::getRank() const { 211 ImplicitConversionRank Rank = ICR_Exact_Match; 212 if (GetConversionRank(First) > Rank) 213 Rank = GetConversionRank(First); 214 if (GetConversionRank(Second) > Rank) 215 Rank = GetConversionRank(Second); 216 if (GetConversionRank(Third) > Rank) 217 Rank = GetConversionRank(Third); 218 return Rank; 219 } 220 221 /// isPointerConversionToBool - Determines whether this conversion is 222 /// a conversion of a pointer or pointer-to-member to bool. This is 223 /// used as part of the ranking of standard conversion sequences 224 /// (C++ 13.3.3.2p4). 225 bool StandardConversionSequence::isPointerConversionToBool() const { 226 // Note that FromType has not necessarily been transformed by the 227 // array-to-pointer or function-to-pointer implicit conversions, so 228 // check for their presence as well as checking whether FromType is 229 // a pointer. 230 if (getToType(1)->isBooleanType() && 231 (getFromType()->isPointerType() || 232 getFromType()->isMemberPointerType() || 233 getFromType()->isObjCObjectPointerType() || 234 getFromType()->isBlockPointerType() || 235 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 236 return true; 237 238 return false; 239 } 240 241 /// isPointerConversionToVoidPointer - Determines whether this 242 /// conversion is a conversion of a pointer to a void pointer. This is 243 /// used as part of the ranking of standard conversion sequences (C++ 244 /// 13.3.3.2p4). 245 bool 246 StandardConversionSequence:: 247 isPointerConversionToVoidPointer(ASTContext& Context) const { 248 QualType FromType = getFromType(); 249 QualType ToType = getToType(1); 250 251 // Note that FromType has not necessarily been transformed by the 252 // array-to-pointer implicit conversion, so check for its presence 253 // and redo the conversion to get a pointer. 254 if (First == ICK_Array_To_Pointer) 255 FromType = Context.getArrayDecayedType(FromType); 256 257 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 258 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 259 return ToPtrType->getPointeeType()->isVoidType(); 260 261 return false; 262 } 263 264 /// Skip any implicit casts which could be either part of a narrowing conversion 265 /// or after one in an implicit conversion. 266 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx, 267 const Expr *Converted) { 268 // We can have cleanups wrapping the converted expression; these need to be 269 // preserved so that destructors run if necessary. 270 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) { 271 Expr *Inner = 272 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr())); 273 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(), 274 EWC->getObjects()); 275 } 276 277 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 278 switch (ICE->getCastKind()) { 279 case CK_NoOp: 280 case CK_IntegralCast: 281 case CK_IntegralToBoolean: 282 case CK_IntegralToFloating: 283 case CK_BooleanToSignedIntegral: 284 case CK_FloatingToIntegral: 285 case CK_FloatingToBoolean: 286 case CK_FloatingCast: 287 Converted = ICE->getSubExpr(); 288 continue; 289 290 default: 291 return Converted; 292 } 293 } 294 295 return Converted; 296 } 297 298 /// Check if this standard conversion sequence represents a narrowing 299 /// conversion, according to C++11 [dcl.init.list]p7. 300 /// 301 /// \param Ctx The AST context. 302 /// \param Converted The result of applying this standard conversion sequence. 303 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 304 /// value of the expression prior to the narrowing conversion. 305 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 306 /// type of the expression prior to the narrowing conversion. 307 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 308 /// from floating point types to integral types should be ignored. 309 NarrowingKind StandardConversionSequence::getNarrowingKind( 310 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 311 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 312 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 313 314 // C++11 [dcl.init.list]p7: 315 // A narrowing conversion is an implicit conversion ... 316 QualType FromType = getToType(0); 317 QualType ToType = getToType(1); 318 319 // A conversion to an enumeration type is narrowing if the conversion to 320 // the underlying type is narrowing. This only arises for expressions of 321 // the form 'Enum{init}'. 322 if (auto *ET = ToType->getAs<EnumType>()) 323 ToType = ET->getDecl()->getIntegerType(); 324 325 switch (Second) { 326 // 'bool' is an integral type; dispatch to the right place to handle it. 327 case ICK_Boolean_Conversion: 328 if (FromType->isRealFloatingType()) 329 goto FloatingIntegralConversion; 330 if (FromType->isIntegralOrUnscopedEnumerationType()) 331 goto IntegralConversion; 332 // -- from a pointer type or pointer-to-member type to bool, or 333 return NK_Type_Narrowing; 334 335 // -- from a floating-point type to an integer type, or 336 // 337 // -- from an integer type or unscoped enumeration type to a floating-point 338 // type, except where the source is a constant expression and the actual 339 // value after conversion will fit into the target type and will produce 340 // the original value when converted back to the original type, or 341 case ICK_Floating_Integral: 342 FloatingIntegralConversion: 343 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 344 return NK_Type_Narrowing; 345 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 346 ToType->isRealFloatingType()) { 347 if (IgnoreFloatToIntegralConversion) 348 return NK_Not_Narrowing; 349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 350 assert(Initializer && "Unknown conversion expression"); 351 352 // If it's value-dependent, we can't tell whether it's narrowing. 353 if (Initializer->isValueDependent()) 354 return NK_Dependent_Narrowing; 355 356 if (Optional<llvm::APSInt> IntConstantValue = 357 Initializer->getIntegerConstantExpr(Ctx)) { 358 // Convert the integer to the floating type. 359 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 360 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(), 361 llvm::APFloat::rmNearestTiesToEven); 362 // And back. 363 llvm::APSInt ConvertedValue = *IntConstantValue; 364 bool ignored; 365 Result.convertToInteger(ConvertedValue, 366 llvm::APFloat::rmTowardZero, &ignored); 367 // If the resulting value is different, this was a narrowing conversion. 368 if (*IntConstantValue != ConvertedValue) { 369 ConstantValue = APValue(*IntConstantValue); 370 ConstantType = Initializer->getType(); 371 return NK_Constant_Narrowing; 372 } 373 } else { 374 // Variables are always narrowings. 375 return NK_Variable_Narrowing; 376 } 377 } 378 return NK_Not_Narrowing; 379 380 // -- from long double to double or float, or from double to float, except 381 // where the source is a constant expression and the actual value after 382 // conversion is within the range of values that can be represented (even 383 // if it cannot be represented exactly), or 384 case ICK_Floating_Conversion: 385 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 386 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 387 // FromType is larger than ToType. 388 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 389 390 // If it's value-dependent, we can't tell whether it's narrowing. 391 if (Initializer->isValueDependent()) 392 return NK_Dependent_Narrowing; 393 394 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 395 // Constant! 396 assert(ConstantValue.isFloat()); 397 llvm::APFloat FloatVal = ConstantValue.getFloat(); 398 // Convert the source value into the target type. 399 bool ignored; 400 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 401 Ctx.getFloatTypeSemantics(ToType), 402 llvm::APFloat::rmNearestTiesToEven, &ignored); 403 // If there was no overflow, the source value is within the range of 404 // values that can be represented. 405 if (ConvertStatus & llvm::APFloat::opOverflow) { 406 ConstantType = Initializer->getType(); 407 return NK_Constant_Narrowing; 408 } 409 } else { 410 return NK_Variable_Narrowing; 411 } 412 } 413 return NK_Not_Narrowing; 414 415 // -- from an integer type or unscoped enumeration type to an integer type 416 // that cannot represent all the values of the original type, except where 417 // the source is a constant expression and the actual value after 418 // conversion will fit into the target type and will produce the original 419 // value when converted back to the original type. 420 case ICK_Integral_Conversion: 421 IntegralConversion: { 422 assert(FromType->isIntegralOrUnscopedEnumerationType()); 423 assert(ToType->isIntegralOrUnscopedEnumerationType()); 424 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 425 const unsigned FromWidth = Ctx.getIntWidth(FromType); 426 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 427 const unsigned ToWidth = Ctx.getIntWidth(ToType); 428 429 if (FromWidth > ToWidth || 430 (FromWidth == ToWidth && FromSigned != ToSigned) || 431 (FromSigned && !ToSigned)) { 432 // Not all values of FromType can be represented in ToType. 433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 434 435 // If it's value-dependent, we can't tell whether it's narrowing. 436 if (Initializer->isValueDependent()) 437 return NK_Dependent_Narrowing; 438 439 Optional<llvm::APSInt> OptInitializerValue; 440 if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) { 441 // Such conversions on variables are always narrowing. 442 return NK_Variable_Narrowing; 443 } 444 llvm::APSInt &InitializerValue = *OptInitializerValue; 445 bool Narrowing = false; 446 if (FromWidth < ToWidth) { 447 // Negative -> unsigned is narrowing. Otherwise, more bits is never 448 // narrowing. 449 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 450 Narrowing = true; 451 } else { 452 // Add a bit to the InitializerValue so we don't have to worry about 453 // signed vs. unsigned comparisons. 454 InitializerValue = InitializerValue.extend( 455 InitializerValue.getBitWidth() + 1); 456 // Convert the initializer to and from the target width and signed-ness. 457 llvm::APSInt ConvertedValue = InitializerValue; 458 ConvertedValue = ConvertedValue.trunc(ToWidth); 459 ConvertedValue.setIsSigned(ToSigned); 460 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 461 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 462 // If the result is different, this was a narrowing conversion. 463 if (ConvertedValue != InitializerValue) 464 Narrowing = true; 465 } 466 if (Narrowing) { 467 ConstantType = Initializer->getType(); 468 ConstantValue = APValue(InitializerValue); 469 return NK_Constant_Narrowing; 470 } 471 } 472 return NK_Not_Narrowing; 473 } 474 475 default: 476 // Other kinds of conversions are not narrowings. 477 return NK_Not_Narrowing; 478 } 479 } 480 481 /// dump - Print this standard conversion sequence to standard 482 /// error. Useful for debugging overloading issues. 483 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 484 raw_ostream &OS = llvm::errs(); 485 bool PrintedSomething = false; 486 if (First != ICK_Identity) { 487 OS << GetImplicitConversionName(First); 488 PrintedSomething = true; 489 } 490 491 if (Second != ICK_Identity) { 492 if (PrintedSomething) { 493 OS << " -> "; 494 } 495 OS << GetImplicitConversionName(Second); 496 497 if (CopyConstructor) { 498 OS << " (by copy constructor)"; 499 } else if (DirectBinding) { 500 OS << " (direct reference binding)"; 501 } else if (ReferenceBinding) { 502 OS << " (reference binding)"; 503 } 504 PrintedSomething = true; 505 } 506 507 if (Third != ICK_Identity) { 508 if (PrintedSomething) { 509 OS << " -> "; 510 } 511 OS << GetImplicitConversionName(Third); 512 PrintedSomething = true; 513 } 514 515 if (!PrintedSomething) { 516 OS << "No conversions required"; 517 } 518 } 519 520 /// dump - Print this user-defined conversion sequence to standard 521 /// error. Useful for debugging overloading issues. 522 void UserDefinedConversionSequence::dump() const { 523 raw_ostream &OS = llvm::errs(); 524 if (Before.First || Before.Second || Before.Third) { 525 Before.dump(); 526 OS << " -> "; 527 } 528 if (ConversionFunction) 529 OS << '\'' << *ConversionFunction << '\''; 530 else 531 OS << "aggregate initialization"; 532 if (After.First || After.Second || After.Third) { 533 OS << " -> "; 534 After.dump(); 535 } 536 } 537 538 /// dump - Print this implicit conversion sequence to standard 539 /// error. Useful for debugging overloading issues. 540 void ImplicitConversionSequence::dump() const { 541 raw_ostream &OS = llvm::errs(); 542 if (isStdInitializerListElement()) 543 OS << "Worst std::initializer_list element conversion: "; 544 switch (ConversionKind) { 545 case StandardConversion: 546 OS << "Standard conversion: "; 547 Standard.dump(); 548 break; 549 case UserDefinedConversion: 550 OS << "User-defined conversion: "; 551 UserDefined.dump(); 552 break; 553 case EllipsisConversion: 554 OS << "Ellipsis conversion"; 555 break; 556 case AmbiguousConversion: 557 OS << "Ambiguous conversion"; 558 break; 559 case BadConversion: 560 OS << "Bad conversion"; 561 break; 562 } 563 564 OS << "\n"; 565 } 566 567 void AmbiguousConversionSequence::construct() { 568 new (&conversions()) ConversionSet(); 569 } 570 571 void AmbiguousConversionSequence::destruct() { 572 conversions().~ConversionSet(); 573 } 574 575 void 576 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 577 FromTypePtr = O.FromTypePtr; 578 ToTypePtr = O.ToTypePtr; 579 new (&conversions()) ConversionSet(O.conversions()); 580 } 581 582 namespace { 583 // Structure used by DeductionFailureInfo to store 584 // template argument information. 585 struct DFIArguments { 586 TemplateArgument FirstArg; 587 TemplateArgument SecondArg; 588 }; 589 // Structure used by DeductionFailureInfo to store 590 // template parameter and template argument information. 591 struct DFIParamWithArguments : DFIArguments { 592 TemplateParameter Param; 593 }; 594 // Structure used by DeductionFailureInfo to store template argument 595 // information and the index of the problematic call argument. 596 struct DFIDeducedMismatchArgs : DFIArguments { 597 TemplateArgumentList *TemplateArgs; 598 unsigned CallArgIndex; 599 }; 600 // Structure used by DeductionFailureInfo to store information about 601 // unsatisfied constraints. 602 struct CNSInfo { 603 TemplateArgumentList *TemplateArgs; 604 ConstraintSatisfaction Satisfaction; 605 }; 606 } 607 608 /// Convert from Sema's representation of template deduction information 609 /// to the form used in overload-candidate information. 610 DeductionFailureInfo 611 clang::MakeDeductionFailureInfo(ASTContext &Context, 612 Sema::TemplateDeductionResult TDK, 613 TemplateDeductionInfo &Info) { 614 DeductionFailureInfo Result; 615 Result.Result = static_cast<unsigned>(TDK); 616 Result.HasDiagnostic = false; 617 switch (TDK) { 618 case Sema::TDK_Invalid: 619 case Sema::TDK_InstantiationDepth: 620 case Sema::TDK_TooManyArguments: 621 case Sema::TDK_TooFewArguments: 622 case Sema::TDK_MiscellaneousDeductionFailure: 623 case Sema::TDK_CUDATargetMismatch: 624 Result.Data = nullptr; 625 break; 626 627 case Sema::TDK_Incomplete: 628 case Sema::TDK_InvalidExplicitArguments: 629 Result.Data = Info.Param.getOpaqueValue(); 630 break; 631 632 case Sema::TDK_DeducedMismatch: 633 case Sema::TDK_DeducedMismatchNested: { 634 // FIXME: Should allocate from normal heap so that we can free this later. 635 auto *Saved = new (Context) DFIDeducedMismatchArgs; 636 Saved->FirstArg = Info.FirstArg; 637 Saved->SecondArg = Info.SecondArg; 638 Saved->TemplateArgs = Info.take(); 639 Saved->CallArgIndex = Info.CallArgIndex; 640 Result.Data = Saved; 641 break; 642 } 643 644 case Sema::TDK_NonDeducedMismatch: { 645 // FIXME: Should allocate from normal heap so that we can free this later. 646 DFIArguments *Saved = new (Context) DFIArguments; 647 Saved->FirstArg = Info.FirstArg; 648 Saved->SecondArg = Info.SecondArg; 649 Result.Data = Saved; 650 break; 651 } 652 653 case Sema::TDK_IncompletePack: 654 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 655 case Sema::TDK_Inconsistent: 656 case Sema::TDK_Underqualified: { 657 // FIXME: Should allocate from normal heap so that we can free this later. 658 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 659 Saved->Param = Info.Param; 660 Saved->FirstArg = Info.FirstArg; 661 Saved->SecondArg = Info.SecondArg; 662 Result.Data = Saved; 663 break; 664 } 665 666 case Sema::TDK_SubstitutionFailure: 667 Result.Data = Info.take(); 668 if (Info.hasSFINAEDiagnostic()) { 669 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 670 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 671 Info.takeSFINAEDiagnostic(*Diag); 672 Result.HasDiagnostic = true; 673 } 674 break; 675 676 case Sema::TDK_ConstraintsNotSatisfied: { 677 CNSInfo *Saved = new (Context) CNSInfo; 678 Saved->TemplateArgs = Info.take(); 679 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 680 Result.Data = Saved; 681 break; 682 } 683 684 case Sema::TDK_Success: 685 case Sema::TDK_NonDependentConversionFailure: 686 llvm_unreachable("not a deduction failure"); 687 } 688 689 return Result; 690 } 691 692 void DeductionFailureInfo::Destroy() { 693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 694 case Sema::TDK_Success: 695 case Sema::TDK_Invalid: 696 case Sema::TDK_InstantiationDepth: 697 case Sema::TDK_Incomplete: 698 case Sema::TDK_TooManyArguments: 699 case Sema::TDK_TooFewArguments: 700 case Sema::TDK_InvalidExplicitArguments: 701 case Sema::TDK_CUDATargetMismatch: 702 case Sema::TDK_NonDependentConversionFailure: 703 break; 704 705 case Sema::TDK_IncompletePack: 706 case Sema::TDK_Inconsistent: 707 case Sema::TDK_Underqualified: 708 case Sema::TDK_DeducedMismatch: 709 case Sema::TDK_DeducedMismatchNested: 710 case Sema::TDK_NonDeducedMismatch: 711 // FIXME: Destroy the data? 712 Data = nullptr; 713 break; 714 715 case Sema::TDK_SubstitutionFailure: 716 // FIXME: Destroy the template argument list? 717 Data = nullptr; 718 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 719 Diag->~PartialDiagnosticAt(); 720 HasDiagnostic = false; 721 } 722 break; 723 724 case Sema::TDK_ConstraintsNotSatisfied: 725 // FIXME: Destroy the template argument list? 726 Data = nullptr; 727 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 728 Diag->~PartialDiagnosticAt(); 729 HasDiagnostic = false; 730 } 731 break; 732 733 // Unhandled 734 case Sema::TDK_MiscellaneousDeductionFailure: 735 break; 736 } 737 } 738 739 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 740 if (HasDiagnostic) 741 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 742 return nullptr; 743 } 744 745 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 746 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 747 case Sema::TDK_Success: 748 case Sema::TDK_Invalid: 749 case Sema::TDK_InstantiationDepth: 750 case Sema::TDK_TooManyArguments: 751 case Sema::TDK_TooFewArguments: 752 case Sema::TDK_SubstitutionFailure: 753 case Sema::TDK_DeducedMismatch: 754 case Sema::TDK_DeducedMismatchNested: 755 case Sema::TDK_NonDeducedMismatch: 756 case Sema::TDK_CUDATargetMismatch: 757 case Sema::TDK_NonDependentConversionFailure: 758 case Sema::TDK_ConstraintsNotSatisfied: 759 return TemplateParameter(); 760 761 case Sema::TDK_Incomplete: 762 case Sema::TDK_InvalidExplicitArguments: 763 return TemplateParameter::getFromOpaqueValue(Data); 764 765 case Sema::TDK_IncompletePack: 766 case Sema::TDK_Inconsistent: 767 case Sema::TDK_Underqualified: 768 return static_cast<DFIParamWithArguments*>(Data)->Param; 769 770 // Unhandled 771 case Sema::TDK_MiscellaneousDeductionFailure: 772 break; 773 } 774 775 return TemplateParameter(); 776 } 777 778 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 779 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 780 case Sema::TDK_Success: 781 case Sema::TDK_Invalid: 782 case Sema::TDK_InstantiationDepth: 783 case Sema::TDK_TooManyArguments: 784 case Sema::TDK_TooFewArguments: 785 case Sema::TDK_Incomplete: 786 case Sema::TDK_IncompletePack: 787 case Sema::TDK_InvalidExplicitArguments: 788 case Sema::TDK_Inconsistent: 789 case Sema::TDK_Underqualified: 790 case Sema::TDK_NonDeducedMismatch: 791 case Sema::TDK_CUDATargetMismatch: 792 case Sema::TDK_NonDependentConversionFailure: 793 return nullptr; 794 795 case Sema::TDK_DeducedMismatch: 796 case Sema::TDK_DeducedMismatchNested: 797 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 798 799 case Sema::TDK_SubstitutionFailure: 800 return static_cast<TemplateArgumentList*>(Data); 801 802 case Sema::TDK_ConstraintsNotSatisfied: 803 return static_cast<CNSInfo*>(Data)->TemplateArgs; 804 805 // Unhandled 806 case Sema::TDK_MiscellaneousDeductionFailure: 807 break; 808 } 809 810 return nullptr; 811 } 812 813 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 814 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 815 case Sema::TDK_Success: 816 case Sema::TDK_Invalid: 817 case Sema::TDK_InstantiationDepth: 818 case Sema::TDK_Incomplete: 819 case Sema::TDK_TooManyArguments: 820 case Sema::TDK_TooFewArguments: 821 case Sema::TDK_InvalidExplicitArguments: 822 case Sema::TDK_SubstitutionFailure: 823 case Sema::TDK_CUDATargetMismatch: 824 case Sema::TDK_NonDependentConversionFailure: 825 case Sema::TDK_ConstraintsNotSatisfied: 826 return nullptr; 827 828 case Sema::TDK_IncompletePack: 829 case Sema::TDK_Inconsistent: 830 case Sema::TDK_Underqualified: 831 case Sema::TDK_DeducedMismatch: 832 case Sema::TDK_DeducedMismatchNested: 833 case Sema::TDK_NonDeducedMismatch: 834 return &static_cast<DFIArguments*>(Data)->FirstArg; 835 836 // Unhandled 837 case Sema::TDK_MiscellaneousDeductionFailure: 838 break; 839 } 840 841 return nullptr; 842 } 843 844 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 845 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 846 case Sema::TDK_Success: 847 case Sema::TDK_Invalid: 848 case Sema::TDK_InstantiationDepth: 849 case Sema::TDK_Incomplete: 850 case Sema::TDK_IncompletePack: 851 case Sema::TDK_TooManyArguments: 852 case Sema::TDK_TooFewArguments: 853 case Sema::TDK_InvalidExplicitArguments: 854 case Sema::TDK_SubstitutionFailure: 855 case Sema::TDK_CUDATargetMismatch: 856 case Sema::TDK_NonDependentConversionFailure: 857 case Sema::TDK_ConstraintsNotSatisfied: 858 return nullptr; 859 860 case Sema::TDK_Inconsistent: 861 case Sema::TDK_Underqualified: 862 case Sema::TDK_DeducedMismatch: 863 case Sema::TDK_DeducedMismatchNested: 864 case Sema::TDK_NonDeducedMismatch: 865 return &static_cast<DFIArguments*>(Data)->SecondArg; 866 867 // Unhandled 868 case Sema::TDK_MiscellaneousDeductionFailure: 869 break; 870 } 871 872 return nullptr; 873 } 874 875 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 876 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 877 case Sema::TDK_DeducedMismatch: 878 case Sema::TDK_DeducedMismatchNested: 879 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 880 881 default: 882 return llvm::None; 883 } 884 } 885 886 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 887 OverloadedOperatorKind Op) { 888 if (!AllowRewrittenCandidates) 889 return false; 890 return Op == OO_EqualEqual || Op == OO_Spaceship; 891 } 892 893 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 894 ASTContext &Ctx, const FunctionDecl *FD) { 895 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 896 return false; 897 // Don't bother adding a reversed candidate that can never be a better 898 // match than the non-reversed version. 899 return FD->getNumParams() != 2 || 900 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 901 FD->getParamDecl(1)->getType()) || 902 FD->hasAttr<EnableIfAttr>(); 903 } 904 905 void OverloadCandidateSet::destroyCandidates() { 906 for (iterator i = begin(), e = end(); i != e; ++i) { 907 for (auto &C : i->Conversions) 908 C.~ImplicitConversionSequence(); 909 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 910 i->DeductionFailure.Destroy(); 911 } 912 } 913 914 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 915 destroyCandidates(); 916 SlabAllocator.Reset(); 917 NumInlineBytesUsed = 0; 918 Candidates.clear(); 919 Functions.clear(); 920 Kind = CSK; 921 } 922 923 namespace { 924 class UnbridgedCastsSet { 925 struct Entry { 926 Expr **Addr; 927 Expr *Saved; 928 }; 929 SmallVector<Entry, 2> Entries; 930 931 public: 932 void save(Sema &S, Expr *&E) { 933 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 934 Entry entry = { &E, E }; 935 Entries.push_back(entry); 936 E = S.stripARCUnbridgedCast(E); 937 } 938 939 void restore() { 940 for (SmallVectorImpl<Entry>::iterator 941 i = Entries.begin(), e = Entries.end(); i != e; ++i) 942 *i->Addr = i->Saved; 943 } 944 }; 945 } 946 947 /// checkPlaceholderForOverload - Do any interesting placeholder-like 948 /// preprocessing on the given expression. 949 /// 950 /// \param unbridgedCasts a collection to which to add unbridged casts; 951 /// without this, they will be immediately diagnosed as errors 952 /// 953 /// Return true on unrecoverable error. 954 static bool 955 checkPlaceholderForOverload(Sema &S, Expr *&E, 956 UnbridgedCastsSet *unbridgedCasts = nullptr) { 957 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 958 // We can't handle overloaded expressions here because overload 959 // resolution might reasonably tweak them. 960 if (placeholder->getKind() == BuiltinType::Overload) return false; 961 962 // If the context potentially accepts unbridged ARC casts, strip 963 // the unbridged cast and add it to the collection for later restoration. 964 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 965 unbridgedCasts) { 966 unbridgedCasts->save(S, E); 967 return false; 968 } 969 970 // Go ahead and check everything else. 971 ExprResult result = S.CheckPlaceholderExpr(E); 972 if (result.isInvalid()) 973 return true; 974 975 E = result.get(); 976 return false; 977 } 978 979 // Nothing to do. 980 return false; 981 } 982 983 /// checkArgPlaceholdersForOverload - Check a set of call operands for 984 /// placeholders. 985 static bool checkArgPlaceholdersForOverload(Sema &S, 986 MultiExprArg Args, 987 UnbridgedCastsSet &unbridged) { 988 for (unsigned i = 0, e = Args.size(); i != e; ++i) 989 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 990 return true; 991 992 return false; 993 } 994 995 /// Determine whether the given New declaration is an overload of the 996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 997 /// New and Old cannot be overloaded, e.g., if New has the same signature as 998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 999 /// functions (or function templates) at all. When it does return Ovl_Match or 1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1002 /// declaration. 1003 /// 1004 /// Example: Given the following input: 1005 /// 1006 /// void f(int, float); // #1 1007 /// void f(int, int); // #2 1008 /// int f(int, int); // #3 1009 /// 1010 /// When we process #1, there is no previous declaration of "f", so IsOverload 1011 /// will not be used. 1012 /// 1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1016 /// unchanged. 1017 /// 1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1022 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1023 /// 1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1025 /// by a using declaration. The rules for whether to hide shadow declarations 1026 /// ignore some properties which otherwise figure into a function template's 1027 /// signature. 1028 Sema::OverloadKind 1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1030 NamedDecl *&Match, bool NewIsUsingDecl) { 1031 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1032 I != E; ++I) { 1033 NamedDecl *OldD = *I; 1034 1035 bool OldIsUsingDecl = false; 1036 if (isa<UsingShadowDecl>(OldD)) { 1037 OldIsUsingDecl = true; 1038 1039 // We can always introduce two using declarations into the same 1040 // context, even if they have identical signatures. 1041 if (NewIsUsingDecl) continue; 1042 1043 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1044 } 1045 1046 // A using-declaration does not conflict with another declaration 1047 // if one of them is hidden. 1048 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1049 continue; 1050 1051 // If either declaration was introduced by a using declaration, 1052 // we'll need to use slightly different rules for matching. 1053 // Essentially, these rules are the normal rules, except that 1054 // function templates hide function templates with different 1055 // return types or template parameter lists. 1056 bool UseMemberUsingDeclRules = 1057 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1058 !New->getFriendObjectKind(); 1059 1060 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1061 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1062 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1063 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1064 continue; 1065 } 1066 1067 if (!isa<FunctionTemplateDecl>(OldD) && 1068 !shouldLinkPossiblyHiddenDecl(*I, New)) 1069 continue; 1070 1071 Match = *I; 1072 return Ovl_Match; 1073 } 1074 1075 // Builtins that have custom typechecking or have a reference should 1076 // not be overloadable or redeclarable. 1077 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1078 Match = *I; 1079 return Ovl_NonFunction; 1080 } 1081 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1082 // We can overload with these, which can show up when doing 1083 // redeclaration checks for UsingDecls. 1084 assert(Old.getLookupKind() == LookupUsingDeclName); 1085 } else if (isa<TagDecl>(OldD)) { 1086 // We can always overload with tags by hiding them. 1087 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1088 // Optimistically assume that an unresolved using decl will 1089 // overload; if it doesn't, we'll have to diagnose during 1090 // template instantiation. 1091 // 1092 // Exception: if the scope is dependent and this is not a class 1093 // member, the using declaration can only introduce an enumerator. 1094 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1095 Match = *I; 1096 return Ovl_NonFunction; 1097 } 1098 } else { 1099 // (C++ 13p1): 1100 // Only function declarations can be overloaded; object and type 1101 // declarations cannot be overloaded. 1102 Match = *I; 1103 return Ovl_NonFunction; 1104 } 1105 } 1106 1107 // C++ [temp.friend]p1: 1108 // For a friend function declaration that is not a template declaration: 1109 // -- if the name of the friend is a qualified or unqualified template-id, 1110 // [...], otherwise 1111 // -- if the name of the friend is a qualified-id and a matching 1112 // non-template function is found in the specified class or namespace, 1113 // the friend declaration refers to that function, otherwise, 1114 // -- if the name of the friend is a qualified-id and a matching function 1115 // template is found in the specified class or namespace, the friend 1116 // declaration refers to the deduced specialization of that function 1117 // template, otherwise 1118 // -- the name shall be an unqualified-id [...] 1119 // If we get here for a qualified friend declaration, we've just reached the 1120 // third bullet. If the type of the friend is dependent, skip this lookup 1121 // until instantiation. 1122 if (New->getFriendObjectKind() && New->getQualifier() && 1123 !New->getDescribedFunctionTemplate() && 1124 !New->getDependentSpecializationInfo() && 1125 !New->getType()->isDependentType()) { 1126 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1127 TemplateSpecResult.addAllDecls(Old); 1128 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1129 /*QualifiedFriend*/true)) { 1130 New->setInvalidDecl(); 1131 return Ovl_Overload; 1132 } 1133 1134 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1135 return Ovl_Match; 1136 } 1137 1138 return Ovl_Overload; 1139 } 1140 1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1142 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1143 bool ConsiderRequiresClauses) { 1144 // C++ [basic.start.main]p2: This function shall not be overloaded. 1145 if (New->isMain()) 1146 return false; 1147 1148 // MSVCRT user defined entry points cannot be overloaded. 1149 if (New->isMSVCRTEntryPoint()) 1150 return false; 1151 1152 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1153 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1154 1155 // C++ [temp.fct]p2: 1156 // A function template can be overloaded with other function templates 1157 // and with normal (non-template) functions. 1158 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1159 return true; 1160 1161 // Is the function New an overload of the function Old? 1162 QualType OldQType = Context.getCanonicalType(Old->getType()); 1163 QualType NewQType = Context.getCanonicalType(New->getType()); 1164 1165 // Compare the signatures (C++ 1.3.10) of the two functions to 1166 // determine whether they are overloads. If we find any mismatch 1167 // in the signature, they are overloads. 1168 1169 // If either of these functions is a K&R-style function (no 1170 // prototype), then we consider them to have matching signatures. 1171 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1172 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1173 return false; 1174 1175 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1176 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1177 1178 // The signature of a function includes the types of its 1179 // parameters (C++ 1.3.10), which includes the presence or absence 1180 // of the ellipsis; see C++ DR 357). 1181 if (OldQType != NewQType && 1182 (OldType->getNumParams() != NewType->getNumParams() || 1183 OldType->isVariadic() != NewType->isVariadic() || 1184 !FunctionParamTypesAreEqual(OldType, NewType))) 1185 return true; 1186 1187 // C++ [temp.over.link]p4: 1188 // The signature of a function template consists of its function 1189 // signature, its return type and its template parameter list. The names 1190 // of the template parameters are significant only for establishing the 1191 // relationship between the template parameters and the rest of the 1192 // signature. 1193 // 1194 // We check the return type and template parameter lists for function 1195 // templates first; the remaining checks follow. 1196 // 1197 // However, we don't consider either of these when deciding whether 1198 // a member introduced by a shadow declaration is hidden. 1199 if (!UseMemberUsingDeclRules && NewTemplate && 1200 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1201 OldTemplate->getTemplateParameters(), 1202 false, TPL_TemplateMatch) || 1203 !Context.hasSameType(Old->getDeclaredReturnType(), 1204 New->getDeclaredReturnType()))) 1205 return true; 1206 1207 // If the function is a class member, its signature includes the 1208 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1209 // 1210 // As part of this, also check whether one of the member functions 1211 // is static, in which case they are not overloads (C++ 1212 // 13.1p2). While not part of the definition of the signature, 1213 // this check is important to determine whether these functions 1214 // can be overloaded. 1215 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1216 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1217 if (OldMethod && NewMethod && 1218 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1219 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1220 if (!UseMemberUsingDeclRules && 1221 (OldMethod->getRefQualifier() == RQ_None || 1222 NewMethod->getRefQualifier() == RQ_None)) { 1223 // C++0x [over.load]p2: 1224 // - Member function declarations with the same name and the same 1225 // parameter-type-list as well as member function template 1226 // declarations with the same name, the same parameter-type-list, and 1227 // the same template parameter lists cannot be overloaded if any of 1228 // them, but not all, have a ref-qualifier (8.3.5). 1229 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1230 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1231 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1232 } 1233 return true; 1234 } 1235 1236 // We may not have applied the implicit const for a constexpr member 1237 // function yet (because we haven't yet resolved whether this is a static 1238 // or non-static member function). Add it now, on the assumption that this 1239 // is a redeclaration of OldMethod. 1240 auto OldQuals = OldMethod->getMethodQualifiers(); 1241 auto NewQuals = NewMethod->getMethodQualifiers(); 1242 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1243 !isa<CXXConstructorDecl>(NewMethod)) 1244 NewQuals.addConst(); 1245 // We do not allow overloading based off of '__restrict'. 1246 OldQuals.removeRestrict(); 1247 NewQuals.removeRestrict(); 1248 if (OldQuals != NewQuals) 1249 return true; 1250 } 1251 1252 // Though pass_object_size is placed on parameters and takes an argument, we 1253 // consider it to be a function-level modifier for the sake of function 1254 // identity. Either the function has one or more parameters with 1255 // pass_object_size or it doesn't. 1256 if (functionHasPassObjectSizeParams(New) != 1257 functionHasPassObjectSizeParams(Old)) 1258 return true; 1259 1260 // enable_if attributes are an order-sensitive part of the signature. 1261 for (specific_attr_iterator<EnableIfAttr> 1262 NewI = New->specific_attr_begin<EnableIfAttr>(), 1263 NewE = New->specific_attr_end<EnableIfAttr>(), 1264 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1265 OldE = Old->specific_attr_end<EnableIfAttr>(); 1266 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1267 if (NewI == NewE || OldI == OldE) 1268 return true; 1269 llvm::FoldingSetNodeID NewID, OldID; 1270 NewI->getCond()->Profile(NewID, Context, true); 1271 OldI->getCond()->Profile(OldID, Context, true); 1272 if (NewID != OldID) 1273 return true; 1274 } 1275 1276 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1277 // Don't allow overloading of destructors. (In theory we could, but it 1278 // would be a giant change to clang.) 1279 if (!isa<CXXDestructorDecl>(New)) { 1280 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1281 OldTarget = IdentifyCUDATarget(Old); 1282 if (NewTarget != CFT_InvalidTarget) { 1283 assert((OldTarget != CFT_InvalidTarget) && 1284 "Unexpected invalid target."); 1285 1286 // Allow overloading of functions with same signature and different CUDA 1287 // target attributes. 1288 if (NewTarget != OldTarget) 1289 return true; 1290 } 1291 } 1292 } 1293 1294 if (ConsiderRequiresClauses) { 1295 Expr *NewRC = New->getTrailingRequiresClause(), 1296 *OldRC = Old->getTrailingRequiresClause(); 1297 if ((NewRC != nullptr) != (OldRC != nullptr)) 1298 // RC are most certainly different - these are overloads. 1299 return true; 1300 1301 if (NewRC) { 1302 llvm::FoldingSetNodeID NewID, OldID; 1303 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1304 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1305 if (NewID != OldID) 1306 // RCs are not equivalent - these are overloads. 1307 return true; 1308 } 1309 } 1310 1311 // The signatures match; this is not an overload. 1312 return false; 1313 } 1314 1315 /// Tries a user-defined conversion from From to ToType. 1316 /// 1317 /// Produces an implicit conversion sequence for when a standard conversion 1318 /// is not an option. See TryImplicitConversion for more information. 1319 static ImplicitConversionSequence 1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1321 bool SuppressUserConversions, 1322 AllowedExplicit AllowExplicit, 1323 bool InOverloadResolution, 1324 bool CStyle, 1325 bool AllowObjCWritebackConversion, 1326 bool AllowObjCConversionOnExplicit) { 1327 ImplicitConversionSequence ICS; 1328 1329 if (SuppressUserConversions) { 1330 // We're not in the case above, so there is no conversion that 1331 // we can perform. 1332 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1333 return ICS; 1334 } 1335 1336 // Attempt user-defined conversion. 1337 OverloadCandidateSet Conversions(From->getExprLoc(), 1338 OverloadCandidateSet::CSK_Normal); 1339 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1340 Conversions, AllowExplicit, 1341 AllowObjCConversionOnExplicit)) { 1342 case OR_Success: 1343 case OR_Deleted: 1344 ICS.setUserDefined(); 1345 // C++ [over.ics.user]p4: 1346 // A conversion of an expression of class type to the same class 1347 // type is given Exact Match rank, and a conversion of an 1348 // expression of class type to a base class of that type is 1349 // given Conversion rank, in spite of the fact that a copy 1350 // constructor (i.e., a user-defined conversion function) is 1351 // called for those cases. 1352 if (CXXConstructorDecl *Constructor 1353 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1354 QualType FromCanon 1355 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1356 QualType ToCanon 1357 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1358 if (Constructor->isCopyConstructor() && 1359 (FromCanon == ToCanon || 1360 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1361 // Turn this into a "standard" conversion sequence, so that it 1362 // gets ranked with standard conversion sequences. 1363 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1364 ICS.setStandard(); 1365 ICS.Standard.setAsIdentityConversion(); 1366 ICS.Standard.setFromType(From->getType()); 1367 ICS.Standard.setAllToTypes(ToType); 1368 ICS.Standard.CopyConstructor = Constructor; 1369 ICS.Standard.FoundCopyConstructor = Found; 1370 if (ToCanon != FromCanon) 1371 ICS.Standard.Second = ICK_Derived_To_Base; 1372 } 1373 } 1374 break; 1375 1376 case OR_Ambiguous: 1377 ICS.setAmbiguous(); 1378 ICS.Ambiguous.setFromType(From->getType()); 1379 ICS.Ambiguous.setToType(ToType); 1380 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1381 Cand != Conversions.end(); ++Cand) 1382 if (Cand->Best) 1383 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1384 break; 1385 1386 // Fall through. 1387 case OR_No_Viable_Function: 1388 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1389 break; 1390 } 1391 1392 return ICS; 1393 } 1394 1395 /// TryImplicitConversion - Attempt to perform an implicit conversion 1396 /// from the given expression (Expr) to the given type (ToType). This 1397 /// function returns an implicit conversion sequence that can be used 1398 /// to perform the initialization. Given 1399 /// 1400 /// void f(float f); 1401 /// void g(int i) { f(i); } 1402 /// 1403 /// this routine would produce an implicit conversion sequence to 1404 /// describe the initialization of f from i, which will be a standard 1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1407 // 1408 /// Note that this routine only determines how the conversion can be 1409 /// performed; it does not actually perform the conversion. As such, 1410 /// it will not produce any diagnostics if no conversion is available, 1411 /// but will instead return an implicit conversion sequence of kind 1412 /// "BadConversion". 1413 /// 1414 /// If @p SuppressUserConversions, then user-defined conversions are 1415 /// not permitted. 1416 /// If @p AllowExplicit, then explicit user-defined conversions are 1417 /// permitted. 1418 /// 1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1420 /// writeback conversion, which allows __autoreleasing id* parameters to 1421 /// be initialized with __strong id* or __weak id* arguments. 1422 static ImplicitConversionSequence 1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1424 bool SuppressUserConversions, 1425 AllowedExplicit AllowExplicit, 1426 bool InOverloadResolution, 1427 bool CStyle, 1428 bool AllowObjCWritebackConversion, 1429 bool AllowObjCConversionOnExplicit) { 1430 ImplicitConversionSequence ICS; 1431 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1432 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1433 ICS.setStandard(); 1434 return ICS; 1435 } 1436 1437 if (!S.getLangOpts().CPlusPlus) { 1438 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1439 return ICS; 1440 } 1441 1442 // C++ [over.ics.user]p4: 1443 // A conversion of an expression of class type to the same class 1444 // type is given Exact Match rank, and a conversion of an 1445 // expression of class type to a base class of that type is 1446 // given Conversion rank, in spite of the fact that a copy/move 1447 // constructor (i.e., a user-defined conversion function) is 1448 // called for those cases. 1449 QualType FromType = From->getType(); 1450 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1451 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1452 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1453 ICS.setStandard(); 1454 ICS.Standard.setAsIdentityConversion(); 1455 ICS.Standard.setFromType(FromType); 1456 ICS.Standard.setAllToTypes(ToType); 1457 1458 // We don't actually check at this point whether there is a valid 1459 // copy/move constructor, since overloading just assumes that it 1460 // exists. When we actually perform initialization, we'll find the 1461 // appropriate constructor to copy the returned object, if needed. 1462 ICS.Standard.CopyConstructor = nullptr; 1463 1464 // Determine whether this is considered a derived-to-base conversion. 1465 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1466 ICS.Standard.Second = ICK_Derived_To_Base; 1467 1468 return ICS; 1469 } 1470 1471 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1472 AllowExplicit, InOverloadResolution, CStyle, 1473 AllowObjCWritebackConversion, 1474 AllowObjCConversionOnExplicit); 1475 } 1476 1477 ImplicitConversionSequence 1478 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1479 bool SuppressUserConversions, 1480 AllowedExplicit AllowExplicit, 1481 bool InOverloadResolution, 1482 bool CStyle, 1483 bool AllowObjCWritebackConversion) { 1484 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1485 AllowExplicit, InOverloadResolution, CStyle, 1486 AllowObjCWritebackConversion, 1487 /*AllowObjCConversionOnExplicit=*/false); 1488 } 1489 1490 /// PerformImplicitConversion - Perform an implicit conversion of the 1491 /// expression From to the type ToType. Returns the 1492 /// converted expression. Flavor is the kind of conversion we're 1493 /// performing, used in the error message. If @p AllowExplicit, 1494 /// explicit user-defined conversions are permitted. 1495 ExprResult 1496 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1497 AssignmentAction Action, bool AllowExplicit) { 1498 ImplicitConversionSequence ICS; 1499 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1500 } 1501 1502 ExprResult 1503 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1504 AssignmentAction Action, bool AllowExplicit, 1505 ImplicitConversionSequence& ICS) { 1506 if (checkPlaceholderForOverload(*this, From)) 1507 return ExprError(); 1508 1509 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1510 bool AllowObjCWritebackConversion 1511 = getLangOpts().ObjCAutoRefCount && 1512 (Action == AA_Passing || Action == AA_Sending); 1513 if (getLangOpts().ObjC) 1514 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1515 From->getType(), From); 1516 ICS = ::TryImplicitConversion(*this, From, ToType, 1517 /*SuppressUserConversions=*/false, 1518 AllowExplicit ? AllowedExplicit::All 1519 : AllowedExplicit::None, 1520 /*InOverloadResolution=*/false, 1521 /*CStyle=*/false, AllowObjCWritebackConversion, 1522 /*AllowObjCConversionOnExplicit=*/false); 1523 return PerformImplicitConversion(From, ToType, ICS, Action); 1524 } 1525 1526 /// Determine whether the conversion from FromType to ToType is a valid 1527 /// conversion that strips "noexcept" or "noreturn" off the nested function 1528 /// type. 1529 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1530 QualType &ResultTy) { 1531 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1532 return false; 1533 1534 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1535 // or F(t noexcept) -> F(t) 1536 // where F adds one of the following at most once: 1537 // - a pointer 1538 // - a member pointer 1539 // - a block pointer 1540 // Changes here need matching changes in FindCompositePointerType. 1541 CanQualType CanTo = Context.getCanonicalType(ToType); 1542 CanQualType CanFrom = Context.getCanonicalType(FromType); 1543 Type::TypeClass TyClass = CanTo->getTypeClass(); 1544 if (TyClass != CanFrom->getTypeClass()) return false; 1545 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1546 if (TyClass == Type::Pointer) { 1547 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1548 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1549 } else if (TyClass == Type::BlockPointer) { 1550 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1551 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1552 } else if (TyClass == Type::MemberPointer) { 1553 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1554 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1555 // A function pointer conversion cannot change the class of the function. 1556 if (ToMPT->getClass() != FromMPT->getClass()) 1557 return false; 1558 CanTo = ToMPT->getPointeeType(); 1559 CanFrom = FromMPT->getPointeeType(); 1560 } else { 1561 return false; 1562 } 1563 1564 TyClass = CanTo->getTypeClass(); 1565 if (TyClass != CanFrom->getTypeClass()) return false; 1566 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1567 return false; 1568 } 1569 1570 const auto *FromFn = cast<FunctionType>(CanFrom); 1571 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1572 1573 const auto *ToFn = cast<FunctionType>(CanTo); 1574 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1575 1576 bool Changed = false; 1577 1578 // Drop 'noreturn' if not present in target type. 1579 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1580 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1581 Changed = true; 1582 } 1583 1584 // Drop 'noexcept' if not present in target type. 1585 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1586 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1587 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1588 FromFn = cast<FunctionType>( 1589 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1590 EST_None) 1591 .getTypePtr()); 1592 Changed = true; 1593 } 1594 1595 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1596 // only if the ExtParameterInfo lists of the two function prototypes can be 1597 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1598 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1599 bool CanUseToFPT, CanUseFromFPT; 1600 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1601 CanUseFromFPT, NewParamInfos) && 1602 CanUseToFPT && !CanUseFromFPT) { 1603 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1604 ExtInfo.ExtParameterInfos = 1605 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1606 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1607 FromFPT->getParamTypes(), ExtInfo); 1608 FromFn = QT->getAs<FunctionType>(); 1609 Changed = true; 1610 } 1611 } 1612 1613 if (!Changed) 1614 return false; 1615 1616 assert(QualType(FromFn, 0).isCanonical()); 1617 if (QualType(FromFn, 0) != CanTo) return false; 1618 1619 ResultTy = ToType; 1620 return true; 1621 } 1622 1623 /// Determine whether the conversion from FromType to ToType is a valid 1624 /// vector conversion. 1625 /// 1626 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1627 /// conversion. 1628 static bool IsVectorConversion(Sema &S, QualType FromType, 1629 QualType ToType, ImplicitConversionKind &ICK) { 1630 // We need at least one of these types to be a vector type to have a vector 1631 // conversion. 1632 if (!ToType->isVectorType() && !FromType->isVectorType()) 1633 return false; 1634 1635 // Identical types require no conversions. 1636 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1637 return false; 1638 1639 // There are no conversions between extended vector types, only identity. 1640 if (ToType->isExtVectorType()) { 1641 // There are no conversions between extended vector types other than the 1642 // identity conversion. 1643 if (FromType->isExtVectorType()) 1644 return false; 1645 1646 // Vector splat from any arithmetic type to a vector. 1647 if (FromType->isArithmeticType()) { 1648 ICK = ICK_Vector_Splat; 1649 return true; 1650 } 1651 } 1652 1653 // We can perform the conversion between vector types in the following cases: 1654 // 1)vector types are equivalent AltiVec and GCC vector types 1655 // 2)lax vector conversions are permitted and the vector types are of the 1656 // same size 1657 // 3)the destination type does not have the ARM MVE strict-polymorphism 1658 // attribute, which inhibits lax vector conversion for overload resolution 1659 // only 1660 if (ToType->isVectorType() && FromType->isVectorType()) { 1661 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1662 (S.isLaxVectorConversion(FromType, ToType) && 1663 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1664 ICK = ICK_Vector_Conversion; 1665 return true; 1666 } 1667 } 1668 1669 return false; 1670 } 1671 1672 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1673 bool InOverloadResolution, 1674 StandardConversionSequence &SCS, 1675 bool CStyle); 1676 1677 /// IsStandardConversion - Determines whether there is a standard 1678 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1679 /// expression From to the type ToType. Standard conversion sequences 1680 /// only consider non-class types; for conversions that involve class 1681 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1682 /// contain the standard conversion sequence required to perform this 1683 /// conversion and this routine will return true. Otherwise, this 1684 /// routine will return false and the value of SCS is unspecified. 1685 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1686 bool InOverloadResolution, 1687 StandardConversionSequence &SCS, 1688 bool CStyle, 1689 bool AllowObjCWritebackConversion) { 1690 QualType FromType = From->getType(); 1691 1692 // Standard conversions (C++ [conv]) 1693 SCS.setAsIdentityConversion(); 1694 SCS.IncompatibleObjC = false; 1695 SCS.setFromType(FromType); 1696 SCS.CopyConstructor = nullptr; 1697 1698 // There are no standard conversions for class types in C++, so 1699 // abort early. When overloading in C, however, we do permit them. 1700 if (S.getLangOpts().CPlusPlus && 1701 (FromType->isRecordType() || ToType->isRecordType())) 1702 return false; 1703 1704 // The first conversion can be an lvalue-to-rvalue conversion, 1705 // array-to-pointer conversion, or function-to-pointer conversion 1706 // (C++ 4p1). 1707 1708 if (FromType == S.Context.OverloadTy) { 1709 DeclAccessPair AccessPair; 1710 if (FunctionDecl *Fn 1711 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1712 AccessPair)) { 1713 // We were able to resolve the address of the overloaded function, 1714 // so we can convert to the type of that function. 1715 FromType = Fn->getType(); 1716 SCS.setFromType(FromType); 1717 1718 // we can sometimes resolve &foo<int> regardless of ToType, so check 1719 // if the type matches (identity) or we are converting to bool 1720 if (!S.Context.hasSameUnqualifiedType( 1721 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1722 QualType resultTy; 1723 // if the function type matches except for [[noreturn]], it's ok 1724 if (!S.IsFunctionConversion(FromType, 1725 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1726 // otherwise, only a boolean conversion is standard 1727 if (!ToType->isBooleanType()) 1728 return false; 1729 } 1730 1731 // Check if the "from" expression is taking the address of an overloaded 1732 // function and recompute the FromType accordingly. Take advantage of the 1733 // fact that non-static member functions *must* have such an address-of 1734 // expression. 1735 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1736 if (Method && !Method->isStatic()) { 1737 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1738 "Non-unary operator on non-static member address"); 1739 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1740 == UO_AddrOf && 1741 "Non-address-of operator on non-static member address"); 1742 const Type *ClassType 1743 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1744 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1745 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1746 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1747 UO_AddrOf && 1748 "Non-address-of operator for overloaded function expression"); 1749 FromType = S.Context.getPointerType(FromType); 1750 } 1751 1752 // Check that we've computed the proper type after overload resolution. 1753 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1754 // be calling it from within an NDEBUG block. 1755 assert(S.Context.hasSameType( 1756 FromType, 1757 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1758 } else { 1759 return false; 1760 } 1761 } 1762 // Lvalue-to-rvalue conversion (C++11 4.1): 1763 // A glvalue (3.10) of a non-function, non-array type T can 1764 // be converted to a prvalue. 1765 bool argIsLValue = From->isGLValue(); 1766 if (argIsLValue && 1767 !FromType->isFunctionType() && !FromType->isArrayType() && 1768 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1769 SCS.First = ICK_Lvalue_To_Rvalue; 1770 1771 // C11 6.3.2.1p2: 1772 // ... if the lvalue has atomic type, the value has the non-atomic version 1773 // of the type of the lvalue ... 1774 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1775 FromType = Atomic->getValueType(); 1776 1777 // If T is a non-class type, the type of the rvalue is the 1778 // cv-unqualified version of T. Otherwise, the type of the rvalue 1779 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1780 // just strip the qualifiers because they don't matter. 1781 FromType = FromType.getUnqualifiedType(); 1782 } else if (FromType->isArrayType()) { 1783 // Array-to-pointer conversion (C++ 4.2) 1784 SCS.First = ICK_Array_To_Pointer; 1785 1786 // An lvalue or rvalue of type "array of N T" or "array of unknown 1787 // bound of T" can be converted to an rvalue of type "pointer to 1788 // T" (C++ 4.2p1). 1789 FromType = S.Context.getArrayDecayedType(FromType); 1790 1791 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1792 // This conversion is deprecated in C++03 (D.4) 1793 SCS.DeprecatedStringLiteralToCharPtr = true; 1794 1795 // For the purpose of ranking in overload resolution 1796 // (13.3.3.1.1), this conversion is considered an 1797 // array-to-pointer conversion followed by a qualification 1798 // conversion (4.4). (C++ 4.2p2) 1799 SCS.Second = ICK_Identity; 1800 SCS.Third = ICK_Qualification; 1801 SCS.QualificationIncludesObjCLifetime = false; 1802 SCS.setAllToTypes(FromType); 1803 return true; 1804 } 1805 } else if (FromType->isFunctionType() && argIsLValue) { 1806 // Function-to-pointer conversion (C++ 4.3). 1807 SCS.First = ICK_Function_To_Pointer; 1808 1809 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1810 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1811 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1812 return false; 1813 1814 // An lvalue of function type T can be converted to an rvalue of 1815 // type "pointer to T." The result is a pointer to the 1816 // function. (C++ 4.3p1). 1817 FromType = S.Context.getPointerType(FromType); 1818 } else { 1819 // We don't require any conversions for the first step. 1820 SCS.First = ICK_Identity; 1821 } 1822 SCS.setToType(0, FromType); 1823 1824 // The second conversion can be an integral promotion, floating 1825 // point promotion, integral conversion, floating point conversion, 1826 // floating-integral conversion, pointer conversion, 1827 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1828 // For overloading in C, this can also be a "compatible-type" 1829 // conversion. 1830 bool IncompatibleObjC = false; 1831 ImplicitConversionKind SecondICK = ICK_Identity; 1832 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1833 // The unqualified versions of the types are the same: there's no 1834 // conversion to do. 1835 SCS.Second = ICK_Identity; 1836 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1837 // Integral promotion (C++ 4.5). 1838 SCS.Second = ICK_Integral_Promotion; 1839 FromType = ToType.getUnqualifiedType(); 1840 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1841 // Floating point promotion (C++ 4.6). 1842 SCS.Second = ICK_Floating_Promotion; 1843 FromType = ToType.getUnqualifiedType(); 1844 } else if (S.IsComplexPromotion(FromType, ToType)) { 1845 // Complex promotion (Clang extension) 1846 SCS.Second = ICK_Complex_Promotion; 1847 FromType = ToType.getUnqualifiedType(); 1848 } else if (ToType->isBooleanType() && 1849 (FromType->isArithmeticType() || 1850 FromType->isAnyPointerType() || 1851 FromType->isBlockPointerType() || 1852 FromType->isMemberPointerType())) { 1853 // Boolean conversions (C++ 4.12). 1854 SCS.Second = ICK_Boolean_Conversion; 1855 FromType = S.Context.BoolTy; 1856 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1857 ToType->isIntegralType(S.Context)) { 1858 // Integral conversions (C++ 4.7). 1859 SCS.Second = ICK_Integral_Conversion; 1860 FromType = ToType.getUnqualifiedType(); 1861 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1862 // Complex conversions (C99 6.3.1.6) 1863 SCS.Second = ICK_Complex_Conversion; 1864 FromType = ToType.getUnqualifiedType(); 1865 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1866 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1867 // Complex-real conversions (C99 6.3.1.7) 1868 SCS.Second = ICK_Complex_Real; 1869 FromType = ToType.getUnqualifiedType(); 1870 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1871 // FIXME: disable conversions between long double and __float128 if 1872 // their representation is different until there is back end support 1873 // We of course allow this conversion if long double is really double. 1874 1875 // Conversions between bfloat and other floats are not permitted. 1876 if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty) 1877 return false; 1878 if (&S.Context.getFloatTypeSemantics(FromType) != 1879 &S.Context.getFloatTypeSemantics(ToType)) { 1880 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1881 ToType == S.Context.LongDoubleTy) || 1882 (FromType == S.Context.LongDoubleTy && 1883 ToType == S.Context.Float128Ty)); 1884 if (Float128AndLongDouble && 1885 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1886 &llvm::APFloat::PPCDoubleDouble())) 1887 return false; 1888 } 1889 // Floating point conversions (C++ 4.8). 1890 SCS.Second = ICK_Floating_Conversion; 1891 FromType = ToType.getUnqualifiedType(); 1892 } else if ((FromType->isRealFloatingType() && 1893 ToType->isIntegralType(S.Context)) || 1894 (FromType->isIntegralOrUnscopedEnumerationType() && 1895 ToType->isRealFloatingType())) { 1896 // Conversions between bfloat and int are not permitted. 1897 if (FromType->isBFloat16Type() || ToType->isBFloat16Type()) 1898 return false; 1899 1900 // Floating-integral conversions (C++ 4.9). 1901 SCS.Second = ICK_Floating_Integral; 1902 FromType = ToType.getUnqualifiedType(); 1903 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1904 SCS.Second = ICK_Block_Pointer_Conversion; 1905 } else if (AllowObjCWritebackConversion && 1906 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1907 SCS.Second = ICK_Writeback_Conversion; 1908 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1909 FromType, IncompatibleObjC)) { 1910 // Pointer conversions (C++ 4.10). 1911 SCS.Second = ICK_Pointer_Conversion; 1912 SCS.IncompatibleObjC = IncompatibleObjC; 1913 FromType = FromType.getUnqualifiedType(); 1914 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1915 InOverloadResolution, FromType)) { 1916 // Pointer to member conversions (4.11). 1917 SCS.Second = ICK_Pointer_Member; 1918 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1919 SCS.Second = SecondICK; 1920 FromType = ToType.getUnqualifiedType(); 1921 } else if (!S.getLangOpts().CPlusPlus && 1922 S.Context.typesAreCompatible(ToType, FromType)) { 1923 // Compatible conversions (Clang extension for C function overloading) 1924 SCS.Second = ICK_Compatible_Conversion; 1925 FromType = ToType.getUnqualifiedType(); 1926 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1927 InOverloadResolution, 1928 SCS, CStyle)) { 1929 SCS.Second = ICK_TransparentUnionConversion; 1930 FromType = ToType; 1931 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1932 CStyle)) { 1933 // tryAtomicConversion has updated the standard conversion sequence 1934 // appropriately. 1935 return true; 1936 } else if (ToType->isEventT() && 1937 From->isIntegerConstantExpr(S.getASTContext()) && 1938 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1939 SCS.Second = ICK_Zero_Event_Conversion; 1940 FromType = ToType; 1941 } else if (ToType->isQueueT() && 1942 From->isIntegerConstantExpr(S.getASTContext()) && 1943 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1944 SCS.Second = ICK_Zero_Queue_Conversion; 1945 FromType = ToType; 1946 } else if (ToType->isSamplerT() && 1947 From->isIntegerConstantExpr(S.getASTContext())) { 1948 SCS.Second = ICK_Compatible_Conversion; 1949 FromType = ToType; 1950 } else { 1951 // No second conversion required. 1952 SCS.Second = ICK_Identity; 1953 } 1954 SCS.setToType(1, FromType); 1955 1956 // The third conversion can be a function pointer conversion or a 1957 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1958 bool ObjCLifetimeConversion; 1959 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1960 // Function pointer conversions (removing 'noexcept') including removal of 1961 // 'noreturn' (Clang extension). 1962 SCS.Third = ICK_Function_Conversion; 1963 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1964 ObjCLifetimeConversion)) { 1965 SCS.Third = ICK_Qualification; 1966 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1967 FromType = ToType; 1968 } else { 1969 // No conversion required 1970 SCS.Third = ICK_Identity; 1971 } 1972 1973 // C++ [over.best.ics]p6: 1974 // [...] Any difference in top-level cv-qualification is 1975 // subsumed by the initialization itself and does not constitute 1976 // a conversion. [...] 1977 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1978 QualType CanonTo = S.Context.getCanonicalType(ToType); 1979 if (CanonFrom.getLocalUnqualifiedType() 1980 == CanonTo.getLocalUnqualifiedType() && 1981 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1982 FromType = ToType; 1983 CanonFrom = CanonTo; 1984 } 1985 1986 SCS.setToType(2, FromType); 1987 1988 if (CanonFrom == CanonTo) 1989 return true; 1990 1991 // If we have not converted the argument type to the parameter type, 1992 // this is a bad conversion sequence, unless we're resolving an overload in C. 1993 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1994 return false; 1995 1996 ExprResult ER = ExprResult{From}; 1997 Sema::AssignConvertType Conv = 1998 S.CheckSingleAssignmentConstraints(ToType, ER, 1999 /*Diagnose=*/false, 2000 /*DiagnoseCFAudited=*/false, 2001 /*ConvertRHS=*/false); 2002 ImplicitConversionKind SecondConv; 2003 switch (Conv) { 2004 case Sema::Compatible: 2005 SecondConv = ICK_C_Only_Conversion; 2006 break; 2007 // For our purposes, discarding qualifiers is just as bad as using an 2008 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2009 // qualifiers, as well. 2010 case Sema::CompatiblePointerDiscardsQualifiers: 2011 case Sema::IncompatiblePointer: 2012 case Sema::IncompatiblePointerSign: 2013 SecondConv = ICK_Incompatible_Pointer_Conversion; 2014 break; 2015 default: 2016 return false; 2017 } 2018 2019 // First can only be an lvalue conversion, so we pretend that this was the 2020 // second conversion. First should already be valid from earlier in the 2021 // function. 2022 SCS.Second = SecondConv; 2023 SCS.setToType(1, ToType); 2024 2025 // Third is Identity, because Second should rank us worse than any other 2026 // conversion. This could also be ICK_Qualification, but it's simpler to just 2027 // lump everything in with the second conversion, and we don't gain anything 2028 // from making this ICK_Qualification. 2029 SCS.Third = ICK_Identity; 2030 SCS.setToType(2, ToType); 2031 return true; 2032 } 2033 2034 static bool 2035 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2036 QualType &ToType, 2037 bool InOverloadResolution, 2038 StandardConversionSequence &SCS, 2039 bool CStyle) { 2040 2041 const RecordType *UT = ToType->getAsUnionType(); 2042 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2043 return false; 2044 // The field to initialize within the transparent union. 2045 RecordDecl *UD = UT->getDecl(); 2046 // It's compatible if the expression matches any of the fields. 2047 for (const auto *it : UD->fields()) { 2048 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2049 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2050 ToType = it->getType(); 2051 return true; 2052 } 2053 } 2054 return false; 2055 } 2056 2057 /// IsIntegralPromotion - Determines whether the conversion from the 2058 /// expression From (whose potentially-adjusted type is FromType) to 2059 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2060 /// sets PromotedType to the promoted type. 2061 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2062 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2063 // All integers are built-in. 2064 if (!To) { 2065 return false; 2066 } 2067 2068 // An rvalue of type char, signed char, unsigned char, short int, or 2069 // unsigned short int can be converted to an rvalue of type int if 2070 // int can represent all the values of the source type; otherwise, 2071 // the source rvalue can be converted to an rvalue of type unsigned 2072 // int (C++ 4.5p1). 2073 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2074 !FromType->isEnumeralType()) { 2075 if (// We can promote any signed, promotable integer type to an int 2076 (FromType->isSignedIntegerType() || 2077 // We can promote any unsigned integer type whose size is 2078 // less than int to an int. 2079 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2080 return To->getKind() == BuiltinType::Int; 2081 } 2082 2083 return To->getKind() == BuiltinType::UInt; 2084 } 2085 2086 // C++11 [conv.prom]p3: 2087 // A prvalue of an unscoped enumeration type whose underlying type is not 2088 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2089 // following types that can represent all the values of the enumeration 2090 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2091 // unsigned int, long int, unsigned long int, long long int, or unsigned 2092 // long long int. If none of the types in that list can represent all the 2093 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2094 // type can be converted to an rvalue a prvalue of the extended integer type 2095 // with lowest integer conversion rank (4.13) greater than the rank of long 2096 // long in which all the values of the enumeration can be represented. If 2097 // there are two such extended types, the signed one is chosen. 2098 // C++11 [conv.prom]p4: 2099 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2100 // can be converted to a prvalue of its underlying type. Moreover, if 2101 // integral promotion can be applied to its underlying type, a prvalue of an 2102 // unscoped enumeration type whose underlying type is fixed can also be 2103 // converted to a prvalue of the promoted underlying type. 2104 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2105 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2106 // provided for a scoped enumeration. 2107 if (FromEnumType->getDecl()->isScoped()) 2108 return false; 2109 2110 // We can perform an integral promotion to the underlying type of the enum, 2111 // even if that's not the promoted type. Note that the check for promoting 2112 // the underlying type is based on the type alone, and does not consider 2113 // the bitfield-ness of the actual source expression. 2114 if (FromEnumType->getDecl()->isFixed()) { 2115 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2116 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2117 IsIntegralPromotion(nullptr, Underlying, ToType); 2118 } 2119 2120 // We have already pre-calculated the promotion type, so this is trivial. 2121 if (ToType->isIntegerType() && 2122 isCompleteType(From->getBeginLoc(), FromType)) 2123 return Context.hasSameUnqualifiedType( 2124 ToType, FromEnumType->getDecl()->getPromotionType()); 2125 2126 // C++ [conv.prom]p5: 2127 // If the bit-field has an enumerated type, it is treated as any other 2128 // value of that type for promotion purposes. 2129 // 2130 // ... so do not fall through into the bit-field checks below in C++. 2131 if (getLangOpts().CPlusPlus) 2132 return false; 2133 } 2134 2135 // C++0x [conv.prom]p2: 2136 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2137 // to an rvalue a prvalue of the first of the following types that can 2138 // represent all the values of its underlying type: int, unsigned int, 2139 // long int, unsigned long int, long long int, or unsigned long long int. 2140 // If none of the types in that list can represent all the values of its 2141 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2142 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2143 // type. 2144 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2145 ToType->isIntegerType()) { 2146 // Determine whether the type we're converting from is signed or 2147 // unsigned. 2148 bool FromIsSigned = FromType->isSignedIntegerType(); 2149 uint64_t FromSize = Context.getTypeSize(FromType); 2150 2151 // The types we'll try to promote to, in the appropriate 2152 // order. Try each of these types. 2153 QualType PromoteTypes[6] = { 2154 Context.IntTy, Context.UnsignedIntTy, 2155 Context.LongTy, Context.UnsignedLongTy , 2156 Context.LongLongTy, Context.UnsignedLongLongTy 2157 }; 2158 for (int Idx = 0; Idx < 6; ++Idx) { 2159 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2160 if (FromSize < ToSize || 2161 (FromSize == ToSize && 2162 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2163 // We found the type that we can promote to. If this is the 2164 // type we wanted, we have a promotion. Otherwise, no 2165 // promotion. 2166 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2167 } 2168 } 2169 } 2170 2171 // An rvalue for an integral bit-field (9.6) can be converted to an 2172 // rvalue of type int if int can represent all the values of the 2173 // bit-field; otherwise, it can be converted to unsigned int if 2174 // unsigned int can represent all the values of the bit-field. If 2175 // the bit-field is larger yet, no integral promotion applies to 2176 // it. If the bit-field has an enumerated type, it is treated as any 2177 // other value of that type for promotion purposes (C++ 4.5p3). 2178 // FIXME: We should delay checking of bit-fields until we actually perform the 2179 // conversion. 2180 // 2181 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2182 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2183 // bit-fields and those whose underlying type is larger than int) for GCC 2184 // compatibility. 2185 if (From) { 2186 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2187 Optional<llvm::APSInt> BitWidth; 2188 if (FromType->isIntegralType(Context) && 2189 (BitWidth = 2190 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) { 2191 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned()); 2192 ToSize = Context.getTypeSize(ToType); 2193 2194 // Are we promoting to an int from a bitfield that fits in an int? 2195 if (*BitWidth < ToSize || 2196 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) { 2197 return To->getKind() == BuiltinType::Int; 2198 } 2199 2200 // Are we promoting to an unsigned int from an unsigned bitfield 2201 // that fits into an unsigned int? 2202 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) { 2203 return To->getKind() == BuiltinType::UInt; 2204 } 2205 2206 return false; 2207 } 2208 } 2209 } 2210 2211 // An rvalue of type bool can be converted to an rvalue of type int, 2212 // with false becoming zero and true becoming one (C++ 4.5p4). 2213 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2214 return true; 2215 } 2216 2217 return false; 2218 } 2219 2220 /// IsFloatingPointPromotion - Determines whether the conversion from 2221 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2222 /// returns true and sets PromotedType to the promoted type. 2223 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2226 /// An rvalue of type float can be converted to an rvalue of type 2227 /// double. (C++ 4.6p1). 2228 if (FromBuiltin->getKind() == BuiltinType::Float && 2229 ToBuiltin->getKind() == BuiltinType::Double) 2230 return true; 2231 2232 // C99 6.3.1.5p1: 2233 // When a float is promoted to double or long double, or a 2234 // double is promoted to long double [...]. 2235 if (!getLangOpts().CPlusPlus && 2236 (FromBuiltin->getKind() == BuiltinType::Float || 2237 FromBuiltin->getKind() == BuiltinType::Double) && 2238 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2239 ToBuiltin->getKind() == BuiltinType::Float128)) 2240 return true; 2241 2242 // Half can be promoted to float. 2243 if (!getLangOpts().NativeHalfType && 2244 FromBuiltin->getKind() == BuiltinType::Half && 2245 ToBuiltin->getKind() == BuiltinType::Float) 2246 return true; 2247 } 2248 2249 return false; 2250 } 2251 2252 /// Determine if a conversion is a complex promotion. 2253 /// 2254 /// A complex promotion is defined as a complex -> complex conversion 2255 /// where the conversion between the underlying real types is a 2256 /// floating-point or integral promotion. 2257 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2258 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2259 if (!FromComplex) 2260 return false; 2261 2262 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2263 if (!ToComplex) 2264 return false; 2265 2266 return IsFloatingPointPromotion(FromComplex->getElementType(), 2267 ToComplex->getElementType()) || 2268 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2269 ToComplex->getElementType()); 2270 } 2271 2272 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2273 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2274 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2275 /// if non-empty, will be a pointer to ToType that may or may not have 2276 /// the right set of qualifiers on its pointee. 2277 /// 2278 static QualType 2279 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2280 QualType ToPointee, QualType ToType, 2281 ASTContext &Context, 2282 bool StripObjCLifetime = false) { 2283 assert((FromPtr->getTypeClass() == Type::Pointer || 2284 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2285 "Invalid similarly-qualified pointer type"); 2286 2287 /// Conversions to 'id' subsume cv-qualifier conversions. 2288 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2289 return ToType.getUnqualifiedType(); 2290 2291 QualType CanonFromPointee 2292 = Context.getCanonicalType(FromPtr->getPointeeType()); 2293 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2294 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2295 2296 if (StripObjCLifetime) 2297 Quals.removeObjCLifetime(); 2298 2299 // Exact qualifier match -> return the pointer type we're converting to. 2300 if (CanonToPointee.getLocalQualifiers() == Quals) { 2301 // ToType is exactly what we need. Return it. 2302 if (!ToType.isNull()) 2303 return ToType.getUnqualifiedType(); 2304 2305 // Build a pointer to ToPointee. It has the right qualifiers 2306 // already. 2307 if (isa<ObjCObjectPointerType>(ToType)) 2308 return Context.getObjCObjectPointerType(ToPointee); 2309 return Context.getPointerType(ToPointee); 2310 } 2311 2312 // Just build a canonical type that has the right qualifiers. 2313 QualType QualifiedCanonToPointee 2314 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2315 2316 if (isa<ObjCObjectPointerType>(ToType)) 2317 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2318 return Context.getPointerType(QualifiedCanonToPointee); 2319 } 2320 2321 static bool isNullPointerConstantForConversion(Expr *Expr, 2322 bool InOverloadResolution, 2323 ASTContext &Context) { 2324 // Handle value-dependent integral null pointer constants correctly. 2325 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2326 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2327 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2328 return !InOverloadResolution; 2329 2330 return Expr->isNullPointerConstant(Context, 2331 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2332 : Expr::NPC_ValueDependentIsNull); 2333 } 2334 2335 /// IsPointerConversion - Determines whether the conversion of the 2336 /// expression From, which has the (possibly adjusted) type FromType, 2337 /// can be converted to the type ToType via a pointer conversion (C++ 2338 /// 4.10). If so, returns true and places the converted type (that 2339 /// might differ from ToType in its cv-qualifiers at some level) into 2340 /// ConvertedType. 2341 /// 2342 /// This routine also supports conversions to and from block pointers 2343 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2344 /// pointers to interfaces. FIXME: Once we've determined the 2345 /// appropriate overloading rules for Objective-C, we may want to 2346 /// split the Objective-C checks into a different routine; however, 2347 /// GCC seems to consider all of these conversions to be pointer 2348 /// conversions, so for now they live here. IncompatibleObjC will be 2349 /// set if the conversion is an allowed Objective-C conversion that 2350 /// should result in a warning. 2351 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2352 bool InOverloadResolution, 2353 QualType& ConvertedType, 2354 bool &IncompatibleObjC) { 2355 IncompatibleObjC = false; 2356 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2357 IncompatibleObjC)) 2358 return true; 2359 2360 // Conversion from a null pointer constant to any Objective-C pointer type. 2361 if (ToType->isObjCObjectPointerType() && 2362 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2363 ConvertedType = ToType; 2364 return true; 2365 } 2366 2367 // Blocks: Block pointers can be converted to void*. 2368 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2369 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2370 ConvertedType = ToType; 2371 return true; 2372 } 2373 // Blocks: A null pointer constant can be converted to a block 2374 // pointer type. 2375 if (ToType->isBlockPointerType() && 2376 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2377 ConvertedType = ToType; 2378 return true; 2379 } 2380 2381 // If the left-hand-side is nullptr_t, the right side can be a null 2382 // pointer constant. 2383 if (ToType->isNullPtrType() && 2384 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2385 ConvertedType = ToType; 2386 return true; 2387 } 2388 2389 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2390 if (!ToTypePtr) 2391 return false; 2392 2393 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2394 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2395 ConvertedType = ToType; 2396 return true; 2397 } 2398 2399 // Beyond this point, both types need to be pointers 2400 // , including objective-c pointers. 2401 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2402 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2403 !getLangOpts().ObjCAutoRefCount) { 2404 ConvertedType = BuildSimilarlyQualifiedPointerType( 2405 FromType->getAs<ObjCObjectPointerType>(), 2406 ToPointeeType, 2407 ToType, Context); 2408 return true; 2409 } 2410 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2411 if (!FromTypePtr) 2412 return false; 2413 2414 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2415 2416 // If the unqualified pointee types are the same, this can't be a 2417 // pointer conversion, so don't do all of the work below. 2418 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2419 return false; 2420 2421 // An rvalue of type "pointer to cv T," where T is an object type, 2422 // can be converted to an rvalue of type "pointer to cv void" (C++ 2423 // 4.10p2). 2424 if (FromPointeeType->isIncompleteOrObjectType() && 2425 ToPointeeType->isVoidType()) { 2426 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2427 ToPointeeType, 2428 ToType, Context, 2429 /*StripObjCLifetime=*/true); 2430 return true; 2431 } 2432 2433 // MSVC allows implicit function to void* type conversion. 2434 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2435 ToPointeeType->isVoidType()) { 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2437 ToPointeeType, 2438 ToType, Context); 2439 return true; 2440 } 2441 2442 // When we're overloading in C, we allow a special kind of pointer 2443 // conversion for compatible-but-not-identical pointee types. 2444 if (!getLangOpts().CPlusPlus && 2445 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2446 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2447 ToPointeeType, 2448 ToType, Context); 2449 return true; 2450 } 2451 2452 // C++ [conv.ptr]p3: 2453 // 2454 // An rvalue of type "pointer to cv D," where D is a class type, 2455 // can be converted to an rvalue of type "pointer to cv B," where 2456 // B is a base class (clause 10) of D. If B is an inaccessible 2457 // (clause 11) or ambiguous (10.2) base class of D, a program that 2458 // necessitates this conversion is ill-formed. The result of the 2459 // conversion is a pointer to the base class sub-object of the 2460 // derived class object. The null pointer value is converted to 2461 // the null pointer value of the destination type. 2462 // 2463 // Note that we do not check for ambiguity or inaccessibility 2464 // here. That is handled by CheckPointerConversion. 2465 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2466 ToPointeeType->isRecordType() && 2467 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2468 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2469 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2470 ToPointeeType, 2471 ToType, Context); 2472 return true; 2473 } 2474 2475 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2476 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2477 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2478 ToPointeeType, 2479 ToType, Context); 2480 return true; 2481 } 2482 2483 return false; 2484 } 2485 2486 /// Adopt the given qualifiers for the given type. 2487 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2488 Qualifiers TQs = T.getQualifiers(); 2489 2490 // Check whether qualifiers already match. 2491 if (TQs == Qs) 2492 return T; 2493 2494 if (Qs.compatiblyIncludes(TQs)) 2495 return Context.getQualifiedType(T, Qs); 2496 2497 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2498 } 2499 2500 /// isObjCPointerConversion - Determines whether this is an 2501 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2502 /// with the same arguments and return values. 2503 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2504 QualType& ConvertedType, 2505 bool &IncompatibleObjC) { 2506 if (!getLangOpts().ObjC) 2507 return false; 2508 2509 // The set of qualifiers on the type we're converting from. 2510 Qualifiers FromQualifiers = FromType.getQualifiers(); 2511 2512 // First, we handle all conversions on ObjC object pointer types. 2513 const ObjCObjectPointerType* ToObjCPtr = 2514 ToType->getAs<ObjCObjectPointerType>(); 2515 const ObjCObjectPointerType *FromObjCPtr = 2516 FromType->getAs<ObjCObjectPointerType>(); 2517 2518 if (ToObjCPtr && FromObjCPtr) { 2519 // If the pointee types are the same (ignoring qualifications), 2520 // then this is not a pointer conversion. 2521 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2522 FromObjCPtr->getPointeeType())) 2523 return false; 2524 2525 // Conversion between Objective-C pointers. 2526 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2527 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2528 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2529 if (getLangOpts().CPlusPlus && LHS && RHS && 2530 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2531 FromObjCPtr->getPointeeType())) 2532 return false; 2533 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2534 ToObjCPtr->getPointeeType(), 2535 ToType, Context); 2536 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2537 return true; 2538 } 2539 2540 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2541 // Okay: this is some kind of implicit downcast of Objective-C 2542 // interfaces, which is permitted. However, we're going to 2543 // complain about it. 2544 IncompatibleObjC = true; 2545 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2546 ToObjCPtr->getPointeeType(), 2547 ToType, Context); 2548 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2549 return true; 2550 } 2551 } 2552 // Beyond this point, both types need to be C pointers or block pointers. 2553 QualType ToPointeeType; 2554 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2555 ToPointeeType = ToCPtr->getPointeeType(); 2556 else if (const BlockPointerType *ToBlockPtr = 2557 ToType->getAs<BlockPointerType>()) { 2558 // Objective C++: We're able to convert from a pointer to any object 2559 // to a block pointer type. 2560 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2561 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2562 return true; 2563 } 2564 ToPointeeType = ToBlockPtr->getPointeeType(); 2565 } 2566 else if (FromType->getAs<BlockPointerType>() && 2567 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2568 // Objective C++: We're able to convert from a block pointer type to a 2569 // pointer to any object. 2570 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2571 return true; 2572 } 2573 else 2574 return false; 2575 2576 QualType FromPointeeType; 2577 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2578 FromPointeeType = FromCPtr->getPointeeType(); 2579 else if (const BlockPointerType *FromBlockPtr = 2580 FromType->getAs<BlockPointerType>()) 2581 FromPointeeType = FromBlockPtr->getPointeeType(); 2582 else 2583 return false; 2584 2585 // If we have pointers to pointers, recursively check whether this 2586 // is an Objective-C conversion. 2587 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2588 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2589 IncompatibleObjC)) { 2590 // We always complain about this conversion. 2591 IncompatibleObjC = true; 2592 ConvertedType = Context.getPointerType(ConvertedType); 2593 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2594 return true; 2595 } 2596 // Allow conversion of pointee being objective-c pointer to another one; 2597 // as in I* to id. 2598 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2599 ToPointeeType->getAs<ObjCObjectPointerType>() && 2600 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2601 IncompatibleObjC)) { 2602 2603 ConvertedType = Context.getPointerType(ConvertedType); 2604 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2605 return true; 2606 } 2607 2608 // If we have pointers to functions or blocks, check whether the only 2609 // differences in the argument and result types are in Objective-C 2610 // pointer conversions. If so, we permit the conversion (but 2611 // complain about it). 2612 const FunctionProtoType *FromFunctionType 2613 = FromPointeeType->getAs<FunctionProtoType>(); 2614 const FunctionProtoType *ToFunctionType 2615 = ToPointeeType->getAs<FunctionProtoType>(); 2616 if (FromFunctionType && ToFunctionType) { 2617 // If the function types are exactly the same, this isn't an 2618 // Objective-C pointer conversion. 2619 if (Context.getCanonicalType(FromPointeeType) 2620 == Context.getCanonicalType(ToPointeeType)) 2621 return false; 2622 2623 // Perform the quick checks that will tell us whether these 2624 // function types are obviously different. 2625 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2626 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2627 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2628 return false; 2629 2630 bool HasObjCConversion = false; 2631 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2632 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2633 // Okay, the types match exactly. Nothing to do. 2634 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2635 ToFunctionType->getReturnType(), 2636 ConvertedType, IncompatibleObjC)) { 2637 // Okay, we have an Objective-C pointer conversion. 2638 HasObjCConversion = true; 2639 } else { 2640 // Function types are too different. Abort. 2641 return false; 2642 } 2643 2644 // Check argument types. 2645 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2646 ArgIdx != NumArgs; ++ArgIdx) { 2647 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2648 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2649 if (Context.getCanonicalType(FromArgType) 2650 == Context.getCanonicalType(ToArgType)) { 2651 // Okay, the types match exactly. Nothing to do. 2652 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2653 ConvertedType, IncompatibleObjC)) { 2654 // Okay, we have an Objective-C pointer conversion. 2655 HasObjCConversion = true; 2656 } else { 2657 // Argument types are too different. Abort. 2658 return false; 2659 } 2660 } 2661 2662 if (HasObjCConversion) { 2663 // We had an Objective-C conversion. Allow this pointer 2664 // conversion, but complain about it. 2665 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2666 IncompatibleObjC = true; 2667 return true; 2668 } 2669 } 2670 2671 return false; 2672 } 2673 2674 /// Determine whether this is an Objective-C writeback conversion, 2675 /// used for parameter passing when performing automatic reference counting. 2676 /// 2677 /// \param FromType The type we're converting form. 2678 /// 2679 /// \param ToType The type we're converting to. 2680 /// 2681 /// \param ConvertedType The type that will be produced after applying 2682 /// this conversion. 2683 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2684 QualType &ConvertedType) { 2685 if (!getLangOpts().ObjCAutoRefCount || 2686 Context.hasSameUnqualifiedType(FromType, ToType)) 2687 return false; 2688 2689 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2690 QualType ToPointee; 2691 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2692 ToPointee = ToPointer->getPointeeType(); 2693 else 2694 return false; 2695 2696 Qualifiers ToQuals = ToPointee.getQualifiers(); 2697 if (!ToPointee->isObjCLifetimeType() || 2698 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2699 !ToQuals.withoutObjCLifetime().empty()) 2700 return false; 2701 2702 // Argument must be a pointer to __strong to __weak. 2703 QualType FromPointee; 2704 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2705 FromPointee = FromPointer->getPointeeType(); 2706 else 2707 return false; 2708 2709 Qualifiers FromQuals = FromPointee.getQualifiers(); 2710 if (!FromPointee->isObjCLifetimeType() || 2711 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2712 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2713 return false; 2714 2715 // Make sure that we have compatible qualifiers. 2716 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2717 if (!ToQuals.compatiblyIncludes(FromQuals)) 2718 return false; 2719 2720 // Remove qualifiers from the pointee type we're converting from; they 2721 // aren't used in the compatibility check belong, and we'll be adding back 2722 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2723 FromPointee = FromPointee.getUnqualifiedType(); 2724 2725 // The unqualified form of the pointee types must be compatible. 2726 ToPointee = ToPointee.getUnqualifiedType(); 2727 bool IncompatibleObjC; 2728 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2729 FromPointee = ToPointee; 2730 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2731 IncompatibleObjC)) 2732 return false; 2733 2734 /// Construct the type we're converting to, which is a pointer to 2735 /// __autoreleasing pointee. 2736 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2737 ConvertedType = Context.getPointerType(FromPointee); 2738 return true; 2739 } 2740 2741 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2742 QualType& ConvertedType) { 2743 QualType ToPointeeType; 2744 if (const BlockPointerType *ToBlockPtr = 2745 ToType->getAs<BlockPointerType>()) 2746 ToPointeeType = ToBlockPtr->getPointeeType(); 2747 else 2748 return false; 2749 2750 QualType FromPointeeType; 2751 if (const BlockPointerType *FromBlockPtr = 2752 FromType->getAs<BlockPointerType>()) 2753 FromPointeeType = FromBlockPtr->getPointeeType(); 2754 else 2755 return false; 2756 // We have pointer to blocks, check whether the only 2757 // differences in the argument and result types are in Objective-C 2758 // pointer conversions. If so, we permit the conversion. 2759 2760 const FunctionProtoType *FromFunctionType 2761 = FromPointeeType->getAs<FunctionProtoType>(); 2762 const FunctionProtoType *ToFunctionType 2763 = ToPointeeType->getAs<FunctionProtoType>(); 2764 2765 if (!FromFunctionType || !ToFunctionType) 2766 return false; 2767 2768 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2769 return true; 2770 2771 // Perform the quick checks that will tell us whether these 2772 // function types are obviously different. 2773 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2774 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2775 return false; 2776 2777 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2778 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2779 if (FromEInfo != ToEInfo) 2780 return false; 2781 2782 bool IncompatibleObjC = false; 2783 if (Context.hasSameType(FromFunctionType->getReturnType(), 2784 ToFunctionType->getReturnType())) { 2785 // Okay, the types match exactly. Nothing to do. 2786 } else { 2787 QualType RHS = FromFunctionType->getReturnType(); 2788 QualType LHS = ToFunctionType->getReturnType(); 2789 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2790 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2791 LHS = LHS.getUnqualifiedType(); 2792 2793 if (Context.hasSameType(RHS,LHS)) { 2794 // OK exact match. 2795 } else if (isObjCPointerConversion(RHS, LHS, 2796 ConvertedType, IncompatibleObjC)) { 2797 if (IncompatibleObjC) 2798 return false; 2799 // Okay, we have an Objective-C pointer conversion. 2800 } 2801 else 2802 return false; 2803 } 2804 2805 // Check argument types. 2806 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2807 ArgIdx != NumArgs; ++ArgIdx) { 2808 IncompatibleObjC = false; 2809 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2810 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2811 if (Context.hasSameType(FromArgType, ToArgType)) { 2812 // Okay, the types match exactly. Nothing to do. 2813 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2814 ConvertedType, IncompatibleObjC)) { 2815 if (IncompatibleObjC) 2816 return false; 2817 // Okay, we have an Objective-C pointer conversion. 2818 } else 2819 // Argument types are too different. Abort. 2820 return false; 2821 } 2822 2823 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2824 bool CanUseToFPT, CanUseFromFPT; 2825 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2826 CanUseToFPT, CanUseFromFPT, 2827 NewParamInfos)) 2828 return false; 2829 2830 ConvertedType = ToType; 2831 return true; 2832 } 2833 2834 enum { 2835 ft_default, 2836 ft_different_class, 2837 ft_parameter_arity, 2838 ft_parameter_mismatch, 2839 ft_return_type, 2840 ft_qualifer_mismatch, 2841 ft_noexcept 2842 }; 2843 2844 /// Attempts to get the FunctionProtoType from a Type. Handles 2845 /// MemberFunctionPointers properly. 2846 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2847 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2848 return FPT; 2849 2850 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2851 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2852 2853 return nullptr; 2854 } 2855 2856 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2857 /// function types. Catches different number of parameter, mismatch in 2858 /// parameter types, and different return types. 2859 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2860 QualType FromType, QualType ToType) { 2861 // If either type is not valid, include no extra info. 2862 if (FromType.isNull() || ToType.isNull()) { 2863 PDiag << ft_default; 2864 return; 2865 } 2866 2867 // Get the function type from the pointers. 2868 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2869 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2870 *ToMember = ToType->castAs<MemberPointerType>(); 2871 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2872 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2873 << QualType(FromMember->getClass(), 0); 2874 return; 2875 } 2876 FromType = FromMember->getPointeeType(); 2877 ToType = ToMember->getPointeeType(); 2878 } 2879 2880 if (FromType->isPointerType()) 2881 FromType = FromType->getPointeeType(); 2882 if (ToType->isPointerType()) 2883 ToType = ToType->getPointeeType(); 2884 2885 // Remove references. 2886 FromType = FromType.getNonReferenceType(); 2887 ToType = ToType.getNonReferenceType(); 2888 2889 // Don't print extra info for non-specialized template functions. 2890 if (FromType->isInstantiationDependentType() && 2891 !FromType->getAs<TemplateSpecializationType>()) { 2892 PDiag << ft_default; 2893 return; 2894 } 2895 2896 // No extra info for same types. 2897 if (Context.hasSameType(FromType, ToType)) { 2898 PDiag << ft_default; 2899 return; 2900 } 2901 2902 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2903 *ToFunction = tryGetFunctionProtoType(ToType); 2904 2905 // Both types need to be function types. 2906 if (!FromFunction || !ToFunction) { 2907 PDiag << ft_default; 2908 return; 2909 } 2910 2911 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2912 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2913 << FromFunction->getNumParams(); 2914 return; 2915 } 2916 2917 // Handle different parameter types. 2918 unsigned ArgPos; 2919 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2920 PDiag << ft_parameter_mismatch << ArgPos + 1 2921 << ToFunction->getParamType(ArgPos) 2922 << FromFunction->getParamType(ArgPos); 2923 return; 2924 } 2925 2926 // Handle different return type. 2927 if (!Context.hasSameType(FromFunction->getReturnType(), 2928 ToFunction->getReturnType())) { 2929 PDiag << ft_return_type << ToFunction->getReturnType() 2930 << FromFunction->getReturnType(); 2931 return; 2932 } 2933 2934 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2935 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2936 << FromFunction->getMethodQuals(); 2937 return; 2938 } 2939 2940 // Handle exception specification differences on canonical type (in C++17 2941 // onwards). 2942 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2943 ->isNothrow() != 2944 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2945 ->isNothrow()) { 2946 PDiag << ft_noexcept; 2947 return; 2948 } 2949 2950 // Unable to find a difference, so add no extra info. 2951 PDiag << ft_default; 2952 } 2953 2954 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2955 /// for equality of their argument types. Caller has already checked that 2956 /// they have same number of arguments. If the parameters are different, 2957 /// ArgPos will have the parameter index of the first different parameter. 2958 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2959 const FunctionProtoType *NewType, 2960 unsigned *ArgPos) { 2961 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2962 N = NewType->param_type_begin(), 2963 E = OldType->param_type_end(); 2964 O && (O != E); ++O, ++N) { 2965 // Ignore address spaces in pointee type. This is to disallow overloading 2966 // on __ptr32/__ptr64 address spaces. 2967 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2968 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2969 2970 if (!Context.hasSameType(Old, New)) { 2971 if (ArgPos) 2972 *ArgPos = O - OldType->param_type_begin(); 2973 return false; 2974 } 2975 } 2976 return true; 2977 } 2978 2979 /// CheckPointerConversion - Check the pointer conversion from the 2980 /// expression From to the type ToType. This routine checks for 2981 /// ambiguous or inaccessible derived-to-base pointer 2982 /// conversions for which IsPointerConversion has already returned 2983 /// true. It returns true and produces a diagnostic if there was an 2984 /// error, or returns false otherwise. 2985 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2986 CastKind &Kind, 2987 CXXCastPath& BasePath, 2988 bool IgnoreBaseAccess, 2989 bool Diagnose) { 2990 QualType FromType = From->getType(); 2991 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2992 2993 Kind = CK_BitCast; 2994 2995 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2996 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2997 Expr::NPCK_ZeroExpression) { 2998 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2999 DiagRuntimeBehavior(From->getExprLoc(), From, 3000 PDiag(diag::warn_impcast_bool_to_null_pointer) 3001 << ToType << From->getSourceRange()); 3002 else if (!isUnevaluatedContext()) 3003 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 3004 << ToType << From->getSourceRange(); 3005 } 3006 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 3007 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 3008 QualType FromPointeeType = FromPtrType->getPointeeType(), 3009 ToPointeeType = ToPtrType->getPointeeType(); 3010 3011 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3012 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3013 // We must have a derived-to-base conversion. Check an 3014 // ambiguous or inaccessible conversion. 3015 unsigned InaccessibleID = 0; 3016 unsigned AmbiguousID = 0; 3017 if (Diagnose) { 3018 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3019 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3020 } 3021 if (CheckDerivedToBaseConversion( 3022 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3023 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3024 &BasePath, IgnoreBaseAccess)) 3025 return true; 3026 3027 // The conversion was successful. 3028 Kind = CK_DerivedToBase; 3029 } 3030 3031 if (Diagnose && !IsCStyleOrFunctionalCast && 3032 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3033 assert(getLangOpts().MSVCCompat && 3034 "this should only be possible with MSVCCompat!"); 3035 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3036 << From->getSourceRange(); 3037 } 3038 } 3039 } else if (const ObjCObjectPointerType *ToPtrType = 3040 ToType->getAs<ObjCObjectPointerType>()) { 3041 if (const ObjCObjectPointerType *FromPtrType = 3042 FromType->getAs<ObjCObjectPointerType>()) { 3043 // Objective-C++ conversions are always okay. 3044 // FIXME: We should have a different class of conversions for the 3045 // Objective-C++ implicit conversions. 3046 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3047 return false; 3048 } else if (FromType->isBlockPointerType()) { 3049 Kind = CK_BlockPointerToObjCPointerCast; 3050 } else { 3051 Kind = CK_CPointerToObjCPointerCast; 3052 } 3053 } else if (ToType->isBlockPointerType()) { 3054 if (!FromType->isBlockPointerType()) 3055 Kind = CK_AnyPointerToBlockPointerCast; 3056 } 3057 3058 // We shouldn't fall into this case unless it's valid for other 3059 // reasons. 3060 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3061 Kind = CK_NullToPointer; 3062 3063 return false; 3064 } 3065 3066 /// IsMemberPointerConversion - Determines whether the conversion of the 3067 /// expression From, which has the (possibly adjusted) type FromType, can be 3068 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3069 /// If so, returns true and places the converted type (that might differ from 3070 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3071 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3072 QualType ToType, 3073 bool InOverloadResolution, 3074 QualType &ConvertedType) { 3075 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3076 if (!ToTypePtr) 3077 return false; 3078 3079 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3080 if (From->isNullPointerConstant(Context, 3081 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3082 : Expr::NPC_ValueDependentIsNull)) { 3083 ConvertedType = ToType; 3084 return true; 3085 } 3086 3087 // Otherwise, both types have to be member pointers. 3088 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3089 if (!FromTypePtr) 3090 return false; 3091 3092 // A pointer to member of B can be converted to a pointer to member of D, 3093 // where D is derived from B (C++ 4.11p2). 3094 QualType FromClass(FromTypePtr->getClass(), 0); 3095 QualType ToClass(ToTypePtr->getClass(), 0); 3096 3097 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3098 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3099 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3100 ToClass.getTypePtr()); 3101 return true; 3102 } 3103 3104 return false; 3105 } 3106 3107 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3108 /// expression From to the type ToType. This routine checks for ambiguous or 3109 /// virtual or inaccessible base-to-derived member pointer conversions 3110 /// for which IsMemberPointerConversion has already returned true. It returns 3111 /// true and produces a diagnostic if there was an error, or returns false 3112 /// otherwise. 3113 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3114 CastKind &Kind, 3115 CXXCastPath &BasePath, 3116 bool IgnoreBaseAccess) { 3117 QualType FromType = From->getType(); 3118 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3119 if (!FromPtrType) { 3120 // This must be a null pointer to member pointer conversion 3121 assert(From->isNullPointerConstant(Context, 3122 Expr::NPC_ValueDependentIsNull) && 3123 "Expr must be null pointer constant!"); 3124 Kind = CK_NullToMemberPointer; 3125 return false; 3126 } 3127 3128 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3129 assert(ToPtrType && "No member pointer cast has a target type " 3130 "that is not a member pointer."); 3131 3132 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3133 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3134 3135 // FIXME: What about dependent types? 3136 assert(FromClass->isRecordType() && "Pointer into non-class."); 3137 assert(ToClass->isRecordType() && "Pointer into non-class."); 3138 3139 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3140 /*DetectVirtual=*/true); 3141 bool DerivationOkay = 3142 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3143 assert(DerivationOkay && 3144 "Should not have been called if derivation isn't OK."); 3145 (void)DerivationOkay; 3146 3147 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3148 getUnqualifiedType())) { 3149 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3150 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3151 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3152 return true; 3153 } 3154 3155 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3156 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3157 << FromClass << ToClass << QualType(VBase, 0) 3158 << From->getSourceRange(); 3159 return true; 3160 } 3161 3162 if (!IgnoreBaseAccess) 3163 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3164 Paths.front(), 3165 diag::err_downcast_from_inaccessible_base); 3166 3167 // Must be a base to derived member conversion. 3168 BuildBasePathArray(Paths, BasePath); 3169 Kind = CK_BaseToDerivedMemberPointer; 3170 return false; 3171 } 3172 3173 /// Determine whether the lifetime conversion between the two given 3174 /// qualifiers sets is nontrivial. 3175 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3176 Qualifiers ToQuals) { 3177 // Converting anything to const __unsafe_unretained is trivial. 3178 if (ToQuals.hasConst() && 3179 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3180 return false; 3181 3182 return true; 3183 } 3184 3185 /// Perform a single iteration of the loop for checking if a qualification 3186 /// conversion is valid. 3187 /// 3188 /// Specifically, check whether any change between the qualifiers of \p 3189 /// FromType and \p ToType is permissible, given knowledge about whether every 3190 /// outer layer is const-qualified. 3191 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3192 bool CStyle, bool IsTopLevel, 3193 bool &PreviousToQualsIncludeConst, 3194 bool &ObjCLifetimeConversion) { 3195 Qualifiers FromQuals = FromType.getQualifiers(); 3196 Qualifiers ToQuals = ToType.getQualifiers(); 3197 3198 // Ignore __unaligned qualifier if this type is void. 3199 if (ToType.getUnqualifiedType()->isVoidType()) 3200 FromQuals.removeUnaligned(); 3201 3202 // Objective-C ARC: 3203 // Check Objective-C lifetime conversions. 3204 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3205 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3206 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3207 ObjCLifetimeConversion = true; 3208 FromQuals.removeObjCLifetime(); 3209 ToQuals.removeObjCLifetime(); 3210 } else { 3211 // Qualification conversions cannot cast between different 3212 // Objective-C lifetime qualifiers. 3213 return false; 3214 } 3215 } 3216 3217 // Allow addition/removal of GC attributes but not changing GC attributes. 3218 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3219 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3220 FromQuals.removeObjCGCAttr(); 3221 ToQuals.removeObjCGCAttr(); 3222 } 3223 3224 // -- for every j > 0, if const is in cv 1,j then const is in cv 3225 // 2,j, and similarly for volatile. 3226 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3227 return false; 3228 3229 // If address spaces mismatch: 3230 // - in top level it is only valid to convert to addr space that is a 3231 // superset in all cases apart from C-style casts where we allow 3232 // conversions between overlapping address spaces. 3233 // - in non-top levels it is not a valid conversion. 3234 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3235 (!IsTopLevel || 3236 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3237 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3238 return false; 3239 3240 // -- if the cv 1,j and cv 2,j are different, then const is in 3241 // every cv for 0 < k < j. 3242 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3243 !PreviousToQualsIncludeConst) 3244 return false; 3245 3246 // Keep track of whether all prior cv-qualifiers in the "to" type 3247 // include const. 3248 PreviousToQualsIncludeConst = 3249 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3250 return true; 3251 } 3252 3253 /// IsQualificationConversion - Determines whether the conversion from 3254 /// an rvalue of type FromType to ToType is a qualification conversion 3255 /// (C++ 4.4). 3256 /// 3257 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3258 /// when the qualification conversion involves a change in the Objective-C 3259 /// object lifetime. 3260 bool 3261 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3262 bool CStyle, bool &ObjCLifetimeConversion) { 3263 FromType = Context.getCanonicalType(FromType); 3264 ToType = Context.getCanonicalType(ToType); 3265 ObjCLifetimeConversion = false; 3266 3267 // If FromType and ToType are the same type, this is not a 3268 // qualification conversion. 3269 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3270 return false; 3271 3272 // (C++ 4.4p4): 3273 // A conversion can add cv-qualifiers at levels other than the first 3274 // in multi-level pointers, subject to the following rules: [...] 3275 bool PreviousToQualsIncludeConst = true; 3276 bool UnwrappedAnyPointer = false; 3277 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3278 if (!isQualificationConversionStep( 3279 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3280 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3281 return false; 3282 UnwrappedAnyPointer = true; 3283 } 3284 3285 // We are left with FromType and ToType being the pointee types 3286 // after unwrapping the original FromType and ToType the same number 3287 // of times. If we unwrapped any pointers, and if FromType and 3288 // ToType have the same unqualified type (since we checked 3289 // qualifiers above), then this is a qualification conversion. 3290 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3291 } 3292 3293 /// - Determine whether this is a conversion from a scalar type to an 3294 /// atomic type. 3295 /// 3296 /// If successful, updates \c SCS's second and third steps in the conversion 3297 /// sequence to finish the conversion. 3298 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3299 bool InOverloadResolution, 3300 StandardConversionSequence &SCS, 3301 bool CStyle) { 3302 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3303 if (!ToAtomic) 3304 return false; 3305 3306 StandardConversionSequence InnerSCS; 3307 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3308 InOverloadResolution, InnerSCS, 3309 CStyle, /*AllowObjCWritebackConversion=*/false)) 3310 return false; 3311 3312 SCS.Second = InnerSCS.Second; 3313 SCS.setToType(1, InnerSCS.getToType(1)); 3314 SCS.Third = InnerSCS.Third; 3315 SCS.QualificationIncludesObjCLifetime 3316 = InnerSCS.QualificationIncludesObjCLifetime; 3317 SCS.setToType(2, InnerSCS.getToType(2)); 3318 return true; 3319 } 3320 3321 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3322 CXXConstructorDecl *Constructor, 3323 QualType Type) { 3324 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3325 if (CtorType->getNumParams() > 0) { 3326 QualType FirstArg = CtorType->getParamType(0); 3327 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3328 return true; 3329 } 3330 return false; 3331 } 3332 3333 static OverloadingResult 3334 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3335 CXXRecordDecl *To, 3336 UserDefinedConversionSequence &User, 3337 OverloadCandidateSet &CandidateSet, 3338 bool AllowExplicit) { 3339 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3340 for (auto *D : S.LookupConstructors(To)) { 3341 auto Info = getConstructorInfo(D); 3342 if (!Info) 3343 continue; 3344 3345 bool Usable = !Info.Constructor->isInvalidDecl() && 3346 S.isInitListConstructor(Info.Constructor); 3347 if (Usable) { 3348 // If the first argument is (a reference to) the target type, 3349 // suppress conversions. 3350 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3351 S.Context, Info.Constructor, ToType); 3352 if (Info.ConstructorTmpl) 3353 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3354 /*ExplicitArgs*/ nullptr, From, 3355 CandidateSet, SuppressUserConversions, 3356 /*PartialOverloading*/ false, 3357 AllowExplicit); 3358 else 3359 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3360 CandidateSet, SuppressUserConversions, 3361 /*PartialOverloading*/ false, AllowExplicit); 3362 } 3363 } 3364 3365 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3366 3367 OverloadCandidateSet::iterator Best; 3368 switch (auto Result = 3369 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3370 case OR_Deleted: 3371 case OR_Success: { 3372 // Record the standard conversion we used and the conversion function. 3373 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3374 QualType ThisType = Constructor->getThisType(); 3375 // Initializer lists don't have conversions as such. 3376 User.Before.setAsIdentityConversion(); 3377 User.HadMultipleCandidates = HadMultipleCandidates; 3378 User.ConversionFunction = Constructor; 3379 User.FoundConversionFunction = Best->FoundDecl; 3380 User.After.setAsIdentityConversion(); 3381 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3382 User.After.setAllToTypes(ToType); 3383 return Result; 3384 } 3385 3386 case OR_No_Viable_Function: 3387 return OR_No_Viable_Function; 3388 case OR_Ambiguous: 3389 return OR_Ambiguous; 3390 } 3391 3392 llvm_unreachable("Invalid OverloadResult!"); 3393 } 3394 3395 /// Determines whether there is a user-defined conversion sequence 3396 /// (C++ [over.ics.user]) that converts expression From to the type 3397 /// ToType. If such a conversion exists, User will contain the 3398 /// user-defined conversion sequence that performs such a conversion 3399 /// and this routine will return true. Otherwise, this routine returns 3400 /// false and User is unspecified. 3401 /// 3402 /// \param AllowExplicit true if the conversion should consider C++0x 3403 /// "explicit" conversion functions as well as non-explicit conversion 3404 /// functions (C++0x [class.conv.fct]p2). 3405 /// 3406 /// \param AllowObjCConversionOnExplicit true if the conversion should 3407 /// allow an extra Objective-C pointer conversion on uses of explicit 3408 /// constructors. Requires \c AllowExplicit to also be set. 3409 static OverloadingResult 3410 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3411 UserDefinedConversionSequence &User, 3412 OverloadCandidateSet &CandidateSet, 3413 AllowedExplicit AllowExplicit, 3414 bool AllowObjCConversionOnExplicit) { 3415 assert(AllowExplicit != AllowedExplicit::None || 3416 !AllowObjCConversionOnExplicit); 3417 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3418 3419 // Whether we will only visit constructors. 3420 bool ConstructorsOnly = false; 3421 3422 // If the type we are conversion to is a class type, enumerate its 3423 // constructors. 3424 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3425 // C++ [over.match.ctor]p1: 3426 // When objects of class type are direct-initialized (8.5), or 3427 // copy-initialized from an expression of the same or a 3428 // derived class type (8.5), overload resolution selects the 3429 // constructor. [...] For copy-initialization, the candidate 3430 // functions are all the converting constructors (12.3.1) of 3431 // that class. The argument list is the expression-list within 3432 // the parentheses of the initializer. 3433 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3434 (From->getType()->getAs<RecordType>() && 3435 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3436 ConstructorsOnly = true; 3437 3438 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3439 // We're not going to find any constructors. 3440 } else if (CXXRecordDecl *ToRecordDecl 3441 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3442 3443 Expr **Args = &From; 3444 unsigned NumArgs = 1; 3445 bool ListInitializing = false; 3446 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3447 // But first, see if there is an init-list-constructor that will work. 3448 OverloadingResult Result = IsInitializerListConstructorConversion( 3449 S, From, ToType, ToRecordDecl, User, CandidateSet, 3450 AllowExplicit == AllowedExplicit::All); 3451 if (Result != OR_No_Viable_Function) 3452 return Result; 3453 // Never mind. 3454 CandidateSet.clear( 3455 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3456 3457 // If we're list-initializing, we pass the individual elements as 3458 // arguments, not the entire list. 3459 Args = InitList->getInits(); 3460 NumArgs = InitList->getNumInits(); 3461 ListInitializing = true; 3462 } 3463 3464 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3465 auto Info = getConstructorInfo(D); 3466 if (!Info) 3467 continue; 3468 3469 bool Usable = !Info.Constructor->isInvalidDecl(); 3470 if (!ListInitializing) 3471 Usable = Usable && Info.Constructor->isConvertingConstructor( 3472 /*AllowExplicit*/ true); 3473 if (Usable) { 3474 bool SuppressUserConversions = !ConstructorsOnly; 3475 if (SuppressUserConversions && ListInitializing) { 3476 SuppressUserConversions = false; 3477 if (NumArgs == 1) { 3478 // If the first argument is (a reference to) the target type, 3479 // suppress conversions. 3480 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3481 S.Context, Info.Constructor, ToType); 3482 } 3483 } 3484 if (Info.ConstructorTmpl) 3485 S.AddTemplateOverloadCandidate( 3486 Info.ConstructorTmpl, Info.FoundDecl, 3487 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3488 CandidateSet, SuppressUserConversions, 3489 /*PartialOverloading*/ false, 3490 AllowExplicit == AllowedExplicit::All); 3491 else 3492 // Allow one user-defined conversion when user specifies a 3493 // From->ToType conversion via an static cast (c-style, etc). 3494 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3495 llvm::makeArrayRef(Args, NumArgs), 3496 CandidateSet, SuppressUserConversions, 3497 /*PartialOverloading*/ false, 3498 AllowExplicit == AllowedExplicit::All); 3499 } 3500 } 3501 } 3502 } 3503 3504 // Enumerate conversion functions, if we're allowed to. 3505 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3506 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3507 // No conversion functions from incomplete types. 3508 } else if (const RecordType *FromRecordType = 3509 From->getType()->getAs<RecordType>()) { 3510 if (CXXRecordDecl *FromRecordDecl 3511 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3512 // Add all of the conversion functions as candidates. 3513 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3514 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3515 DeclAccessPair FoundDecl = I.getPair(); 3516 NamedDecl *D = FoundDecl.getDecl(); 3517 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3518 if (isa<UsingShadowDecl>(D)) 3519 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3520 3521 CXXConversionDecl *Conv; 3522 FunctionTemplateDecl *ConvTemplate; 3523 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3524 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3525 else 3526 Conv = cast<CXXConversionDecl>(D); 3527 3528 if (ConvTemplate) 3529 S.AddTemplateConversionCandidate( 3530 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3531 CandidateSet, AllowObjCConversionOnExplicit, 3532 AllowExplicit != AllowedExplicit::None); 3533 else 3534 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3535 CandidateSet, AllowObjCConversionOnExplicit, 3536 AllowExplicit != AllowedExplicit::None); 3537 } 3538 } 3539 } 3540 3541 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3542 3543 OverloadCandidateSet::iterator Best; 3544 switch (auto Result = 3545 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3546 case OR_Success: 3547 case OR_Deleted: 3548 // Record the standard conversion we used and the conversion function. 3549 if (CXXConstructorDecl *Constructor 3550 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3551 // C++ [over.ics.user]p1: 3552 // If the user-defined conversion is specified by a 3553 // constructor (12.3.1), the initial standard conversion 3554 // sequence converts the source type to the type required by 3555 // the argument of the constructor. 3556 // 3557 QualType ThisType = Constructor->getThisType(); 3558 if (isa<InitListExpr>(From)) { 3559 // Initializer lists don't have conversions as such. 3560 User.Before.setAsIdentityConversion(); 3561 } else { 3562 if (Best->Conversions[0].isEllipsis()) 3563 User.EllipsisConversion = true; 3564 else { 3565 User.Before = Best->Conversions[0].Standard; 3566 User.EllipsisConversion = false; 3567 } 3568 } 3569 User.HadMultipleCandidates = HadMultipleCandidates; 3570 User.ConversionFunction = Constructor; 3571 User.FoundConversionFunction = Best->FoundDecl; 3572 User.After.setAsIdentityConversion(); 3573 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3574 User.After.setAllToTypes(ToType); 3575 return Result; 3576 } 3577 if (CXXConversionDecl *Conversion 3578 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3579 // C++ [over.ics.user]p1: 3580 // 3581 // [...] If the user-defined conversion is specified by a 3582 // conversion function (12.3.2), the initial standard 3583 // conversion sequence converts the source type to the 3584 // implicit object parameter of the conversion function. 3585 User.Before = Best->Conversions[0].Standard; 3586 User.HadMultipleCandidates = HadMultipleCandidates; 3587 User.ConversionFunction = Conversion; 3588 User.FoundConversionFunction = Best->FoundDecl; 3589 User.EllipsisConversion = false; 3590 3591 // C++ [over.ics.user]p2: 3592 // The second standard conversion sequence converts the 3593 // result of the user-defined conversion to the target type 3594 // for the sequence. Since an implicit conversion sequence 3595 // is an initialization, the special rules for 3596 // initialization by user-defined conversion apply when 3597 // selecting the best user-defined conversion for a 3598 // user-defined conversion sequence (see 13.3.3 and 3599 // 13.3.3.1). 3600 User.After = Best->FinalConversion; 3601 return Result; 3602 } 3603 llvm_unreachable("Not a constructor or conversion function?"); 3604 3605 case OR_No_Viable_Function: 3606 return OR_No_Viable_Function; 3607 3608 case OR_Ambiguous: 3609 return OR_Ambiguous; 3610 } 3611 3612 llvm_unreachable("Invalid OverloadResult!"); 3613 } 3614 3615 bool 3616 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3617 ImplicitConversionSequence ICS; 3618 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3619 OverloadCandidateSet::CSK_Normal); 3620 OverloadingResult OvResult = 3621 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3622 CandidateSet, AllowedExplicit::None, false); 3623 3624 if (!(OvResult == OR_Ambiguous || 3625 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3626 return false; 3627 3628 auto Cands = CandidateSet.CompleteCandidates( 3629 *this, 3630 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3631 From); 3632 if (OvResult == OR_Ambiguous) 3633 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3634 << From->getType() << ToType << From->getSourceRange(); 3635 else { // OR_No_Viable_Function && !CandidateSet.empty() 3636 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3637 diag::err_typecheck_nonviable_condition_incomplete, 3638 From->getType(), From->getSourceRange())) 3639 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3640 << false << From->getType() << From->getSourceRange() << ToType; 3641 } 3642 3643 CandidateSet.NoteCandidates( 3644 *this, From, Cands); 3645 return true; 3646 } 3647 3648 /// Compare the user-defined conversion functions or constructors 3649 /// of two user-defined conversion sequences to determine whether any ordering 3650 /// is possible. 3651 static ImplicitConversionSequence::CompareKind 3652 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3653 FunctionDecl *Function2) { 3654 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3655 return ImplicitConversionSequence::Indistinguishable; 3656 3657 // Objective-C++: 3658 // If both conversion functions are implicitly-declared conversions from 3659 // a lambda closure type to a function pointer and a block pointer, 3660 // respectively, always prefer the conversion to a function pointer, 3661 // because the function pointer is more lightweight and is more likely 3662 // to keep code working. 3663 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3664 if (!Conv1) 3665 return ImplicitConversionSequence::Indistinguishable; 3666 3667 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3668 if (!Conv2) 3669 return ImplicitConversionSequence::Indistinguishable; 3670 3671 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3672 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3673 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3674 if (Block1 != Block2) 3675 return Block1 ? ImplicitConversionSequence::Worse 3676 : ImplicitConversionSequence::Better; 3677 } 3678 3679 return ImplicitConversionSequence::Indistinguishable; 3680 } 3681 3682 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3683 const ImplicitConversionSequence &ICS) { 3684 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3685 (ICS.isUserDefined() && 3686 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3687 } 3688 3689 /// CompareImplicitConversionSequences - Compare two implicit 3690 /// conversion sequences to determine whether one is better than the 3691 /// other or if they are indistinguishable (C++ 13.3.3.2). 3692 static ImplicitConversionSequence::CompareKind 3693 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3694 const ImplicitConversionSequence& ICS1, 3695 const ImplicitConversionSequence& ICS2) 3696 { 3697 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3698 // conversion sequences (as defined in 13.3.3.1) 3699 // -- a standard conversion sequence (13.3.3.1.1) is a better 3700 // conversion sequence than a user-defined conversion sequence or 3701 // an ellipsis conversion sequence, and 3702 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3703 // conversion sequence than an ellipsis conversion sequence 3704 // (13.3.3.1.3). 3705 // 3706 // C++0x [over.best.ics]p10: 3707 // For the purpose of ranking implicit conversion sequences as 3708 // described in 13.3.3.2, the ambiguous conversion sequence is 3709 // treated as a user-defined sequence that is indistinguishable 3710 // from any other user-defined conversion sequence. 3711 3712 // String literal to 'char *' conversion has been deprecated in C++03. It has 3713 // been removed from C++11. We still accept this conversion, if it happens at 3714 // the best viable function. Otherwise, this conversion is considered worse 3715 // than ellipsis conversion. Consider this as an extension; this is not in the 3716 // standard. For example: 3717 // 3718 // int &f(...); // #1 3719 // void f(char*); // #2 3720 // void g() { int &r = f("foo"); } 3721 // 3722 // In C++03, we pick #2 as the best viable function. 3723 // In C++11, we pick #1 as the best viable function, because ellipsis 3724 // conversion is better than string-literal to char* conversion (since there 3725 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3726 // convert arguments, #2 would be the best viable function in C++11. 3727 // If the best viable function has this conversion, a warning will be issued 3728 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3729 3730 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3731 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3732 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3733 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3734 ? ImplicitConversionSequence::Worse 3735 : ImplicitConversionSequence::Better; 3736 3737 if (ICS1.getKindRank() < ICS2.getKindRank()) 3738 return ImplicitConversionSequence::Better; 3739 if (ICS2.getKindRank() < ICS1.getKindRank()) 3740 return ImplicitConversionSequence::Worse; 3741 3742 // The following checks require both conversion sequences to be of 3743 // the same kind. 3744 if (ICS1.getKind() != ICS2.getKind()) 3745 return ImplicitConversionSequence::Indistinguishable; 3746 3747 ImplicitConversionSequence::CompareKind Result = 3748 ImplicitConversionSequence::Indistinguishable; 3749 3750 // Two implicit conversion sequences of the same form are 3751 // indistinguishable conversion sequences unless one of the 3752 // following rules apply: (C++ 13.3.3.2p3): 3753 3754 // List-initialization sequence L1 is a better conversion sequence than 3755 // list-initialization sequence L2 if: 3756 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3757 // if not that, 3758 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3759 // and N1 is smaller than N2., 3760 // even if one of the other rules in this paragraph would otherwise apply. 3761 if (!ICS1.isBad()) { 3762 if (ICS1.isStdInitializerListElement() && 3763 !ICS2.isStdInitializerListElement()) 3764 return ImplicitConversionSequence::Better; 3765 if (!ICS1.isStdInitializerListElement() && 3766 ICS2.isStdInitializerListElement()) 3767 return ImplicitConversionSequence::Worse; 3768 } 3769 3770 if (ICS1.isStandard()) 3771 // Standard conversion sequence S1 is a better conversion sequence than 3772 // standard conversion sequence S2 if [...] 3773 Result = CompareStandardConversionSequences(S, Loc, 3774 ICS1.Standard, ICS2.Standard); 3775 else if (ICS1.isUserDefined()) { 3776 // User-defined conversion sequence U1 is a better conversion 3777 // sequence than another user-defined conversion sequence U2 if 3778 // they contain the same user-defined conversion function or 3779 // constructor and if the second standard conversion sequence of 3780 // U1 is better than the second standard conversion sequence of 3781 // U2 (C++ 13.3.3.2p3). 3782 if (ICS1.UserDefined.ConversionFunction == 3783 ICS2.UserDefined.ConversionFunction) 3784 Result = CompareStandardConversionSequences(S, Loc, 3785 ICS1.UserDefined.After, 3786 ICS2.UserDefined.After); 3787 else 3788 Result = compareConversionFunctions(S, 3789 ICS1.UserDefined.ConversionFunction, 3790 ICS2.UserDefined.ConversionFunction); 3791 } 3792 3793 return Result; 3794 } 3795 3796 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3797 // determine if one is a proper subset of the other. 3798 static ImplicitConversionSequence::CompareKind 3799 compareStandardConversionSubsets(ASTContext &Context, 3800 const StandardConversionSequence& SCS1, 3801 const StandardConversionSequence& SCS2) { 3802 ImplicitConversionSequence::CompareKind Result 3803 = ImplicitConversionSequence::Indistinguishable; 3804 3805 // the identity conversion sequence is considered to be a subsequence of 3806 // any non-identity conversion sequence 3807 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3808 return ImplicitConversionSequence::Better; 3809 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3810 return ImplicitConversionSequence::Worse; 3811 3812 if (SCS1.Second != SCS2.Second) { 3813 if (SCS1.Second == ICK_Identity) 3814 Result = ImplicitConversionSequence::Better; 3815 else if (SCS2.Second == ICK_Identity) 3816 Result = ImplicitConversionSequence::Worse; 3817 else 3818 return ImplicitConversionSequence::Indistinguishable; 3819 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3820 return ImplicitConversionSequence::Indistinguishable; 3821 3822 if (SCS1.Third == SCS2.Third) { 3823 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3824 : ImplicitConversionSequence::Indistinguishable; 3825 } 3826 3827 if (SCS1.Third == ICK_Identity) 3828 return Result == ImplicitConversionSequence::Worse 3829 ? ImplicitConversionSequence::Indistinguishable 3830 : ImplicitConversionSequence::Better; 3831 3832 if (SCS2.Third == ICK_Identity) 3833 return Result == ImplicitConversionSequence::Better 3834 ? ImplicitConversionSequence::Indistinguishable 3835 : ImplicitConversionSequence::Worse; 3836 3837 return ImplicitConversionSequence::Indistinguishable; 3838 } 3839 3840 /// Determine whether one of the given reference bindings is better 3841 /// than the other based on what kind of bindings they are. 3842 static bool 3843 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3844 const StandardConversionSequence &SCS2) { 3845 // C++0x [over.ics.rank]p3b4: 3846 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3847 // implicit object parameter of a non-static member function declared 3848 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3849 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3850 // lvalue reference to a function lvalue and S2 binds an rvalue 3851 // reference*. 3852 // 3853 // FIXME: Rvalue references. We're going rogue with the above edits, 3854 // because the semantics in the current C++0x working paper (N3225 at the 3855 // time of this writing) break the standard definition of std::forward 3856 // and std::reference_wrapper when dealing with references to functions. 3857 // Proposed wording changes submitted to CWG for consideration. 3858 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3859 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3860 return false; 3861 3862 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3863 SCS2.IsLvalueReference) || 3864 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3865 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3866 } 3867 3868 enum class FixedEnumPromotion { 3869 None, 3870 ToUnderlyingType, 3871 ToPromotedUnderlyingType 3872 }; 3873 3874 /// Returns kind of fixed enum promotion the \a SCS uses. 3875 static FixedEnumPromotion 3876 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3877 3878 if (SCS.Second != ICK_Integral_Promotion) 3879 return FixedEnumPromotion::None; 3880 3881 QualType FromType = SCS.getFromType(); 3882 if (!FromType->isEnumeralType()) 3883 return FixedEnumPromotion::None; 3884 3885 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3886 if (!Enum->isFixed()) 3887 return FixedEnumPromotion::None; 3888 3889 QualType UnderlyingType = Enum->getIntegerType(); 3890 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3891 return FixedEnumPromotion::ToUnderlyingType; 3892 3893 return FixedEnumPromotion::ToPromotedUnderlyingType; 3894 } 3895 3896 /// CompareStandardConversionSequences - Compare two standard 3897 /// conversion sequences to determine whether one is better than the 3898 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3899 static ImplicitConversionSequence::CompareKind 3900 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3901 const StandardConversionSequence& SCS1, 3902 const StandardConversionSequence& SCS2) 3903 { 3904 // Standard conversion sequence S1 is a better conversion sequence 3905 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3906 3907 // -- S1 is a proper subsequence of S2 (comparing the conversion 3908 // sequences in the canonical form defined by 13.3.3.1.1, 3909 // excluding any Lvalue Transformation; the identity conversion 3910 // sequence is considered to be a subsequence of any 3911 // non-identity conversion sequence) or, if not that, 3912 if (ImplicitConversionSequence::CompareKind CK 3913 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3914 return CK; 3915 3916 // -- the rank of S1 is better than the rank of S2 (by the rules 3917 // defined below), or, if not that, 3918 ImplicitConversionRank Rank1 = SCS1.getRank(); 3919 ImplicitConversionRank Rank2 = SCS2.getRank(); 3920 if (Rank1 < Rank2) 3921 return ImplicitConversionSequence::Better; 3922 else if (Rank2 < Rank1) 3923 return ImplicitConversionSequence::Worse; 3924 3925 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3926 // are indistinguishable unless one of the following rules 3927 // applies: 3928 3929 // A conversion that is not a conversion of a pointer, or 3930 // pointer to member, to bool is better than another conversion 3931 // that is such a conversion. 3932 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3933 return SCS2.isPointerConversionToBool() 3934 ? ImplicitConversionSequence::Better 3935 : ImplicitConversionSequence::Worse; 3936 3937 // C++14 [over.ics.rank]p4b2: 3938 // This is retroactively applied to C++11 by CWG 1601. 3939 // 3940 // A conversion that promotes an enumeration whose underlying type is fixed 3941 // to its underlying type is better than one that promotes to the promoted 3942 // underlying type, if the two are different. 3943 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3944 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3945 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3946 FEP1 != FEP2) 3947 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3948 ? ImplicitConversionSequence::Better 3949 : ImplicitConversionSequence::Worse; 3950 3951 // C++ [over.ics.rank]p4b2: 3952 // 3953 // If class B is derived directly or indirectly from class A, 3954 // conversion of B* to A* is better than conversion of B* to 3955 // void*, and conversion of A* to void* is better than conversion 3956 // of B* to void*. 3957 bool SCS1ConvertsToVoid 3958 = SCS1.isPointerConversionToVoidPointer(S.Context); 3959 bool SCS2ConvertsToVoid 3960 = SCS2.isPointerConversionToVoidPointer(S.Context); 3961 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3962 // Exactly one of the conversion sequences is a conversion to 3963 // a void pointer; it's the worse conversion. 3964 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3965 : ImplicitConversionSequence::Worse; 3966 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3967 // Neither conversion sequence converts to a void pointer; compare 3968 // their derived-to-base conversions. 3969 if (ImplicitConversionSequence::CompareKind DerivedCK 3970 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3971 return DerivedCK; 3972 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3973 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3974 // Both conversion sequences are conversions to void 3975 // pointers. Compare the source types to determine if there's an 3976 // inheritance relationship in their sources. 3977 QualType FromType1 = SCS1.getFromType(); 3978 QualType FromType2 = SCS2.getFromType(); 3979 3980 // Adjust the types we're converting from via the array-to-pointer 3981 // conversion, if we need to. 3982 if (SCS1.First == ICK_Array_To_Pointer) 3983 FromType1 = S.Context.getArrayDecayedType(FromType1); 3984 if (SCS2.First == ICK_Array_To_Pointer) 3985 FromType2 = S.Context.getArrayDecayedType(FromType2); 3986 3987 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3988 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3989 3990 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3991 return ImplicitConversionSequence::Better; 3992 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3993 return ImplicitConversionSequence::Worse; 3994 3995 // Objective-C++: If one interface is more specific than the 3996 // other, it is the better one. 3997 const ObjCObjectPointerType* FromObjCPtr1 3998 = FromType1->getAs<ObjCObjectPointerType>(); 3999 const ObjCObjectPointerType* FromObjCPtr2 4000 = FromType2->getAs<ObjCObjectPointerType>(); 4001 if (FromObjCPtr1 && FromObjCPtr2) { 4002 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 4003 FromObjCPtr2); 4004 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 4005 FromObjCPtr1); 4006 if (AssignLeft != AssignRight) { 4007 return AssignLeft? ImplicitConversionSequence::Better 4008 : ImplicitConversionSequence::Worse; 4009 } 4010 } 4011 } 4012 4013 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4014 // Check for a better reference binding based on the kind of bindings. 4015 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4016 return ImplicitConversionSequence::Better; 4017 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4018 return ImplicitConversionSequence::Worse; 4019 } 4020 4021 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4022 // bullet 3). 4023 if (ImplicitConversionSequence::CompareKind QualCK 4024 = CompareQualificationConversions(S, SCS1, SCS2)) 4025 return QualCK; 4026 4027 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4028 // C++ [over.ics.rank]p3b4: 4029 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4030 // which the references refer are the same type except for 4031 // top-level cv-qualifiers, and the type to which the reference 4032 // initialized by S2 refers is more cv-qualified than the type 4033 // to which the reference initialized by S1 refers. 4034 QualType T1 = SCS1.getToType(2); 4035 QualType T2 = SCS2.getToType(2); 4036 T1 = S.Context.getCanonicalType(T1); 4037 T2 = S.Context.getCanonicalType(T2); 4038 Qualifiers T1Quals, T2Quals; 4039 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4040 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4041 if (UnqualT1 == UnqualT2) { 4042 // Objective-C++ ARC: If the references refer to objects with different 4043 // lifetimes, prefer bindings that don't change lifetime. 4044 if (SCS1.ObjCLifetimeConversionBinding != 4045 SCS2.ObjCLifetimeConversionBinding) { 4046 return SCS1.ObjCLifetimeConversionBinding 4047 ? ImplicitConversionSequence::Worse 4048 : ImplicitConversionSequence::Better; 4049 } 4050 4051 // If the type is an array type, promote the element qualifiers to the 4052 // type for comparison. 4053 if (isa<ArrayType>(T1) && T1Quals) 4054 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4055 if (isa<ArrayType>(T2) && T2Quals) 4056 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4057 if (T2.isMoreQualifiedThan(T1)) 4058 return ImplicitConversionSequence::Better; 4059 if (T1.isMoreQualifiedThan(T2)) 4060 return ImplicitConversionSequence::Worse; 4061 } 4062 } 4063 4064 // In Microsoft mode, prefer an integral conversion to a 4065 // floating-to-integral conversion if the integral conversion 4066 // is between types of the same size. 4067 // For example: 4068 // void f(float); 4069 // void f(int); 4070 // int main { 4071 // long a; 4072 // f(a); 4073 // } 4074 // Here, MSVC will call f(int) instead of generating a compile error 4075 // as clang will do in standard mode. 4076 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4077 SCS2.Second == ICK_Floating_Integral && 4078 S.Context.getTypeSize(SCS1.getFromType()) == 4079 S.Context.getTypeSize(SCS1.getToType(2))) 4080 return ImplicitConversionSequence::Better; 4081 4082 // Prefer a compatible vector conversion over a lax vector conversion 4083 // For example: 4084 // 4085 // typedef float __v4sf __attribute__((__vector_size__(16))); 4086 // void f(vector float); 4087 // void f(vector signed int); 4088 // int main() { 4089 // __v4sf a; 4090 // f(a); 4091 // } 4092 // Here, we'd like to choose f(vector float) and not 4093 // report an ambiguous call error 4094 if (SCS1.Second == ICK_Vector_Conversion && 4095 SCS2.Second == ICK_Vector_Conversion) { 4096 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4097 SCS1.getFromType(), SCS1.getToType(2)); 4098 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4099 SCS2.getFromType(), SCS2.getToType(2)); 4100 4101 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4102 return SCS1IsCompatibleVectorConversion 4103 ? ImplicitConversionSequence::Better 4104 : ImplicitConversionSequence::Worse; 4105 } 4106 4107 return ImplicitConversionSequence::Indistinguishable; 4108 } 4109 4110 /// CompareQualificationConversions - Compares two standard conversion 4111 /// sequences to determine whether they can be ranked based on their 4112 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4113 static ImplicitConversionSequence::CompareKind 4114 CompareQualificationConversions(Sema &S, 4115 const StandardConversionSequence& SCS1, 4116 const StandardConversionSequence& SCS2) { 4117 // C++ 13.3.3.2p3: 4118 // -- S1 and S2 differ only in their qualification conversion and 4119 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4120 // cv-qualification signature of type T1 is a proper subset of 4121 // the cv-qualification signature of type T2, and S1 is not the 4122 // deprecated string literal array-to-pointer conversion (4.2). 4123 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4124 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4125 return ImplicitConversionSequence::Indistinguishable; 4126 4127 // FIXME: the example in the standard doesn't use a qualification 4128 // conversion (!) 4129 QualType T1 = SCS1.getToType(2); 4130 QualType T2 = SCS2.getToType(2); 4131 T1 = S.Context.getCanonicalType(T1); 4132 T2 = S.Context.getCanonicalType(T2); 4133 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4134 Qualifiers T1Quals, T2Quals; 4135 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4136 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4137 4138 // If the types are the same, we won't learn anything by unwrapping 4139 // them. 4140 if (UnqualT1 == UnqualT2) 4141 return ImplicitConversionSequence::Indistinguishable; 4142 4143 ImplicitConversionSequence::CompareKind Result 4144 = ImplicitConversionSequence::Indistinguishable; 4145 4146 // Objective-C++ ARC: 4147 // Prefer qualification conversions not involving a change in lifetime 4148 // to qualification conversions that do not change lifetime. 4149 if (SCS1.QualificationIncludesObjCLifetime != 4150 SCS2.QualificationIncludesObjCLifetime) { 4151 Result = SCS1.QualificationIncludesObjCLifetime 4152 ? ImplicitConversionSequence::Worse 4153 : ImplicitConversionSequence::Better; 4154 } 4155 4156 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4157 // Within each iteration of the loop, we check the qualifiers to 4158 // determine if this still looks like a qualification 4159 // conversion. Then, if all is well, we unwrap one more level of 4160 // pointers or pointers-to-members and do it all again 4161 // until there are no more pointers or pointers-to-members left 4162 // to unwrap. This essentially mimics what 4163 // IsQualificationConversion does, but here we're checking for a 4164 // strict subset of qualifiers. 4165 if (T1.getQualifiers().withoutObjCLifetime() == 4166 T2.getQualifiers().withoutObjCLifetime()) 4167 // The qualifiers are the same, so this doesn't tell us anything 4168 // about how the sequences rank. 4169 // ObjC ownership quals are omitted above as they interfere with 4170 // the ARC overload rule. 4171 ; 4172 else if (T2.isMoreQualifiedThan(T1)) { 4173 // T1 has fewer qualifiers, so it could be the better sequence. 4174 if (Result == ImplicitConversionSequence::Worse) 4175 // Neither has qualifiers that are a subset of the other's 4176 // qualifiers. 4177 return ImplicitConversionSequence::Indistinguishable; 4178 4179 Result = ImplicitConversionSequence::Better; 4180 } else if (T1.isMoreQualifiedThan(T2)) { 4181 // T2 has fewer qualifiers, so it could be the better sequence. 4182 if (Result == ImplicitConversionSequence::Better) 4183 // Neither has qualifiers that are a subset of the other's 4184 // qualifiers. 4185 return ImplicitConversionSequence::Indistinguishable; 4186 4187 Result = ImplicitConversionSequence::Worse; 4188 } else { 4189 // Qualifiers are disjoint. 4190 return ImplicitConversionSequence::Indistinguishable; 4191 } 4192 4193 // If the types after this point are equivalent, we're done. 4194 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4195 break; 4196 } 4197 4198 // Check that the winning standard conversion sequence isn't using 4199 // the deprecated string literal array to pointer conversion. 4200 switch (Result) { 4201 case ImplicitConversionSequence::Better: 4202 if (SCS1.DeprecatedStringLiteralToCharPtr) 4203 Result = ImplicitConversionSequence::Indistinguishable; 4204 break; 4205 4206 case ImplicitConversionSequence::Indistinguishable: 4207 break; 4208 4209 case ImplicitConversionSequence::Worse: 4210 if (SCS2.DeprecatedStringLiteralToCharPtr) 4211 Result = ImplicitConversionSequence::Indistinguishable; 4212 break; 4213 } 4214 4215 return Result; 4216 } 4217 4218 /// CompareDerivedToBaseConversions - Compares two standard conversion 4219 /// sequences to determine whether they can be ranked based on their 4220 /// various kinds of derived-to-base conversions (C++ 4221 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4222 /// conversions between Objective-C interface types. 4223 static ImplicitConversionSequence::CompareKind 4224 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4225 const StandardConversionSequence& SCS1, 4226 const StandardConversionSequence& SCS2) { 4227 QualType FromType1 = SCS1.getFromType(); 4228 QualType ToType1 = SCS1.getToType(1); 4229 QualType FromType2 = SCS2.getFromType(); 4230 QualType ToType2 = SCS2.getToType(1); 4231 4232 // Adjust the types we're converting from via the array-to-pointer 4233 // conversion, if we need to. 4234 if (SCS1.First == ICK_Array_To_Pointer) 4235 FromType1 = S.Context.getArrayDecayedType(FromType1); 4236 if (SCS2.First == ICK_Array_To_Pointer) 4237 FromType2 = S.Context.getArrayDecayedType(FromType2); 4238 4239 // Canonicalize all of the types. 4240 FromType1 = S.Context.getCanonicalType(FromType1); 4241 ToType1 = S.Context.getCanonicalType(ToType1); 4242 FromType2 = S.Context.getCanonicalType(FromType2); 4243 ToType2 = S.Context.getCanonicalType(ToType2); 4244 4245 // C++ [over.ics.rank]p4b3: 4246 // 4247 // If class B is derived directly or indirectly from class A and 4248 // class C is derived directly or indirectly from B, 4249 // 4250 // Compare based on pointer conversions. 4251 if (SCS1.Second == ICK_Pointer_Conversion && 4252 SCS2.Second == ICK_Pointer_Conversion && 4253 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4254 FromType1->isPointerType() && FromType2->isPointerType() && 4255 ToType1->isPointerType() && ToType2->isPointerType()) { 4256 QualType FromPointee1 = 4257 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4258 QualType ToPointee1 = 4259 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4260 QualType FromPointee2 = 4261 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4262 QualType ToPointee2 = 4263 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4264 4265 // -- conversion of C* to B* is better than conversion of C* to A*, 4266 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4267 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4268 return ImplicitConversionSequence::Better; 4269 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4270 return ImplicitConversionSequence::Worse; 4271 } 4272 4273 // -- conversion of B* to A* is better than conversion of C* to A*, 4274 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4275 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4276 return ImplicitConversionSequence::Better; 4277 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4278 return ImplicitConversionSequence::Worse; 4279 } 4280 } else if (SCS1.Second == ICK_Pointer_Conversion && 4281 SCS2.Second == ICK_Pointer_Conversion) { 4282 const ObjCObjectPointerType *FromPtr1 4283 = FromType1->getAs<ObjCObjectPointerType>(); 4284 const ObjCObjectPointerType *FromPtr2 4285 = FromType2->getAs<ObjCObjectPointerType>(); 4286 const ObjCObjectPointerType *ToPtr1 4287 = ToType1->getAs<ObjCObjectPointerType>(); 4288 const ObjCObjectPointerType *ToPtr2 4289 = ToType2->getAs<ObjCObjectPointerType>(); 4290 4291 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4292 // Apply the same conversion ranking rules for Objective-C pointer types 4293 // that we do for C++ pointers to class types. However, we employ the 4294 // Objective-C pseudo-subtyping relationship used for assignment of 4295 // Objective-C pointer types. 4296 bool FromAssignLeft 4297 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4298 bool FromAssignRight 4299 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4300 bool ToAssignLeft 4301 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4302 bool ToAssignRight 4303 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4304 4305 // A conversion to an a non-id object pointer type or qualified 'id' 4306 // type is better than a conversion to 'id'. 4307 if (ToPtr1->isObjCIdType() && 4308 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4309 return ImplicitConversionSequence::Worse; 4310 if (ToPtr2->isObjCIdType() && 4311 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4312 return ImplicitConversionSequence::Better; 4313 4314 // A conversion to a non-id object pointer type is better than a 4315 // conversion to a qualified 'id' type 4316 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4317 return ImplicitConversionSequence::Worse; 4318 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4319 return ImplicitConversionSequence::Better; 4320 4321 // A conversion to an a non-Class object pointer type or qualified 'Class' 4322 // type is better than a conversion to 'Class'. 4323 if (ToPtr1->isObjCClassType() && 4324 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4325 return ImplicitConversionSequence::Worse; 4326 if (ToPtr2->isObjCClassType() && 4327 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4328 return ImplicitConversionSequence::Better; 4329 4330 // A conversion to a non-Class object pointer type is better than a 4331 // conversion to a qualified 'Class' type. 4332 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4333 return ImplicitConversionSequence::Worse; 4334 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4335 return ImplicitConversionSequence::Better; 4336 4337 // -- "conversion of C* to B* is better than conversion of C* to A*," 4338 if (S.Context.hasSameType(FromType1, FromType2) && 4339 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4340 (ToAssignLeft != ToAssignRight)) { 4341 if (FromPtr1->isSpecialized()) { 4342 // "conversion of B<A> * to B * is better than conversion of B * to 4343 // C *. 4344 bool IsFirstSame = 4345 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4346 bool IsSecondSame = 4347 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4348 if (IsFirstSame) { 4349 if (!IsSecondSame) 4350 return ImplicitConversionSequence::Better; 4351 } else if (IsSecondSame) 4352 return ImplicitConversionSequence::Worse; 4353 } 4354 return ToAssignLeft? ImplicitConversionSequence::Worse 4355 : ImplicitConversionSequence::Better; 4356 } 4357 4358 // -- "conversion of B* to A* is better than conversion of C* to A*," 4359 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4360 (FromAssignLeft != FromAssignRight)) 4361 return FromAssignLeft? ImplicitConversionSequence::Better 4362 : ImplicitConversionSequence::Worse; 4363 } 4364 } 4365 4366 // Ranking of member-pointer types. 4367 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4368 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4369 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4370 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4371 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4372 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4373 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4374 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4375 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4376 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4377 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4378 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4379 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4380 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4381 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4382 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4383 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4384 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4385 return ImplicitConversionSequence::Worse; 4386 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4387 return ImplicitConversionSequence::Better; 4388 } 4389 // conversion of B::* to C::* is better than conversion of A::* to C::* 4390 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4391 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4392 return ImplicitConversionSequence::Better; 4393 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4394 return ImplicitConversionSequence::Worse; 4395 } 4396 } 4397 4398 if (SCS1.Second == ICK_Derived_To_Base) { 4399 // -- conversion of C to B is better than conversion of C to A, 4400 // -- binding of an expression of type C to a reference of type 4401 // B& is better than binding an expression of type C to a 4402 // reference of type A&, 4403 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4404 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4405 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4406 return ImplicitConversionSequence::Better; 4407 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4408 return ImplicitConversionSequence::Worse; 4409 } 4410 4411 // -- conversion of B to A is better than conversion of C to A. 4412 // -- binding of an expression of type B to a reference of type 4413 // A& is better than binding an expression of type C to a 4414 // reference of type A&, 4415 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4416 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4417 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4418 return ImplicitConversionSequence::Better; 4419 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4420 return ImplicitConversionSequence::Worse; 4421 } 4422 } 4423 4424 return ImplicitConversionSequence::Indistinguishable; 4425 } 4426 4427 /// Determine whether the given type is valid, e.g., it is not an invalid 4428 /// C++ class. 4429 static bool isTypeValid(QualType T) { 4430 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4431 return !Record->isInvalidDecl(); 4432 4433 return true; 4434 } 4435 4436 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4437 if (!T.getQualifiers().hasUnaligned()) 4438 return T; 4439 4440 Qualifiers Q; 4441 T = Ctx.getUnqualifiedArrayType(T, Q); 4442 Q.removeUnaligned(); 4443 return Ctx.getQualifiedType(T, Q); 4444 } 4445 4446 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4447 /// determine whether they are reference-compatible, 4448 /// reference-related, or incompatible, for use in C++ initialization by 4449 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4450 /// type, and the first type (T1) is the pointee type of the reference 4451 /// type being initialized. 4452 Sema::ReferenceCompareResult 4453 Sema::CompareReferenceRelationship(SourceLocation Loc, 4454 QualType OrigT1, QualType OrigT2, 4455 ReferenceConversions *ConvOut) { 4456 assert(!OrigT1->isReferenceType() && 4457 "T1 must be the pointee type of the reference type"); 4458 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4459 4460 QualType T1 = Context.getCanonicalType(OrigT1); 4461 QualType T2 = Context.getCanonicalType(OrigT2); 4462 Qualifiers T1Quals, T2Quals; 4463 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4464 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4465 4466 ReferenceConversions ConvTmp; 4467 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4468 Conv = ReferenceConversions(); 4469 4470 // C++2a [dcl.init.ref]p4: 4471 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4472 // reference-related to "cv2 T2" if T1 is similar to T2, or 4473 // T1 is a base class of T2. 4474 // "cv1 T1" is reference-compatible with "cv2 T2" if 4475 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4476 // "pointer to cv1 T1" via a standard conversion sequence. 4477 4478 // Check for standard conversions we can apply to pointers: derived-to-base 4479 // conversions, ObjC pointer conversions, and function pointer conversions. 4480 // (Qualification conversions are checked last.) 4481 QualType ConvertedT2; 4482 if (UnqualT1 == UnqualT2) { 4483 // Nothing to do. 4484 } else if (isCompleteType(Loc, OrigT2) && 4485 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4486 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4487 Conv |= ReferenceConversions::DerivedToBase; 4488 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4489 UnqualT2->isObjCObjectOrInterfaceType() && 4490 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4491 Conv |= ReferenceConversions::ObjC; 4492 else if (UnqualT2->isFunctionType() && 4493 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4494 Conv |= ReferenceConversions::Function; 4495 // No need to check qualifiers; function types don't have them. 4496 return Ref_Compatible; 4497 } 4498 bool ConvertedReferent = Conv != 0; 4499 4500 // We can have a qualification conversion. Compute whether the types are 4501 // similar at the same time. 4502 bool PreviousToQualsIncludeConst = true; 4503 bool TopLevel = true; 4504 do { 4505 if (T1 == T2) 4506 break; 4507 4508 // We will need a qualification conversion. 4509 Conv |= ReferenceConversions::Qualification; 4510 4511 // Track whether we performed a qualification conversion anywhere other 4512 // than the top level. This matters for ranking reference bindings in 4513 // overload resolution. 4514 if (!TopLevel) 4515 Conv |= ReferenceConversions::NestedQualification; 4516 4517 // MS compiler ignores __unaligned qualifier for references; do the same. 4518 T1 = withoutUnaligned(Context, T1); 4519 T2 = withoutUnaligned(Context, T2); 4520 4521 // If we find a qualifier mismatch, the types are not reference-compatible, 4522 // but are still be reference-related if they're similar. 4523 bool ObjCLifetimeConversion = false; 4524 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4525 PreviousToQualsIncludeConst, 4526 ObjCLifetimeConversion)) 4527 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4528 ? Ref_Related 4529 : Ref_Incompatible; 4530 4531 // FIXME: Should we track this for any level other than the first? 4532 if (ObjCLifetimeConversion) 4533 Conv |= ReferenceConversions::ObjCLifetime; 4534 4535 TopLevel = false; 4536 } while (Context.UnwrapSimilarTypes(T1, T2)); 4537 4538 // At this point, if the types are reference-related, we must either have the 4539 // same inner type (ignoring qualifiers), or must have already worked out how 4540 // to convert the referent. 4541 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4542 ? Ref_Compatible 4543 : Ref_Incompatible; 4544 } 4545 4546 /// Look for a user-defined conversion to a value reference-compatible 4547 /// with DeclType. Return true if something definite is found. 4548 static bool 4549 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4550 QualType DeclType, SourceLocation DeclLoc, 4551 Expr *Init, QualType T2, bool AllowRvalues, 4552 bool AllowExplicit) { 4553 assert(T2->isRecordType() && "Can only find conversions of record types."); 4554 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4555 4556 OverloadCandidateSet CandidateSet( 4557 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4558 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4559 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4560 NamedDecl *D = *I; 4561 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4562 if (isa<UsingShadowDecl>(D)) 4563 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4564 4565 FunctionTemplateDecl *ConvTemplate 4566 = dyn_cast<FunctionTemplateDecl>(D); 4567 CXXConversionDecl *Conv; 4568 if (ConvTemplate) 4569 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4570 else 4571 Conv = cast<CXXConversionDecl>(D); 4572 4573 if (AllowRvalues) { 4574 // If we are initializing an rvalue reference, don't permit conversion 4575 // functions that return lvalues. 4576 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4577 const ReferenceType *RefType 4578 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4579 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4580 continue; 4581 } 4582 4583 if (!ConvTemplate && 4584 S.CompareReferenceRelationship( 4585 DeclLoc, 4586 Conv->getConversionType() 4587 .getNonReferenceType() 4588 .getUnqualifiedType(), 4589 DeclType.getNonReferenceType().getUnqualifiedType()) == 4590 Sema::Ref_Incompatible) 4591 continue; 4592 } else { 4593 // If the conversion function doesn't return a reference type, 4594 // it can't be considered for this conversion. An rvalue reference 4595 // is only acceptable if its referencee is a function type. 4596 4597 const ReferenceType *RefType = 4598 Conv->getConversionType()->getAs<ReferenceType>(); 4599 if (!RefType || 4600 (!RefType->isLValueReferenceType() && 4601 !RefType->getPointeeType()->isFunctionType())) 4602 continue; 4603 } 4604 4605 if (ConvTemplate) 4606 S.AddTemplateConversionCandidate( 4607 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4608 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4609 else 4610 S.AddConversionCandidate( 4611 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4612 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4613 } 4614 4615 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4616 4617 OverloadCandidateSet::iterator Best; 4618 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4619 case OR_Success: 4620 // C++ [over.ics.ref]p1: 4621 // 4622 // [...] If the parameter binds directly to the result of 4623 // applying a conversion function to the argument 4624 // expression, the implicit conversion sequence is a 4625 // user-defined conversion sequence (13.3.3.1.2), with the 4626 // second standard conversion sequence either an identity 4627 // conversion or, if the conversion function returns an 4628 // entity of a type that is a derived class of the parameter 4629 // type, a derived-to-base Conversion. 4630 if (!Best->FinalConversion.DirectBinding) 4631 return false; 4632 4633 ICS.setUserDefined(); 4634 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4635 ICS.UserDefined.After = Best->FinalConversion; 4636 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4637 ICS.UserDefined.ConversionFunction = Best->Function; 4638 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4639 ICS.UserDefined.EllipsisConversion = false; 4640 assert(ICS.UserDefined.After.ReferenceBinding && 4641 ICS.UserDefined.After.DirectBinding && 4642 "Expected a direct reference binding!"); 4643 return true; 4644 4645 case OR_Ambiguous: 4646 ICS.setAmbiguous(); 4647 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4648 Cand != CandidateSet.end(); ++Cand) 4649 if (Cand->Best) 4650 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4651 return true; 4652 4653 case OR_No_Viable_Function: 4654 case OR_Deleted: 4655 // There was no suitable conversion, or we found a deleted 4656 // conversion; continue with other checks. 4657 return false; 4658 } 4659 4660 llvm_unreachable("Invalid OverloadResult!"); 4661 } 4662 4663 /// Compute an implicit conversion sequence for reference 4664 /// initialization. 4665 static ImplicitConversionSequence 4666 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4667 SourceLocation DeclLoc, 4668 bool SuppressUserConversions, 4669 bool AllowExplicit) { 4670 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4671 4672 // Most paths end in a failed conversion. 4673 ImplicitConversionSequence ICS; 4674 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4675 4676 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4677 QualType T2 = Init->getType(); 4678 4679 // If the initializer is the address of an overloaded function, try 4680 // to resolve the overloaded function. If all goes well, T2 is the 4681 // type of the resulting function. 4682 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4683 DeclAccessPair Found; 4684 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4685 false, Found)) 4686 T2 = Fn->getType(); 4687 } 4688 4689 // Compute some basic properties of the types and the initializer. 4690 bool isRValRef = DeclType->isRValueReferenceType(); 4691 Expr::Classification InitCategory = Init->Classify(S.Context); 4692 4693 Sema::ReferenceConversions RefConv; 4694 Sema::ReferenceCompareResult RefRelationship = 4695 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4696 4697 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4698 ICS.setStandard(); 4699 ICS.Standard.First = ICK_Identity; 4700 // FIXME: A reference binding can be a function conversion too. We should 4701 // consider that when ordering reference-to-function bindings. 4702 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4703 ? ICK_Derived_To_Base 4704 : (RefConv & Sema::ReferenceConversions::ObjC) 4705 ? ICK_Compatible_Conversion 4706 : ICK_Identity; 4707 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4708 // a reference binding that performs a non-top-level qualification 4709 // conversion as a qualification conversion, not as an identity conversion. 4710 ICS.Standard.Third = (RefConv & 4711 Sema::ReferenceConversions::NestedQualification) 4712 ? ICK_Qualification 4713 : ICK_Identity; 4714 ICS.Standard.setFromType(T2); 4715 ICS.Standard.setToType(0, T2); 4716 ICS.Standard.setToType(1, T1); 4717 ICS.Standard.setToType(2, T1); 4718 ICS.Standard.ReferenceBinding = true; 4719 ICS.Standard.DirectBinding = BindsDirectly; 4720 ICS.Standard.IsLvalueReference = !isRValRef; 4721 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4722 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4723 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4724 ICS.Standard.ObjCLifetimeConversionBinding = 4725 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4726 ICS.Standard.CopyConstructor = nullptr; 4727 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4728 }; 4729 4730 // C++0x [dcl.init.ref]p5: 4731 // A reference to type "cv1 T1" is initialized by an expression 4732 // of type "cv2 T2" as follows: 4733 4734 // -- If reference is an lvalue reference and the initializer expression 4735 if (!isRValRef) { 4736 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4737 // reference-compatible with "cv2 T2," or 4738 // 4739 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4740 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4741 // C++ [over.ics.ref]p1: 4742 // When a parameter of reference type binds directly (8.5.3) 4743 // to an argument expression, the implicit conversion sequence 4744 // is the identity conversion, unless the argument expression 4745 // has a type that is a derived class of the parameter type, 4746 // in which case the implicit conversion sequence is a 4747 // derived-to-base Conversion (13.3.3.1). 4748 SetAsReferenceBinding(/*BindsDirectly=*/true); 4749 4750 // Nothing more to do: the inaccessibility/ambiguity check for 4751 // derived-to-base conversions is suppressed when we're 4752 // computing the implicit conversion sequence (C++ 4753 // [over.best.ics]p2). 4754 return ICS; 4755 } 4756 4757 // -- has a class type (i.e., T2 is a class type), where T1 is 4758 // not reference-related to T2, and can be implicitly 4759 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4760 // is reference-compatible with "cv3 T3" 92) (this 4761 // conversion is selected by enumerating the applicable 4762 // conversion functions (13.3.1.6) and choosing the best 4763 // one through overload resolution (13.3)), 4764 if (!SuppressUserConversions && T2->isRecordType() && 4765 S.isCompleteType(DeclLoc, T2) && 4766 RefRelationship == Sema::Ref_Incompatible) { 4767 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4768 Init, T2, /*AllowRvalues=*/false, 4769 AllowExplicit)) 4770 return ICS; 4771 } 4772 } 4773 4774 // -- Otherwise, the reference shall be an lvalue reference to a 4775 // non-volatile const type (i.e., cv1 shall be const), or the reference 4776 // shall be an rvalue reference. 4777 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4778 return ICS; 4779 4780 // -- If the initializer expression 4781 // 4782 // -- is an xvalue, class prvalue, array prvalue or function 4783 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4784 if (RefRelationship == Sema::Ref_Compatible && 4785 (InitCategory.isXValue() || 4786 (InitCategory.isPRValue() && 4787 (T2->isRecordType() || T2->isArrayType())) || 4788 (InitCategory.isLValue() && T2->isFunctionType()))) { 4789 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4790 // binding unless we're binding to a class prvalue. 4791 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4792 // allow the use of rvalue references in C++98/03 for the benefit of 4793 // standard library implementors; therefore, we need the xvalue check here. 4794 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4795 !(InitCategory.isPRValue() || T2->isRecordType())); 4796 return ICS; 4797 } 4798 4799 // -- has a class type (i.e., T2 is a class type), where T1 is not 4800 // reference-related to T2, and can be implicitly converted to 4801 // an xvalue, class prvalue, or function lvalue of type 4802 // "cv3 T3", where "cv1 T1" is reference-compatible with 4803 // "cv3 T3", 4804 // 4805 // then the reference is bound to the value of the initializer 4806 // expression in the first case and to the result of the conversion 4807 // in the second case (or, in either case, to an appropriate base 4808 // class subobject). 4809 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4810 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4811 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4812 Init, T2, /*AllowRvalues=*/true, 4813 AllowExplicit)) { 4814 // In the second case, if the reference is an rvalue reference 4815 // and the second standard conversion sequence of the 4816 // user-defined conversion sequence includes an lvalue-to-rvalue 4817 // conversion, the program is ill-formed. 4818 if (ICS.isUserDefined() && isRValRef && 4819 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4820 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4821 4822 return ICS; 4823 } 4824 4825 // A temporary of function type cannot be created; don't even try. 4826 if (T1->isFunctionType()) 4827 return ICS; 4828 4829 // -- Otherwise, a temporary of type "cv1 T1" is created and 4830 // initialized from the initializer expression using the 4831 // rules for a non-reference copy initialization (8.5). The 4832 // reference is then bound to the temporary. If T1 is 4833 // reference-related to T2, cv1 must be the same 4834 // cv-qualification as, or greater cv-qualification than, 4835 // cv2; otherwise, the program is ill-formed. 4836 if (RefRelationship == Sema::Ref_Related) { 4837 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4838 // we would be reference-compatible or reference-compatible with 4839 // added qualification. But that wasn't the case, so the reference 4840 // initialization fails. 4841 // 4842 // Note that we only want to check address spaces and cvr-qualifiers here. 4843 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4844 Qualifiers T1Quals = T1.getQualifiers(); 4845 Qualifiers T2Quals = T2.getQualifiers(); 4846 T1Quals.removeObjCGCAttr(); 4847 T1Quals.removeObjCLifetime(); 4848 T2Quals.removeObjCGCAttr(); 4849 T2Quals.removeObjCLifetime(); 4850 // MS compiler ignores __unaligned qualifier for references; do the same. 4851 T1Quals.removeUnaligned(); 4852 T2Quals.removeUnaligned(); 4853 if (!T1Quals.compatiblyIncludes(T2Quals)) 4854 return ICS; 4855 } 4856 4857 // If at least one of the types is a class type, the types are not 4858 // related, and we aren't allowed any user conversions, the 4859 // reference binding fails. This case is important for breaking 4860 // recursion, since TryImplicitConversion below will attempt to 4861 // create a temporary through the use of a copy constructor. 4862 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4863 (T1->isRecordType() || T2->isRecordType())) 4864 return ICS; 4865 4866 // If T1 is reference-related to T2 and the reference is an rvalue 4867 // reference, the initializer expression shall not be an lvalue. 4868 if (RefRelationship >= Sema::Ref_Related && 4869 isRValRef && Init->Classify(S.Context).isLValue()) 4870 return ICS; 4871 4872 // C++ [over.ics.ref]p2: 4873 // When a parameter of reference type is not bound directly to 4874 // an argument expression, the conversion sequence is the one 4875 // required to convert the argument expression to the 4876 // underlying type of the reference according to 4877 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4878 // to copy-initializing a temporary of the underlying type with 4879 // the argument expression. Any difference in top-level 4880 // cv-qualification is subsumed by the initialization itself 4881 // and does not constitute a conversion. 4882 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4883 AllowedExplicit::None, 4884 /*InOverloadResolution=*/false, 4885 /*CStyle=*/false, 4886 /*AllowObjCWritebackConversion=*/false, 4887 /*AllowObjCConversionOnExplicit=*/false); 4888 4889 // Of course, that's still a reference binding. 4890 if (ICS.isStandard()) { 4891 ICS.Standard.ReferenceBinding = true; 4892 ICS.Standard.IsLvalueReference = !isRValRef; 4893 ICS.Standard.BindsToFunctionLvalue = false; 4894 ICS.Standard.BindsToRvalue = true; 4895 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4896 ICS.Standard.ObjCLifetimeConversionBinding = false; 4897 } else if (ICS.isUserDefined()) { 4898 const ReferenceType *LValRefType = 4899 ICS.UserDefined.ConversionFunction->getReturnType() 4900 ->getAs<LValueReferenceType>(); 4901 4902 // C++ [over.ics.ref]p3: 4903 // Except for an implicit object parameter, for which see 13.3.1, a 4904 // standard conversion sequence cannot be formed if it requires [...] 4905 // binding an rvalue reference to an lvalue other than a function 4906 // lvalue. 4907 // Note that the function case is not possible here. 4908 if (DeclType->isRValueReferenceType() && LValRefType) { 4909 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4910 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4911 // reference to an rvalue! 4912 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4913 return ICS; 4914 } 4915 4916 ICS.UserDefined.After.ReferenceBinding = true; 4917 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4918 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4919 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4920 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4921 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4922 } 4923 4924 return ICS; 4925 } 4926 4927 static ImplicitConversionSequence 4928 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4929 bool SuppressUserConversions, 4930 bool InOverloadResolution, 4931 bool AllowObjCWritebackConversion, 4932 bool AllowExplicit = false); 4933 4934 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4935 /// initializer list From. 4936 static ImplicitConversionSequence 4937 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4938 bool SuppressUserConversions, 4939 bool InOverloadResolution, 4940 bool AllowObjCWritebackConversion) { 4941 // C++11 [over.ics.list]p1: 4942 // When an argument is an initializer list, it is not an expression and 4943 // special rules apply for converting it to a parameter type. 4944 4945 ImplicitConversionSequence Result; 4946 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4947 4948 // We need a complete type for what follows. Incomplete types can never be 4949 // initialized from init lists. 4950 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4951 return Result; 4952 4953 // Per DR1467: 4954 // If the parameter type is a class X and the initializer list has a single 4955 // element of type cv U, where U is X or a class derived from X, the 4956 // implicit conversion sequence is the one required to convert the element 4957 // to the parameter type. 4958 // 4959 // Otherwise, if the parameter type is a character array [... ] 4960 // and the initializer list has a single element that is an 4961 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4962 // implicit conversion sequence is the identity conversion. 4963 if (From->getNumInits() == 1) { 4964 if (ToType->isRecordType()) { 4965 QualType InitType = From->getInit(0)->getType(); 4966 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4967 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4968 return TryCopyInitialization(S, From->getInit(0), ToType, 4969 SuppressUserConversions, 4970 InOverloadResolution, 4971 AllowObjCWritebackConversion); 4972 } 4973 // FIXME: Check the other conditions here: array of character type, 4974 // initializer is a string literal. 4975 if (ToType->isArrayType()) { 4976 InitializedEntity Entity = 4977 InitializedEntity::InitializeParameter(S.Context, ToType, 4978 /*Consumed=*/false); 4979 if (S.CanPerformCopyInitialization(Entity, From)) { 4980 Result.setStandard(); 4981 Result.Standard.setAsIdentityConversion(); 4982 Result.Standard.setFromType(ToType); 4983 Result.Standard.setAllToTypes(ToType); 4984 return Result; 4985 } 4986 } 4987 } 4988 4989 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4990 // C++11 [over.ics.list]p2: 4991 // If the parameter type is std::initializer_list<X> or "array of X" and 4992 // all the elements can be implicitly converted to X, the implicit 4993 // conversion sequence is the worst conversion necessary to convert an 4994 // element of the list to X. 4995 // 4996 // C++14 [over.ics.list]p3: 4997 // Otherwise, if the parameter type is "array of N X", if the initializer 4998 // list has exactly N elements or if it has fewer than N elements and X is 4999 // default-constructible, and if all the elements of the initializer list 5000 // can be implicitly converted to X, the implicit conversion sequence is 5001 // the worst conversion necessary to convert an element of the list to X. 5002 // 5003 // FIXME: We're missing a lot of these checks. 5004 bool toStdInitializerList = false; 5005 QualType X; 5006 if (ToType->isArrayType()) 5007 X = S.Context.getAsArrayType(ToType)->getElementType(); 5008 else 5009 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5010 if (!X.isNull()) { 5011 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5012 Expr *Init = From->getInit(i); 5013 ImplicitConversionSequence ICS = 5014 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5015 InOverloadResolution, 5016 AllowObjCWritebackConversion); 5017 // If a single element isn't convertible, fail. 5018 if (ICS.isBad()) { 5019 Result = ICS; 5020 break; 5021 } 5022 // Otherwise, look for the worst conversion. 5023 if (Result.isBad() || CompareImplicitConversionSequences( 5024 S, From->getBeginLoc(), ICS, Result) == 5025 ImplicitConversionSequence::Worse) 5026 Result = ICS; 5027 } 5028 5029 // For an empty list, we won't have computed any conversion sequence. 5030 // Introduce the identity conversion sequence. 5031 if (From->getNumInits() == 0) { 5032 Result.setStandard(); 5033 Result.Standard.setAsIdentityConversion(); 5034 Result.Standard.setFromType(ToType); 5035 Result.Standard.setAllToTypes(ToType); 5036 } 5037 5038 Result.setStdInitializerListElement(toStdInitializerList); 5039 return Result; 5040 } 5041 5042 // C++14 [over.ics.list]p4: 5043 // C++11 [over.ics.list]p3: 5044 // Otherwise, if the parameter is a non-aggregate class X and overload 5045 // resolution chooses a single best constructor [...] the implicit 5046 // conversion sequence is a user-defined conversion sequence. If multiple 5047 // constructors are viable but none is better than the others, the 5048 // implicit conversion sequence is a user-defined conversion sequence. 5049 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5050 // This function can deal with initializer lists. 5051 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5052 AllowedExplicit::None, 5053 InOverloadResolution, /*CStyle=*/false, 5054 AllowObjCWritebackConversion, 5055 /*AllowObjCConversionOnExplicit=*/false); 5056 } 5057 5058 // C++14 [over.ics.list]p5: 5059 // C++11 [over.ics.list]p4: 5060 // Otherwise, if the parameter has an aggregate type which can be 5061 // initialized from the initializer list [...] the implicit conversion 5062 // sequence is a user-defined conversion sequence. 5063 if (ToType->isAggregateType()) { 5064 // Type is an aggregate, argument is an init list. At this point it comes 5065 // down to checking whether the initialization works. 5066 // FIXME: Find out whether this parameter is consumed or not. 5067 InitializedEntity Entity = 5068 InitializedEntity::InitializeParameter(S.Context, ToType, 5069 /*Consumed=*/false); 5070 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5071 From)) { 5072 Result.setUserDefined(); 5073 Result.UserDefined.Before.setAsIdentityConversion(); 5074 // Initializer lists don't have a type. 5075 Result.UserDefined.Before.setFromType(QualType()); 5076 Result.UserDefined.Before.setAllToTypes(QualType()); 5077 5078 Result.UserDefined.After.setAsIdentityConversion(); 5079 Result.UserDefined.After.setFromType(ToType); 5080 Result.UserDefined.After.setAllToTypes(ToType); 5081 Result.UserDefined.ConversionFunction = nullptr; 5082 } 5083 return Result; 5084 } 5085 5086 // C++14 [over.ics.list]p6: 5087 // C++11 [over.ics.list]p5: 5088 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5089 if (ToType->isReferenceType()) { 5090 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5091 // mention initializer lists in any way. So we go by what list- 5092 // initialization would do and try to extrapolate from that. 5093 5094 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5095 5096 // If the initializer list has a single element that is reference-related 5097 // to the parameter type, we initialize the reference from that. 5098 if (From->getNumInits() == 1) { 5099 Expr *Init = From->getInit(0); 5100 5101 QualType T2 = Init->getType(); 5102 5103 // If the initializer is the address of an overloaded function, try 5104 // to resolve the overloaded function. If all goes well, T2 is the 5105 // type of the resulting function. 5106 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5107 DeclAccessPair Found; 5108 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5109 Init, ToType, false, Found)) 5110 T2 = Fn->getType(); 5111 } 5112 5113 // Compute some basic properties of the types and the initializer. 5114 Sema::ReferenceCompareResult RefRelationship = 5115 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5116 5117 if (RefRelationship >= Sema::Ref_Related) { 5118 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5119 SuppressUserConversions, 5120 /*AllowExplicit=*/false); 5121 } 5122 } 5123 5124 // Otherwise, we bind the reference to a temporary created from the 5125 // initializer list. 5126 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5127 InOverloadResolution, 5128 AllowObjCWritebackConversion); 5129 if (Result.isFailure()) 5130 return Result; 5131 assert(!Result.isEllipsis() && 5132 "Sub-initialization cannot result in ellipsis conversion."); 5133 5134 // Can we even bind to a temporary? 5135 if (ToType->isRValueReferenceType() || 5136 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5137 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5138 Result.UserDefined.After; 5139 SCS.ReferenceBinding = true; 5140 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5141 SCS.BindsToRvalue = true; 5142 SCS.BindsToFunctionLvalue = false; 5143 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5144 SCS.ObjCLifetimeConversionBinding = false; 5145 } else 5146 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5147 From, ToType); 5148 return Result; 5149 } 5150 5151 // C++14 [over.ics.list]p7: 5152 // C++11 [over.ics.list]p6: 5153 // Otherwise, if the parameter type is not a class: 5154 if (!ToType->isRecordType()) { 5155 // - if the initializer list has one element that is not itself an 5156 // initializer list, the implicit conversion sequence is the one 5157 // required to convert the element to the parameter type. 5158 unsigned NumInits = From->getNumInits(); 5159 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5160 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5161 SuppressUserConversions, 5162 InOverloadResolution, 5163 AllowObjCWritebackConversion); 5164 // - if the initializer list has no elements, the implicit conversion 5165 // sequence is the identity conversion. 5166 else if (NumInits == 0) { 5167 Result.setStandard(); 5168 Result.Standard.setAsIdentityConversion(); 5169 Result.Standard.setFromType(ToType); 5170 Result.Standard.setAllToTypes(ToType); 5171 } 5172 return Result; 5173 } 5174 5175 // C++14 [over.ics.list]p8: 5176 // C++11 [over.ics.list]p7: 5177 // In all cases other than those enumerated above, no conversion is possible 5178 return Result; 5179 } 5180 5181 /// TryCopyInitialization - Try to copy-initialize a value of type 5182 /// ToType from the expression From. Return the implicit conversion 5183 /// sequence required to pass this argument, which may be a bad 5184 /// conversion sequence (meaning that the argument cannot be passed to 5185 /// a parameter of this type). If @p SuppressUserConversions, then we 5186 /// do not permit any user-defined conversion sequences. 5187 static ImplicitConversionSequence 5188 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5189 bool SuppressUserConversions, 5190 bool InOverloadResolution, 5191 bool AllowObjCWritebackConversion, 5192 bool AllowExplicit) { 5193 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5194 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5195 InOverloadResolution,AllowObjCWritebackConversion); 5196 5197 if (ToType->isReferenceType()) 5198 return TryReferenceInit(S, From, ToType, 5199 /*FIXME:*/ From->getBeginLoc(), 5200 SuppressUserConversions, AllowExplicit); 5201 5202 return TryImplicitConversion(S, From, ToType, 5203 SuppressUserConversions, 5204 AllowedExplicit::None, 5205 InOverloadResolution, 5206 /*CStyle=*/false, 5207 AllowObjCWritebackConversion, 5208 /*AllowObjCConversionOnExplicit=*/false); 5209 } 5210 5211 static bool TryCopyInitialization(const CanQualType FromQTy, 5212 const CanQualType ToQTy, 5213 Sema &S, 5214 SourceLocation Loc, 5215 ExprValueKind FromVK) { 5216 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5217 ImplicitConversionSequence ICS = 5218 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5219 5220 return !ICS.isBad(); 5221 } 5222 5223 /// TryObjectArgumentInitialization - Try to initialize the object 5224 /// parameter of the given member function (@c Method) from the 5225 /// expression @p From. 5226 static ImplicitConversionSequence 5227 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5228 Expr::Classification FromClassification, 5229 CXXMethodDecl *Method, 5230 CXXRecordDecl *ActingContext) { 5231 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5232 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5233 // const volatile object. 5234 Qualifiers Quals = Method->getMethodQualifiers(); 5235 if (isa<CXXDestructorDecl>(Method)) { 5236 Quals.addConst(); 5237 Quals.addVolatile(); 5238 } 5239 5240 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5241 5242 // Set up the conversion sequence as a "bad" conversion, to allow us 5243 // to exit early. 5244 ImplicitConversionSequence ICS; 5245 5246 // We need to have an object of class type. 5247 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5248 FromType = PT->getPointeeType(); 5249 5250 // When we had a pointer, it's implicitly dereferenced, so we 5251 // better have an lvalue. 5252 assert(FromClassification.isLValue()); 5253 } 5254 5255 assert(FromType->isRecordType()); 5256 5257 // C++0x [over.match.funcs]p4: 5258 // For non-static member functions, the type of the implicit object 5259 // parameter is 5260 // 5261 // - "lvalue reference to cv X" for functions declared without a 5262 // ref-qualifier or with the & ref-qualifier 5263 // - "rvalue reference to cv X" for functions declared with the && 5264 // ref-qualifier 5265 // 5266 // where X is the class of which the function is a member and cv is the 5267 // cv-qualification on the member function declaration. 5268 // 5269 // However, when finding an implicit conversion sequence for the argument, we 5270 // are not allowed to perform user-defined conversions 5271 // (C++ [over.match.funcs]p5). We perform a simplified version of 5272 // reference binding here, that allows class rvalues to bind to 5273 // non-constant references. 5274 5275 // First check the qualifiers. 5276 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5277 if (ImplicitParamType.getCVRQualifiers() 5278 != FromTypeCanon.getLocalCVRQualifiers() && 5279 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5280 ICS.setBad(BadConversionSequence::bad_qualifiers, 5281 FromType, ImplicitParamType); 5282 return ICS; 5283 } 5284 5285 if (FromTypeCanon.hasAddressSpace()) { 5286 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5287 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5288 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5289 ICS.setBad(BadConversionSequence::bad_qualifiers, 5290 FromType, ImplicitParamType); 5291 return ICS; 5292 } 5293 } 5294 5295 // Check that we have either the same type or a derived type. It 5296 // affects the conversion rank. 5297 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5298 ImplicitConversionKind SecondKind; 5299 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5300 SecondKind = ICK_Identity; 5301 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5302 SecondKind = ICK_Derived_To_Base; 5303 else { 5304 ICS.setBad(BadConversionSequence::unrelated_class, 5305 FromType, ImplicitParamType); 5306 return ICS; 5307 } 5308 5309 // Check the ref-qualifier. 5310 switch (Method->getRefQualifier()) { 5311 case RQ_None: 5312 // Do nothing; we don't care about lvalueness or rvalueness. 5313 break; 5314 5315 case RQ_LValue: 5316 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5317 // non-const lvalue reference cannot bind to an rvalue 5318 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5319 ImplicitParamType); 5320 return ICS; 5321 } 5322 break; 5323 5324 case RQ_RValue: 5325 if (!FromClassification.isRValue()) { 5326 // rvalue reference cannot bind to an lvalue 5327 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5328 ImplicitParamType); 5329 return ICS; 5330 } 5331 break; 5332 } 5333 5334 // Success. Mark this as a reference binding. 5335 ICS.setStandard(); 5336 ICS.Standard.setAsIdentityConversion(); 5337 ICS.Standard.Second = SecondKind; 5338 ICS.Standard.setFromType(FromType); 5339 ICS.Standard.setAllToTypes(ImplicitParamType); 5340 ICS.Standard.ReferenceBinding = true; 5341 ICS.Standard.DirectBinding = true; 5342 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5343 ICS.Standard.BindsToFunctionLvalue = false; 5344 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5345 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5346 = (Method->getRefQualifier() == RQ_None); 5347 return ICS; 5348 } 5349 5350 /// PerformObjectArgumentInitialization - Perform initialization of 5351 /// the implicit object parameter for the given Method with the given 5352 /// expression. 5353 ExprResult 5354 Sema::PerformObjectArgumentInitialization(Expr *From, 5355 NestedNameSpecifier *Qualifier, 5356 NamedDecl *FoundDecl, 5357 CXXMethodDecl *Method) { 5358 QualType FromRecordType, DestType; 5359 QualType ImplicitParamRecordType = 5360 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5361 5362 Expr::Classification FromClassification; 5363 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5364 FromRecordType = PT->getPointeeType(); 5365 DestType = Method->getThisType(); 5366 FromClassification = Expr::Classification::makeSimpleLValue(); 5367 } else { 5368 FromRecordType = From->getType(); 5369 DestType = ImplicitParamRecordType; 5370 FromClassification = From->Classify(Context); 5371 5372 // When performing member access on an rvalue, materialize a temporary. 5373 if (From->isRValue()) { 5374 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5375 Method->getRefQualifier() != 5376 RefQualifierKind::RQ_RValue); 5377 } 5378 } 5379 5380 // Note that we always use the true parent context when performing 5381 // the actual argument initialization. 5382 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5383 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5384 Method->getParent()); 5385 if (ICS.isBad()) { 5386 switch (ICS.Bad.Kind) { 5387 case BadConversionSequence::bad_qualifiers: { 5388 Qualifiers FromQs = FromRecordType.getQualifiers(); 5389 Qualifiers ToQs = DestType.getQualifiers(); 5390 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5391 if (CVR) { 5392 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5393 << Method->getDeclName() << FromRecordType << (CVR - 1) 5394 << From->getSourceRange(); 5395 Diag(Method->getLocation(), diag::note_previous_decl) 5396 << Method->getDeclName(); 5397 return ExprError(); 5398 } 5399 break; 5400 } 5401 5402 case BadConversionSequence::lvalue_ref_to_rvalue: 5403 case BadConversionSequence::rvalue_ref_to_lvalue: { 5404 bool IsRValueQualified = 5405 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5406 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5407 << Method->getDeclName() << FromClassification.isRValue() 5408 << IsRValueQualified; 5409 Diag(Method->getLocation(), diag::note_previous_decl) 5410 << Method->getDeclName(); 5411 return ExprError(); 5412 } 5413 5414 case BadConversionSequence::no_conversion: 5415 case BadConversionSequence::unrelated_class: 5416 break; 5417 } 5418 5419 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5420 << ImplicitParamRecordType << FromRecordType 5421 << From->getSourceRange(); 5422 } 5423 5424 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5425 ExprResult FromRes = 5426 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5427 if (FromRes.isInvalid()) 5428 return ExprError(); 5429 From = FromRes.get(); 5430 } 5431 5432 if (!Context.hasSameType(From->getType(), DestType)) { 5433 CastKind CK; 5434 QualType PteeTy = DestType->getPointeeType(); 5435 LangAS DestAS = 5436 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5437 if (FromRecordType.getAddressSpace() != DestAS) 5438 CK = CK_AddressSpaceConversion; 5439 else 5440 CK = CK_NoOp; 5441 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5442 } 5443 return From; 5444 } 5445 5446 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5447 /// expression From to bool (C++0x [conv]p3). 5448 static ImplicitConversionSequence 5449 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5450 // C++ [dcl.init]/17.8: 5451 // - Otherwise, if the initialization is direct-initialization, the source 5452 // type is std::nullptr_t, and the destination type is bool, the initial 5453 // value of the object being initialized is false. 5454 if (From->getType()->isNullPtrType()) 5455 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5456 S.Context.BoolTy, 5457 From->isGLValue()); 5458 5459 // All other direct-initialization of bool is equivalent to an implicit 5460 // conversion to bool in which explicit conversions are permitted. 5461 return TryImplicitConversion(S, From, S.Context.BoolTy, 5462 /*SuppressUserConversions=*/false, 5463 AllowedExplicit::Conversions, 5464 /*InOverloadResolution=*/false, 5465 /*CStyle=*/false, 5466 /*AllowObjCWritebackConversion=*/false, 5467 /*AllowObjCConversionOnExplicit=*/false); 5468 } 5469 5470 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5471 /// of the expression From to bool (C++0x [conv]p3). 5472 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5473 if (checkPlaceholderForOverload(*this, From)) 5474 return ExprError(); 5475 5476 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5477 if (!ICS.isBad()) 5478 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5479 5480 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5481 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5482 << From->getType() << From->getSourceRange(); 5483 return ExprError(); 5484 } 5485 5486 /// Check that the specified conversion is permitted in a converted constant 5487 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5488 /// is acceptable. 5489 static bool CheckConvertedConstantConversions(Sema &S, 5490 StandardConversionSequence &SCS) { 5491 // Since we know that the target type is an integral or unscoped enumeration 5492 // type, most conversion kinds are impossible. All possible First and Third 5493 // conversions are fine. 5494 switch (SCS.Second) { 5495 case ICK_Identity: 5496 case ICK_Function_Conversion: 5497 case ICK_Integral_Promotion: 5498 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5499 case ICK_Zero_Queue_Conversion: 5500 return true; 5501 5502 case ICK_Boolean_Conversion: 5503 // Conversion from an integral or unscoped enumeration type to bool is 5504 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5505 // conversion, so we allow it in a converted constant expression. 5506 // 5507 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5508 // a lot of popular code. We should at least add a warning for this 5509 // (non-conforming) extension. 5510 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5511 SCS.getToType(2)->isBooleanType(); 5512 5513 case ICK_Pointer_Conversion: 5514 case ICK_Pointer_Member: 5515 // C++1z: null pointer conversions and null member pointer conversions are 5516 // only permitted if the source type is std::nullptr_t. 5517 return SCS.getFromType()->isNullPtrType(); 5518 5519 case ICK_Floating_Promotion: 5520 case ICK_Complex_Promotion: 5521 case ICK_Floating_Conversion: 5522 case ICK_Complex_Conversion: 5523 case ICK_Floating_Integral: 5524 case ICK_Compatible_Conversion: 5525 case ICK_Derived_To_Base: 5526 case ICK_Vector_Conversion: 5527 case ICK_Vector_Splat: 5528 case ICK_Complex_Real: 5529 case ICK_Block_Pointer_Conversion: 5530 case ICK_TransparentUnionConversion: 5531 case ICK_Writeback_Conversion: 5532 case ICK_Zero_Event_Conversion: 5533 case ICK_C_Only_Conversion: 5534 case ICK_Incompatible_Pointer_Conversion: 5535 return false; 5536 5537 case ICK_Lvalue_To_Rvalue: 5538 case ICK_Array_To_Pointer: 5539 case ICK_Function_To_Pointer: 5540 llvm_unreachable("found a first conversion kind in Second"); 5541 5542 case ICK_Qualification: 5543 llvm_unreachable("found a third conversion kind in Second"); 5544 5545 case ICK_Num_Conversion_Kinds: 5546 break; 5547 } 5548 5549 llvm_unreachable("unknown conversion kind"); 5550 } 5551 5552 /// CheckConvertedConstantExpression - Check that the expression From is a 5553 /// converted constant expression of type T, perform the conversion and produce 5554 /// the converted expression, per C++11 [expr.const]p3. 5555 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5556 QualType T, APValue &Value, 5557 Sema::CCEKind CCE, 5558 bool RequireInt) { 5559 assert(S.getLangOpts().CPlusPlus11 && 5560 "converted constant expression outside C++11"); 5561 5562 if (checkPlaceholderForOverload(S, From)) 5563 return ExprError(); 5564 5565 // C++1z [expr.const]p3: 5566 // A converted constant expression of type T is an expression, 5567 // implicitly converted to type T, where the converted 5568 // expression is a constant expression and the implicit conversion 5569 // sequence contains only [... list of conversions ...]. 5570 // C++1z [stmt.if]p2: 5571 // If the if statement is of the form if constexpr, the value of the 5572 // condition shall be a contextually converted constant expression of type 5573 // bool. 5574 ImplicitConversionSequence ICS = 5575 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5576 ? TryContextuallyConvertToBool(S, From) 5577 : TryCopyInitialization(S, From, T, 5578 /*SuppressUserConversions=*/false, 5579 /*InOverloadResolution=*/false, 5580 /*AllowObjCWritebackConversion=*/false, 5581 /*AllowExplicit=*/false); 5582 StandardConversionSequence *SCS = nullptr; 5583 switch (ICS.getKind()) { 5584 case ImplicitConversionSequence::StandardConversion: 5585 SCS = &ICS.Standard; 5586 break; 5587 case ImplicitConversionSequence::UserDefinedConversion: 5588 // We are converting to a non-class type, so the Before sequence 5589 // must be trivial. 5590 SCS = &ICS.UserDefined.After; 5591 break; 5592 case ImplicitConversionSequence::AmbiguousConversion: 5593 case ImplicitConversionSequence::BadConversion: 5594 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5595 return S.Diag(From->getBeginLoc(), 5596 diag::err_typecheck_converted_constant_expression) 5597 << From->getType() << From->getSourceRange() << T; 5598 return ExprError(); 5599 5600 case ImplicitConversionSequence::EllipsisConversion: 5601 llvm_unreachable("ellipsis conversion in converted constant expression"); 5602 } 5603 5604 // Check that we would only use permitted conversions. 5605 if (!CheckConvertedConstantConversions(S, *SCS)) { 5606 return S.Diag(From->getBeginLoc(), 5607 diag::err_typecheck_converted_constant_expression_disallowed) 5608 << From->getType() << From->getSourceRange() << T; 5609 } 5610 // [...] and where the reference binding (if any) binds directly. 5611 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5612 return S.Diag(From->getBeginLoc(), 5613 diag::err_typecheck_converted_constant_expression_indirect) 5614 << From->getType() << From->getSourceRange() << T; 5615 } 5616 5617 ExprResult Result = 5618 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5619 if (Result.isInvalid()) 5620 return Result; 5621 5622 // C++2a [intro.execution]p5: 5623 // A full-expression is [...] a constant-expression [...] 5624 Result = 5625 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5626 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5627 if (Result.isInvalid()) 5628 return Result; 5629 5630 // Check for a narrowing implicit conversion. 5631 bool ReturnPreNarrowingValue = false; 5632 APValue PreNarrowingValue; 5633 QualType PreNarrowingType; 5634 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5635 PreNarrowingType)) { 5636 case NK_Dependent_Narrowing: 5637 // Implicit conversion to a narrower type, but the expression is 5638 // value-dependent so we can't tell whether it's actually narrowing. 5639 case NK_Variable_Narrowing: 5640 // Implicit conversion to a narrower type, and the value is not a constant 5641 // expression. We'll diagnose this in a moment. 5642 case NK_Not_Narrowing: 5643 break; 5644 5645 case NK_Constant_Narrowing: 5646 if (CCE == Sema::CCEK_ArrayBound && 5647 PreNarrowingType->isIntegralOrEnumerationType() && 5648 PreNarrowingValue.isInt()) { 5649 // Don't diagnose array bound narrowing here; we produce more precise 5650 // errors by allowing the un-narrowed value through. 5651 ReturnPreNarrowingValue = true; 5652 break; 5653 } 5654 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5655 << CCE << /*Constant*/ 1 5656 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5657 break; 5658 5659 case NK_Type_Narrowing: 5660 // FIXME: It would be better to diagnose that the expression is not a 5661 // constant expression. 5662 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5663 << CCE << /*Constant*/ 0 << From->getType() << T; 5664 break; 5665 } 5666 5667 if (Result.get()->isValueDependent()) { 5668 Value = APValue(); 5669 return Result; 5670 } 5671 5672 // Check the expression is a constant expression. 5673 SmallVector<PartialDiagnosticAt, 8> Notes; 5674 Expr::EvalResult Eval; 5675 Eval.Diag = &Notes; 5676 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5677 ? Expr::EvaluateForMangling 5678 : Expr::EvaluateForCodeGen; 5679 5680 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5681 (RequireInt && !Eval.Val.isInt())) { 5682 // The expression can't be folded, so we can't keep it at this position in 5683 // the AST. 5684 Result = ExprError(); 5685 } else { 5686 Value = Eval.Val; 5687 5688 if (Notes.empty()) { 5689 // It's a constant expression. 5690 Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value); 5691 if (ReturnPreNarrowingValue) 5692 Value = std::move(PreNarrowingValue); 5693 return E; 5694 } 5695 } 5696 5697 // It's not a constant expression. Produce an appropriate diagnostic. 5698 if (Notes.size() == 1 && 5699 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5700 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5701 else { 5702 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5703 << CCE << From->getSourceRange(); 5704 for (unsigned I = 0; I < Notes.size(); ++I) 5705 S.Diag(Notes[I].first, Notes[I].second); 5706 } 5707 return ExprError(); 5708 } 5709 5710 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5711 APValue &Value, CCEKind CCE) { 5712 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5713 } 5714 5715 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5716 llvm::APSInt &Value, 5717 CCEKind CCE) { 5718 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5719 5720 APValue V; 5721 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5722 if (!R.isInvalid() && !R.get()->isValueDependent()) 5723 Value = V.getInt(); 5724 return R; 5725 } 5726 5727 5728 /// dropPointerConversions - If the given standard conversion sequence 5729 /// involves any pointer conversions, remove them. This may change 5730 /// the result type of the conversion sequence. 5731 static void dropPointerConversion(StandardConversionSequence &SCS) { 5732 if (SCS.Second == ICK_Pointer_Conversion) { 5733 SCS.Second = ICK_Identity; 5734 SCS.Third = ICK_Identity; 5735 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5736 } 5737 } 5738 5739 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5740 /// convert the expression From to an Objective-C pointer type. 5741 static ImplicitConversionSequence 5742 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5743 // Do an implicit conversion to 'id'. 5744 QualType Ty = S.Context.getObjCIdType(); 5745 ImplicitConversionSequence ICS 5746 = TryImplicitConversion(S, From, Ty, 5747 // FIXME: Are these flags correct? 5748 /*SuppressUserConversions=*/false, 5749 AllowedExplicit::Conversions, 5750 /*InOverloadResolution=*/false, 5751 /*CStyle=*/false, 5752 /*AllowObjCWritebackConversion=*/false, 5753 /*AllowObjCConversionOnExplicit=*/true); 5754 5755 // Strip off any final conversions to 'id'. 5756 switch (ICS.getKind()) { 5757 case ImplicitConversionSequence::BadConversion: 5758 case ImplicitConversionSequence::AmbiguousConversion: 5759 case ImplicitConversionSequence::EllipsisConversion: 5760 break; 5761 5762 case ImplicitConversionSequence::UserDefinedConversion: 5763 dropPointerConversion(ICS.UserDefined.After); 5764 break; 5765 5766 case ImplicitConversionSequence::StandardConversion: 5767 dropPointerConversion(ICS.Standard); 5768 break; 5769 } 5770 5771 return ICS; 5772 } 5773 5774 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5775 /// conversion of the expression From to an Objective-C pointer type. 5776 /// Returns a valid but null ExprResult if no conversion sequence exists. 5777 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5778 if (checkPlaceholderForOverload(*this, From)) 5779 return ExprError(); 5780 5781 QualType Ty = Context.getObjCIdType(); 5782 ImplicitConversionSequence ICS = 5783 TryContextuallyConvertToObjCPointer(*this, From); 5784 if (!ICS.isBad()) 5785 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5786 return ExprResult(); 5787 } 5788 5789 /// Determine whether the provided type is an integral type, or an enumeration 5790 /// type of a permitted flavor. 5791 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5792 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5793 : T->isIntegralOrUnscopedEnumerationType(); 5794 } 5795 5796 static ExprResult 5797 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5798 Sema::ContextualImplicitConverter &Converter, 5799 QualType T, UnresolvedSetImpl &ViableConversions) { 5800 5801 if (Converter.Suppress) 5802 return ExprError(); 5803 5804 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5805 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5806 CXXConversionDecl *Conv = 5807 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5808 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5809 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5810 } 5811 return From; 5812 } 5813 5814 static bool 5815 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5816 Sema::ContextualImplicitConverter &Converter, 5817 QualType T, bool HadMultipleCandidates, 5818 UnresolvedSetImpl &ExplicitConversions) { 5819 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5820 DeclAccessPair Found = ExplicitConversions[0]; 5821 CXXConversionDecl *Conversion = 5822 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5823 5824 // The user probably meant to invoke the given explicit 5825 // conversion; use it. 5826 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5827 std::string TypeStr; 5828 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5829 5830 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5831 << FixItHint::CreateInsertion(From->getBeginLoc(), 5832 "static_cast<" + TypeStr + ">(") 5833 << FixItHint::CreateInsertion( 5834 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5835 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5836 5837 // If we aren't in a SFINAE context, build a call to the 5838 // explicit conversion function. 5839 if (SemaRef.isSFINAEContext()) 5840 return true; 5841 5842 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5843 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5844 HadMultipleCandidates); 5845 if (Result.isInvalid()) 5846 return true; 5847 // Record usage of conversion in an implicit cast. 5848 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5849 CK_UserDefinedConversion, Result.get(), 5850 nullptr, Result.get()->getValueKind()); 5851 } 5852 return false; 5853 } 5854 5855 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5856 Sema::ContextualImplicitConverter &Converter, 5857 QualType T, bool HadMultipleCandidates, 5858 DeclAccessPair &Found) { 5859 CXXConversionDecl *Conversion = 5860 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5861 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5862 5863 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5864 if (!Converter.SuppressConversion) { 5865 if (SemaRef.isSFINAEContext()) 5866 return true; 5867 5868 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5869 << From->getSourceRange(); 5870 } 5871 5872 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5873 HadMultipleCandidates); 5874 if (Result.isInvalid()) 5875 return true; 5876 // Record usage of conversion in an implicit cast. 5877 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5878 CK_UserDefinedConversion, Result.get(), 5879 nullptr, Result.get()->getValueKind()); 5880 return false; 5881 } 5882 5883 static ExprResult finishContextualImplicitConversion( 5884 Sema &SemaRef, SourceLocation Loc, Expr *From, 5885 Sema::ContextualImplicitConverter &Converter) { 5886 if (!Converter.match(From->getType()) && !Converter.Suppress) 5887 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5888 << From->getSourceRange(); 5889 5890 return SemaRef.DefaultLvalueConversion(From); 5891 } 5892 5893 static void 5894 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5895 UnresolvedSetImpl &ViableConversions, 5896 OverloadCandidateSet &CandidateSet) { 5897 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5898 DeclAccessPair FoundDecl = ViableConversions[I]; 5899 NamedDecl *D = FoundDecl.getDecl(); 5900 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5901 if (isa<UsingShadowDecl>(D)) 5902 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5903 5904 CXXConversionDecl *Conv; 5905 FunctionTemplateDecl *ConvTemplate; 5906 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5907 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5908 else 5909 Conv = cast<CXXConversionDecl>(D); 5910 5911 if (ConvTemplate) 5912 SemaRef.AddTemplateConversionCandidate( 5913 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5914 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5915 else 5916 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5917 ToType, CandidateSet, 5918 /*AllowObjCConversionOnExplicit=*/false, 5919 /*AllowExplicit*/ true); 5920 } 5921 } 5922 5923 /// Attempt to convert the given expression to a type which is accepted 5924 /// by the given converter. 5925 /// 5926 /// This routine will attempt to convert an expression of class type to a 5927 /// type accepted by the specified converter. In C++11 and before, the class 5928 /// must have a single non-explicit conversion function converting to a matching 5929 /// type. In C++1y, there can be multiple such conversion functions, but only 5930 /// one target type. 5931 /// 5932 /// \param Loc The source location of the construct that requires the 5933 /// conversion. 5934 /// 5935 /// \param From The expression we're converting from. 5936 /// 5937 /// \param Converter Used to control and diagnose the conversion process. 5938 /// 5939 /// \returns The expression, converted to an integral or enumeration type if 5940 /// successful. 5941 ExprResult Sema::PerformContextualImplicitConversion( 5942 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5943 // We can't perform any more checking for type-dependent expressions. 5944 if (From->isTypeDependent()) 5945 return From; 5946 5947 // Process placeholders immediately. 5948 if (From->hasPlaceholderType()) { 5949 ExprResult result = CheckPlaceholderExpr(From); 5950 if (result.isInvalid()) 5951 return result; 5952 From = result.get(); 5953 } 5954 5955 // If the expression already has a matching type, we're golden. 5956 QualType T = From->getType(); 5957 if (Converter.match(T)) 5958 return DefaultLvalueConversion(From); 5959 5960 // FIXME: Check for missing '()' if T is a function type? 5961 5962 // We can only perform contextual implicit conversions on objects of class 5963 // type. 5964 const RecordType *RecordTy = T->getAs<RecordType>(); 5965 if (!RecordTy || !getLangOpts().CPlusPlus) { 5966 if (!Converter.Suppress) 5967 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5968 return From; 5969 } 5970 5971 // We must have a complete class type. 5972 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5973 ContextualImplicitConverter &Converter; 5974 Expr *From; 5975 5976 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5977 : Converter(Converter), From(From) {} 5978 5979 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5980 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5981 } 5982 } IncompleteDiagnoser(Converter, From); 5983 5984 if (Converter.Suppress ? !isCompleteType(Loc, T) 5985 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5986 return From; 5987 5988 // Look for a conversion to an integral or enumeration type. 5989 UnresolvedSet<4> 5990 ViableConversions; // These are *potentially* viable in C++1y. 5991 UnresolvedSet<4> ExplicitConversions; 5992 const auto &Conversions = 5993 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5994 5995 bool HadMultipleCandidates = 5996 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5997 5998 // To check that there is only one target type, in C++1y: 5999 QualType ToType; 6000 bool HasUniqueTargetType = true; 6001 6002 // Collect explicit or viable (potentially in C++1y) conversions. 6003 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 6004 NamedDecl *D = (*I)->getUnderlyingDecl(); 6005 CXXConversionDecl *Conversion; 6006 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 6007 if (ConvTemplate) { 6008 if (getLangOpts().CPlusPlus14) 6009 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 6010 else 6011 continue; // C++11 does not consider conversion operator templates(?). 6012 } else 6013 Conversion = cast<CXXConversionDecl>(D); 6014 6015 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 6016 "Conversion operator templates are considered potentially " 6017 "viable in C++1y"); 6018 6019 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 6020 if (Converter.match(CurToType) || ConvTemplate) { 6021 6022 if (Conversion->isExplicit()) { 6023 // FIXME: For C++1y, do we need this restriction? 6024 // cf. diagnoseNoViableConversion() 6025 if (!ConvTemplate) 6026 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6027 } else { 6028 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6029 if (ToType.isNull()) 6030 ToType = CurToType.getUnqualifiedType(); 6031 else if (HasUniqueTargetType && 6032 (CurToType.getUnqualifiedType() != ToType)) 6033 HasUniqueTargetType = false; 6034 } 6035 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6036 } 6037 } 6038 } 6039 6040 if (getLangOpts().CPlusPlus14) { 6041 // C++1y [conv]p6: 6042 // ... An expression e of class type E appearing in such a context 6043 // is said to be contextually implicitly converted to a specified 6044 // type T and is well-formed if and only if e can be implicitly 6045 // converted to a type T that is determined as follows: E is searched 6046 // for conversion functions whose return type is cv T or reference to 6047 // cv T such that T is allowed by the context. There shall be 6048 // exactly one such T. 6049 6050 // If no unique T is found: 6051 if (ToType.isNull()) { 6052 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6053 HadMultipleCandidates, 6054 ExplicitConversions)) 6055 return ExprError(); 6056 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6057 } 6058 6059 // If more than one unique Ts are found: 6060 if (!HasUniqueTargetType) 6061 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6062 ViableConversions); 6063 6064 // If one unique T is found: 6065 // First, build a candidate set from the previously recorded 6066 // potentially viable conversions. 6067 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6068 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6069 CandidateSet); 6070 6071 // Then, perform overload resolution over the candidate set. 6072 OverloadCandidateSet::iterator Best; 6073 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6074 case OR_Success: { 6075 // Apply this conversion. 6076 DeclAccessPair Found = 6077 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6078 if (recordConversion(*this, Loc, From, Converter, T, 6079 HadMultipleCandidates, Found)) 6080 return ExprError(); 6081 break; 6082 } 6083 case OR_Ambiguous: 6084 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6085 ViableConversions); 6086 case OR_No_Viable_Function: 6087 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6088 HadMultipleCandidates, 6089 ExplicitConversions)) 6090 return ExprError(); 6091 LLVM_FALLTHROUGH; 6092 case OR_Deleted: 6093 // We'll complain below about a non-integral condition type. 6094 break; 6095 } 6096 } else { 6097 switch (ViableConversions.size()) { 6098 case 0: { 6099 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6100 HadMultipleCandidates, 6101 ExplicitConversions)) 6102 return ExprError(); 6103 6104 // We'll complain below about a non-integral condition type. 6105 break; 6106 } 6107 case 1: { 6108 // Apply this conversion. 6109 DeclAccessPair Found = ViableConversions[0]; 6110 if (recordConversion(*this, Loc, From, Converter, T, 6111 HadMultipleCandidates, Found)) 6112 return ExprError(); 6113 break; 6114 } 6115 default: 6116 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6117 ViableConversions); 6118 } 6119 } 6120 6121 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6122 } 6123 6124 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6125 /// an acceptable non-member overloaded operator for a call whose 6126 /// arguments have types T1 (and, if non-empty, T2). This routine 6127 /// implements the check in C++ [over.match.oper]p3b2 concerning 6128 /// enumeration types. 6129 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6130 FunctionDecl *Fn, 6131 ArrayRef<Expr *> Args) { 6132 QualType T1 = Args[0]->getType(); 6133 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6134 6135 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6136 return true; 6137 6138 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6139 return true; 6140 6141 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6142 if (Proto->getNumParams() < 1) 6143 return false; 6144 6145 if (T1->isEnumeralType()) { 6146 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6147 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6148 return true; 6149 } 6150 6151 if (Proto->getNumParams() < 2) 6152 return false; 6153 6154 if (!T2.isNull() && T2->isEnumeralType()) { 6155 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6156 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6157 return true; 6158 } 6159 6160 return false; 6161 } 6162 6163 /// AddOverloadCandidate - Adds the given function to the set of 6164 /// candidate functions, using the given function call arguments. If 6165 /// @p SuppressUserConversions, then don't allow user-defined 6166 /// conversions via constructors or conversion operators. 6167 /// 6168 /// \param PartialOverloading true if we are performing "partial" overloading 6169 /// based on an incomplete set of function arguments. This feature is used by 6170 /// code completion. 6171 void Sema::AddOverloadCandidate( 6172 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6173 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6174 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6175 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6176 OverloadCandidateParamOrder PO) { 6177 const FunctionProtoType *Proto 6178 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6179 assert(Proto && "Functions without a prototype cannot be overloaded"); 6180 assert(!Function->getDescribedFunctionTemplate() && 6181 "Use AddTemplateOverloadCandidate for function templates"); 6182 6183 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6184 if (!isa<CXXConstructorDecl>(Method)) { 6185 // If we get here, it's because we're calling a member function 6186 // that is named without a member access expression (e.g., 6187 // "this->f") that was either written explicitly or created 6188 // implicitly. This can happen with a qualified call to a member 6189 // function, e.g., X::f(). We use an empty type for the implied 6190 // object argument (C++ [over.call.func]p3), and the acting context 6191 // is irrelevant. 6192 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6193 Expr::Classification::makeSimpleLValue(), Args, 6194 CandidateSet, SuppressUserConversions, 6195 PartialOverloading, EarlyConversions, PO); 6196 return; 6197 } 6198 // We treat a constructor like a non-member function, since its object 6199 // argument doesn't participate in overload resolution. 6200 } 6201 6202 if (!CandidateSet.isNewCandidate(Function, PO)) 6203 return; 6204 6205 // C++11 [class.copy]p11: [DR1402] 6206 // A defaulted move constructor that is defined as deleted is ignored by 6207 // overload resolution. 6208 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6209 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6210 Constructor->isMoveConstructor()) 6211 return; 6212 6213 // Overload resolution is always an unevaluated context. 6214 EnterExpressionEvaluationContext Unevaluated( 6215 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6216 6217 // C++ [over.match.oper]p3: 6218 // if no operand has a class type, only those non-member functions in the 6219 // lookup set that have a first parameter of type T1 or "reference to 6220 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6221 // is a right operand) a second parameter of type T2 or "reference to 6222 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6223 // candidate functions. 6224 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6225 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6226 return; 6227 6228 // Add this candidate 6229 OverloadCandidate &Candidate = 6230 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6231 Candidate.FoundDecl = FoundDecl; 6232 Candidate.Function = Function; 6233 Candidate.Viable = true; 6234 Candidate.RewriteKind = 6235 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6236 Candidate.IsSurrogate = false; 6237 Candidate.IsADLCandidate = IsADLCandidate; 6238 Candidate.IgnoreObjectArgument = false; 6239 Candidate.ExplicitCallArguments = Args.size(); 6240 6241 // Explicit functions are not actually candidates at all if we're not 6242 // allowing them in this context, but keep them around so we can point 6243 // to them in diagnostics. 6244 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6245 Candidate.Viable = false; 6246 Candidate.FailureKind = ovl_fail_explicit; 6247 return; 6248 } 6249 6250 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6251 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6252 Candidate.Viable = false; 6253 Candidate.FailureKind = ovl_non_default_multiversion_function; 6254 return; 6255 } 6256 6257 if (Constructor) { 6258 // C++ [class.copy]p3: 6259 // A member function template is never instantiated to perform the copy 6260 // of a class object to an object of its class type. 6261 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6262 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6263 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6264 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6265 ClassType))) { 6266 Candidate.Viable = false; 6267 Candidate.FailureKind = ovl_fail_illegal_constructor; 6268 return; 6269 } 6270 6271 // C++ [over.match.funcs]p8: (proposed DR resolution) 6272 // A constructor inherited from class type C that has a first parameter 6273 // of type "reference to P" (including such a constructor instantiated 6274 // from a template) is excluded from the set of candidate functions when 6275 // constructing an object of type cv D if the argument list has exactly 6276 // one argument and D is reference-related to P and P is reference-related 6277 // to C. 6278 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6279 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6280 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6281 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6282 QualType C = Context.getRecordType(Constructor->getParent()); 6283 QualType D = Context.getRecordType(Shadow->getParent()); 6284 SourceLocation Loc = Args.front()->getExprLoc(); 6285 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6286 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6287 Candidate.Viable = false; 6288 Candidate.FailureKind = ovl_fail_inhctor_slice; 6289 return; 6290 } 6291 } 6292 6293 // Check that the constructor is capable of constructing an object in the 6294 // destination address space. 6295 if (!Qualifiers::isAddressSpaceSupersetOf( 6296 Constructor->getMethodQualifiers().getAddressSpace(), 6297 CandidateSet.getDestAS())) { 6298 Candidate.Viable = false; 6299 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6300 } 6301 } 6302 6303 unsigned NumParams = Proto->getNumParams(); 6304 6305 // (C++ 13.3.2p2): A candidate function having fewer than m 6306 // parameters is viable only if it has an ellipsis in its parameter 6307 // list (8.3.5). 6308 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6309 !Proto->isVariadic()) { 6310 Candidate.Viable = false; 6311 Candidate.FailureKind = ovl_fail_too_many_arguments; 6312 return; 6313 } 6314 6315 // (C++ 13.3.2p2): A candidate function having more than m parameters 6316 // is viable only if the (m+1)st parameter has a default argument 6317 // (8.3.6). For the purposes of overload resolution, the 6318 // parameter list is truncated on the right, so that there are 6319 // exactly m parameters. 6320 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6321 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6322 // Not enough arguments. 6323 Candidate.Viable = false; 6324 Candidate.FailureKind = ovl_fail_too_few_arguments; 6325 return; 6326 } 6327 6328 // (CUDA B.1): Check for invalid calls between targets. 6329 if (getLangOpts().CUDA) 6330 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6331 // Skip the check for callers that are implicit members, because in this 6332 // case we may not yet know what the member's target is; the target is 6333 // inferred for the member automatically, based on the bases and fields of 6334 // the class. 6335 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6336 Candidate.Viable = false; 6337 Candidate.FailureKind = ovl_fail_bad_target; 6338 return; 6339 } 6340 6341 if (Function->getTrailingRequiresClause()) { 6342 ConstraintSatisfaction Satisfaction; 6343 if (CheckFunctionConstraints(Function, Satisfaction) || 6344 !Satisfaction.IsSatisfied) { 6345 Candidate.Viable = false; 6346 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6347 return; 6348 } 6349 } 6350 6351 // Determine the implicit conversion sequences for each of the 6352 // arguments. 6353 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6354 unsigned ConvIdx = 6355 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6356 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6357 // We already formed a conversion sequence for this parameter during 6358 // template argument deduction. 6359 } else if (ArgIdx < NumParams) { 6360 // (C++ 13.3.2p3): for F to be a viable function, there shall 6361 // exist for each argument an implicit conversion sequence 6362 // (13.3.3.1) that converts that argument to the corresponding 6363 // parameter of F. 6364 QualType ParamType = Proto->getParamType(ArgIdx); 6365 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6366 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6367 /*InOverloadResolution=*/true, 6368 /*AllowObjCWritebackConversion=*/ 6369 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6370 if (Candidate.Conversions[ConvIdx].isBad()) { 6371 Candidate.Viable = false; 6372 Candidate.FailureKind = ovl_fail_bad_conversion; 6373 return; 6374 } 6375 } else { 6376 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6377 // argument for which there is no corresponding parameter is 6378 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6379 Candidate.Conversions[ConvIdx].setEllipsis(); 6380 } 6381 } 6382 6383 if (EnableIfAttr *FailedAttr = 6384 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6385 Candidate.Viable = false; 6386 Candidate.FailureKind = ovl_fail_enable_if; 6387 Candidate.DeductionFailure.Data = FailedAttr; 6388 return; 6389 } 6390 6391 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6392 Candidate.Viable = false; 6393 Candidate.FailureKind = ovl_fail_ext_disabled; 6394 return; 6395 } 6396 } 6397 6398 ObjCMethodDecl * 6399 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6400 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6401 if (Methods.size() <= 1) 6402 return nullptr; 6403 6404 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6405 bool Match = true; 6406 ObjCMethodDecl *Method = Methods[b]; 6407 unsigned NumNamedArgs = Sel.getNumArgs(); 6408 // Method might have more arguments than selector indicates. This is due 6409 // to addition of c-style arguments in method. 6410 if (Method->param_size() > NumNamedArgs) 6411 NumNamedArgs = Method->param_size(); 6412 if (Args.size() < NumNamedArgs) 6413 continue; 6414 6415 for (unsigned i = 0; i < NumNamedArgs; i++) { 6416 // We can't do any type-checking on a type-dependent argument. 6417 if (Args[i]->isTypeDependent()) { 6418 Match = false; 6419 break; 6420 } 6421 6422 ParmVarDecl *param = Method->parameters()[i]; 6423 Expr *argExpr = Args[i]; 6424 assert(argExpr && "SelectBestMethod(): missing expression"); 6425 6426 // Strip the unbridged-cast placeholder expression off unless it's 6427 // a consumed argument. 6428 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6429 !param->hasAttr<CFConsumedAttr>()) 6430 argExpr = stripARCUnbridgedCast(argExpr); 6431 6432 // If the parameter is __unknown_anytype, move on to the next method. 6433 if (param->getType() == Context.UnknownAnyTy) { 6434 Match = false; 6435 break; 6436 } 6437 6438 ImplicitConversionSequence ConversionState 6439 = TryCopyInitialization(*this, argExpr, param->getType(), 6440 /*SuppressUserConversions*/false, 6441 /*InOverloadResolution=*/true, 6442 /*AllowObjCWritebackConversion=*/ 6443 getLangOpts().ObjCAutoRefCount, 6444 /*AllowExplicit*/false); 6445 // This function looks for a reasonably-exact match, so we consider 6446 // incompatible pointer conversions to be a failure here. 6447 if (ConversionState.isBad() || 6448 (ConversionState.isStandard() && 6449 ConversionState.Standard.Second == 6450 ICK_Incompatible_Pointer_Conversion)) { 6451 Match = false; 6452 break; 6453 } 6454 } 6455 // Promote additional arguments to variadic methods. 6456 if (Match && Method->isVariadic()) { 6457 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6458 if (Args[i]->isTypeDependent()) { 6459 Match = false; 6460 break; 6461 } 6462 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6463 nullptr); 6464 if (Arg.isInvalid()) { 6465 Match = false; 6466 break; 6467 } 6468 } 6469 } else { 6470 // Check for extra arguments to non-variadic methods. 6471 if (Args.size() != NumNamedArgs) 6472 Match = false; 6473 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6474 // Special case when selectors have no argument. In this case, select 6475 // one with the most general result type of 'id'. 6476 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6477 QualType ReturnT = Methods[b]->getReturnType(); 6478 if (ReturnT->isObjCIdType()) 6479 return Methods[b]; 6480 } 6481 } 6482 } 6483 6484 if (Match) 6485 return Method; 6486 } 6487 return nullptr; 6488 } 6489 6490 static bool convertArgsForAvailabilityChecks( 6491 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6492 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6493 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6494 if (ThisArg) { 6495 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6496 assert(!isa<CXXConstructorDecl>(Method) && 6497 "Shouldn't have `this` for ctors!"); 6498 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6499 ExprResult R = S.PerformObjectArgumentInitialization( 6500 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6501 if (R.isInvalid()) 6502 return false; 6503 ConvertedThis = R.get(); 6504 } else { 6505 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6506 (void)MD; 6507 assert((MissingImplicitThis || MD->isStatic() || 6508 isa<CXXConstructorDecl>(MD)) && 6509 "Expected `this` for non-ctor instance methods"); 6510 } 6511 ConvertedThis = nullptr; 6512 } 6513 6514 // Ignore any variadic arguments. Converting them is pointless, since the 6515 // user can't refer to them in the function condition. 6516 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6517 6518 // Convert the arguments. 6519 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6520 ExprResult R; 6521 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6522 S.Context, Function->getParamDecl(I)), 6523 SourceLocation(), Args[I]); 6524 6525 if (R.isInvalid()) 6526 return false; 6527 6528 ConvertedArgs.push_back(R.get()); 6529 } 6530 6531 if (Trap.hasErrorOccurred()) 6532 return false; 6533 6534 // Push default arguments if needed. 6535 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6536 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6537 ParmVarDecl *P = Function->getParamDecl(i); 6538 if (!P->hasDefaultArg()) 6539 return false; 6540 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6541 if (R.isInvalid()) 6542 return false; 6543 ConvertedArgs.push_back(R.get()); 6544 } 6545 6546 if (Trap.hasErrorOccurred()) 6547 return false; 6548 } 6549 return true; 6550 } 6551 6552 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6553 SourceLocation CallLoc, 6554 ArrayRef<Expr *> Args, 6555 bool MissingImplicitThis) { 6556 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6557 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6558 return nullptr; 6559 6560 SFINAETrap Trap(*this); 6561 SmallVector<Expr *, 16> ConvertedArgs; 6562 // FIXME: We should look into making enable_if late-parsed. 6563 Expr *DiscardedThis; 6564 if (!convertArgsForAvailabilityChecks( 6565 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6566 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6567 return *EnableIfAttrs.begin(); 6568 6569 for (auto *EIA : EnableIfAttrs) { 6570 APValue Result; 6571 // FIXME: This doesn't consider value-dependent cases, because doing so is 6572 // very difficult. Ideally, we should handle them more gracefully. 6573 if (EIA->getCond()->isValueDependent() || 6574 !EIA->getCond()->EvaluateWithSubstitution( 6575 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6576 return EIA; 6577 6578 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6579 return EIA; 6580 } 6581 return nullptr; 6582 } 6583 6584 template <typename CheckFn> 6585 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6586 bool ArgDependent, SourceLocation Loc, 6587 CheckFn &&IsSuccessful) { 6588 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6589 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6590 if (ArgDependent == DIA->getArgDependent()) 6591 Attrs.push_back(DIA); 6592 } 6593 6594 // Common case: No diagnose_if attributes, so we can quit early. 6595 if (Attrs.empty()) 6596 return false; 6597 6598 auto WarningBegin = std::stable_partition( 6599 Attrs.begin(), Attrs.end(), 6600 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6601 6602 // Note that diagnose_if attributes are late-parsed, so they appear in the 6603 // correct order (unlike enable_if attributes). 6604 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6605 IsSuccessful); 6606 if (ErrAttr != WarningBegin) { 6607 const DiagnoseIfAttr *DIA = *ErrAttr; 6608 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6609 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6610 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6611 return true; 6612 } 6613 6614 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6615 if (IsSuccessful(DIA)) { 6616 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6617 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6618 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6619 } 6620 6621 return false; 6622 } 6623 6624 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6625 const Expr *ThisArg, 6626 ArrayRef<const Expr *> Args, 6627 SourceLocation Loc) { 6628 return diagnoseDiagnoseIfAttrsWith( 6629 *this, Function, /*ArgDependent=*/true, Loc, 6630 [&](const DiagnoseIfAttr *DIA) { 6631 APValue Result; 6632 // It's sane to use the same Args for any redecl of this function, since 6633 // EvaluateWithSubstitution only cares about the position of each 6634 // argument in the arg list, not the ParmVarDecl* it maps to. 6635 if (!DIA->getCond()->EvaluateWithSubstitution( 6636 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6637 return false; 6638 return Result.isInt() && Result.getInt().getBoolValue(); 6639 }); 6640 } 6641 6642 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6643 SourceLocation Loc) { 6644 return diagnoseDiagnoseIfAttrsWith( 6645 *this, ND, /*ArgDependent=*/false, Loc, 6646 [&](const DiagnoseIfAttr *DIA) { 6647 bool Result; 6648 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6649 Result; 6650 }); 6651 } 6652 6653 /// Add all of the function declarations in the given function set to 6654 /// the overload candidate set. 6655 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6656 ArrayRef<Expr *> Args, 6657 OverloadCandidateSet &CandidateSet, 6658 TemplateArgumentListInfo *ExplicitTemplateArgs, 6659 bool SuppressUserConversions, 6660 bool PartialOverloading, 6661 bool FirstArgumentIsBase) { 6662 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6663 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6664 ArrayRef<Expr *> FunctionArgs = Args; 6665 6666 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6667 FunctionDecl *FD = 6668 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6669 6670 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6671 QualType ObjectType; 6672 Expr::Classification ObjectClassification; 6673 if (Args.size() > 0) { 6674 if (Expr *E = Args[0]) { 6675 // Use the explicit base to restrict the lookup: 6676 ObjectType = E->getType(); 6677 // Pointers in the object arguments are implicitly dereferenced, so we 6678 // always classify them as l-values. 6679 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6680 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6681 else 6682 ObjectClassification = E->Classify(Context); 6683 } // .. else there is an implicit base. 6684 FunctionArgs = Args.slice(1); 6685 } 6686 if (FunTmpl) { 6687 AddMethodTemplateCandidate( 6688 FunTmpl, F.getPair(), 6689 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6690 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6691 FunctionArgs, CandidateSet, SuppressUserConversions, 6692 PartialOverloading); 6693 } else { 6694 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6695 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6696 ObjectClassification, FunctionArgs, CandidateSet, 6697 SuppressUserConversions, PartialOverloading); 6698 } 6699 } else { 6700 // This branch handles both standalone functions and static methods. 6701 6702 // Slice the first argument (which is the base) when we access 6703 // static method as non-static. 6704 if (Args.size() > 0 && 6705 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6706 !isa<CXXConstructorDecl>(FD)))) { 6707 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6708 FunctionArgs = Args.slice(1); 6709 } 6710 if (FunTmpl) { 6711 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6712 ExplicitTemplateArgs, FunctionArgs, 6713 CandidateSet, SuppressUserConversions, 6714 PartialOverloading); 6715 } else { 6716 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6717 SuppressUserConversions, PartialOverloading); 6718 } 6719 } 6720 } 6721 } 6722 6723 /// AddMethodCandidate - Adds a named decl (which is some kind of 6724 /// method) as a method candidate to the given overload set. 6725 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6726 Expr::Classification ObjectClassification, 6727 ArrayRef<Expr *> Args, 6728 OverloadCandidateSet &CandidateSet, 6729 bool SuppressUserConversions, 6730 OverloadCandidateParamOrder PO) { 6731 NamedDecl *Decl = FoundDecl.getDecl(); 6732 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6733 6734 if (isa<UsingShadowDecl>(Decl)) 6735 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6736 6737 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6738 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6739 "Expected a member function template"); 6740 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6741 /*ExplicitArgs*/ nullptr, ObjectType, 6742 ObjectClassification, Args, CandidateSet, 6743 SuppressUserConversions, false, PO); 6744 } else { 6745 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6746 ObjectType, ObjectClassification, Args, CandidateSet, 6747 SuppressUserConversions, false, None, PO); 6748 } 6749 } 6750 6751 /// AddMethodCandidate - Adds the given C++ member function to the set 6752 /// of candidate functions, using the given function call arguments 6753 /// and the object argument (@c Object). For example, in a call 6754 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6755 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6756 /// allow user-defined conversions via constructors or conversion 6757 /// operators. 6758 void 6759 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6760 CXXRecordDecl *ActingContext, QualType ObjectType, 6761 Expr::Classification ObjectClassification, 6762 ArrayRef<Expr *> Args, 6763 OverloadCandidateSet &CandidateSet, 6764 bool SuppressUserConversions, 6765 bool PartialOverloading, 6766 ConversionSequenceList EarlyConversions, 6767 OverloadCandidateParamOrder PO) { 6768 const FunctionProtoType *Proto 6769 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6770 assert(Proto && "Methods without a prototype cannot be overloaded"); 6771 assert(!isa<CXXConstructorDecl>(Method) && 6772 "Use AddOverloadCandidate for constructors"); 6773 6774 if (!CandidateSet.isNewCandidate(Method, PO)) 6775 return; 6776 6777 // C++11 [class.copy]p23: [DR1402] 6778 // A defaulted move assignment operator that is defined as deleted is 6779 // ignored by overload resolution. 6780 if (Method->isDefaulted() && Method->isDeleted() && 6781 Method->isMoveAssignmentOperator()) 6782 return; 6783 6784 // Overload resolution is always an unevaluated context. 6785 EnterExpressionEvaluationContext Unevaluated( 6786 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6787 6788 // Add this candidate 6789 OverloadCandidate &Candidate = 6790 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6791 Candidate.FoundDecl = FoundDecl; 6792 Candidate.Function = Method; 6793 Candidate.RewriteKind = 6794 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6795 Candidate.IsSurrogate = false; 6796 Candidate.IgnoreObjectArgument = false; 6797 Candidate.ExplicitCallArguments = Args.size(); 6798 6799 unsigned NumParams = Proto->getNumParams(); 6800 6801 // (C++ 13.3.2p2): A candidate function having fewer than m 6802 // parameters is viable only if it has an ellipsis in its parameter 6803 // list (8.3.5). 6804 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6805 !Proto->isVariadic()) { 6806 Candidate.Viable = false; 6807 Candidate.FailureKind = ovl_fail_too_many_arguments; 6808 return; 6809 } 6810 6811 // (C++ 13.3.2p2): A candidate function having more than m parameters 6812 // is viable only if the (m+1)st parameter has a default argument 6813 // (8.3.6). For the purposes of overload resolution, the 6814 // parameter list is truncated on the right, so that there are 6815 // exactly m parameters. 6816 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6817 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6818 // Not enough arguments. 6819 Candidate.Viable = false; 6820 Candidate.FailureKind = ovl_fail_too_few_arguments; 6821 return; 6822 } 6823 6824 Candidate.Viable = true; 6825 6826 if (Method->isStatic() || ObjectType.isNull()) 6827 // The implicit object argument is ignored. 6828 Candidate.IgnoreObjectArgument = true; 6829 else { 6830 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6831 // Determine the implicit conversion sequence for the object 6832 // parameter. 6833 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6834 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6835 Method, ActingContext); 6836 if (Candidate.Conversions[ConvIdx].isBad()) { 6837 Candidate.Viable = false; 6838 Candidate.FailureKind = ovl_fail_bad_conversion; 6839 return; 6840 } 6841 } 6842 6843 // (CUDA B.1): Check for invalid calls between targets. 6844 if (getLangOpts().CUDA) 6845 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6846 if (!IsAllowedCUDACall(Caller, Method)) { 6847 Candidate.Viable = false; 6848 Candidate.FailureKind = ovl_fail_bad_target; 6849 return; 6850 } 6851 6852 if (Method->getTrailingRequiresClause()) { 6853 ConstraintSatisfaction Satisfaction; 6854 if (CheckFunctionConstraints(Method, Satisfaction) || 6855 !Satisfaction.IsSatisfied) { 6856 Candidate.Viable = false; 6857 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6858 return; 6859 } 6860 } 6861 6862 // Determine the implicit conversion sequences for each of the 6863 // arguments. 6864 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6865 unsigned ConvIdx = 6866 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6867 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6868 // We already formed a conversion sequence for this parameter during 6869 // template argument deduction. 6870 } else if (ArgIdx < NumParams) { 6871 // (C++ 13.3.2p3): for F to be a viable function, there shall 6872 // exist for each argument an implicit conversion sequence 6873 // (13.3.3.1) that converts that argument to the corresponding 6874 // parameter of F. 6875 QualType ParamType = Proto->getParamType(ArgIdx); 6876 Candidate.Conversions[ConvIdx] 6877 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6878 SuppressUserConversions, 6879 /*InOverloadResolution=*/true, 6880 /*AllowObjCWritebackConversion=*/ 6881 getLangOpts().ObjCAutoRefCount); 6882 if (Candidate.Conversions[ConvIdx].isBad()) { 6883 Candidate.Viable = false; 6884 Candidate.FailureKind = ovl_fail_bad_conversion; 6885 return; 6886 } 6887 } else { 6888 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6889 // argument for which there is no corresponding parameter is 6890 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6891 Candidate.Conversions[ConvIdx].setEllipsis(); 6892 } 6893 } 6894 6895 if (EnableIfAttr *FailedAttr = 6896 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6897 Candidate.Viable = false; 6898 Candidate.FailureKind = ovl_fail_enable_if; 6899 Candidate.DeductionFailure.Data = FailedAttr; 6900 return; 6901 } 6902 6903 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6904 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6905 Candidate.Viable = false; 6906 Candidate.FailureKind = ovl_non_default_multiversion_function; 6907 } 6908 } 6909 6910 /// Add a C++ member function template as a candidate to the candidate 6911 /// set, using template argument deduction to produce an appropriate member 6912 /// function template specialization. 6913 void Sema::AddMethodTemplateCandidate( 6914 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6915 CXXRecordDecl *ActingContext, 6916 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6917 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6918 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6919 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6920 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6921 return; 6922 6923 // C++ [over.match.funcs]p7: 6924 // In each case where a candidate is a function template, candidate 6925 // function template specializations are generated using template argument 6926 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6927 // candidate functions in the usual way.113) A given name can refer to one 6928 // or more function templates and also to a set of overloaded non-template 6929 // functions. In such a case, the candidate functions generated from each 6930 // function template are combined with the set of non-template candidate 6931 // functions. 6932 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6933 FunctionDecl *Specialization = nullptr; 6934 ConversionSequenceList Conversions; 6935 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6936 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6937 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6938 return CheckNonDependentConversions( 6939 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6940 SuppressUserConversions, ActingContext, ObjectType, 6941 ObjectClassification, PO); 6942 })) { 6943 OverloadCandidate &Candidate = 6944 CandidateSet.addCandidate(Conversions.size(), Conversions); 6945 Candidate.FoundDecl = FoundDecl; 6946 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6947 Candidate.Viable = false; 6948 Candidate.RewriteKind = 6949 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6950 Candidate.IsSurrogate = false; 6951 Candidate.IgnoreObjectArgument = 6952 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6953 ObjectType.isNull(); 6954 Candidate.ExplicitCallArguments = Args.size(); 6955 if (Result == TDK_NonDependentConversionFailure) 6956 Candidate.FailureKind = ovl_fail_bad_conversion; 6957 else { 6958 Candidate.FailureKind = ovl_fail_bad_deduction; 6959 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6960 Info); 6961 } 6962 return; 6963 } 6964 6965 // Add the function template specialization produced by template argument 6966 // deduction as a candidate. 6967 assert(Specialization && "Missing member function template specialization?"); 6968 assert(isa<CXXMethodDecl>(Specialization) && 6969 "Specialization is not a member function?"); 6970 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6971 ActingContext, ObjectType, ObjectClassification, Args, 6972 CandidateSet, SuppressUserConversions, PartialOverloading, 6973 Conversions, PO); 6974 } 6975 6976 /// Determine whether a given function template has a simple explicit specifier 6977 /// or a non-value-dependent explicit-specification that evaluates to true. 6978 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6979 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6980 } 6981 6982 /// Add a C++ function template specialization as a candidate 6983 /// in the candidate set, using template argument deduction to produce 6984 /// an appropriate function template specialization. 6985 void Sema::AddTemplateOverloadCandidate( 6986 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6987 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6988 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6989 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6990 OverloadCandidateParamOrder PO) { 6991 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6992 return; 6993 6994 // If the function template has a non-dependent explicit specification, 6995 // exclude it now if appropriate; we are not permitted to perform deduction 6996 // and substitution in this case. 6997 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6998 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6999 Candidate.FoundDecl = FoundDecl; 7000 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7001 Candidate.Viable = false; 7002 Candidate.FailureKind = ovl_fail_explicit; 7003 return; 7004 } 7005 7006 // C++ [over.match.funcs]p7: 7007 // In each case where a candidate is a function template, candidate 7008 // function template specializations are generated using template argument 7009 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 7010 // candidate functions in the usual way.113) A given name can refer to one 7011 // or more function templates and also to a set of overloaded non-template 7012 // functions. In such a case, the candidate functions generated from each 7013 // function template are combined with the set of non-template candidate 7014 // functions. 7015 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7016 FunctionDecl *Specialization = nullptr; 7017 ConversionSequenceList Conversions; 7018 if (TemplateDeductionResult Result = DeduceTemplateArguments( 7019 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 7020 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 7021 return CheckNonDependentConversions( 7022 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 7023 SuppressUserConversions, nullptr, QualType(), {}, PO); 7024 })) { 7025 OverloadCandidate &Candidate = 7026 CandidateSet.addCandidate(Conversions.size(), Conversions); 7027 Candidate.FoundDecl = FoundDecl; 7028 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7029 Candidate.Viable = false; 7030 Candidate.RewriteKind = 7031 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7032 Candidate.IsSurrogate = false; 7033 Candidate.IsADLCandidate = IsADLCandidate; 7034 // Ignore the object argument if there is one, since we don't have an object 7035 // type. 7036 Candidate.IgnoreObjectArgument = 7037 isa<CXXMethodDecl>(Candidate.Function) && 7038 !isa<CXXConstructorDecl>(Candidate.Function); 7039 Candidate.ExplicitCallArguments = Args.size(); 7040 if (Result == TDK_NonDependentConversionFailure) 7041 Candidate.FailureKind = ovl_fail_bad_conversion; 7042 else { 7043 Candidate.FailureKind = ovl_fail_bad_deduction; 7044 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7045 Info); 7046 } 7047 return; 7048 } 7049 7050 // Add the function template specialization produced by template argument 7051 // deduction as a candidate. 7052 assert(Specialization && "Missing function template specialization?"); 7053 AddOverloadCandidate( 7054 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7055 PartialOverloading, AllowExplicit, 7056 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7057 } 7058 7059 /// Check that implicit conversion sequences can be formed for each argument 7060 /// whose corresponding parameter has a non-dependent type, per DR1391's 7061 /// [temp.deduct.call]p10. 7062 bool Sema::CheckNonDependentConversions( 7063 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7064 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7065 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7066 CXXRecordDecl *ActingContext, QualType ObjectType, 7067 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7068 // FIXME: The cases in which we allow explicit conversions for constructor 7069 // arguments never consider calling a constructor template. It's not clear 7070 // that is correct. 7071 const bool AllowExplicit = false; 7072 7073 auto *FD = FunctionTemplate->getTemplatedDecl(); 7074 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7075 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7076 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7077 7078 Conversions = 7079 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7080 7081 // Overload resolution is always an unevaluated context. 7082 EnterExpressionEvaluationContext Unevaluated( 7083 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7084 7085 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7086 // require that, but this check should never result in a hard error, and 7087 // overload resolution is permitted to sidestep instantiations. 7088 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7089 !ObjectType.isNull()) { 7090 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7091 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7092 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7093 Method, ActingContext); 7094 if (Conversions[ConvIdx].isBad()) 7095 return true; 7096 } 7097 7098 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7099 ++I) { 7100 QualType ParamType = ParamTypes[I]; 7101 if (!ParamType->isDependentType()) { 7102 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7103 ? 0 7104 : (ThisConversions + I); 7105 Conversions[ConvIdx] 7106 = TryCopyInitialization(*this, Args[I], ParamType, 7107 SuppressUserConversions, 7108 /*InOverloadResolution=*/true, 7109 /*AllowObjCWritebackConversion=*/ 7110 getLangOpts().ObjCAutoRefCount, 7111 AllowExplicit); 7112 if (Conversions[ConvIdx].isBad()) 7113 return true; 7114 } 7115 } 7116 7117 return false; 7118 } 7119 7120 /// Determine whether this is an allowable conversion from the result 7121 /// of an explicit conversion operator to the expected type, per C++ 7122 /// [over.match.conv]p1 and [over.match.ref]p1. 7123 /// 7124 /// \param ConvType The return type of the conversion function. 7125 /// 7126 /// \param ToType The type we are converting to. 7127 /// 7128 /// \param AllowObjCPointerConversion Allow a conversion from one 7129 /// Objective-C pointer to another. 7130 /// 7131 /// \returns true if the conversion is allowable, false otherwise. 7132 static bool isAllowableExplicitConversion(Sema &S, 7133 QualType ConvType, QualType ToType, 7134 bool AllowObjCPointerConversion) { 7135 QualType ToNonRefType = ToType.getNonReferenceType(); 7136 7137 // Easy case: the types are the same. 7138 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7139 return true; 7140 7141 // Allow qualification conversions. 7142 bool ObjCLifetimeConversion; 7143 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7144 ObjCLifetimeConversion)) 7145 return true; 7146 7147 // If we're not allowed to consider Objective-C pointer conversions, 7148 // we're done. 7149 if (!AllowObjCPointerConversion) 7150 return false; 7151 7152 // Is this an Objective-C pointer conversion? 7153 bool IncompatibleObjC = false; 7154 QualType ConvertedType; 7155 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7156 IncompatibleObjC); 7157 } 7158 7159 /// AddConversionCandidate - Add a C++ conversion function as a 7160 /// candidate in the candidate set (C++ [over.match.conv], 7161 /// C++ [over.match.copy]). From is the expression we're converting from, 7162 /// and ToType is the type that we're eventually trying to convert to 7163 /// (which may or may not be the same type as the type that the 7164 /// conversion function produces). 7165 void Sema::AddConversionCandidate( 7166 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7167 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7168 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7169 bool AllowExplicit, bool AllowResultConversion) { 7170 assert(!Conversion->getDescribedFunctionTemplate() && 7171 "Conversion function templates use AddTemplateConversionCandidate"); 7172 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7173 if (!CandidateSet.isNewCandidate(Conversion)) 7174 return; 7175 7176 // If the conversion function has an undeduced return type, trigger its 7177 // deduction now. 7178 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7179 if (DeduceReturnType(Conversion, From->getExprLoc())) 7180 return; 7181 ConvType = Conversion->getConversionType().getNonReferenceType(); 7182 } 7183 7184 // If we don't allow any conversion of the result type, ignore conversion 7185 // functions that don't convert to exactly (possibly cv-qualified) T. 7186 if (!AllowResultConversion && 7187 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7188 return; 7189 7190 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7191 // operator is only a candidate if its return type is the target type or 7192 // can be converted to the target type with a qualification conversion. 7193 // 7194 // FIXME: Include such functions in the candidate list and explain why we 7195 // can't select them. 7196 if (Conversion->isExplicit() && 7197 !isAllowableExplicitConversion(*this, ConvType, ToType, 7198 AllowObjCConversionOnExplicit)) 7199 return; 7200 7201 // Overload resolution is always an unevaluated context. 7202 EnterExpressionEvaluationContext Unevaluated( 7203 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7204 7205 // Add this candidate 7206 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7207 Candidate.FoundDecl = FoundDecl; 7208 Candidate.Function = Conversion; 7209 Candidate.IsSurrogate = false; 7210 Candidate.IgnoreObjectArgument = false; 7211 Candidate.FinalConversion.setAsIdentityConversion(); 7212 Candidate.FinalConversion.setFromType(ConvType); 7213 Candidate.FinalConversion.setAllToTypes(ToType); 7214 Candidate.Viable = true; 7215 Candidate.ExplicitCallArguments = 1; 7216 7217 // Explicit functions are not actually candidates at all if we're not 7218 // allowing them in this context, but keep them around so we can point 7219 // to them in diagnostics. 7220 if (!AllowExplicit && Conversion->isExplicit()) { 7221 Candidate.Viable = false; 7222 Candidate.FailureKind = ovl_fail_explicit; 7223 return; 7224 } 7225 7226 // C++ [over.match.funcs]p4: 7227 // For conversion functions, the function is considered to be a member of 7228 // the class of the implicit implied object argument for the purpose of 7229 // defining the type of the implicit object parameter. 7230 // 7231 // Determine the implicit conversion sequence for the implicit 7232 // object parameter. 7233 QualType ImplicitParamType = From->getType(); 7234 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7235 ImplicitParamType = FromPtrType->getPointeeType(); 7236 CXXRecordDecl *ConversionContext 7237 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7238 7239 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7240 *this, CandidateSet.getLocation(), From->getType(), 7241 From->Classify(Context), Conversion, ConversionContext); 7242 7243 if (Candidate.Conversions[0].isBad()) { 7244 Candidate.Viable = false; 7245 Candidate.FailureKind = ovl_fail_bad_conversion; 7246 return; 7247 } 7248 7249 if (Conversion->getTrailingRequiresClause()) { 7250 ConstraintSatisfaction Satisfaction; 7251 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7252 !Satisfaction.IsSatisfied) { 7253 Candidate.Viable = false; 7254 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7255 return; 7256 } 7257 } 7258 7259 // We won't go through a user-defined type conversion function to convert a 7260 // derived to base as such conversions are given Conversion Rank. They only 7261 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7262 QualType FromCanon 7263 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7264 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7265 if (FromCanon == ToCanon || 7266 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7267 Candidate.Viable = false; 7268 Candidate.FailureKind = ovl_fail_trivial_conversion; 7269 return; 7270 } 7271 7272 // To determine what the conversion from the result of calling the 7273 // conversion function to the type we're eventually trying to 7274 // convert to (ToType), we need to synthesize a call to the 7275 // conversion function and attempt copy initialization from it. This 7276 // makes sure that we get the right semantics with respect to 7277 // lvalues/rvalues and the type. Fortunately, we can allocate this 7278 // call on the stack and we don't need its arguments to be 7279 // well-formed. 7280 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7281 VK_LValue, From->getBeginLoc()); 7282 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7283 Context.getPointerType(Conversion->getType()), 7284 CK_FunctionToPointerDecay, 7285 &ConversionRef, VK_RValue); 7286 7287 QualType ConversionType = Conversion->getConversionType(); 7288 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7289 Candidate.Viable = false; 7290 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7291 return; 7292 } 7293 7294 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7295 7296 // Note that it is safe to allocate CallExpr on the stack here because 7297 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7298 // allocator). 7299 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7300 7301 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7302 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7303 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7304 7305 ImplicitConversionSequence ICS = 7306 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7307 /*SuppressUserConversions=*/true, 7308 /*InOverloadResolution=*/false, 7309 /*AllowObjCWritebackConversion=*/false); 7310 7311 switch (ICS.getKind()) { 7312 case ImplicitConversionSequence::StandardConversion: 7313 Candidate.FinalConversion = ICS.Standard; 7314 7315 // C++ [over.ics.user]p3: 7316 // If the user-defined conversion is specified by a specialization of a 7317 // conversion function template, the second standard conversion sequence 7318 // shall have exact match rank. 7319 if (Conversion->getPrimaryTemplate() && 7320 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7321 Candidate.Viable = false; 7322 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7323 return; 7324 } 7325 7326 // C++0x [dcl.init.ref]p5: 7327 // In the second case, if the reference is an rvalue reference and 7328 // the second standard conversion sequence of the user-defined 7329 // conversion sequence includes an lvalue-to-rvalue conversion, the 7330 // program is ill-formed. 7331 if (ToType->isRValueReferenceType() && 7332 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7333 Candidate.Viable = false; 7334 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7335 return; 7336 } 7337 break; 7338 7339 case ImplicitConversionSequence::BadConversion: 7340 Candidate.Viable = false; 7341 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7342 return; 7343 7344 default: 7345 llvm_unreachable( 7346 "Can only end up with a standard conversion sequence or failure"); 7347 } 7348 7349 if (EnableIfAttr *FailedAttr = 7350 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7351 Candidate.Viable = false; 7352 Candidate.FailureKind = ovl_fail_enable_if; 7353 Candidate.DeductionFailure.Data = FailedAttr; 7354 return; 7355 } 7356 7357 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7358 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7359 Candidate.Viable = false; 7360 Candidate.FailureKind = ovl_non_default_multiversion_function; 7361 } 7362 } 7363 7364 /// Adds a conversion function template specialization 7365 /// candidate to the overload set, using template argument deduction 7366 /// to deduce the template arguments of the conversion function 7367 /// template from the type that we are converting to (C++ 7368 /// [temp.deduct.conv]). 7369 void Sema::AddTemplateConversionCandidate( 7370 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7371 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7372 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7373 bool AllowExplicit, bool AllowResultConversion) { 7374 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7375 "Only conversion function templates permitted here"); 7376 7377 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7378 return; 7379 7380 // If the function template has a non-dependent explicit specification, 7381 // exclude it now if appropriate; we are not permitted to perform deduction 7382 // and substitution in this case. 7383 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7384 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7385 Candidate.FoundDecl = FoundDecl; 7386 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7387 Candidate.Viable = false; 7388 Candidate.FailureKind = ovl_fail_explicit; 7389 return; 7390 } 7391 7392 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7393 CXXConversionDecl *Specialization = nullptr; 7394 if (TemplateDeductionResult Result 7395 = DeduceTemplateArguments(FunctionTemplate, ToType, 7396 Specialization, Info)) { 7397 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7398 Candidate.FoundDecl = FoundDecl; 7399 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7400 Candidate.Viable = false; 7401 Candidate.FailureKind = ovl_fail_bad_deduction; 7402 Candidate.IsSurrogate = false; 7403 Candidate.IgnoreObjectArgument = false; 7404 Candidate.ExplicitCallArguments = 1; 7405 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7406 Info); 7407 return; 7408 } 7409 7410 // Add the conversion function template specialization produced by 7411 // template argument deduction as a candidate. 7412 assert(Specialization && "Missing function template specialization?"); 7413 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7414 CandidateSet, AllowObjCConversionOnExplicit, 7415 AllowExplicit, AllowResultConversion); 7416 } 7417 7418 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7419 /// converts the given @c Object to a function pointer via the 7420 /// conversion function @c Conversion, and then attempts to call it 7421 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7422 /// the type of function that we'll eventually be calling. 7423 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7424 DeclAccessPair FoundDecl, 7425 CXXRecordDecl *ActingContext, 7426 const FunctionProtoType *Proto, 7427 Expr *Object, 7428 ArrayRef<Expr *> Args, 7429 OverloadCandidateSet& CandidateSet) { 7430 if (!CandidateSet.isNewCandidate(Conversion)) 7431 return; 7432 7433 // Overload resolution is always an unevaluated context. 7434 EnterExpressionEvaluationContext Unevaluated( 7435 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7436 7437 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7438 Candidate.FoundDecl = FoundDecl; 7439 Candidate.Function = nullptr; 7440 Candidate.Surrogate = Conversion; 7441 Candidate.Viable = true; 7442 Candidate.IsSurrogate = true; 7443 Candidate.IgnoreObjectArgument = false; 7444 Candidate.ExplicitCallArguments = Args.size(); 7445 7446 // Determine the implicit conversion sequence for the implicit 7447 // object parameter. 7448 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7449 *this, CandidateSet.getLocation(), Object->getType(), 7450 Object->Classify(Context), Conversion, ActingContext); 7451 if (ObjectInit.isBad()) { 7452 Candidate.Viable = false; 7453 Candidate.FailureKind = ovl_fail_bad_conversion; 7454 Candidate.Conversions[0] = ObjectInit; 7455 return; 7456 } 7457 7458 // The first conversion is actually a user-defined conversion whose 7459 // first conversion is ObjectInit's standard conversion (which is 7460 // effectively a reference binding). Record it as such. 7461 Candidate.Conversions[0].setUserDefined(); 7462 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7463 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7464 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7465 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7466 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7467 Candidate.Conversions[0].UserDefined.After 7468 = Candidate.Conversions[0].UserDefined.Before; 7469 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7470 7471 // Find the 7472 unsigned NumParams = Proto->getNumParams(); 7473 7474 // (C++ 13.3.2p2): A candidate function having fewer than m 7475 // parameters is viable only if it has an ellipsis in its parameter 7476 // list (8.3.5). 7477 if (Args.size() > NumParams && !Proto->isVariadic()) { 7478 Candidate.Viable = false; 7479 Candidate.FailureKind = ovl_fail_too_many_arguments; 7480 return; 7481 } 7482 7483 // Function types don't have any default arguments, so just check if 7484 // we have enough arguments. 7485 if (Args.size() < NumParams) { 7486 // Not enough arguments. 7487 Candidate.Viable = false; 7488 Candidate.FailureKind = ovl_fail_too_few_arguments; 7489 return; 7490 } 7491 7492 // Determine the implicit conversion sequences for each of the 7493 // arguments. 7494 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7495 if (ArgIdx < NumParams) { 7496 // (C++ 13.3.2p3): for F to be a viable function, there shall 7497 // exist for each argument an implicit conversion sequence 7498 // (13.3.3.1) that converts that argument to the corresponding 7499 // parameter of F. 7500 QualType ParamType = Proto->getParamType(ArgIdx); 7501 Candidate.Conversions[ArgIdx + 1] 7502 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7503 /*SuppressUserConversions=*/false, 7504 /*InOverloadResolution=*/false, 7505 /*AllowObjCWritebackConversion=*/ 7506 getLangOpts().ObjCAutoRefCount); 7507 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7508 Candidate.Viable = false; 7509 Candidate.FailureKind = ovl_fail_bad_conversion; 7510 return; 7511 } 7512 } else { 7513 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7514 // argument for which there is no corresponding parameter is 7515 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7516 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7517 } 7518 } 7519 7520 if (EnableIfAttr *FailedAttr = 7521 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7522 Candidate.Viable = false; 7523 Candidate.FailureKind = ovl_fail_enable_if; 7524 Candidate.DeductionFailure.Data = FailedAttr; 7525 return; 7526 } 7527 } 7528 7529 /// Add all of the non-member operator function declarations in the given 7530 /// function set to the overload candidate set. 7531 void Sema::AddNonMemberOperatorCandidates( 7532 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7533 OverloadCandidateSet &CandidateSet, 7534 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7535 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7536 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7537 ArrayRef<Expr *> FunctionArgs = Args; 7538 7539 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7540 FunctionDecl *FD = 7541 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7542 7543 // Don't consider rewritten functions if we're not rewriting. 7544 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7545 continue; 7546 7547 assert(!isa<CXXMethodDecl>(FD) && 7548 "unqualified operator lookup found a member function"); 7549 7550 if (FunTmpl) { 7551 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7552 FunctionArgs, CandidateSet); 7553 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7554 AddTemplateOverloadCandidate( 7555 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7556 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7557 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7558 } else { 7559 if (ExplicitTemplateArgs) 7560 continue; 7561 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7562 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7563 AddOverloadCandidate(FD, F.getPair(), 7564 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7565 false, false, true, false, ADLCallKind::NotADL, 7566 None, OverloadCandidateParamOrder::Reversed); 7567 } 7568 } 7569 } 7570 7571 /// Add overload candidates for overloaded operators that are 7572 /// member functions. 7573 /// 7574 /// Add the overloaded operator candidates that are member functions 7575 /// for the operator Op that was used in an operator expression such 7576 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7577 /// CandidateSet will store the added overload candidates. (C++ 7578 /// [over.match.oper]). 7579 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7580 SourceLocation OpLoc, 7581 ArrayRef<Expr *> Args, 7582 OverloadCandidateSet &CandidateSet, 7583 OverloadCandidateParamOrder PO) { 7584 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7585 7586 // C++ [over.match.oper]p3: 7587 // For a unary operator @ with an operand of a type whose 7588 // cv-unqualified version is T1, and for a binary operator @ with 7589 // a left operand of a type whose cv-unqualified version is T1 and 7590 // a right operand of a type whose cv-unqualified version is T2, 7591 // three sets of candidate functions, designated member 7592 // candidates, non-member candidates and built-in candidates, are 7593 // constructed as follows: 7594 QualType T1 = Args[0]->getType(); 7595 7596 // -- If T1 is a complete class type or a class currently being 7597 // defined, the set of member candidates is the result of the 7598 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7599 // the set of member candidates is empty. 7600 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7601 // Complete the type if it can be completed. 7602 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7603 return; 7604 // If the type is neither complete nor being defined, bail out now. 7605 if (!T1Rec->getDecl()->getDefinition()) 7606 return; 7607 7608 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7609 LookupQualifiedName(Operators, T1Rec->getDecl()); 7610 Operators.suppressDiagnostics(); 7611 7612 for (LookupResult::iterator Oper = Operators.begin(), 7613 OperEnd = Operators.end(); 7614 Oper != OperEnd; 7615 ++Oper) 7616 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7617 Args[0]->Classify(Context), Args.slice(1), 7618 CandidateSet, /*SuppressUserConversion=*/false, PO); 7619 } 7620 } 7621 7622 /// AddBuiltinCandidate - Add a candidate for a built-in 7623 /// operator. ResultTy and ParamTys are the result and parameter types 7624 /// of the built-in candidate, respectively. Args and NumArgs are the 7625 /// arguments being passed to the candidate. IsAssignmentOperator 7626 /// should be true when this built-in candidate is an assignment 7627 /// operator. NumContextualBoolArguments is the number of arguments 7628 /// (at the beginning of the argument list) that will be contextually 7629 /// converted to bool. 7630 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7631 OverloadCandidateSet& CandidateSet, 7632 bool IsAssignmentOperator, 7633 unsigned NumContextualBoolArguments) { 7634 // Overload resolution is always an unevaluated context. 7635 EnterExpressionEvaluationContext Unevaluated( 7636 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7637 7638 // Add this candidate 7639 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7640 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7641 Candidate.Function = nullptr; 7642 Candidate.IsSurrogate = false; 7643 Candidate.IgnoreObjectArgument = false; 7644 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7645 7646 // Determine the implicit conversion sequences for each of the 7647 // arguments. 7648 Candidate.Viable = true; 7649 Candidate.ExplicitCallArguments = Args.size(); 7650 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7651 // C++ [over.match.oper]p4: 7652 // For the built-in assignment operators, conversions of the 7653 // left operand are restricted as follows: 7654 // -- no temporaries are introduced to hold the left operand, and 7655 // -- no user-defined conversions are applied to the left 7656 // operand to achieve a type match with the left-most 7657 // parameter of a built-in candidate. 7658 // 7659 // We block these conversions by turning off user-defined 7660 // conversions, since that is the only way that initialization of 7661 // a reference to a non-class type can occur from something that 7662 // is not of the same type. 7663 if (ArgIdx < NumContextualBoolArguments) { 7664 assert(ParamTys[ArgIdx] == Context.BoolTy && 7665 "Contextual conversion to bool requires bool type"); 7666 Candidate.Conversions[ArgIdx] 7667 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7668 } else { 7669 Candidate.Conversions[ArgIdx] 7670 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7671 ArgIdx == 0 && IsAssignmentOperator, 7672 /*InOverloadResolution=*/false, 7673 /*AllowObjCWritebackConversion=*/ 7674 getLangOpts().ObjCAutoRefCount); 7675 } 7676 if (Candidate.Conversions[ArgIdx].isBad()) { 7677 Candidate.Viable = false; 7678 Candidate.FailureKind = ovl_fail_bad_conversion; 7679 break; 7680 } 7681 } 7682 } 7683 7684 namespace { 7685 7686 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7687 /// candidate operator functions for built-in operators (C++ 7688 /// [over.built]). The types are separated into pointer types and 7689 /// enumeration types. 7690 class BuiltinCandidateTypeSet { 7691 /// TypeSet - A set of types. 7692 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7693 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7694 7695 /// PointerTypes - The set of pointer types that will be used in the 7696 /// built-in candidates. 7697 TypeSet PointerTypes; 7698 7699 /// MemberPointerTypes - The set of member pointer types that will be 7700 /// used in the built-in candidates. 7701 TypeSet MemberPointerTypes; 7702 7703 /// EnumerationTypes - The set of enumeration types that will be 7704 /// used in the built-in candidates. 7705 TypeSet EnumerationTypes; 7706 7707 /// The set of vector types that will be used in the built-in 7708 /// candidates. 7709 TypeSet VectorTypes; 7710 7711 /// The set of matrix types that will be used in the built-in 7712 /// candidates. 7713 TypeSet MatrixTypes; 7714 7715 /// A flag indicating non-record types are viable candidates 7716 bool HasNonRecordTypes; 7717 7718 /// A flag indicating whether either arithmetic or enumeration types 7719 /// were present in the candidate set. 7720 bool HasArithmeticOrEnumeralTypes; 7721 7722 /// A flag indicating whether the nullptr type was present in the 7723 /// candidate set. 7724 bool HasNullPtrType; 7725 7726 /// Sema - The semantic analysis instance where we are building the 7727 /// candidate type set. 7728 Sema &SemaRef; 7729 7730 /// Context - The AST context in which we will build the type sets. 7731 ASTContext &Context; 7732 7733 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7734 const Qualifiers &VisibleQuals); 7735 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7736 7737 public: 7738 /// iterator - Iterates through the types that are part of the set. 7739 typedef TypeSet::iterator iterator; 7740 7741 BuiltinCandidateTypeSet(Sema &SemaRef) 7742 : HasNonRecordTypes(false), 7743 HasArithmeticOrEnumeralTypes(false), 7744 HasNullPtrType(false), 7745 SemaRef(SemaRef), 7746 Context(SemaRef.Context) { } 7747 7748 void AddTypesConvertedFrom(QualType Ty, 7749 SourceLocation Loc, 7750 bool AllowUserConversions, 7751 bool AllowExplicitConversions, 7752 const Qualifiers &VisibleTypeConversionsQuals); 7753 7754 /// pointer_begin - First pointer type found; 7755 iterator pointer_begin() { return PointerTypes.begin(); } 7756 7757 /// pointer_end - Past the last pointer type found; 7758 iterator pointer_end() { return PointerTypes.end(); } 7759 7760 /// member_pointer_begin - First member pointer type found; 7761 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7762 7763 /// member_pointer_end - Past the last member pointer type found; 7764 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7765 7766 /// enumeration_begin - First enumeration type found; 7767 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7768 7769 /// enumeration_end - Past the last enumeration type found; 7770 iterator enumeration_end() { return EnumerationTypes.end(); } 7771 7772 llvm::iterator_range<iterator> vector_types() { return VectorTypes; } 7773 7774 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7775 7776 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7777 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7778 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7779 bool hasNullPtrType() const { return HasNullPtrType; } 7780 }; 7781 7782 } // end anonymous namespace 7783 7784 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7785 /// the set of pointer types along with any more-qualified variants of 7786 /// that type. For example, if @p Ty is "int const *", this routine 7787 /// will add "int const *", "int const volatile *", "int const 7788 /// restrict *", and "int const volatile restrict *" to the set of 7789 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7790 /// false otherwise. 7791 /// 7792 /// FIXME: what to do about extended qualifiers? 7793 bool 7794 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7795 const Qualifiers &VisibleQuals) { 7796 7797 // Insert this type. 7798 if (!PointerTypes.insert(Ty)) 7799 return false; 7800 7801 QualType PointeeTy; 7802 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7803 bool buildObjCPtr = false; 7804 if (!PointerTy) { 7805 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7806 PointeeTy = PTy->getPointeeType(); 7807 buildObjCPtr = true; 7808 } else { 7809 PointeeTy = PointerTy->getPointeeType(); 7810 } 7811 7812 // Don't add qualified variants of arrays. For one, they're not allowed 7813 // (the qualifier would sink to the element type), and for another, the 7814 // only overload situation where it matters is subscript or pointer +- int, 7815 // and those shouldn't have qualifier variants anyway. 7816 if (PointeeTy->isArrayType()) 7817 return true; 7818 7819 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7820 bool hasVolatile = VisibleQuals.hasVolatile(); 7821 bool hasRestrict = VisibleQuals.hasRestrict(); 7822 7823 // Iterate through all strict supersets of BaseCVR. 7824 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7825 if ((CVR | BaseCVR) != CVR) continue; 7826 // Skip over volatile if no volatile found anywhere in the types. 7827 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7828 7829 // Skip over restrict if no restrict found anywhere in the types, or if 7830 // the type cannot be restrict-qualified. 7831 if ((CVR & Qualifiers::Restrict) && 7832 (!hasRestrict || 7833 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7834 continue; 7835 7836 // Build qualified pointee type. 7837 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7838 7839 // Build qualified pointer type. 7840 QualType QPointerTy; 7841 if (!buildObjCPtr) 7842 QPointerTy = Context.getPointerType(QPointeeTy); 7843 else 7844 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7845 7846 // Insert qualified pointer type. 7847 PointerTypes.insert(QPointerTy); 7848 } 7849 7850 return true; 7851 } 7852 7853 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7854 /// to the set of pointer types along with any more-qualified variants of 7855 /// that type. For example, if @p Ty is "int const *", this routine 7856 /// will add "int const *", "int const volatile *", "int const 7857 /// restrict *", and "int const volatile restrict *" to the set of 7858 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7859 /// false otherwise. 7860 /// 7861 /// FIXME: what to do about extended qualifiers? 7862 bool 7863 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7864 QualType Ty) { 7865 // Insert this type. 7866 if (!MemberPointerTypes.insert(Ty)) 7867 return false; 7868 7869 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7870 assert(PointerTy && "type was not a member pointer type!"); 7871 7872 QualType PointeeTy = PointerTy->getPointeeType(); 7873 // Don't add qualified variants of arrays. For one, they're not allowed 7874 // (the qualifier would sink to the element type), and for another, the 7875 // only overload situation where it matters is subscript or pointer +- int, 7876 // and those shouldn't have qualifier variants anyway. 7877 if (PointeeTy->isArrayType()) 7878 return true; 7879 const Type *ClassTy = PointerTy->getClass(); 7880 7881 // Iterate through all strict supersets of the pointee type's CVR 7882 // qualifiers. 7883 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7884 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7885 if ((CVR | BaseCVR) != CVR) continue; 7886 7887 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7888 MemberPointerTypes.insert( 7889 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7890 } 7891 7892 return true; 7893 } 7894 7895 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7896 /// Ty can be implicit converted to the given set of @p Types. We're 7897 /// primarily interested in pointer types and enumeration types. We also 7898 /// take member pointer types, for the conditional operator. 7899 /// AllowUserConversions is true if we should look at the conversion 7900 /// functions of a class type, and AllowExplicitConversions if we 7901 /// should also include the explicit conversion functions of a class 7902 /// type. 7903 void 7904 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7905 SourceLocation Loc, 7906 bool AllowUserConversions, 7907 bool AllowExplicitConversions, 7908 const Qualifiers &VisibleQuals) { 7909 // Only deal with canonical types. 7910 Ty = Context.getCanonicalType(Ty); 7911 7912 // Look through reference types; they aren't part of the type of an 7913 // expression for the purposes of conversions. 7914 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7915 Ty = RefTy->getPointeeType(); 7916 7917 // If we're dealing with an array type, decay to the pointer. 7918 if (Ty->isArrayType()) 7919 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7920 7921 // Otherwise, we don't care about qualifiers on the type. 7922 Ty = Ty.getLocalUnqualifiedType(); 7923 7924 // Flag if we ever add a non-record type. 7925 const RecordType *TyRec = Ty->getAs<RecordType>(); 7926 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7927 7928 // Flag if we encounter an arithmetic type. 7929 HasArithmeticOrEnumeralTypes = 7930 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7931 7932 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7933 PointerTypes.insert(Ty); 7934 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7935 // Insert our type, and its more-qualified variants, into the set 7936 // of types. 7937 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7938 return; 7939 } else if (Ty->isMemberPointerType()) { 7940 // Member pointers are far easier, since the pointee can't be converted. 7941 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7942 return; 7943 } else if (Ty->isEnumeralType()) { 7944 HasArithmeticOrEnumeralTypes = true; 7945 EnumerationTypes.insert(Ty); 7946 } else if (Ty->isVectorType()) { 7947 // We treat vector types as arithmetic types in many contexts as an 7948 // extension. 7949 HasArithmeticOrEnumeralTypes = true; 7950 VectorTypes.insert(Ty); 7951 } else if (Ty->isMatrixType()) { 7952 // Similar to vector types, we treat vector types as arithmetic types in 7953 // many contexts as an extension. 7954 HasArithmeticOrEnumeralTypes = true; 7955 MatrixTypes.insert(Ty); 7956 } else if (Ty->isNullPtrType()) { 7957 HasNullPtrType = true; 7958 } else if (AllowUserConversions && TyRec) { 7959 // No conversion functions in incomplete types. 7960 if (!SemaRef.isCompleteType(Loc, Ty)) 7961 return; 7962 7963 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7964 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7965 if (isa<UsingShadowDecl>(D)) 7966 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7967 7968 // Skip conversion function templates; they don't tell us anything 7969 // about which builtin types we can convert to. 7970 if (isa<FunctionTemplateDecl>(D)) 7971 continue; 7972 7973 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7974 if (AllowExplicitConversions || !Conv->isExplicit()) { 7975 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7976 VisibleQuals); 7977 } 7978 } 7979 } 7980 } 7981 /// Helper function for adjusting address spaces for the pointer or reference 7982 /// operands of builtin operators depending on the argument. 7983 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7984 Expr *Arg) { 7985 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7986 } 7987 7988 /// Helper function for AddBuiltinOperatorCandidates() that adds 7989 /// the volatile- and non-volatile-qualified assignment operators for the 7990 /// given type to the candidate set. 7991 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7992 QualType T, 7993 ArrayRef<Expr *> Args, 7994 OverloadCandidateSet &CandidateSet) { 7995 QualType ParamTypes[2]; 7996 7997 // T& operator=(T&, T) 7998 ParamTypes[0] = S.Context.getLValueReferenceType( 7999 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 8000 ParamTypes[1] = T; 8001 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8002 /*IsAssignmentOperator=*/true); 8003 8004 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 8005 // volatile T& operator=(volatile T&, T) 8006 ParamTypes[0] = S.Context.getLValueReferenceType( 8007 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 8008 Args[0])); 8009 ParamTypes[1] = T; 8010 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8011 /*IsAssignmentOperator=*/true); 8012 } 8013 } 8014 8015 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 8016 /// if any, found in visible type conversion functions found in ArgExpr's type. 8017 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 8018 Qualifiers VRQuals; 8019 const RecordType *TyRec; 8020 if (const MemberPointerType *RHSMPType = 8021 ArgExpr->getType()->getAs<MemberPointerType>()) 8022 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8023 else 8024 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8025 if (!TyRec) { 8026 // Just to be safe, assume the worst case. 8027 VRQuals.addVolatile(); 8028 VRQuals.addRestrict(); 8029 return VRQuals; 8030 } 8031 8032 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8033 if (!ClassDecl->hasDefinition()) 8034 return VRQuals; 8035 8036 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8037 if (isa<UsingShadowDecl>(D)) 8038 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8039 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8040 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8041 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8042 CanTy = ResTypeRef->getPointeeType(); 8043 // Need to go down the pointer/mempointer chain and add qualifiers 8044 // as see them. 8045 bool done = false; 8046 while (!done) { 8047 if (CanTy.isRestrictQualified()) 8048 VRQuals.addRestrict(); 8049 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8050 CanTy = ResTypePtr->getPointeeType(); 8051 else if (const MemberPointerType *ResTypeMPtr = 8052 CanTy->getAs<MemberPointerType>()) 8053 CanTy = ResTypeMPtr->getPointeeType(); 8054 else 8055 done = true; 8056 if (CanTy.isVolatileQualified()) 8057 VRQuals.addVolatile(); 8058 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8059 return VRQuals; 8060 } 8061 } 8062 } 8063 return VRQuals; 8064 } 8065 8066 namespace { 8067 8068 /// Helper class to manage the addition of builtin operator overload 8069 /// candidates. It provides shared state and utility methods used throughout 8070 /// the process, as well as a helper method to add each group of builtin 8071 /// operator overloads from the standard to a candidate set. 8072 class BuiltinOperatorOverloadBuilder { 8073 // Common instance state available to all overload candidate addition methods. 8074 Sema &S; 8075 ArrayRef<Expr *> Args; 8076 Qualifiers VisibleTypeConversionsQuals; 8077 bool HasArithmeticOrEnumeralCandidateType; 8078 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8079 OverloadCandidateSet &CandidateSet; 8080 8081 static constexpr int ArithmeticTypesCap = 24; 8082 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8083 8084 // Define some indices used to iterate over the arithmetic types in 8085 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8086 // types are that preserved by promotion (C++ [over.built]p2). 8087 unsigned FirstIntegralType, 8088 LastIntegralType; 8089 unsigned FirstPromotedIntegralType, 8090 LastPromotedIntegralType; 8091 unsigned FirstPromotedArithmeticType, 8092 LastPromotedArithmeticType; 8093 unsigned NumArithmeticTypes; 8094 8095 void InitArithmeticTypes() { 8096 // Start of promoted types. 8097 FirstPromotedArithmeticType = 0; 8098 ArithmeticTypes.push_back(S.Context.FloatTy); 8099 ArithmeticTypes.push_back(S.Context.DoubleTy); 8100 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8101 if (S.Context.getTargetInfo().hasFloat128Type()) 8102 ArithmeticTypes.push_back(S.Context.Float128Ty); 8103 8104 // Start of integral types. 8105 FirstIntegralType = ArithmeticTypes.size(); 8106 FirstPromotedIntegralType = ArithmeticTypes.size(); 8107 ArithmeticTypes.push_back(S.Context.IntTy); 8108 ArithmeticTypes.push_back(S.Context.LongTy); 8109 ArithmeticTypes.push_back(S.Context.LongLongTy); 8110 if (S.Context.getTargetInfo().hasInt128Type()) 8111 ArithmeticTypes.push_back(S.Context.Int128Ty); 8112 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8113 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8114 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8115 if (S.Context.getTargetInfo().hasInt128Type()) 8116 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8117 LastPromotedIntegralType = ArithmeticTypes.size(); 8118 LastPromotedArithmeticType = ArithmeticTypes.size(); 8119 // End of promoted types. 8120 8121 ArithmeticTypes.push_back(S.Context.BoolTy); 8122 ArithmeticTypes.push_back(S.Context.CharTy); 8123 ArithmeticTypes.push_back(S.Context.WCharTy); 8124 if (S.Context.getLangOpts().Char8) 8125 ArithmeticTypes.push_back(S.Context.Char8Ty); 8126 ArithmeticTypes.push_back(S.Context.Char16Ty); 8127 ArithmeticTypes.push_back(S.Context.Char32Ty); 8128 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8129 ArithmeticTypes.push_back(S.Context.ShortTy); 8130 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8131 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8132 LastIntegralType = ArithmeticTypes.size(); 8133 NumArithmeticTypes = ArithmeticTypes.size(); 8134 // End of integral types. 8135 // FIXME: What about complex? What about half? 8136 8137 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8138 "Enough inline storage for all arithmetic types."); 8139 } 8140 8141 /// Helper method to factor out the common pattern of adding overloads 8142 /// for '++' and '--' builtin operators. 8143 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8144 bool HasVolatile, 8145 bool HasRestrict) { 8146 QualType ParamTypes[2] = { 8147 S.Context.getLValueReferenceType(CandidateTy), 8148 S.Context.IntTy 8149 }; 8150 8151 // Non-volatile version. 8152 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8153 8154 // Use a heuristic to reduce number of builtin candidates in the set: 8155 // add volatile version only if there are conversions to a volatile type. 8156 if (HasVolatile) { 8157 ParamTypes[0] = 8158 S.Context.getLValueReferenceType( 8159 S.Context.getVolatileType(CandidateTy)); 8160 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8161 } 8162 8163 // Add restrict version only if there are conversions to a restrict type 8164 // and our candidate type is a non-restrict-qualified pointer. 8165 if (HasRestrict && CandidateTy->isAnyPointerType() && 8166 !CandidateTy.isRestrictQualified()) { 8167 ParamTypes[0] 8168 = S.Context.getLValueReferenceType( 8169 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8170 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8171 8172 if (HasVolatile) { 8173 ParamTypes[0] 8174 = S.Context.getLValueReferenceType( 8175 S.Context.getCVRQualifiedType(CandidateTy, 8176 (Qualifiers::Volatile | 8177 Qualifiers::Restrict))); 8178 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8179 } 8180 } 8181 8182 } 8183 8184 /// Helper to add an overload candidate for a binary builtin with types \p L 8185 /// and \p R. 8186 void AddCandidate(QualType L, QualType R) { 8187 QualType LandR[2] = {L, R}; 8188 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8189 } 8190 8191 public: 8192 BuiltinOperatorOverloadBuilder( 8193 Sema &S, ArrayRef<Expr *> Args, 8194 Qualifiers VisibleTypeConversionsQuals, 8195 bool HasArithmeticOrEnumeralCandidateType, 8196 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8197 OverloadCandidateSet &CandidateSet) 8198 : S(S), Args(Args), 8199 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8200 HasArithmeticOrEnumeralCandidateType( 8201 HasArithmeticOrEnumeralCandidateType), 8202 CandidateTypes(CandidateTypes), 8203 CandidateSet(CandidateSet) { 8204 8205 InitArithmeticTypes(); 8206 } 8207 8208 // Increment is deprecated for bool since C++17. 8209 // 8210 // C++ [over.built]p3: 8211 // 8212 // For every pair (T, VQ), where T is an arithmetic type other 8213 // than bool, and VQ is either volatile or empty, there exist 8214 // candidate operator functions of the form 8215 // 8216 // VQ T& operator++(VQ T&); 8217 // T operator++(VQ T&, int); 8218 // 8219 // C++ [over.built]p4: 8220 // 8221 // For every pair (T, VQ), where T is an arithmetic type other 8222 // than bool, and VQ is either volatile or empty, there exist 8223 // candidate operator functions of the form 8224 // 8225 // VQ T& operator--(VQ T&); 8226 // T operator--(VQ T&, int); 8227 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8228 if (!HasArithmeticOrEnumeralCandidateType) 8229 return; 8230 8231 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8232 const auto TypeOfT = ArithmeticTypes[Arith]; 8233 if (TypeOfT == S.Context.BoolTy) { 8234 if (Op == OO_MinusMinus) 8235 continue; 8236 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8237 continue; 8238 } 8239 addPlusPlusMinusMinusStyleOverloads( 8240 TypeOfT, 8241 VisibleTypeConversionsQuals.hasVolatile(), 8242 VisibleTypeConversionsQuals.hasRestrict()); 8243 } 8244 } 8245 8246 // C++ [over.built]p5: 8247 // 8248 // For every pair (T, VQ), where T is a cv-qualified or 8249 // cv-unqualified object type, and VQ is either volatile or 8250 // empty, there exist candidate operator functions of the form 8251 // 8252 // T*VQ& operator++(T*VQ&); 8253 // T*VQ& operator--(T*VQ&); 8254 // T* operator++(T*VQ&, int); 8255 // T* operator--(T*VQ&, int); 8256 void addPlusPlusMinusMinusPointerOverloads() { 8257 for (BuiltinCandidateTypeSet::iterator 8258 Ptr = CandidateTypes[0].pointer_begin(), 8259 PtrEnd = CandidateTypes[0].pointer_end(); 8260 Ptr != PtrEnd; ++Ptr) { 8261 // Skip pointer types that aren't pointers to object types. 8262 if (!(*Ptr)->getPointeeType()->isObjectType()) 8263 continue; 8264 8265 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8266 (!(*Ptr).isVolatileQualified() && 8267 VisibleTypeConversionsQuals.hasVolatile()), 8268 (!(*Ptr).isRestrictQualified() && 8269 VisibleTypeConversionsQuals.hasRestrict())); 8270 } 8271 } 8272 8273 // C++ [over.built]p6: 8274 // For every cv-qualified or cv-unqualified object type T, there 8275 // exist candidate operator functions of the form 8276 // 8277 // T& operator*(T*); 8278 // 8279 // C++ [over.built]p7: 8280 // For every function type T that does not have cv-qualifiers or a 8281 // ref-qualifier, there exist candidate operator functions of the form 8282 // T& operator*(T*); 8283 void addUnaryStarPointerOverloads() { 8284 for (BuiltinCandidateTypeSet::iterator 8285 Ptr = CandidateTypes[0].pointer_begin(), 8286 PtrEnd = CandidateTypes[0].pointer_end(); 8287 Ptr != PtrEnd; ++Ptr) { 8288 QualType ParamTy = *Ptr; 8289 QualType PointeeTy = ParamTy->getPointeeType(); 8290 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8291 continue; 8292 8293 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8294 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8295 continue; 8296 8297 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8298 } 8299 } 8300 8301 // C++ [over.built]p9: 8302 // For every promoted arithmetic type T, there exist candidate 8303 // operator functions of the form 8304 // 8305 // T operator+(T); 8306 // T operator-(T); 8307 void addUnaryPlusOrMinusArithmeticOverloads() { 8308 if (!HasArithmeticOrEnumeralCandidateType) 8309 return; 8310 8311 for (unsigned Arith = FirstPromotedArithmeticType; 8312 Arith < LastPromotedArithmeticType; ++Arith) { 8313 QualType ArithTy = ArithmeticTypes[Arith]; 8314 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8315 } 8316 8317 // Extension: We also add these operators for vector types. 8318 for (QualType VecTy : CandidateTypes[0].vector_types()) 8319 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8320 } 8321 8322 // C++ [over.built]p8: 8323 // For every type T, there exist candidate operator functions of 8324 // the form 8325 // 8326 // T* operator+(T*); 8327 void addUnaryPlusPointerOverloads() { 8328 for (BuiltinCandidateTypeSet::iterator 8329 Ptr = CandidateTypes[0].pointer_begin(), 8330 PtrEnd = CandidateTypes[0].pointer_end(); 8331 Ptr != PtrEnd; ++Ptr) { 8332 QualType ParamTy = *Ptr; 8333 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8334 } 8335 } 8336 8337 // C++ [over.built]p10: 8338 // For every promoted integral type T, there exist candidate 8339 // operator functions of the form 8340 // 8341 // T operator~(T); 8342 void addUnaryTildePromotedIntegralOverloads() { 8343 if (!HasArithmeticOrEnumeralCandidateType) 8344 return; 8345 8346 for (unsigned Int = FirstPromotedIntegralType; 8347 Int < LastPromotedIntegralType; ++Int) { 8348 QualType IntTy = ArithmeticTypes[Int]; 8349 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8350 } 8351 8352 // Extension: We also add this operator for vector types. 8353 for (QualType VecTy : CandidateTypes[0].vector_types()) 8354 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8355 } 8356 8357 // C++ [over.match.oper]p16: 8358 // For every pointer to member type T or type std::nullptr_t, there 8359 // exist candidate operator functions of the form 8360 // 8361 // bool operator==(T,T); 8362 // bool operator!=(T,T); 8363 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8364 /// Set of (canonical) types that we've already handled. 8365 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8366 8367 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8368 for (BuiltinCandidateTypeSet::iterator 8369 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8370 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8371 MemPtr != MemPtrEnd; 8372 ++MemPtr) { 8373 // Don't add the same builtin candidate twice. 8374 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8375 continue; 8376 8377 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8378 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8379 } 8380 8381 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8382 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8383 if (AddedTypes.insert(NullPtrTy).second) { 8384 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8385 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8386 } 8387 } 8388 } 8389 } 8390 8391 // C++ [over.built]p15: 8392 // 8393 // For every T, where T is an enumeration type or a pointer type, 8394 // there exist candidate operator functions of the form 8395 // 8396 // bool operator<(T, T); 8397 // bool operator>(T, T); 8398 // bool operator<=(T, T); 8399 // bool operator>=(T, T); 8400 // bool operator==(T, T); 8401 // bool operator!=(T, T); 8402 // R operator<=>(T, T) 8403 void addGenericBinaryPointerOrEnumeralOverloads() { 8404 // C++ [over.match.oper]p3: 8405 // [...]the built-in candidates include all of the candidate operator 8406 // functions defined in 13.6 that, compared to the given operator, [...] 8407 // do not have the same parameter-type-list as any non-template non-member 8408 // candidate. 8409 // 8410 // Note that in practice, this only affects enumeration types because there 8411 // aren't any built-in candidates of record type, and a user-defined operator 8412 // must have an operand of record or enumeration type. Also, the only other 8413 // overloaded operator with enumeration arguments, operator=, 8414 // cannot be overloaded for enumeration types, so this is the only place 8415 // where we must suppress candidates like this. 8416 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8417 UserDefinedBinaryOperators; 8418 8419 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8420 if (CandidateTypes[ArgIdx].enumeration_begin() != 8421 CandidateTypes[ArgIdx].enumeration_end()) { 8422 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8423 CEnd = CandidateSet.end(); 8424 C != CEnd; ++C) { 8425 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8426 continue; 8427 8428 if (C->Function->isFunctionTemplateSpecialization()) 8429 continue; 8430 8431 // We interpret "same parameter-type-list" as applying to the 8432 // "synthesized candidate, with the order of the two parameters 8433 // reversed", not to the original function. 8434 bool Reversed = C->isReversed(); 8435 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8436 ->getType() 8437 .getUnqualifiedType(); 8438 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8439 ->getType() 8440 .getUnqualifiedType(); 8441 8442 // Skip if either parameter isn't of enumeral type. 8443 if (!FirstParamType->isEnumeralType() || 8444 !SecondParamType->isEnumeralType()) 8445 continue; 8446 8447 // Add this operator to the set of known user-defined operators. 8448 UserDefinedBinaryOperators.insert( 8449 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8450 S.Context.getCanonicalType(SecondParamType))); 8451 } 8452 } 8453 } 8454 8455 /// Set of (canonical) types that we've already handled. 8456 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8457 8458 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8459 for (BuiltinCandidateTypeSet::iterator 8460 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8461 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8462 Ptr != PtrEnd; ++Ptr) { 8463 // Don't add the same builtin candidate twice. 8464 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8465 continue; 8466 8467 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8469 } 8470 for (BuiltinCandidateTypeSet::iterator 8471 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8472 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8473 Enum != EnumEnd; ++Enum) { 8474 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8475 8476 // Don't add the same builtin candidate twice, or if a user defined 8477 // candidate exists. 8478 if (!AddedTypes.insert(CanonType).second || 8479 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8480 CanonType))) 8481 continue; 8482 QualType ParamTypes[2] = { *Enum, *Enum }; 8483 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8484 } 8485 } 8486 } 8487 8488 // C++ [over.built]p13: 8489 // 8490 // For every cv-qualified or cv-unqualified object type T 8491 // there exist candidate operator functions of the form 8492 // 8493 // T* operator+(T*, ptrdiff_t); 8494 // T& operator[](T*, ptrdiff_t); [BELOW] 8495 // T* operator-(T*, ptrdiff_t); 8496 // T* operator+(ptrdiff_t, T*); 8497 // T& operator[](ptrdiff_t, T*); [BELOW] 8498 // 8499 // C++ [over.built]p14: 8500 // 8501 // For every T, where T is a pointer to object type, there 8502 // exist candidate operator functions of the form 8503 // 8504 // ptrdiff_t operator-(T, T); 8505 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8506 /// Set of (canonical) types that we've already handled. 8507 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8508 8509 for (int Arg = 0; Arg < 2; ++Arg) { 8510 QualType AsymmetricParamTypes[2] = { 8511 S.Context.getPointerDiffType(), 8512 S.Context.getPointerDiffType(), 8513 }; 8514 for (BuiltinCandidateTypeSet::iterator 8515 Ptr = CandidateTypes[Arg].pointer_begin(), 8516 PtrEnd = CandidateTypes[Arg].pointer_end(); 8517 Ptr != PtrEnd; ++Ptr) { 8518 QualType PointeeTy = (*Ptr)->getPointeeType(); 8519 if (!PointeeTy->isObjectType()) 8520 continue; 8521 8522 AsymmetricParamTypes[Arg] = *Ptr; 8523 if (Arg == 0 || Op == OO_Plus) { 8524 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8525 // T* operator+(ptrdiff_t, T*); 8526 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8527 } 8528 if (Op == OO_Minus) { 8529 // ptrdiff_t operator-(T, T); 8530 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8531 continue; 8532 8533 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8534 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8535 } 8536 } 8537 } 8538 } 8539 8540 // C++ [over.built]p12: 8541 // 8542 // For every pair of promoted arithmetic types L and R, there 8543 // exist candidate operator functions of the form 8544 // 8545 // LR operator*(L, R); 8546 // LR operator/(L, R); 8547 // LR operator+(L, R); 8548 // LR operator-(L, R); 8549 // bool operator<(L, R); 8550 // bool operator>(L, R); 8551 // bool operator<=(L, R); 8552 // bool operator>=(L, R); 8553 // bool operator==(L, R); 8554 // bool operator!=(L, R); 8555 // 8556 // where LR is the result of the usual arithmetic conversions 8557 // between types L and R. 8558 // 8559 // C++ [over.built]p24: 8560 // 8561 // For every pair of promoted arithmetic types L and R, there exist 8562 // candidate operator functions of the form 8563 // 8564 // LR operator?(bool, L, R); 8565 // 8566 // where LR is the result of the usual arithmetic conversions 8567 // between types L and R. 8568 // Our candidates ignore the first parameter. 8569 void addGenericBinaryArithmeticOverloads() { 8570 if (!HasArithmeticOrEnumeralCandidateType) 8571 return; 8572 8573 for (unsigned Left = FirstPromotedArithmeticType; 8574 Left < LastPromotedArithmeticType; ++Left) { 8575 for (unsigned Right = FirstPromotedArithmeticType; 8576 Right < LastPromotedArithmeticType; ++Right) { 8577 QualType LandR[2] = { ArithmeticTypes[Left], 8578 ArithmeticTypes[Right] }; 8579 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8580 } 8581 } 8582 8583 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8584 // conditional operator for vector types. 8585 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8586 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) { 8587 QualType LandR[2] = {Vec1Ty, Vec2Ty}; 8588 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8589 } 8590 } 8591 8592 /// Add binary operator overloads for each candidate matrix type M1, M2: 8593 /// * (M1, M1) -> M1 8594 /// * (M1, M1.getElementType()) -> M1 8595 /// * (M2.getElementType(), M2) -> M2 8596 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8597 void addMatrixBinaryArithmeticOverloads() { 8598 if (!HasArithmeticOrEnumeralCandidateType) 8599 return; 8600 8601 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8602 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8603 AddCandidate(M1, M1); 8604 } 8605 8606 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8607 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8608 if (!CandidateTypes[0].containsMatrixType(M2)) 8609 AddCandidate(M2, M2); 8610 } 8611 } 8612 8613 // C++2a [over.built]p14: 8614 // 8615 // For every integral type T there exists a candidate operator function 8616 // of the form 8617 // 8618 // std::strong_ordering operator<=>(T, T) 8619 // 8620 // C++2a [over.built]p15: 8621 // 8622 // For every pair of floating-point types L and R, there exists a candidate 8623 // operator function of the form 8624 // 8625 // std::partial_ordering operator<=>(L, R); 8626 // 8627 // FIXME: The current specification for integral types doesn't play nice with 8628 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8629 // comparisons. Under the current spec this can lead to ambiguity during 8630 // overload resolution. For example: 8631 // 8632 // enum A : int {a}; 8633 // auto x = (a <=> (long)42); 8634 // 8635 // error: call is ambiguous for arguments 'A' and 'long'. 8636 // note: candidate operator<=>(int, int) 8637 // note: candidate operator<=>(long, long) 8638 // 8639 // To avoid this error, this function deviates from the specification and adds 8640 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8641 // arithmetic types (the same as the generic relational overloads). 8642 // 8643 // For now this function acts as a placeholder. 8644 void addThreeWayArithmeticOverloads() { 8645 addGenericBinaryArithmeticOverloads(); 8646 } 8647 8648 // C++ [over.built]p17: 8649 // 8650 // For every pair of promoted integral types L and R, there 8651 // exist candidate operator functions of the form 8652 // 8653 // LR operator%(L, R); 8654 // LR operator&(L, R); 8655 // LR operator^(L, R); 8656 // LR operator|(L, R); 8657 // L operator<<(L, R); 8658 // L operator>>(L, R); 8659 // 8660 // where LR is the result of the usual arithmetic conversions 8661 // between types L and R. 8662 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8663 if (!HasArithmeticOrEnumeralCandidateType) 8664 return; 8665 8666 for (unsigned Left = FirstPromotedIntegralType; 8667 Left < LastPromotedIntegralType; ++Left) { 8668 for (unsigned Right = FirstPromotedIntegralType; 8669 Right < LastPromotedIntegralType; ++Right) { 8670 QualType LandR[2] = { ArithmeticTypes[Left], 8671 ArithmeticTypes[Right] }; 8672 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8673 } 8674 } 8675 } 8676 8677 // C++ [over.built]p20: 8678 // 8679 // For every pair (T, VQ), where T is an enumeration or 8680 // pointer to member type and VQ is either volatile or 8681 // empty, there exist candidate operator functions of the form 8682 // 8683 // VQ T& operator=(VQ T&, T); 8684 void addAssignmentMemberPointerOrEnumeralOverloads() { 8685 /// Set of (canonical) types that we've already handled. 8686 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8687 8688 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8689 for (BuiltinCandidateTypeSet::iterator 8690 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8691 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8692 Enum != EnumEnd; ++Enum) { 8693 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8694 continue; 8695 8696 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8697 } 8698 8699 for (BuiltinCandidateTypeSet::iterator 8700 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8701 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8702 MemPtr != MemPtrEnd; ++MemPtr) { 8703 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8704 continue; 8705 8706 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8707 } 8708 } 8709 } 8710 8711 // C++ [over.built]p19: 8712 // 8713 // For every pair (T, VQ), where T is any type and VQ is either 8714 // volatile or empty, there exist candidate operator functions 8715 // of the form 8716 // 8717 // T*VQ& operator=(T*VQ&, T*); 8718 // 8719 // C++ [over.built]p21: 8720 // 8721 // For every pair (T, VQ), where T is a cv-qualified or 8722 // cv-unqualified object type and VQ is either volatile or 8723 // empty, there exist candidate operator functions of the form 8724 // 8725 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8726 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8727 void addAssignmentPointerOverloads(bool isEqualOp) { 8728 /// Set of (canonical) types that we've already handled. 8729 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8730 8731 for (BuiltinCandidateTypeSet::iterator 8732 Ptr = CandidateTypes[0].pointer_begin(), 8733 PtrEnd = CandidateTypes[0].pointer_end(); 8734 Ptr != PtrEnd; ++Ptr) { 8735 // If this is operator=, keep track of the builtin candidates we added. 8736 if (isEqualOp) 8737 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8738 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8739 continue; 8740 8741 // non-volatile version 8742 QualType ParamTypes[2] = { 8743 S.Context.getLValueReferenceType(*Ptr), 8744 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8745 }; 8746 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8747 /*IsAssignmentOperator=*/ isEqualOp); 8748 8749 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8750 VisibleTypeConversionsQuals.hasVolatile(); 8751 if (NeedVolatile) { 8752 // volatile version 8753 ParamTypes[0] = 8754 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8755 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8756 /*IsAssignmentOperator=*/isEqualOp); 8757 } 8758 8759 if (!(*Ptr).isRestrictQualified() && 8760 VisibleTypeConversionsQuals.hasRestrict()) { 8761 // restrict version 8762 ParamTypes[0] 8763 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8764 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8765 /*IsAssignmentOperator=*/isEqualOp); 8766 8767 if (NeedVolatile) { 8768 // volatile restrict version 8769 ParamTypes[0] 8770 = S.Context.getLValueReferenceType( 8771 S.Context.getCVRQualifiedType(*Ptr, 8772 (Qualifiers::Volatile | 8773 Qualifiers::Restrict))); 8774 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8775 /*IsAssignmentOperator=*/isEqualOp); 8776 } 8777 } 8778 } 8779 8780 if (isEqualOp) { 8781 for (BuiltinCandidateTypeSet::iterator 8782 Ptr = CandidateTypes[1].pointer_begin(), 8783 PtrEnd = CandidateTypes[1].pointer_end(); 8784 Ptr != PtrEnd; ++Ptr) { 8785 // Make sure we don't add the same candidate twice. 8786 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8787 continue; 8788 8789 QualType ParamTypes[2] = { 8790 S.Context.getLValueReferenceType(*Ptr), 8791 *Ptr, 8792 }; 8793 8794 // non-volatile version 8795 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8796 /*IsAssignmentOperator=*/true); 8797 8798 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8799 VisibleTypeConversionsQuals.hasVolatile(); 8800 if (NeedVolatile) { 8801 // volatile version 8802 ParamTypes[0] = 8803 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8804 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8805 /*IsAssignmentOperator=*/true); 8806 } 8807 8808 if (!(*Ptr).isRestrictQualified() && 8809 VisibleTypeConversionsQuals.hasRestrict()) { 8810 // restrict version 8811 ParamTypes[0] 8812 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8813 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8814 /*IsAssignmentOperator=*/true); 8815 8816 if (NeedVolatile) { 8817 // volatile restrict version 8818 ParamTypes[0] 8819 = S.Context.getLValueReferenceType( 8820 S.Context.getCVRQualifiedType(*Ptr, 8821 (Qualifiers::Volatile | 8822 Qualifiers::Restrict))); 8823 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8824 /*IsAssignmentOperator=*/true); 8825 } 8826 } 8827 } 8828 } 8829 } 8830 8831 // C++ [over.built]p18: 8832 // 8833 // For every triple (L, VQ, R), where L is an arithmetic type, 8834 // VQ is either volatile or empty, and R is a promoted 8835 // arithmetic type, there exist candidate operator functions of 8836 // the form 8837 // 8838 // VQ L& operator=(VQ L&, R); 8839 // VQ L& operator*=(VQ L&, R); 8840 // VQ L& operator/=(VQ L&, R); 8841 // VQ L& operator+=(VQ L&, R); 8842 // VQ L& operator-=(VQ L&, R); 8843 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8844 if (!HasArithmeticOrEnumeralCandidateType) 8845 return; 8846 8847 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8848 for (unsigned Right = FirstPromotedArithmeticType; 8849 Right < LastPromotedArithmeticType; ++Right) { 8850 QualType ParamTypes[2]; 8851 ParamTypes[1] = ArithmeticTypes[Right]; 8852 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8853 S, ArithmeticTypes[Left], Args[0]); 8854 // Add this built-in operator as a candidate (VQ is empty). 8855 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8856 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8857 /*IsAssignmentOperator=*/isEqualOp); 8858 8859 // Add this built-in operator as a candidate (VQ is 'volatile'). 8860 if (VisibleTypeConversionsQuals.hasVolatile()) { 8861 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8862 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8863 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8864 /*IsAssignmentOperator=*/isEqualOp); 8865 } 8866 } 8867 } 8868 8869 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8870 for (QualType Vec1Ty : CandidateTypes[0].vector_types()) 8871 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) { 8872 QualType ParamTypes[2]; 8873 ParamTypes[1] = Vec2Ty; 8874 // Add this built-in operator as a candidate (VQ is empty). 8875 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty); 8876 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8877 /*IsAssignmentOperator=*/isEqualOp); 8878 8879 // Add this built-in operator as a candidate (VQ is 'volatile'). 8880 if (VisibleTypeConversionsQuals.hasVolatile()) { 8881 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty); 8882 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8883 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8884 /*IsAssignmentOperator=*/isEqualOp); 8885 } 8886 } 8887 } 8888 8889 // C++ [over.built]p22: 8890 // 8891 // For every triple (L, VQ, R), where L is an integral type, VQ 8892 // is either volatile or empty, and R is a promoted integral 8893 // type, there exist candidate operator functions of the form 8894 // 8895 // VQ L& operator%=(VQ L&, R); 8896 // VQ L& operator<<=(VQ L&, R); 8897 // VQ L& operator>>=(VQ L&, R); 8898 // VQ L& operator&=(VQ L&, R); 8899 // VQ L& operator^=(VQ L&, R); 8900 // VQ L& operator|=(VQ L&, R); 8901 void addAssignmentIntegralOverloads() { 8902 if (!HasArithmeticOrEnumeralCandidateType) 8903 return; 8904 8905 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8906 for (unsigned Right = FirstPromotedIntegralType; 8907 Right < LastPromotedIntegralType; ++Right) { 8908 QualType ParamTypes[2]; 8909 ParamTypes[1] = ArithmeticTypes[Right]; 8910 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8911 S, ArithmeticTypes[Left], Args[0]); 8912 // Add this built-in operator as a candidate (VQ is empty). 8913 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8914 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8915 if (VisibleTypeConversionsQuals.hasVolatile()) { 8916 // Add this built-in operator as a candidate (VQ is 'volatile'). 8917 ParamTypes[0] = LeftBaseTy; 8918 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8919 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8920 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8921 } 8922 } 8923 } 8924 } 8925 8926 // C++ [over.operator]p23: 8927 // 8928 // There also exist candidate operator functions of the form 8929 // 8930 // bool operator!(bool); 8931 // bool operator&&(bool, bool); 8932 // bool operator||(bool, bool); 8933 void addExclaimOverload() { 8934 QualType ParamTy = S.Context.BoolTy; 8935 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8936 /*IsAssignmentOperator=*/false, 8937 /*NumContextualBoolArguments=*/1); 8938 } 8939 void addAmpAmpOrPipePipeOverload() { 8940 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8941 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8942 /*IsAssignmentOperator=*/false, 8943 /*NumContextualBoolArguments=*/2); 8944 } 8945 8946 // C++ [over.built]p13: 8947 // 8948 // For every cv-qualified or cv-unqualified object type T there 8949 // exist candidate operator functions of the form 8950 // 8951 // T* operator+(T*, ptrdiff_t); [ABOVE] 8952 // T& operator[](T*, ptrdiff_t); 8953 // T* operator-(T*, ptrdiff_t); [ABOVE] 8954 // T* operator+(ptrdiff_t, T*); [ABOVE] 8955 // T& operator[](ptrdiff_t, T*); 8956 void addSubscriptOverloads() { 8957 for (BuiltinCandidateTypeSet::iterator 8958 Ptr = CandidateTypes[0].pointer_begin(), 8959 PtrEnd = CandidateTypes[0].pointer_end(); 8960 Ptr != PtrEnd; ++Ptr) { 8961 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8962 QualType PointeeType = (*Ptr)->getPointeeType(); 8963 if (!PointeeType->isObjectType()) 8964 continue; 8965 8966 // T& operator[](T*, ptrdiff_t) 8967 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8968 } 8969 8970 for (BuiltinCandidateTypeSet::iterator 8971 Ptr = CandidateTypes[1].pointer_begin(), 8972 PtrEnd = CandidateTypes[1].pointer_end(); 8973 Ptr != PtrEnd; ++Ptr) { 8974 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8975 QualType PointeeType = (*Ptr)->getPointeeType(); 8976 if (!PointeeType->isObjectType()) 8977 continue; 8978 8979 // T& operator[](ptrdiff_t, T*) 8980 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8981 } 8982 } 8983 8984 // C++ [over.built]p11: 8985 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8986 // C1 is the same type as C2 or is a derived class of C2, T is an object 8987 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8988 // there exist candidate operator functions of the form 8989 // 8990 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8991 // 8992 // where CV12 is the union of CV1 and CV2. 8993 void addArrowStarOverloads() { 8994 for (BuiltinCandidateTypeSet::iterator 8995 Ptr = CandidateTypes[0].pointer_begin(), 8996 PtrEnd = CandidateTypes[0].pointer_end(); 8997 Ptr != PtrEnd; ++Ptr) { 8998 QualType C1Ty = (*Ptr); 8999 QualType C1; 9000 QualifierCollector Q1; 9001 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9002 if (!isa<RecordType>(C1)) 9003 continue; 9004 // heuristic to reduce number of builtin candidates in the set. 9005 // Add volatile/restrict version only if there are conversions to a 9006 // volatile/restrict type. 9007 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9008 continue; 9009 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9010 continue; 9011 for (BuiltinCandidateTypeSet::iterator 9012 MemPtr = CandidateTypes[1].member_pointer_begin(), 9013 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 9014 MemPtr != MemPtrEnd; ++MemPtr) { 9015 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 9016 QualType C2 = QualType(mptr->getClass(), 0); 9017 C2 = C2.getUnqualifiedType(); 9018 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9019 break; 9020 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 9021 // build CV12 T& 9022 QualType T = mptr->getPointeeType(); 9023 if (!VisibleTypeConversionsQuals.hasVolatile() && 9024 T.isVolatileQualified()) 9025 continue; 9026 if (!VisibleTypeConversionsQuals.hasRestrict() && 9027 T.isRestrictQualified()) 9028 continue; 9029 T = Q1.apply(S.Context, T); 9030 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9031 } 9032 } 9033 } 9034 9035 // Note that we don't consider the first argument, since it has been 9036 // contextually converted to bool long ago. The candidates below are 9037 // therefore added as binary. 9038 // 9039 // C++ [over.built]p25: 9040 // For every type T, where T is a pointer, pointer-to-member, or scoped 9041 // enumeration type, there exist candidate operator functions of the form 9042 // 9043 // T operator?(bool, T, T); 9044 // 9045 void addConditionalOperatorOverloads() { 9046 /// Set of (canonical) types that we've already handled. 9047 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9048 9049 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9050 for (BuiltinCandidateTypeSet::iterator 9051 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9052 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9053 Ptr != PtrEnd; ++Ptr) { 9054 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9055 continue; 9056 9057 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9058 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9059 } 9060 9061 for (BuiltinCandidateTypeSet::iterator 9062 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9063 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9064 MemPtr != MemPtrEnd; ++MemPtr) { 9065 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9066 continue; 9067 9068 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9069 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9070 } 9071 9072 if (S.getLangOpts().CPlusPlus11) { 9073 for (BuiltinCandidateTypeSet::iterator 9074 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9075 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9076 Enum != EnumEnd; ++Enum) { 9077 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9078 continue; 9079 9080 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9081 continue; 9082 9083 QualType ParamTypes[2] = { *Enum, *Enum }; 9084 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9085 } 9086 } 9087 } 9088 } 9089 }; 9090 9091 } // end anonymous namespace 9092 9093 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9094 /// operator overloads to the candidate set (C++ [over.built]), based 9095 /// on the operator @p Op and the arguments given. For example, if the 9096 /// operator is a binary '+', this routine might add "int 9097 /// operator+(int, int)" to cover integer addition. 9098 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9099 SourceLocation OpLoc, 9100 ArrayRef<Expr *> Args, 9101 OverloadCandidateSet &CandidateSet) { 9102 // Find all of the types that the arguments can convert to, but only 9103 // if the operator we're looking at has built-in operator candidates 9104 // that make use of these types. Also record whether we encounter non-record 9105 // candidate types or either arithmetic or enumeral candidate types. 9106 Qualifiers VisibleTypeConversionsQuals; 9107 VisibleTypeConversionsQuals.addConst(); 9108 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9109 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9110 9111 bool HasNonRecordCandidateType = false; 9112 bool HasArithmeticOrEnumeralCandidateType = false; 9113 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9114 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9115 CandidateTypes.emplace_back(*this); 9116 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9117 OpLoc, 9118 true, 9119 (Op == OO_Exclaim || 9120 Op == OO_AmpAmp || 9121 Op == OO_PipePipe), 9122 VisibleTypeConversionsQuals); 9123 HasNonRecordCandidateType = HasNonRecordCandidateType || 9124 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9125 HasArithmeticOrEnumeralCandidateType = 9126 HasArithmeticOrEnumeralCandidateType || 9127 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9128 } 9129 9130 // Exit early when no non-record types have been added to the candidate set 9131 // for any of the arguments to the operator. 9132 // 9133 // We can't exit early for !, ||, or &&, since there we have always have 9134 // 'bool' overloads. 9135 if (!HasNonRecordCandidateType && 9136 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9137 return; 9138 9139 // Setup an object to manage the common state for building overloads. 9140 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9141 VisibleTypeConversionsQuals, 9142 HasArithmeticOrEnumeralCandidateType, 9143 CandidateTypes, CandidateSet); 9144 9145 // Dispatch over the operation to add in only those overloads which apply. 9146 switch (Op) { 9147 case OO_None: 9148 case NUM_OVERLOADED_OPERATORS: 9149 llvm_unreachable("Expected an overloaded operator"); 9150 9151 case OO_New: 9152 case OO_Delete: 9153 case OO_Array_New: 9154 case OO_Array_Delete: 9155 case OO_Call: 9156 llvm_unreachable( 9157 "Special operators don't use AddBuiltinOperatorCandidates"); 9158 9159 case OO_Comma: 9160 case OO_Arrow: 9161 case OO_Coawait: 9162 // C++ [over.match.oper]p3: 9163 // -- For the operator ',', the unary operator '&', the 9164 // operator '->', or the operator 'co_await', the 9165 // built-in candidates set is empty. 9166 break; 9167 9168 case OO_Plus: // '+' is either unary or binary 9169 if (Args.size() == 1) 9170 OpBuilder.addUnaryPlusPointerOverloads(); 9171 LLVM_FALLTHROUGH; 9172 9173 case OO_Minus: // '-' is either unary or binary 9174 if (Args.size() == 1) { 9175 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9176 } else { 9177 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9178 OpBuilder.addGenericBinaryArithmeticOverloads(); 9179 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9180 } 9181 break; 9182 9183 case OO_Star: // '*' is either unary or binary 9184 if (Args.size() == 1) 9185 OpBuilder.addUnaryStarPointerOverloads(); 9186 else { 9187 OpBuilder.addGenericBinaryArithmeticOverloads(); 9188 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9189 } 9190 break; 9191 9192 case OO_Slash: 9193 OpBuilder.addGenericBinaryArithmeticOverloads(); 9194 break; 9195 9196 case OO_PlusPlus: 9197 case OO_MinusMinus: 9198 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9199 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9200 break; 9201 9202 case OO_EqualEqual: 9203 case OO_ExclaimEqual: 9204 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9205 LLVM_FALLTHROUGH; 9206 9207 case OO_Less: 9208 case OO_Greater: 9209 case OO_LessEqual: 9210 case OO_GreaterEqual: 9211 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9212 OpBuilder.addGenericBinaryArithmeticOverloads(); 9213 break; 9214 9215 case OO_Spaceship: 9216 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9217 OpBuilder.addThreeWayArithmeticOverloads(); 9218 break; 9219 9220 case OO_Percent: 9221 case OO_Caret: 9222 case OO_Pipe: 9223 case OO_LessLess: 9224 case OO_GreaterGreater: 9225 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9226 break; 9227 9228 case OO_Amp: // '&' is either unary or binary 9229 if (Args.size() == 1) 9230 // C++ [over.match.oper]p3: 9231 // -- For the operator ',', the unary operator '&', or the 9232 // operator '->', the built-in candidates set is empty. 9233 break; 9234 9235 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9236 break; 9237 9238 case OO_Tilde: 9239 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9240 break; 9241 9242 case OO_Equal: 9243 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9244 LLVM_FALLTHROUGH; 9245 9246 case OO_PlusEqual: 9247 case OO_MinusEqual: 9248 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9249 LLVM_FALLTHROUGH; 9250 9251 case OO_StarEqual: 9252 case OO_SlashEqual: 9253 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9254 break; 9255 9256 case OO_PercentEqual: 9257 case OO_LessLessEqual: 9258 case OO_GreaterGreaterEqual: 9259 case OO_AmpEqual: 9260 case OO_CaretEqual: 9261 case OO_PipeEqual: 9262 OpBuilder.addAssignmentIntegralOverloads(); 9263 break; 9264 9265 case OO_Exclaim: 9266 OpBuilder.addExclaimOverload(); 9267 break; 9268 9269 case OO_AmpAmp: 9270 case OO_PipePipe: 9271 OpBuilder.addAmpAmpOrPipePipeOverload(); 9272 break; 9273 9274 case OO_Subscript: 9275 OpBuilder.addSubscriptOverloads(); 9276 break; 9277 9278 case OO_ArrowStar: 9279 OpBuilder.addArrowStarOverloads(); 9280 break; 9281 9282 case OO_Conditional: 9283 OpBuilder.addConditionalOperatorOverloads(); 9284 OpBuilder.addGenericBinaryArithmeticOverloads(); 9285 break; 9286 } 9287 } 9288 9289 /// Add function candidates found via argument-dependent lookup 9290 /// to the set of overloading candidates. 9291 /// 9292 /// This routine performs argument-dependent name lookup based on the 9293 /// given function name (which may also be an operator name) and adds 9294 /// all of the overload candidates found by ADL to the overload 9295 /// candidate set (C++ [basic.lookup.argdep]). 9296 void 9297 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9298 SourceLocation Loc, 9299 ArrayRef<Expr *> Args, 9300 TemplateArgumentListInfo *ExplicitTemplateArgs, 9301 OverloadCandidateSet& CandidateSet, 9302 bool PartialOverloading) { 9303 ADLResult Fns; 9304 9305 // FIXME: This approach for uniquing ADL results (and removing 9306 // redundant candidates from the set) relies on pointer-equality, 9307 // which means we need to key off the canonical decl. However, 9308 // always going back to the canonical decl might not get us the 9309 // right set of default arguments. What default arguments are 9310 // we supposed to consider on ADL candidates, anyway? 9311 9312 // FIXME: Pass in the explicit template arguments? 9313 ArgumentDependentLookup(Name, Loc, Args, Fns); 9314 9315 // Erase all of the candidates we already knew about. 9316 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9317 CandEnd = CandidateSet.end(); 9318 Cand != CandEnd; ++Cand) 9319 if (Cand->Function) { 9320 Fns.erase(Cand->Function); 9321 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9322 Fns.erase(FunTmpl); 9323 } 9324 9325 // For each of the ADL candidates we found, add it to the overload 9326 // set. 9327 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9328 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9329 9330 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9331 if (ExplicitTemplateArgs) 9332 continue; 9333 9334 AddOverloadCandidate( 9335 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9336 PartialOverloading, /*AllowExplicit=*/true, 9337 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9338 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9339 AddOverloadCandidate( 9340 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9341 /*SuppressUserConversions=*/false, PartialOverloading, 9342 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9343 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9344 } 9345 } else { 9346 auto *FTD = cast<FunctionTemplateDecl>(*I); 9347 AddTemplateOverloadCandidate( 9348 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9349 /*SuppressUserConversions=*/false, PartialOverloading, 9350 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9351 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9352 Context, FTD->getTemplatedDecl())) { 9353 AddTemplateOverloadCandidate( 9354 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9355 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9356 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9357 OverloadCandidateParamOrder::Reversed); 9358 } 9359 } 9360 } 9361 } 9362 9363 namespace { 9364 enum class Comparison { Equal, Better, Worse }; 9365 } 9366 9367 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9368 /// overload resolution. 9369 /// 9370 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9371 /// Cand1's first N enable_if attributes have precisely the same conditions as 9372 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9373 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9374 /// 9375 /// Note that you can have a pair of candidates such that Cand1's enable_if 9376 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9377 /// worse than Cand1's. 9378 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9379 const FunctionDecl *Cand2) { 9380 // Common case: One (or both) decls don't have enable_if attrs. 9381 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9382 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9383 if (!Cand1Attr || !Cand2Attr) { 9384 if (Cand1Attr == Cand2Attr) 9385 return Comparison::Equal; 9386 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9387 } 9388 9389 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9390 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9391 9392 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9393 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9394 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9395 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9396 9397 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9398 // has fewer enable_if attributes than Cand2, and vice versa. 9399 if (!Cand1A) 9400 return Comparison::Worse; 9401 if (!Cand2A) 9402 return Comparison::Better; 9403 9404 Cand1ID.clear(); 9405 Cand2ID.clear(); 9406 9407 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9408 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9409 if (Cand1ID != Cand2ID) 9410 return Comparison::Worse; 9411 } 9412 9413 return Comparison::Equal; 9414 } 9415 9416 static Comparison 9417 isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9418 const OverloadCandidate &Cand2) { 9419 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9420 !Cand2.Function->isMultiVersion()) 9421 return Comparison::Equal; 9422 9423 // If both are invalid, they are equal. If one of them is invalid, the other 9424 // is better. 9425 if (Cand1.Function->isInvalidDecl()) { 9426 if (Cand2.Function->isInvalidDecl()) 9427 return Comparison::Equal; 9428 return Comparison::Worse; 9429 } 9430 if (Cand2.Function->isInvalidDecl()) 9431 return Comparison::Better; 9432 9433 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9434 // cpu_dispatch, else arbitrarily based on the identifiers. 9435 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9436 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9437 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9438 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9439 9440 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9441 return Comparison::Equal; 9442 9443 if (Cand1CPUDisp && !Cand2CPUDisp) 9444 return Comparison::Better; 9445 if (Cand2CPUDisp && !Cand1CPUDisp) 9446 return Comparison::Worse; 9447 9448 if (Cand1CPUSpec && Cand2CPUSpec) { 9449 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9450 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size() 9451 ? Comparison::Better 9452 : Comparison::Worse; 9453 9454 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9455 FirstDiff = std::mismatch( 9456 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9457 Cand2CPUSpec->cpus_begin(), 9458 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9459 return LHS->getName() == RHS->getName(); 9460 }); 9461 9462 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9463 "Two different cpu-specific versions should not have the same " 9464 "identifier list, otherwise they'd be the same decl!"); 9465 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName() 9466 ? Comparison::Better 9467 : Comparison::Worse; 9468 } 9469 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9470 } 9471 9472 /// Compute the type of the implicit object parameter for the given function, 9473 /// if any. Returns None if there is no implicit object parameter, and a null 9474 /// QualType if there is a 'matches anything' implicit object parameter. 9475 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9476 const FunctionDecl *F) { 9477 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9478 return llvm::None; 9479 9480 auto *M = cast<CXXMethodDecl>(F); 9481 // Static member functions' object parameters match all types. 9482 if (M->isStatic()) 9483 return QualType(); 9484 9485 QualType T = M->getThisObjectType(); 9486 if (M->getRefQualifier() == RQ_RValue) 9487 return Context.getRValueReferenceType(T); 9488 return Context.getLValueReferenceType(T); 9489 } 9490 9491 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9492 const FunctionDecl *F2, unsigned NumParams) { 9493 if (declaresSameEntity(F1, F2)) 9494 return true; 9495 9496 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9497 if (First) { 9498 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9499 return *T; 9500 } 9501 assert(I < F->getNumParams()); 9502 return F->getParamDecl(I++)->getType(); 9503 }; 9504 9505 unsigned I1 = 0, I2 = 0; 9506 for (unsigned I = 0; I != NumParams; ++I) { 9507 QualType T1 = NextParam(F1, I1, I == 0); 9508 QualType T2 = NextParam(F2, I2, I == 0); 9509 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9510 return false; 9511 } 9512 return true; 9513 } 9514 9515 /// isBetterOverloadCandidate - Determines whether the first overload 9516 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9517 bool clang::isBetterOverloadCandidate( 9518 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9519 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9520 // Define viable functions to be better candidates than non-viable 9521 // functions. 9522 if (!Cand2.Viable) 9523 return Cand1.Viable; 9524 else if (!Cand1.Viable) 9525 return false; 9526 9527 // C++ [over.match.best]p1: 9528 // 9529 // -- if F is a static member function, ICS1(F) is defined such 9530 // that ICS1(F) is neither better nor worse than ICS1(G) for 9531 // any function G, and, symmetrically, ICS1(G) is neither 9532 // better nor worse than ICS1(F). 9533 unsigned StartArg = 0; 9534 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9535 StartArg = 1; 9536 9537 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9538 // We don't allow incompatible pointer conversions in C++. 9539 if (!S.getLangOpts().CPlusPlus) 9540 return ICS.isStandard() && 9541 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9542 9543 // The only ill-formed conversion we allow in C++ is the string literal to 9544 // char* conversion, which is only considered ill-formed after C++11. 9545 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9546 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9547 }; 9548 9549 // Define functions that don't require ill-formed conversions for a given 9550 // argument to be better candidates than functions that do. 9551 unsigned NumArgs = Cand1.Conversions.size(); 9552 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9553 bool HasBetterConversion = false; 9554 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9555 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9556 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9557 if (Cand1Bad != Cand2Bad) { 9558 if (Cand1Bad) 9559 return false; 9560 HasBetterConversion = true; 9561 } 9562 } 9563 9564 if (HasBetterConversion) 9565 return true; 9566 9567 // C++ [over.match.best]p1: 9568 // A viable function F1 is defined to be a better function than another 9569 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9570 // conversion sequence than ICSi(F2), and then... 9571 bool HasWorseConversion = false; 9572 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9573 switch (CompareImplicitConversionSequences(S, Loc, 9574 Cand1.Conversions[ArgIdx], 9575 Cand2.Conversions[ArgIdx])) { 9576 case ImplicitConversionSequence::Better: 9577 // Cand1 has a better conversion sequence. 9578 HasBetterConversion = true; 9579 break; 9580 9581 case ImplicitConversionSequence::Worse: 9582 if (Cand1.Function && Cand2.Function && 9583 Cand1.isReversed() != Cand2.isReversed() && 9584 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9585 NumArgs)) { 9586 // Work around large-scale breakage caused by considering reversed 9587 // forms of operator== in C++20: 9588 // 9589 // When comparing a function against a reversed function with the same 9590 // parameter types, if we have a better conversion for one argument and 9591 // a worse conversion for the other, the implicit conversion sequences 9592 // are treated as being equally good. 9593 // 9594 // This prevents a comparison function from being considered ambiguous 9595 // with a reversed form that is written in the same way. 9596 // 9597 // We diagnose this as an extension from CreateOverloadedBinOp. 9598 HasWorseConversion = true; 9599 break; 9600 } 9601 9602 // Cand1 can't be better than Cand2. 9603 return false; 9604 9605 case ImplicitConversionSequence::Indistinguishable: 9606 // Do nothing. 9607 break; 9608 } 9609 } 9610 9611 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9612 // ICSj(F2), or, if not that, 9613 if (HasBetterConversion && !HasWorseConversion) 9614 return true; 9615 9616 // -- the context is an initialization by user-defined conversion 9617 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9618 // from the return type of F1 to the destination type (i.e., 9619 // the type of the entity being initialized) is a better 9620 // conversion sequence than the standard conversion sequence 9621 // from the return type of F2 to the destination type. 9622 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9623 Cand1.Function && Cand2.Function && 9624 isa<CXXConversionDecl>(Cand1.Function) && 9625 isa<CXXConversionDecl>(Cand2.Function)) { 9626 // First check whether we prefer one of the conversion functions over the 9627 // other. This only distinguishes the results in non-standard, extension 9628 // cases such as the conversion from a lambda closure type to a function 9629 // pointer or block. 9630 ImplicitConversionSequence::CompareKind Result = 9631 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9632 if (Result == ImplicitConversionSequence::Indistinguishable) 9633 Result = CompareStandardConversionSequences(S, Loc, 9634 Cand1.FinalConversion, 9635 Cand2.FinalConversion); 9636 9637 if (Result != ImplicitConversionSequence::Indistinguishable) 9638 return Result == ImplicitConversionSequence::Better; 9639 9640 // FIXME: Compare kind of reference binding if conversion functions 9641 // convert to a reference type used in direct reference binding, per 9642 // C++14 [over.match.best]p1 section 2 bullet 3. 9643 } 9644 9645 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9646 // as combined with the resolution to CWG issue 243. 9647 // 9648 // When the context is initialization by constructor ([over.match.ctor] or 9649 // either phase of [over.match.list]), a constructor is preferred over 9650 // a conversion function. 9651 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9652 Cand1.Function && Cand2.Function && 9653 isa<CXXConstructorDecl>(Cand1.Function) != 9654 isa<CXXConstructorDecl>(Cand2.Function)) 9655 return isa<CXXConstructorDecl>(Cand1.Function); 9656 9657 // -- F1 is a non-template function and F2 is a function template 9658 // specialization, or, if not that, 9659 bool Cand1IsSpecialization = Cand1.Function && 9660 Cand1.Function->getPrimaryTemplate(); 9661 bool Cand2IsSpecialization = Cand2.Function && 9662 Cand2.Function->getPrimaryTemplate(); 9663 if (Cand1IsSpecialization != Cand2IsSpecialization) 9664 return Cand2IsSpecialization; 9665 9666 // -- F1 and F2 are function template specializations, and the function 9667 // template for F1 is more specialized than the template for F2 9668 // according to the partial ordering rules described in 14.5.5.2, or, 9669 // if not that, 9670 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9671 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9672 Cand1.Function->getPrimaryTemplate(), 9673 Cand2.Function->getPrimaryTemplate(), Loc, 9674 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9675 : TPOC_Call, 9676 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9677 Cand1.isReversed() ^ Cand2.isReversed())) 9678 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9679 } 9680 9681 // -— F1 and F2 are non-template functions with the same 9682 // parameter-type-lists, and F1 is more constrained than F2 [...], 9683 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9684 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9685 Cand2.Function->hasPrototype()) { 9686 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9687 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9688 if (PT1->getNumParams() == PT2->getNumParams() && 9689 PT1->isVariadic() == PT2->isVariadic() && 9690 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9691 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9692 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9693 if (RC1 && RC2) { 9694 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9695 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9696 {RC2}, AtLeastAsConstrained1) || 9697 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9698 {RC1}, AtLeastAsConstrained2)) 9699 return false; 9700 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9701 return AtLeastAsConstrained1; 9702 } else if (RC1 || RC2) { 9703 return RC1 != nullptr; 9704 } 9705 } 9706 } 9707 9708 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9709 // class B of D, and for all arguments the corresponding parameters of 9710 // F1 and F2 have the same type. 9711 // FIXME: Implement the "all parameters have the same type" check. 9712 bool Cand1IsInherited = 9713 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9714 bool Cand2IsInherited = 9715 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9716 if (Cand1IsInherited != Cand2IsInherited) 9717 return Cand2IsInherited; 9718 else if (Cand1IsInherited) { 9719 assert(Cand2IsInherited); 9720 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9721 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9722 if (Cand1Class->isDerivedFrom(Cand2Class)) 9723 return true; 9724 if (Cand2Class->isDerivedFrom(Cand1Class)) 9725 return false; 9726 // Inherited from sibling base classes: still ambiguous. 9727 } 9728 9729 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9730 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9731 // with reversed order of parameters and F1 is not 9732 // 9733 // We rank reversed + different operator as worse than just reversed, but 9734 // that comparison can never happen, because we only consider reversing for 9735 // the maximally-rewritten operator (== or <=>). 9736 if (Cand1.RewriteKind != Cand2.RewriteKind) 9737 return Cand1.RewriteKind < Cand2.RewriteKind; 9738 9739 // Check C++17 tie-breakers for deduction guides. 9740 { 9741 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9742 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9743 if (Guide1 && Guide2) { 9744 // -- F1 is generated from a deduction-guide and F2 is not 9745 if (Guide1->isImplicit() != Guide2->isImplicit()) 9746 return Guide2->isImplicit(); 9747 9748 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9749 if (Guide1->isCopyDeductionCandidate()) 9750 return true; 9751 } 9752 } 9753 9754 // Check for enable_if value-based overload resolution. 9755 if (Cand1.Function && Cand2.Function) { 9756 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9757 if (Cmp != Comparison::Equal) 9758 return Cmp == Comparison::Better; 9759 } 9760 9761 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9762 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9763 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9764 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9765 } 9766 9767 bool HasPS1 = Cand1.Function != nullptr && 9768 functionHasPassObjectSizeParams(Cand1.Function); 9769 bool HasPS2 = Cand2.Function != nullptr && 9770 functionHasPassObjectSizeParams(Cand2.Function); 9771 if (HasPS1 != HasPS2 && HasPS1) 9772 return true; 9773 9774 Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2); 9775 return MV == Comparison::Better; 9776 } 9777 9778 /// Determine whether two declarations are "equivalent" for the purposes of 9779 /// name lookup and overload resolution. This applies when the same internal/no 9780 /// linkage entity is defined by two modules (probably by textually including 9781 /// the same header). In such a case, we don't consider the declarations to 9782 /// declare the same entity, but we also don't want lookups with both 9783 /// declarations visible to be ambiguous in some cases (this happens when using 9784 /// a modularized libstdc++). 9785 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9786 const NamedDecl *B) { 9787 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9788 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9789 if (!VA || !VB) 9790 return false; 9791 9792 // The declarations must be declaring the same name as an internal linkage 9793 // entity in different modules. 9794 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9795 VB->getDeclContext()->getRedeclContext()) || 9796 getOwningModule(VA) == getOwningModule(VB) || 9797 VA->isExternallyVisible() || VB->isExternallyVisible()) 9798 return false; 9799 9800 // Check that the declarations appear to be equivalent. 9801 // 9802 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9803 // For constants and functions, we should check the initializer or body is 9804 // the same. For non-constant variables, we shouldn't allow it at all. 9805 if (Context.hasSameType(VA->getType(), VB->getType())) 9806 return true; 9807 9808 // Enum constants within unnamed enumerations will have different types, but 9809 // may still be similar enough to be interchangeable for our purposes. 9810 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9811 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9812 // Only handle anonymous enums. If the enumerations were named and 9813 // equivalent, they would have been merged to the same type. 9814 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9815 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9816 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9817 !Context.hasSameType(EnumA->getIntegerType(), 9818 EnumB->getIntegerType())) 9819 return false; 9820 // Allow this only if the value is the same for both enumerators. 9821 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9822 } 9823 } 9824 9825 // Nothing else is sufficiently similar. 9826 return false; 9827 } 9828 9829 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9830 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9831 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9832 9833 Module *M = getOwningModule(D); 9834 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9835 << !M << (M ? M->getFullModuleName() : ""); 9836 9837 for (auto *E : Equiv) { 9838 Module *M = getOwningModule(E); 9839 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9840 << !M << (M ? M->getFullModuleName() : ""); 9841 } 9842 } 9843 9844 /// Computes the best viable function (C++ 13.3.3) 9845 /// within an overload candidate set. 9846 /// 9847 /// \param Loc The location of the function name (or operator symbol) for 9848 /// which overload resolution occurs. 9849 /// 9850 /// \param Best If overload resolution was successful or found a deleted 9851 /// function, \p Best points to the candidate function found. 9852 /// 9853 /// \returns The result of overload resolution. 9854 OverloadingResult 9855 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9856 iterator &Best) { 9857 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9858 std::transform(begin(), end(), std::back_inserter(Candidates), 9859 [](OverloadCandidate &Cand) { return &Cand; }); 9860 9861 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9862 // are accepted by both clang and NVCC. However, during a particular 9863 // compilation mode only one call variant is viable. We need to 9864 // exclude non-viable overload candidates from consideration based 9865 // only on their host/device attributes. Specifically, if one 9866 // candidate call is WrongSide and the other is SameSide, we ignore 9867 // the WrongSide candidate. 9868 if (S.getLangOpts().CUDA) { 9869 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9870 bool ContainsSameSideCandidate = 9871 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9872 // Check viable function only. 9873 return Cand->Viable && Cand->Function && 9874 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9875 Sema::CFP_SameSide; 9876 }); 9877 if (ContainsSameSideCandidate) { 9878 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9879 // Check viable function only to avoid unnecessary data copying/moving. 9880 return Cand->Viable && Cand->Function && 9881 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9882 Sema::CFP_WrongSide; 9883 }; 9884 llvm::erase_if(Candidates, IsWrongSideCandidate); 9885 } 9886 } 9887 9888 // Find the best viable function. 9889 Best = end(); 9890 for (auto *Cand : Candidates) { 9891 Cand->Best = false; 9892 if (Cand->Viable) 9893 if (Best == end() || 9894 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9895 Best = Cand; 9896 } 9897 9898 // If we didn't find any viable functions, abort. 9899 if (Best == end()) 9900 return OR_No_Viable_Function; 9901 9902 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9903 9904 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9905 PendingBest.push_back(&*Best); 9906 Best->Best = true; 9907 9908 // Make sure that this function is better than every other viable 9909 // function. If not, we have an ambiguity. 9910 while (!PendingBest.empty()) { 9911 auto *Curr = PendingBest.pop_back_val(); 9912 for (auto *Cand : Candidates) { 9913 if (Cand->Viable && !Cand->Best && 9914 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9915 PendingBest.push_back(Cand); 9916 Cand->Best = true; 9917 9918 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9919 Curr->Function)) 9920 EquivalentCands.push_back(Cand->Function); 9921 else 9922 Best = end(); 9923 } 9924 } 9925 } 9926 9927 // If we found more than one best candidate, this is ambiguous. 9928 if (Best == end()) 9929 return OR_Ambiguous; 9930 9931 // Best is the best viable function. 9932 if (Best->Function && Best->Function->isDeleted()) 9933 return OR_Deleted; 9934 9935 if (!EquivalentCands.empty()) 9936 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9937 EquivalentCands); 9938 9939 return OR_Success; 9940 } 9941 9942 namespace { 9943 9944 enum OverloadCandidateKind { 9945 oc_function, 9946 oc_method, 9947 oc_reversed_binary_operator, 9948 oc_constructor, 9949 oc_implicit_default_constructor, 9950 oc_implicit_copy_constructor, 9951 oc_implicit_move_constructor, 9952 oc_implicit_copy_assignment, 9953 oc_implicit_move_assignment, 9954 oc_implicit_equality_comparison, 9955 oc_inherited_constructor 9956 }; 9957 9958 enum OverloadCandidateSelect { 9959 ocs_non_template, 9960 ocs_template, 9961 ocs_described_template, 9962 }; 9963 9964 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9965 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9966 OverloadCandidateRewriteKind CRK, 9967 std::string &Description) { 9968 9969 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9970 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9971 isTemplate = true; 9972 Description = S.getTemplateArgumentBindingsText( 9973 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9974 } 9975 9976 OverloadCandidateSelect Select = [&]() { 9977 if (!Description.empty()) 9978 return ocs_described_template; 9979 return isTemplate ? ocs_template : ocs_non_template; 9980 }(); 9981 9982 OverloadCandidateKind Kind = [&]() { 9983 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9984 return oc_implicit_equality_comparison; 9985 9986 if (CRK & CRK_Reversed) 9987 return oc_reversed_binary_operator; 9988 9989 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9990 if (!Ctor->isImplicit()) { 9991 if (isa<ConstructorUsingShadowDecl>(Found)) 9992 return oc_inherited_constructor; 9993 else 9994 return oc_constructor; 9995 } 9996 9997 if (Ctor->isDefaultConstructor()) 9998 return oc_implicit_default_constructor; 9999 10000 if (Ctor->isMoveConstructor()) 10001 return oc_implicit_move_constructor; 10002 10003 assert(Ctor->isCopyConstructor() && 10004 "unexpected sort of implicit constructor"); 10005 return oc_implicit_copy_constructor; 10006 } 10007 10008 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 10009 // This actually gets spelled 'candidate function' for now, but 10010 // it doesn't hurt to split it out. 10011 if (!Meth->isImplicit()) 10012 return oc_method; 10013 10014 if (Meth->isMoveAssignmentOperator()) 10015 return oc_implicit_move_assignment; 10016 10017 if (Meth->isCopyAssignmentOperator()) 10018 return oc_implicit_copy_assignment; 10019 10020 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10021 return oc_method; 10022 } 10023 10024 return oc_function; 10025 }(); 10026 10027 return std::make_pair(Kind, Select); 10028 } 10029 10030 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10031 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10032 // set. 10033 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10034 S.Diag(FoundDecl->getLocation(), 10035 diag::note_ovl_candidate_inherited_constructor) 10036 << Shadow->getNominatedBaseClass(); 10037 } 10038 10039 } // end anonymous namespace 10040 10041 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10042 const FunctionDecl *FD) { 10043 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10044 bool AlwaysTrue; 10045 if (EnableIf->getCond()->isValueDependent() || 10046 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10047 return false; 10048 if (!AlwaysTrue) 10049 return false; 10050 } 10051 return true; 10052 } 10053 10054 /// Returns true if we can take the address of the function. 10055 /// 10056 /// \param Complain - If true, we'll emit a diagnostic 10057 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10058 /// we in overload resolution? 10059 /// \param Loc - The location of the statement we're complaining about. Ignored 10060 /// if we're not complaining, or if we're in overload resolution. 10061 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10062 bool Complain, 10063 bool InOverloadResolution, 10064 SourceLocation Loc) { 10065 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10066 if (Complain) { 10067 if (InOverloadResolution) 10068 S.Diag(FD->getBeginLoc(), 10069 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10070 else 10071 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10072 } 10073 return false; 10074 } 10075 10076 if (FD->getTrailingRequiresClause()) { 10077 ConstraintSatisfaction Satisfaction; 10078 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10079 return false; 10080 if (!Satisfaction.IsSatisfied) { 10081 if (Complain) { 10082 if (InOverloadResolution) 10083 S.Diag(FD->getBeginLoc(), 10084 diag::note_ovl_candidate_unsatisfied_constraints); 10085 else 10086 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10087 << FD; 10088 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10089 } 10090 return false; 10091 } 10092 } 10093 10094 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10095 return P->hasAttr<PassObjectSizeAttr>(); 10096 }); 10097 if (I == FD->param_end()) 10098 return true; 10099 10100 if (Complain) { 10101 // Add one to ParamNo because it's user-facing 10102 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10103 if (InOverloadResolution) 10104 S.Diag(FD->getLocation(), 10105 diag::note_ovl_candidate_has_pass_object_size_params) 10106 << ParamNo; 10107 else 10108 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10109 << FD << ParamNo; 10110 } 10111 return false; 10112 } 10113 10114 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10115 const FunctionDecl *FD) { 10116 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10117 /*InOverloadResolution=*/true, 10118 /*Loc=*/SourceLocation()); 10119 } 10120 10121 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10122 bool Complain, 10123 SourceLocation Loc) { 10124 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10125 /*InOverloadResolution=*/false, 10126 Loc); 10127 } 10128 10129 // Notes the location of an overload candidate. 10130 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10131 OverloadCandidateRewriteKind RewriteKind, 10132 QualType DestType, bool TakingAddress) { 10133 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10134 return; 10135 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10136 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10137 return; 10138 10139 std::string FnDesc; 10140 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10141 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10142 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10143 << (unsigned)KSPair.first << (unsigned)KSPair.second 10144 << Fn << FnDesc; 10145 10146 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10147 Diag(Fn->getLocation(), PD); 10148 MaybeEmitInheritedConstructorNote(*this, Found); 10149 } 10150 10151 static void 10152 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10153 // Perhaps the ambiguity was caused by two atomic constraints that are 10154 // 'identical' but not equivalent: 10155 // 10156 // void foo() requires (sizeof(T) > 4) { } // #1 10157 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10158 // 10159 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10160 // #2 to subsume #1, but these constraint are not considered equivalent 10161 // according to the subsumption rules because they are not the same 10162 // source-level construct. This behavior is quite confusing and we should try 10163 // to help the user figure out what happened. 10164 10165 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10166 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10167 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10168 if (!I->Function) 10169 continue; 10170 SmallVector<const Expr *, 3> AC; 10171 if (auto *Template = I->Function->getPrimaryTemplate()) 10172 Template->getAssociatedConstraints(AC); 10173 else 10174 I->Function->getAssociatedConstraints(AC); 10175 if (AC.empty()) 10176 continue; 10177 if (FirstCand == nullptr) { 10178 FirstCand = I->Function; 10179 FirstAC = AC; 10180 } else if (SecondCand == nullptr) { 10181 SecondCand = I->Function; 10182 SecondAC = AC; 10183 } else { 10184 // We have more than one pair of constrained functions - this check is 10185 // expensive and we'd rather not try to diagnose it. 10186 return; 10187 } 10188 } 10189 if (!SecondCand) 10190 return; 10191 // The diagnostic can only happen if there are associated constraints on 10192 // both sides (there needs to be some identical atomic constraint). 10193 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10194 SecondCand, SecondAC)) 10195 // Just show the user one diagnostic, they'll probably figure it out 10196 // from here. 10197 return; 10198 } 10199 10200 // Notes the location of all overload candidates designated through 10201 // OverloadedExpr 10202 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10203 bool TakingAddress) { 10204 assert(OverloadedExpr->getType() == Context.OverloadTy); 10205 10206 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10207 OverloadExpr *OvlExpr = Ovl.Expression; 10208 10209 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10210 IEnd = OvlExpr->decls_end(); 10211 I != IEnd; ++I) { 10212 if (FunctionTemplateDecl *FunTmpl = 10213 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10214 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10215 TakingAddress); 10216 } else if (FunctionDecl *Fun 10217 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10218 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10219 } 10220 } 10221 } 10222 10223 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10224 /// "lead" diagnostic; it will be given two arguments, the source and 10225 /// target types of the conversion. 10226 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10227 Sema &S, 10228 SourceLocation CaretLoc, 10229 const PartialDiagnostic &PDiag) const { 10230 S.Diag(CaretLoc, PDiag) 10231 << Ambiguous.getFromType() << Ambiguous.getToType(); 10232 // FIXME: The note limiting machinery is borrowed from 10233 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10234 // refactoring here. 10235 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10236 unsigned CandsShown = 0; 10237 AmbiguousConversionSequence::const_iterator I, E; 10238 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10239 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10240 break; 10241 ++CandsShown; 10242 S.NoteOverloadCandidate(I->first, I->second); 10243 } 10244 if (I != E) 10245 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10246 } 10247 10248 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10249 unsigned I, bool TakingCandidateAddress) { 10250 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10251 assert(Conv.isBad()); 10252 assert(Cand->Function && "for now, candidate must be a function"); 10253 FunctionDecl *Fn = Cand->Function; 10254 10255 // There's a conversion slot for the object argument if this is a 10256 // non-constructor method. Note that 'I' corresponds the 10257 // conversion-slot index. 10258 bool isObjectArgument = false; 10259 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10260 if (I == 0) 10261 isObjectArgument = true; 10262 else 10263 I--; 10264 } 10265 10266 std::string FnDesc; 10267 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10268 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10269 FnDesc); 10270 10271 Expr *FromExpr = Conv.Bad.FromExpr; 10272 QualType FromTy = Conv.Bad.getFromType(); 10273 QualType ToTy = Conv.Bad.getToType(); 10274 10275 if (FromTy == S.Context.OverloadTy) { 10276 assert(FromExpr && "overload set argument came from implicit argument?"); 10277 Expr *E = FromExpr->IgnoreParens(); 10278 if (isa<UnaryOperator>(E)) 10279 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10280 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10281 10282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10283 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10284 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10285 << Name << I + 1; 10286 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10287 return; 10288 } 10289 10290 // Do some hand-waving analysis to see if the non-viability is due 10291 // to a qualifier mismatch. 10292 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10293 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10294 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10295 CToTy = RT->getPointeeType(); 10296 else { 10297 // TODO: detect and diagnose the full richness of const mismatches. 10298 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10299 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10300 CFromTy = FromPT->getPointeeType(); 10301 CToTy = ToPT->getPointeeType(); 10302 } 10303 } 10304 10305 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10306 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10307 Qualifiers FromQs = CFromTy.getQualifiers(); 10308 Qualifiers ToQs = CToTy.getQualifiers(); 10309 10310 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10311 if (isObjectArgument) 10312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10313 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10314 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10315 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10316 else 10317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10318 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10319 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10320 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10321 << ToTy->isReferenceType() << I + 1; 10322 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10323 return; 10324 } 10325 10326 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10327 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10328 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10329 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10330 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10331 << (unsigned)isObjectArgument << I + 1; 10332 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10333 return; 10334 } 10335 10336 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10338 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10339 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10340 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10341 << (unsigned)isObjectArgument << I + 1; 10342 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10343 return; 10344 } 10345 10346 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10348 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10349 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10350 << FromQs.hasUnaligned() << I + 1; 10351 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10352 return; 10353 } 10354 10355 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10356 assert(CVR && "unexpected qualifiers mismatch"); 10357 10358 if (isObjectArgument) { 10359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10360 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10361 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10362 << (CVR - 1); 10363 } else { 10364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10365 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10366 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10367 << (CVR - 1) << I + 1; 10368 } 10369 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10370 return; 10371 } 10372 10373 // Special diagnostic for failure to convert an initializer list, since 10374 // telling the user that it has type void is not useful. 10375 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10376 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10377 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10378 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10379 << ToTy << (unsigned)isObjectArgument << I + 1; 10380 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10381 return; 10382 } 10383 10384 // Diagnose references or pointers to incomplete types differently, 10385 // since it's far from impossible that the incompleteness triggered 10386 // the failure. 10387 QualType TempFromTy = FromTy.getNonReferenceType(); 10388 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10389 TempFromTy = PTy->getPointeeType(); 10390 if (TempFromTy->isIncompleteType()) { 10391 // Emit the generic diagnostic and, optionally, add the hints to it. 10392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10393 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10394 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10395 << ToTy << (unsigned)isObjectArgument << I + 1 10396 << (unsigned)(Cand->Fix.Kind); 10397 10398 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10399 return; 10400 } 10401 10402 // Diagnose base -> derived pointer conversions. 10403 unsigned BaseToDerivedConversion = 0; 10404 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10405 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10406 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10407 FromPtrTy->getPointeeType()) && 10408 !FromPtrTy->getPointeeType()->isIncompleteType() && 10409 !ToPtrTy->getPointeeType()->isIncompleteType() && 10410 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10411 FromPtrTy->getPointeeType())) 10412 BaseToDerivedConversion = 1; 10413 } 10414 } else if (const ObjCObjectPointerType *FromPtrTy 10415 = FromTy->getAs<ObjCObjectPointerType>()) { 10416 if (const ObjCObjectPointerType *ToPtrTy 10417 = ToTy->getAs<ObjCObjectPointerType>()) 10418 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10419 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10420 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10421 FromPtrTy->getPointeeType()) && 10422 FromIface->isSuperClassOf(ToIface)) 10423 BaseToDerivedConversion = 2; 10424 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10425 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10426 !FromTy->isIncompleteType() && 10427 !ToRefTy->getPointeeType()->isIncompleteType() && 10428 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10429 BaseToDerivedConversion = 3; 10430 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10431 ToTy.getNonReferenceType().getCanonicalType() == 10432 FromTy.getNonReferenceType().getCanonicalType()) { 10433 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10434 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10435 << (unsigned)isObjectArgument << I + 1 10436 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10437 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10438 return; 10439 } 10440 } 10441 10442 if (BaseToDerivedConversion) { 10443 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10444 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10445 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10446 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10447 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10448 return; 10449 } 10450 10451 if (isa<ObjCObjectPointerType>(CFromTy) && 10452 isa<PointerType>(CToTy)) { 10453 Qualifiers FromQs = CFromTy.getQualifiers(); 10454 Qualifiers ToQs = CToTy.getQualifiers(); 10455 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10456 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10457 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10458 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10459 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10460 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10461 return; 10462 } 10463 } 10464 10465 if (TakingCandidateAddress && 10466 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10467 return; 10468 10469 // Emit the generic diagnostic and, optionally, add the hints to it. 10470 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10471 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10472 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10473 << ToTy << (unsigned)isObjectArgument << I + 1 10474 << (unsigned)(Cand->Fix.Kind); 10475 10476 // If we can fix the conversion, suggest the FixIts. 10477 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10478 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10479 FDiag << *HI; 10480 S.Diag(Fn->getLocation(), FDiag); 10481 10482 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10483 } 10484 10485 /// Additional arity mismatch diagnosis specific to a function overload 10486 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10487 /// over a candidate in any candidate set. 10488 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10489 unsigned NumArgs) { 10490 FunctionDecl *Fn = Cand->Function; 10491 unsigned MinParams = Fn->getMinRequiredArguments(); 10492 10493 // With invalid overloaded operators, it's possible that we think we 10494 // have an arity mismatch when in fact it looks like we have the 10495 // right number of arguments, because only overloaded operators have 10496 // the weird behavior of overloading member and non-member functions. 10497 // Just don't report anything. 10498 if (Fn->isInvalidDecl() && 10499 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10500 return true; 10501 10502 if (NumArgs < MinParams) { 10503 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10504 (Cand->FailureKind == ovl_fail_bad_deduction && 10505 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10506 } else { 10507 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10508 (Cand->FailureKind == ovl_fail_bad_deduction && 10509 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10510 } 10511 10512 return false; 10513 } 10514 10515 /// General arity mismatch diagnosis over a candidate in a candidate set. 10516 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10517 unsigned NumFormalArgs) { 10518 assert(isa<FunctionDecl>(D) && 10519 "The templated declaration should at least be a function" 10520 " when diagnosing bad template argument deduction due to too many" 10521 " or too few arguments"); 10522 10523 FunctionDecl *Fn = cast<FunctionDecl>(D); 10524 10525 // TODO: treat calls to a missing default constructor as a special case 10526 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10527 unsigned MinParams = Fn->getMinRequiredArguments(); 10528 10529 // at least / at most / exactly 10530 unsigned mode, modeCount; 10531 if (NumFormalArgs < MinParams) { 10532 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10533 FnTy->isTemplateVariadic()) 10534 mode = 0; // "at least" 10535 else 10536 mode = 2; // "exactly" 10537 modeCount = MinParams; 10538 } else { 10539 if (MinParams != FnTy->getNumParams()) 10540 mode = 1; // "at most" 10541 else 10542 mode = 2; // "exactly" 10543 modeCount = FnTy->getNumParams(); 10544 } 10545 10546 std::string Description; 10547 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10548 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10549 10550 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10551 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10552 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10553 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10554 else 10555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10556 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10557 << Description << mode << modeCount << NumFormalArgs; 10558 10559 MaybeEmitInheritedConstructorNote(S, Found); 10560 } 10561 10562 /// Arity mismatch diagnosis specific to a function overload candidate. 10563 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10564 unsigned NumFormalArgs) { 10565 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10566 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10567 } 10568 10569 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10570 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10571 return TD; 10572 llvm_unreachable("Unsupported: Getting the described template declaration" 10573 " for bad deduction diagnosis"); 10574 } 10575 10576 /// Diagnose a failed template-argument deduction. 10577 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10578 DeductionFailureInfo &DeductionFailure, 10579 unsigned NumArgs, 10580 bool TakingCandidateAddress) { 10581 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10582 NamedDecl *ParamD; 10583 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10584 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10585 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10586 switch (DeductionFailure.Result) { 10587 case Sema::TDK_Success: 10588 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10589 10590 case Sema::TDK_Incomplete: { 10591 assert(ParamD && "no parameter found for incomplete deduction result"); 10592 S.Diag(Templated->getLocation(), 10593 diag::note_ovl_candidate_incomplete_deduction) 10594 << ParamD->getDeclName(); 10595 MaybeEmitInheritedConstructorNote(S, Found); 10596 return; 10597 } 10598 10599 case Sema::TDK_IncompletePack: { 10600 assert(ParamD && "no parameter found for incomplete deduction result"); 10601 S.Diag(Templated->getLocation(), 10602 diag::note_ovl_candidate_incomplete_deduction_pack) 10603 << ParamD->getDeclName() 10604 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10605 << *DeductionFailure.getFirstArg(); 10606 MaybeEmitInheritedConstructorNote(S, Found); 10607 return; 10608 } 10609 10610 case Sema::TDK_Underqualified: { 10611 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10612 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10613 10614 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10615 10616 // Param will have been canonicalized, but it should just be a 10617 // qualified version of ParamD, so move the qualifiers to that. 10618 QualifierCollector Qs; 10619 Qs.strip(Param); 10620 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10621 assert(S.Context.hasSameType(Param, NonCanonParam)); 10622 10623 // Arg has also been canonicalized, but there's nothing we can do 10624 // about that. It also doesn't matter as much, because it won't 10625 // have any template parameters in it (because deduction isn't 10626 // done on dependent types). 10627 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10628 10629 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10630 << ParamD->getDeclName() << Arg << NonCanonParam; 10631 MaybeEmitInheritedConstructorNote(S, Found); 10632 return; 10633 } 10634 10635 case Sema::TDK_Inconsistent: { 10636 assert(ParamD && "no parameter found for inconsistent deduction result"); 10637 int which = 0; 10638 if (isa<TemplateTypeParmDecl>(ParamD)) 10639 which = 0; 10640 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10641 // Deduction might have failed because we deduced arguments of two 10642 // different types for a non-type template parameter. 10643 // FIXME: Use a different TDK value for this. 10644 QualType T1 = 10645 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10646 QualType T2 = 10647 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10648 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10649 S.Diag(Templated->getLocation(), 10650 diag::note_ovl_candidate_inconsistent_deduction_types) 10651 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10652 << *DeductionFailure.getSecondArg() << T2; 10653 MaybeEmitInheritedConstructorNote(S, Found); 10654 return; 10655 } 10656 10657 which = 1; 10658 } else { 10659 which = 2; 10660 } 10661 10662 // Tweak the diagnostic if the problem is that we deduced packs of 10663 // different arities. We'll print the actual packs anyway in case that 10664 // includes additional useful information. 10665 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10666 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10667 DeductionFailure.getFirstArg()->pack_size() != 10668 DeductionFailure.getSecondArg()->pack_size()) { 10669 which = 3; 10670 } 10671 10672 S.Diag(Templated->getLocation(), 10673 diag::note_ovl_candidate_inconsistent_deduction) 10674 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10675 << *DeductionFailure.getSecondArg(); 10676 MaybeEmitInheritedConstructorNote(S, Found); 10677 return; 10678 } 10679 10680 case Sema::TDK_InvalidExplicitArguments: 10681 assert(ParamD && "no parameter found for invalid explicit arguments"); 10682 if (ParamD->getDeclName()) 10683 S.Diag(Templated->getLocation(), 10684 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10685 << ParamD->getDeclName(); 10686 else { 10687 int index = 0; 10688 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10689 index = TTP->getIndex(); 10690 else if (NonTypeTemplateParmDecl *NTTP 10691 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10692 index = NTTP->getIndex(); 10693 else 10694 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10695 S.Diag(Templated->getLocation(), 10696 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10697 << (index + 1); 10698 } 10699 MaybeEmitInheritedConstructorNote(S, Found); 10700 return; 10701 10702 case Sema::TDK_ConstraintsNotSatisfied: { 10703 // Format the template argument list into the argument string. 10704 SmallString<128> TemplateArgString; 10705 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10706 TemplateArgString = " "; 10707 TemplateArgString += S.getTemplateArgumentBindingsText( 10708 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10709 if (TemplateArgString.size() == 1) 10710 TemplateArgString.clear(); 10711 S.Diag(Templated->getLocation(), 10712 diag::note_ovl_candidate_unsatisfied_constraints) 10713 << TemplateArgString; 10714 10715 S.DiagnoseUnsatisfiedConstraint( 10716 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10717 return; 10718 } 10719 case Sema::TDK_TooManyArguments: 10720 case Sema::TDK_TooFewArguments: 10721 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10722 return; 10723 10724 case Sema::TDK_InstantiationDepth: 10725 S.Diag(Templated->getLocation(), 10726 diag::note_ovl_candidate_instantiation_depth); 10727 MaybeEmitInheritedConstructorNote(S, Found); 10728 return; 10729 10730 case Sema::TDK_SubstitutionFailure: { 10731 // Format the template argument list into the argument string. 10732 SmallString<128> TemplateArgString; 10733 if (TemplateArgumentList *Args = 10734 DeductionFailure.getTemplateArgumentList()) { 10735 TemplateArgString = " "; 10736 TemplateArgString += S.getTemplateArgumentBindingsText( 10737 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10738 if (TemplateArgString.size() == 1) 10739 TemplateArgString.clear(); 10740 } 10741 10742 // If this candidate was disabled by enable_if, say so. 10743 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10744 if (PDiag && PDiag->second.getDiagID() == 10745 diag::err_typename_nested_not_found_enable_if) { 10746 // FIXME: Use the source range of the condition, and the fully-qualified 10747 // name of the enable_if template. These are both present in PDiag. 10748 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10749 << "'enable_if'" << TemplateArgString; 10750 return; 10751 } 10752 10753 // We found a specific requirement that disabled the enable_if. 10754 if (PDiag && PDiag->second.getDiagID() == 10755 diag::err_typename_nested_not_found_requirement) { 10756 S.Diag(Templated->getLocation(), 10757 diag::note_ovl_candidate_disabled_by_requirement) 10758 << PDiag->second.getStringArg(0) << TemplateArgString; 10759 return; 10760 } 10761 10762 // Format the SFINAE diagnostic into the argument string. 10763 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10764 // formatted message in another diagnostic. 10765 SmallString<128> SFINAEArgString; 10766 SourceRange R; 10767 if (PDiag) { 10768 SFINAEArgString = ": "; 10769 R = SourceRange(PDiag->first, PDiag->first); 10770 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10771 } 10772 10773 S.Diag(Templated->getLocation(), 10774 diag::note_ovl_candidate_substitution_failure) 10775 << TemplateArgString << SFINAEArgString << R; 10776 MaybeEmitInheritedConstructorNote(S, Found); 10777 return; 10778 } 10779 10780 case Sema::TDK_DeducedMismatch: 10781 case Sema::TDK_DeducedMismatchNested: { 10782 // Format the template argument list into the argument string. 10783 SmallString<128> TemplateArgString; 10784 if (TemplateArgumentList *Args = 10785 DeductionFailure.getTemplateArgumentList()) { 10786 TemplateArgString = " "; 10787 TemplateArgString += S.getTemplateArgumentBindingsText( 10788 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10789 if (TemplateArgString.size() == 1) 10790 TemplateArgString.clear(); 10791 } 10792 10793 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10794 << (*DeductionFailure.getCallArgIndex() + 1) 10795 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10796 << TemplateArgString 10797 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10798 break; 10799 } 10800 10801 case Sema::TDK_NonDeducedMismatch: { 10802 // FIXME: Provide a source location to indicate what we couldn't match. 10803 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10804 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10805 if (FirstTA.getKind() == TemplateArgument::Template && 10806 SecondTA.getKind() == TemplateArgument::Template) { 10807 TemplateName FirstTN = FirstTA.getAsTemplate(); 10808 TemplateName SecondTN = SecondTA.getAsTemplate(); 10809 if (FirstTN.getKind() == TemplateName::Template && 10810 SecondTN.getKind() == TemplateName::Template) { 10811 if (FirstTN.getAsTemplateDecl()->getName() == 10812 SecondTN.getAsTemplateDecl()->getName()) { 10813 // FIXME: This fixes a bad diagnostic where both templates are named 10814 // the same. This particular case is a bit difficult since: 10815 // 1) It is passed as a string to the diagnostic printer. 10816 // 2) The diagnostic printer only attempts to find a better 10817 // name for types, not decls. 10818 // Ideally, this should folded into the diagnostic printer. 10819 S.Diag(Templated->getLocation(), 10820 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10821 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10822 return; 10823 } 10824 } 10825 } 10826 10827 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10828 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10829 return; 10830 10831 // FIXME: For generic lambda parameters, check if the function is a lambda 10832 // call operator, and if so, emit a prettier and more informative 10833 // diagnostic that mentions 'auto' and lambda in addition to 10834 // (or instead of?) the canonical template type parameters. 10835 S.Diag(Templated->getLocation(), 10836 diag::note_ovl_candidate_non_deduced_mismatch) 10837 << FirstTA << SecondTA; 10838 return; 10839 } 10840 // TODO: diagnose these individually, then kill off 10841 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10842 case Sema::TDK_MiscellaneousDeductionFailure: 10843 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10844 MaybeEmitInheritedConstructorNote(S, Found); 10845 return; 10846 case Sema::TDK_CUDATargetMismatch: 10847 S.Diag(Templated->getLocation(), 10848 diag::note_cuda_ovl_candidate_target_mismatch); 10849 return; 10850 } 10851 } 10852 10853 /// Diagnose a failed template-argument deduction, for function calls. 10854 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10855 unsigned NumArgs, 10856 bool TakingCandidateAddress) { 10857 unsigned TDK = Cand->DeductionFailure.Result; 10858 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10859 if (CheckArityMismatch(S, Cand, NumArgs)) 10860 return; 10861 } 10862 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10863 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10864 } 10865 10866 /// CUDA: diagnose an invalid call across targets. 10867 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10868 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10869 FunctionDecl *Callee = Cand->Function; 10870 10871 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10872 CalleeTarget = S.IdentifyCUDATarget(Callee); 10873 10874 std::string FnDesc; 10875 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10876 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10877 Cand->getRewriteKind(), FnDesc); 10878 10879 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10880 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10881 << FnDesc /* Ignored */ 10882 << CalleeTarget << CallerTarget; 10883 10884 // This could be an implicit constructor for which we could not infer the 10885 // target due to a collsion. Diagnose that case. 10886 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10887 if (Meth != nullptr && Meth->isImplicit()) { 10888 CXXRecordDecl *ParentClass = Meth->getParent(); 10889 Sema::CXXSpecialMember CSM; 10890 10891 switch (FnKindPair.first) { 10892 default: 10893 return; 10894 case oc_implicit_default_constructor: 10895 CSM = Sema::CXXDefaultConstructor; 10896 break; 10897 case oc_implicit_copy_constructor: 10898 CSM = Sema::CXXCopyConstructor; 10899 break; 10900 case oc_implicit_move_constructor: 10901 CSM = Sema::CXXMoveConstructor; 10902 break; 10903 case oc_implicit_copy_assignment: 10904 CSM = Sema::CXXCopyAssignment; 10905 break; 10906 case oc_implicit_move_assignment: 10907 CSM = Sema::CXXMoveAssignment; 10908 break; 10909 }; 10910 10911 bool ConstRHS = false; 10912 if (Meth->getNumParams()) { 10913 if (const ReferenceType *RT = 10914 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10915 ConstRHS = RT->getPointeeType().isConstQualified(); 10916 } 10917 } 10918 10919 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10920 /* ConstRHS */ ConstRHS, 10921 /* Diagnose */ true); 10922 } 10923 } 10924 10925 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10926 FunctionDecl *Callee = Cand->Function; 10927 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10928 10929 S.Diag(Callee->getLocation(), 10930 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10931 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10932 } 10933 10934 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10935 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10936 assert(ES.isExplicit() && "not an explicit candidate"); 10937 10938 unsigned Kind; 10939 switch (Cand->Function->getDeclKind()) { 10940 case Decl::Kind::CXXConstructor: 10941 Kind = 0; 10942 break; 10943 case Decl::Kind::CXXConversion: 10944 Kind = 1; 10945 break; 10946 case Decl::Kind::CXXDeductionGuide: 10947 Kind = Cand->Function->isImplicit() ? 0 : 2; 10948 break; 10949 default: 10950 llvm_unreachable("invalid Decl"); 10951 } 10952 10953 // Note the location of the first (in-class) declaration; a redeclaration 10954 // (particularly an out-of-class definition) will typically lack the 10955 // 'explicit' specifier. 10956 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10957 FunctionDecl *First = Cand->Function->getFirstDecl(); 10958 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10959 First = Pattern->getFirstDecl(); 10960 10961 S.Diag(First->getLocation(), 10962 diag::note_ovl_candidate_explicit) 10963 << Kind << (ES.getExpr() ? 1 : 0) 10964 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10965 } 10966 10967 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10968 FunctionDecl *Callee = Cand->Function; 10969 10970 S.Diag(Callee->getLocation(), 10971 diag::note_ovl_candidate_disabled_by_extension) 10972 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10973 } 10974 10975 /// Generates a 'note' diagnostic for an overload candidate. We've 10976 /// already generated a primary error at the call site. 10977 /// 10978 /// It really does need to be a single diagnostic with its caret 10979 /// pointed at the candidate declaration. Yes, this creates some 10980 /// major challenges of technical writing. Yes, this makes pointing 10981 /// out problems with specific arguments quite awkward. It's still 10982 /// better than generating twenty screens of text for every failed 10983 /// overload. 10984 /// 10985 /// It would be great to be able to express per-candidate problems 10986 /// more richly for those diagnostic clients that cared, but we'd 10987 /// still have to be just as careful with the default diagnostics. 10988 /// \param CtorDestAS Addr space of object being constructed (for ctor 10989 /// candidates only). 10990 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10991 unsigned NumArgs, 10992 bool TakingCandidateAddress, 10993 LangAS CtorDestAS = LangAS::Default) { 10994 FunctionDecl *Fn = Cand->Function; 10995 10996 // Note deleted candidates, but only if they're viable. 10997 if (Cand->Viable) { 10998 if (Fn->isDeleted()) { 10999 std::string FnDesc; 11000 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11001 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11002 Cand->getRewriteKind(), FnDesc); 11003 11004 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 11005 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 11006 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 11007 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11008 return; 11009 } 11010 11011 // We don't really have anything else to say about viable candidates. 11012 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11013 return; 11014 } 11015 11016 switch (Cand->FailureKind) { 11017 case ovl_fail_too_many_arguments: 11018 case ovl_fail_too_few_arguments: 11019 return DiagnoseArityMismatch(S, Cand, NumArgs); 11020 11021 case ovl_fail_bad_deduction: 11022 return DiagnoseBadDeduction(S, Cand, NumArgs, 11023 TakingCandidateAddress); 11024 11025 case ovl_fail_illegal_constructor: { 11026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11027 << (Fn->getPrimaryTemplate() ? 1 : 0); 11028 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11029 return; 11030 } 11031 11032 case ovl_fail_object_addrspace_mismatch: { 11033 Qualifiers QualsForPrinting; 11034 QualsForPrinting.setAddressSpace(CtorDestAS); 11035 S.Diag(Fn->getLocation(), 11036 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11037 << QualsForPrinting; 11038 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11039 return; 11040 } 11041 11042 case ovl_fail_trivial_conversion: 11043 case ovl_fail_bad_final_conversion: 11044 case ovl_fail_final_conversion_not_exact: 11045 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11046 11047 case ovl_fail_bad_conversion: { 11048 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11049 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11050 if (Cand->Conversions[I].isBad()) 11051 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11052 11053 // FIXME: this currently happens when we're called from SemaInit 11054 // when user-conversion overload fails. Figure out how to handle 11055 // those conditions and diagnose them well. 11056 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11057 } 11058 11059 case ovl_fail_bad_target: 11060 return DiagnoseBadTarget(S, Cand); 11061 11062 case ovl_fail_enable_if: 11063 return DiagnoseFailedEnableIfAttr(S, Cand); 11064 11065 case ovl_fail_explicit: 11066 return DiagnoseFailedExplicitSpec(S, Cand); 11067 11068 case ovl_fail_ext_disabled: 11069 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11070 11071 case ovl_fail_inhctor_slice: 11072 // It's generally not interesting to note copy/move constructors here. 11073 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11074 return; 11075 S.Diag(Fn->getLocation(), 11076 diag::note_ovl_candidate_inherited_constructor_slice) 11077 << (Fn->getPrimaryTemplate() ? 1 : 0) 11078 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11079 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11080 return; 11081 11082 case ovl_fail_addr_not_available: { 11083 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11084 (void)Available; 11085 assert(!Available); 11086 break; 11087 } 11088 case ovl_non_default_multiversion_function: 11089 // Do nothing, these should simply be ignored. 11090 break; 11091 11092 case ovl_fail_constraints_not_satisfied: { 11093 std::string FnDesc; 11094 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11095 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11096 Cand->getRewriteKind(), FnDesc); 11097 11098 S.Diag(Fn->getLocation(), 11099 diag::note_ovl_candidate_constraints_not_satisfied) 11100 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11101 << FnDesc /* Ignored */; 11102 ConstraintSatisfaction Satisfaction; 11103 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11104 break; 11105 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11106 } 11107 } 11108 } 11109 11110 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11111 // Desugar the type of the surrogate down to a function type, 11112 // retaining as many typedefs as possible while still showing 11113 // the function type (and, therefore, its parameter types). 11114 QualType FnType = Cand->Surrogate->getConversionType(); 11115 bool isLValueReference = false; 11116 bool isRValueReference = false; 11117 bool isPointer = false; 11118 if (const LValueReferenceType *FnTypeRef = 11119 FnType->getAs<LValueReferenceType>()) { 11120 FnType = FnTypeRef->getPointeeType(); 11121 isLValueReference = true; 11122 } else if (const RValueReferenceType *FnTypeRef = 11123 FnType->getAs<RValueReferenceType>()) { 11124 FnType = FnTypeRef->getPointeeType(); 11125 isRValueReference = true; 11126 } 11127 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11128 FnType = FnTypePtr->getPointeeType(); 11129 isPointer = true; 11130 } 11131 // Desugar down to a function type. 11132 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11133 // Reconstruct the pointer/reference as appropriate. 11134 if (isPointer) FnType = S.Context.getPointerType(FnType); 11135 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11136 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11137 11138 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11139 << FnType; 11140 } 11141 11142 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11143 SourceLocation OpLoc, 11144 OverloadCandidate *Cand) { 11145 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11146 std::string TypeStr("operator"); 11147 TypeStr += Opc; 11148 TypeStr += "("; 11149 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11150 if (Cand->Conversions.size() == 1) { 11151 TypeStr += ")"; 11152 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11153 } else { 11154 TypeStr += ", "; 11155 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11156 TypeStr += ")"; 11157 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11158 } 11159 } 11160 11161 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11162 OverloadCandidate *Cand) { 11163 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11164 if (ICS.isBad()) break; // all meaningless after first invalid 11165 if (!ICS.isAmbiguous()) continue; 11166 11167 ICS.DiagnoseAmbiguousConversion( 11168 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11169 } 11170 } 11171 11172 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11173 if (Cand->Function) 11174 return Cand->Function->getLocation(); 11175 if (Cand->IsSurrogate) 11176 return Cand->Surrogate->getLocation(); 11177 return SourceLocation(); 11178 } 11179 11180 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11181 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11182 case Sema::TDK_Success: 11183 case Sema::TDK_NonDependentConversionFailure: 11184 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11185 11186 case Sema::TDK_Invalid: 11187 case Sema::TDK_Incomplete: 11188 case Sema::TDK_IncompletePack: 11189 return 1; 11190 11191 case Sema::TDK_Underqualified: 11192 case Sema::TDK_Inconsistent: 11193 return 2; 11194 11195 case Sema::TDK_SubstitutionFailure: 11196 case Sema::TDK_DeducedMismatch: 11197 case Sema::TDK_ConstraintsNotSatisfied: 11198 case Sema::TDK_DeducedMismatchNested: 11199 case Sema::TDK_NonDeducedMismatch: 11200 case Sema::TDK_MiscellaneousDeductionFailure: 11201 case Sema::TDK_CUDATargetMismatch: 11202 return 3; 11203 11204 case Sema::TDK_InstantiationDepth: 11205 return 4; 11206 11207 case Sema::TDK_InvalidExplicitArguments: 11208 return 5; 11209 11210 case Sema::TDK_TooManyArguments: 11211 case Sema::TDK_TooFewArguments: 11212 return 6; 11213 } 11214 llvm_unreachable("Unhandled deduction result"); 11215 } 11216 11217 namespace { 11218 struct CompareOverloadCandidatesForDisplay { 11219 Sema &S; 11220 SourceLocation Loc; 11221 size_t NumArgs; 11222 OverloadCandidateSet::CandidateSetKind CSK; 11223 11224 CompareOverloadCandidatesForDisplay( 11225 Sema &S, SourceLocation Loc, size_t NArgs, 11226 OverloadCandidateSet::CandidateSetKind CSK) 11227 : S(S), NumArgs(NArgs), CSK(CSK) {} 11228 11229 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11230 // If there are too many or too few arguments, that's the high-order bit we 11231 // want to sort by, even if the immediate failure kind was something else. 11232 if (C->FailureKind == ovl_fail_too_many_arguments || 11233 C->FailureKind == ovl_fail_too_few_arguments) 11234 return static_cast<OverloadFailureKind>(C->FailureKind); 11235 11236 if (C->Function) { 11237 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11238 return ovl_fail_too_many_arguments; 11239 if (NumArgs < C->Function->getMinRequiredArguments()) 11240 return ovl_fail_too_few_arguments; 11241 } 11242 11243 return static_cast<OverloadFailureKind>(C->FailureKind); 11244 } 11245 11246 bool operator()(const OverloadCandidate *L, 11247 const OverloadCandidate *R) { 11248 // Fast-path this check. 11249 if (L == R) return false; 11250 11251 // Order first by viability. 11252 if (L->Viable) { 11253 if (!R->Viable) return true; 11254 11255 // TODO: introduce a tri-valued comparison for overload 11256 // candidates. Would be more worthwhile if we had a sort 11257 // that could exploit it. 11258 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11259 return true; 11260 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11261 return false; 11262 } else if (R->Viable) 11263 return false; 11264 11265 assert(L->Viable == R->Viable); 11266 11267 // Criteria by which we can sort non-viable candidates: 11268 if (!L->Viable) { 11269 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11270 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11271 11272 // 1. Arity mismatches come after other candidates. 11273 if (LFailureKind == ovl_fail_too_many_arguments || 11274 LFailureKind == ovl_fail_too_few_arguments) { 11275 if (RFailureKind == ovl_fail_too_many_arguments || 11276 RFailureKind == ovl_fail_too_few_arguments) { 11277 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11278 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11279 if (LDist == RDist) { 11280 if (LFailureKind == RFailureKind) 11281 // Sort non-surrogates before surrogates. 11282 return !L->IsSurrogate && R->IsSurrogate; 11283 // Sort candidates requiring fewer parameters than there were 11284 // arguments given after candidates requiring more parameters 11285 // than there were arguments given. 11286 return LFailureKind == ovl_fail_too_many_arguments; 11287 } 11288 return LDist < RDist; 11289 } 11290 return false; 11291 } 11292 if (RFailureKind == ovl_fail_too_many_arguments || 11293 RFailureKind == ovl_fail_too_few_arguments) 11294 return true; 11295 11296 // 2. Bad conversions come first and are ordered by the number 11297 // of bad conversions and quality of good conversions. 11298 if (LFailureKind == ovl_fail_bad_conversion) { 11299 if (RFailureKind != ovl_fail_bad_conversion) 11300 return true; 11301 11302 // The conversion that can be fixed with a smaller number of changes, 11303 // comes first. 11304 unsigned numLFixes = L->Fix.NumConversionsFixed; 11305 unsigned numRFixes = R->Fix.NumConversionsFixed; 11306 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11307 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11308 if (numLFixes != numRFixes) { 11309 return numLFixes < numRFixes; 11310 } 11311 11312 // If there's any ordering between the defined conversions... 11313 // FIXME: this might not be transitive. 11314 assert(L->Conversions.size() == R->Conversions.size()); 11315 11316 int leftBetter = 0; 11317 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11318 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11319 switch (CompareImplicitConversionSequences(S, Loc, 11320 L->Conversions[I], 11321 R->Conversions[I])) { 11322 case ImplicitConversionSequence::Better: 11323 leftBetter++; 11324 break; 11325 11326 case ImplicitConversionSequence::Worse: 11327 leftBetter--; 11328 break; 11329 11330 case ImplicitConversionSequence::Indistinguishable: 11331 break; 11332 } 11333 } 11334 if (leftBetter > 0) return true; 11335 if (leftBetter < 0) return false; 11336 11337 } else if (RFailureKind == ovl_fail_bad_conversion) 11338 return false; 11339 11340 if (LFailureKind == ovl_fail_bad_deduction) { 11341 if (RFailureKind != ovl_fail_bad_deduction) 11342 return true; 11343 11344 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11345 return RankDeductionFailure(L->DeductionFailure) 11346 < RankDeductionFailure(R->DeductionFailure); 11347 } else if (RFailureKind == ovl_fail_bad_deduction) 11348 return false; 11349 11350 // TODO: others? 11351 } 11352 11353 // Sort everything else by location. 11354 SourceLocation LLoc = GetLocationForCandidate(L); 11355 SourceLocation RLoc = GetLocationForCandidate(R); 11356 11357 // Put candidates without locations (e.g. builtins) at the end. 11358 if (LLoc.isInvalid()) return false; 11359 if (RLoc.isInvalid()) return true; 11360 11361 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11362 } 11363 }; 11364 } 11365 11366 /// CompleteNonViableCandidate - Normally, overload resolution only 11367 /// computes up to the first bad conversion. Produces the FixIt set if 11368 /// possible. 11369 static void 11370 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11371 ArrayRef<Expr *> Args, 11372 OverloadCandidateSet::CandidateSetKind CSK) { 11373 assert(!Cand->Viable); 11374 11375 // Don't do anything on failures other than bad conversion. 11376 if (Cand->FailureKind != ovl_fail_bad_conversion) 11377 return; 11378 11379 // We only want the FixIts if all the arguments can be corrected. 11380 bool Unfixable = false; 11381 // Use a implicit copy initialization to check conversion fixes. 11382 Cand->Fix.setConversionChecker(TryCopyInitialization); 11383 11384 // Attempt to fix the bad conversion. 11385 unsigned ConvCount = Cand->Conversions.size(); 11386 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11387 ++ConvIdx) { 11388 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11389 if (Cand->Conversions[ConvIdx].isInitialized() && 11390 Cand->Conversions[ConvIdx].isBad()) { 11391 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11392 break; 11393 } 11394 } 11395 11396 // FIXME: this should probably be preserved from the overload 11397 // operation somehow. 11398 bool SuppressUserConversions = false; 11399 11400 unsigned ConvIdx = 0; 11401 unsigned ArgIdx = 0; 11402 ArrayRef<QualType> ParamTypes; 11403 bool Reversed = Cand->isReversed(); 11404 11405 if (Cand->IsSurrogate) { 11406 QualType ConvType 11407 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11408 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11409 ConvType = ConvPtrType->getPointeeType(); 11410 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11411 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11412 ConvIdx = 1; 11413 } else if (Cand->Function) { 11414 ParamTypes = 11415 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11416 if (isa<CXXMethodDecl>(Cand->Function) && 11417 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11418 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11419 ConvIdx = 1; 11420 if (CSK == OverloadCandidateSet::CSK_Operator && 11421 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11422 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11423 ArgIdx = 1; 11424 } 11425 } else { 11426 // Builtin operator. 11427 assert(ConvCount <= 3); 11428 ParamTypes = Cand->BuiltinParamTypes; 11429 } 11430 11431 // Fill in the rest of the conversions. 11432 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11433 ConvIdx != ConvCount; 11434 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11435 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11436 if (Cand->Conversions[ConvIdx].isInitialized()) { 11437 // We've already checked this conversion. 11438 } else if (ParamIdx < ParamTypes.size()) { 11439 if (ParamTypes[ParamIdx]->isDependentType()) 11440 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11441 Args[ArgIdx]->getType()); 11442 else { 11443 Cand->Conversions[ConvIdx] = 11444 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11445 SuppressUserConversions, 11446 /*InOverloadResolution=*/true, 11447 /*AllowObjCWritebackConversion=*/ 11448 S.getLangOpts().ObjCAutoRefCount); 11449 // Store the FixIt in the candidate if it exists. 11450 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11451 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11452 } 11453 } else 11454 Cand->Conversions[ConvIdx].setEllipsis(); 11455 } 11456 } 11457 11458 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11459 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11460 SourceLocation OpLoc, 11461 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11462 // Sort the candidates by viability and position. Sorting directly would 11463 // be prohibitive, so we make a set of pointers and sort those. 11464 SmallVector<OverloadCandidate*, 32> Cands; 11465 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11466 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11467 if (!Filter(*Cand)) 11468 continue; 11469 switch (OCD) { 11470 case OCD_AllCandidates: 11471 if (!Cand->Viable) { 11472 if (!Cand->Function && !Cand->IsSurrogate) { 11473 // This a non-viable builtin candidate. We do not, in general, 11474 // want to list every possible builtin candidate. 11475 continue; 11476 } 11477 CompleteNonViableCandidate(S, Cand, Args, Kind); 11478 } 11479 break; 11480 11481 case OCD_ViableCandidates: 11482 if (!Cand->Viable) 11483 continue; 11484 break; 11485 11486 case OCD_AmbiguousCandidates: 11487 if (!Cand->Best) 11488 continue; 11489 break; 11490 } 11491 11492 Cands.push_back(Cand); 11493 } 11494 11495 llvm::stable_sort( 11496 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11497 11498 return Cands; 11499 } 11500 11501 /// When overload resolution fails, prints diagnostic messages containing the 11502 /// candidates in the candidate set. 11503 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11504 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11505 StringRef Opc, SourceLocation OpLoc, 11506 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11507 11508 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11509 11510 S.Diag(PD.first, PD.second); 11511 11512 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11513 11514 if (OCD == OCD_AmbiguousCandidates) 11515 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11516 } 11517 11518 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11519 ArrayRef<OverloadCandidate *> Cands, 11520 StringRef Opc, SourceLocation OpLoc) { 11521 bool ReportedAmbiguousConversions = false; 11522 11523 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11524 unsigned CandsShown = 0; 11525 auto I = Cands.begin(), E = Cands.end(); 11526 for (; I != E; ++I) { 11527 OverloadCandidate *Cand = *I; 11528 11529 // Set an arbitrary limit on the number of candidate functions we'll spam 11530 // the user with. FIXME: This limit should depend on details of the 11531 // candidate list. 11532 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11533 break; 11534 } 11535 ++CandsShown; 11536 11537 if (Cand->Function) 11538 NoteFunctionCandidate(S, Cand, Args.size(), 11539 /*TakingCandidateAddress=*/false, DestAS); 11540 else if (Cand->IsSurrogate) 11541 NoteSurrogateCandidate(S, Cand); 11542 else { 11543 assert(Cand->Viable && 11544 "Non-viable built-in candidates are not added to Cands."); 11545 // Generally we only see ambiguities including viable builtin 11546 // operators if overload resolution got screwed up by an 11547 // ambiguous user-defined conversion. 11548 // 11549 // FIXME: It's quite possible for different conversions to see 11550 // different ambiguities, though. 11551 if (!ReportedAmbiguousConversions) { 11552 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11553 ReportedAmbiguousConversions = true; 11554 } 11555 11556 // If this is a viable builtin, print it. 11557 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11558 } 11559 } 11560 11561 if (I != E) 11562 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11563 } 11564 11565 static SourceLocation 11566 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11567 return Cand->Specialization ? Cand->Specialization->getLocation() 11568 : SourceLocation(); 11569 } 11570 11571 namespace { 11572 struct CompareTemplateSpecCandidatesForDisplay { 11573 Sema &S; 11574 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11575 11576 bool operator()(const TemplateSpecCandidate *L, 11577 const TemplateSpecCandidate *R) { 11578 // Fast-path this check. 11579 if (L == R) 11580 return false; 11581 11582 // Assuming that both candidates are not matches... 11583 11584 // Sort by the ranking of deduction failures. 11585 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11586 return RankDeductionFailure(L->DeductionFailure) < 11587 RankDeductionFailure(R->DeductionFailure); 11588 11589 // Sort everything else by location. 11590 SourceLocation LLoc = GetLocationForCandidate(L); 11591 SourceLocation RLoc = GetLocationForCandidate(R); 11592 11593 // Put candidates without locations (e.g. builtins) at the end. 11594 if (LLoc.isInvalid()) 11595 return false; 11596 if (RLoc.isInvalid()) 11597 return true; 11598 11599 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11600 } 11601 }; 11602 } 11603 11604 /// Diagnose a template argument deduction failure. 11605 /// We are treating these failures as overload failures due to bad 11606 /// deductions. 11607 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11608 bool ForTakingAddress) { 11609 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11610 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11611 } 11612 11613 void TemplateSpecCandidateSet::destroyCandidates() { 11614 for (iterator i = begin(), e = end(); i != e; ++i) { 11615 i->DeductionFailure.Destroy(); 11616 } 11617 } 11618 11619 void TemplateSpecCandidateSet::clear() { 11620 destroyCandidates(); 11621 Candidates.clear(); 11622 } 11623 11624 /// NoteCandidates - When no template specialization match is found, prints 11625 /// diagnostic messages containing the non-matching specializations that form 11626 /// the candidate set. 11627 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11628 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11629 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11630 // Sort the candidates by position (assuming no candidate is a match). 11631 // Sorting directly would be prohibitive, so we make a set of pointers 11632 // and sort those. 11633 SmallVector<TemplateSpecCandidate *, 32> Cands; 11634 Cands.reserve(size()); 11635 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11636 if (Cand->Specialization) 11637 Cands.push_back(Cand); 11638 // Otherwise, this is a non-matching builtin candidate. We do not, 11639 // in general, want to list every possible builtin candidate. 11640 } 11641 11642 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11643 11644 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11645 // for generalization purposes (?). 11646 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11647 11648 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11649 unsigned CandsShown = 0; 11650 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11651 TemplateSpecCandidate *Cand = *I; 11652 11653 // Set an arbitrary limit on the number of candidates we'll spam 11654 // the user with. FIXME: This limit should depend on details of the 11655 // candidate list. 11656 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11657 break; 11658 ++CandsShown; 11659 11660 assert(Cand->Specialization && 11661 "Non-matching built-in candidates are not added to Cands."); 11662 Cand->NoteDeductionFailure(S, ForTakingAddress); 11663 } 11664 11665 if (I != E) 11666 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11667 } 11668 11669 // [PossiblyAFunctionType] --> [Return] 11670 // NonFunctionType --> NonFunctionType 11671 // R (A) --> R(A) 11672 // R (*)(A) --> R (A) 11673 // R (&)(A) --> R (A) 11674 // R (S::*)(A) --> R (A) 11675 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11676 QualType Ret = PossiblyAFunctionType; 11677 if (const PointerType *ToTypePtr = 11678 PossiblyAFunctionType->getAs<PointerType>()) 11679 Ret = ToTypePtr->getPointeeType(); 11680 else if (const ReferenceType *ToTypeRef = 11681 PossiblyAFunctionType->getAs<ReferenceType>()) 11682 Ret = ToTypeRef->getPointeeType(); 11683 else if (const MemberPointerType *MemTypePtr = 11684 PossiblyAFunctionType->getAs<MemberPointerType>()) 11685 Ret = MemTypePtr->getPointeeType(); 11686 Ret = 11687 Context.getCanonicalType(Ret).getUnqualifiedType(); 11688 return Ret; 11689 } 11690 11691 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11692 bool Complain = true) { 11693 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11694 S.DeduceReturnType(FD, Loc, Complain)) 11695 return true; 11696 11697 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11698 if (S.getLangOpts().CPlusPlus17 && 11699 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11700 !S.ResolveExceptionSpec(Loc, FPT)) 11701 return true; 11702 11703 return false; 11704 } 11705 11706 namespace { 11707 // A helper class to help with address of function resolution 11708 // - allows us to avoid passing around all those ugly parameters 11709 class AddressOfFunctionResolver { 11710 Sema& S; 11711 Expr* SourceExpr; 11712 const QualType& TargetType; 11713 QualType TargetFunctionType; // Extracted function type from target type 11714 11715 bool Complain; 11716 //DeclAccessPair& ResultFunctionAccessPair; 11717 ASTContext& Context; 11718 11719 bool TargetTypeIsNonStaticMemberFunction; 11720 bool FoundNonTemplateFunction; 11721 bool StaticMemberFunctionFromBoundPointer; 11722 bool HasComplained; 11723 11724 OverloadExpr::FindResult OvlExprInfo; 11725 OverloadExpr *OvlExpr; 11726 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11727 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11728 TemplateSpecCandidateSet FailedCandidates; 11729 11730 public: 11731 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11732 const QualType &TargetType, bool Complain) 11733 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11734 Complain(Complain), Context(S.getASTContext()), 11735 TargetTypeIsNonStaticMemberFunction( 11736 !!TargetType->getAs<MemberPointerType>()), 11737 FoundNonTemplateFunction(false), 11738 StaticMemberFunctionFromBoundPointer(false), 11739 HasComplained(false), 11740 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11741 OvlExpr(OvlExprInfo.Expression), 11742 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11743 ExtractUnqualifiedFunctionTypeFromTargetType(); 11744 11745 if (TargetFunctionType->isFunctionType()) { 11746 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11747 if (!UME->isImplicitAccess() && 11748 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11749 StaticMemberFunctionFromBoundPointer = true; 11750 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11751 DeclAccessPair dap; 11752 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11753 OvlExpr, false, &dap)) { 11754 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11755 if (!Method->isStatic()) { 11756 // If the target type is a non-function type and the function found 11757 // is a non-static member function, pretend as if that was the 11758 // target, it's the only possible type to end up with. 11759 TargetTypeIsNonStaticMemberFunction = true; 11760 11761 // And skip adding the function if its not in the proper form. 11762 // We'll diagnose this due to an empty set of functions. 11763 if (!OvlExprInfo.HasFormOfMemberPointer) 11764 return; 11765 } 11766 11767 Matches.push_back(std::make_pair(dap, Fn)); 11768 } 11769 return; 11770 } 11771 11772 if (OvlExpr->hasExplicitTemplateArgs()) 11773 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11774 11775 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11776 // C++ [over.over]p4: 11777 // If more than one function is selected, [...] 11778 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11779 if (FoundNonTemplateFunction) 11780 EliminateAllTemplateMatches(); 11781 else 11782 EliminateAllExceptMostSpecializedTemplate(); 11783 } 11784 } 11785 11786 if (S.getLangOpts().CUDA && Matches.size() > 1) 11787 EliminateSuboptimalCudaMatches(); 11788 } 11789 11790 bool hasComplained() const { return HasComplained; } 11791 11792 private: 11793 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11794 QualType Discard; 11795 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11796 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11797 } 11798 11799 /// \return true if A is considered a better overload candidate for the 11800 /// desired type than B. 11801 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11802 // If A doesn't have exactly the correct type, we don't want to classify it 11803 // as "better" than anything else. This way, the user is required to 11804 // disambiguate for us if there are multiple candidates and no exact match. 11805 return candidateHasExactlyCorrectType(A) && 11806 (!candidateHasExactlyCorrectType(B) || 11807 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11808 } 11809 11810 /// \return true if we were able to eliminate all but one overload candidate, 11811 /// false otherwise. 11812 bool eliminiateSuboptimalOverloadCandidates() { 11813 // Same algorithm as overload resolution -- one pass to pick the "best", 11814 // another pass to be sure that nothing is better than the best. 11815 auto Best = Matches.begin(); 11816 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11817 if (isBetterCandidate(I->second, Best->second)) 11818 Best = I; 11819 11820 const FunctionDecl *BestFn = Best->second; 11821 auto IsBestOrInferiorToBest = [this, BestFn]( 11822 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11823 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11824 }; 11825 11826 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11827 // option, so we can potentially give the user a better error 11828 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11829 return false; 11830 Matches[0] = *Best; 11831 Matches.resize(1); 11832 return true; 11833 } 11834 11835 bool isTargetTypeAFunction() const { 11836 return TargetFunctionType->isFunctionType(); 11837 } 11838 11839 // [ToType] [Return] 11840 11841 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11842 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11843 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11844 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11845 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11846 } 11847 11848 // return true if any matching specializations were found 11849 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11850 const DeclAccessPair& CurAccessFunPair) { 11851 if (CXXMethodDecl *Method 11852 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11853 // Skip non-static function templates when converting to pointer, and 11854 // static when converting to member pointer. 11855 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11856 return false; 11857 } 11858 else if (TargetTypeIsNonStaticMemberFunction) 11859 return false; 11860 11861 // C++ [over.over]p2: 11862 // If the name is a function template, template argument deduction is 11863 // done (14.8.2.2), and if the argument deduction succeeds, the 11864 // resulting template argument list is used to generate a single 11865 // function template specialization, which is added to the set of 11866 // overloaded functions considered. 11867 FunctionDecl *Specialization = nullptr; 11868 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11869 if (Sema::TemplateDeductionResult Result 11870 = S.DeduceTemplateArguments(FunctionTemplate, 11871 &OvlExplicitTemplateArgs, 11872 TargetFunctionType, Specialization, 11873 Info, /*IsAddressOfFunction*/true)) { 11874 // Make a note of the failed deduction for diagnostics. 11875 FailedCandidates.addCandidate() 11876 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11877 MakeDeductionFailureInfo(Context, Result, Info)); 11878 return false; 11879 } 11880 11881 // Template argument deduction ensures that we have an exact match or 11882 // compatible pointer-to-function arguments that would be adjusted by ICS. 11883 // This function template specicalization works. 11884 assert(S.isSameOrCompatibleFunctionType( 11885 Context.getCanonicalType(Specialization->getType()), 11886 Context.getCanonicalType(TargetFunctionType))); 11887 11888 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11889 return false; 11890 11891 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11892 return true; 11893 } 11894 11895 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11896 const DeclAccessPair& CurAccessFunPair) { 11897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11898 // Skip non-static functions when converting to pointer, and static 11899 // when converting to member pointer. 11900 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11901 return false; 11902 } 11903 else if (TargetTypeIsNonStaticMemberFunction) 11904 return false; 11905 11906 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11907 if (S.getLangOpts().CUDA) 11908 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11909 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11910 return false; 11911 if (FunDecl->isMultiVersion()) { 11912 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11913 if (TA && !TA->isDefaultVersion()) 11914 return false; 11915 } 11916 11917 // If any candidate has a placeholder return type, trigger its deduction 11918 // now. 11919 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11920 Complain)) { 11921 HasComplained |= Complain; 11922 return false; 11923 } 11924 11925 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11926 return false; 11927 11928 // If we're in C, we need to support types that aren't exactly identical. 11929 if (!S.getLangOpts().CPlusPlus || 11930 candidateHasExactlyCorrectType(FunDecl)) { 11931 Matches.push_back(std::make_pair( 11932 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11933 FoundNonTemplateFunction = true; 11934 return true; 11935 } 11936 } 11937 11938 return false; 11939 } 11940 11941 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11942 bool Ret = false; 11943 11944 // If the overload expression doesn't have the form of a pointer to 11945 // member, don't try to convert it to a pointer-to-member type. 11946 if (IsInvalidFormOfPointerToMemberFunction()) 11947 return false; 11948 11949 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11950 E = OvlExpr->decls_end(); 11951 I != E; ++I) { 11952 // Look through any using declarations to find the underlying function. 11953 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11954 11955 // C++ [over.over]p3: 11956 // Non-member functions and static member functions match 11957 // targets of type "pointer-to-function" or "reference-to-function." 11958 // Nonstatic member functions match targets of 11959 // type "pointer-to-member-function." 11960 // Note that according to DR 247, the containing class does not matter. 11961 if (FunctionTemplateDecl *FunctionTemplate 11962 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11963 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11964 Ret = true; 11965 } 11966 // If we have explicit template arguments supplied, skip non-templates. 11967 else if (!OvlExpr->hasExplicitTemplateArgs() && 11968 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11969 Ret = true; 11970 } 11971 assert(Ret || Matches.empty()); 11972 return Ret; 11973 } 11974 11975 void EliminateAllExceptMostSpecializedTemplate() { 11976 // [...] and any given function template specialization F1 is 11977 // eliminated if the set contains a second function template 11978 // specialization whose function template is more specialized 11979 // than the function template of F1 according to the partial 11980 // ordering rules of 14.5.5.2. 11981 11982 // The algorithm specified above is quadratic. We instead use a 11983 // two-pass algorithm (similar to the one used to identify the 11984 // best viable function in an overload set) that identifies the 11985 // best function template (if it exists). 11986 11987 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11988 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11989 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11990 11991 // TODO: It looks like FailedCandidates does not serve much purpose 11992 // here, since the no_viable diagnostic has index 0. 11993 UnresolvedSetIterator Result = S.getMostSpecialized( 11994 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11995 SourceExpr->getBeginLoc(), S.PDiag(), 11996 S.PDiag(diag::err_addr_ovl_ambiguous) 11997 << Matches[0].second->getDeclName(), 11998 S.PDiag(diag::note_ovl_candidate) 11999 << (unsigned)oc_function << (unsigned)ocs_described_template, 12000 Complain, TargetFunctionType); 12001 12002 if (Result != MatchesCopy.end()) { 12003 // Make it the first and only element 12004 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 12005 Matches[0].second = cast<FunctionDecl>(*Result); 12006 Matches.resize(1); 12007 } else 12008 HasComplained |= Complain; 12009 } 12010 12011 void EliminateAllTemplateMatches() { 12012 // [...] any function template specializations in the set are 12013 // eliminated if the set also contains a non-template function, [...] 12014 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12015 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12016 ++I; 12017 else { 12018 Matches[I] = Matches[--N]; 12019 Matches.resize(N); 12020 } 12021 } 12022 } 12023 12024 void EliminateSuboptimalCudaMatches() { 12025 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12026 } 12027 12028 public: 12029 void ComplainNoMatchesFound() const { 12030 assert(Matches.empty()); 12031 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12032 << OvlExpr->getName() << TargetFunctionType 12033 << OvlExpr->getSourceRange(); 12034 if (FailedCandidates.empty()) 12035 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12036 /*TakingAddress=*/true); 12037 else { 12038 // We have some deduction failure messages. Use them to diagnose 12039 // the function templates, and diagnose the non-template candidates 12040 // normally. 12041 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12042 IEnd = OvlExpr->decls_end(); 12043 I != IEnd; ++I) 12044 if (FunctionDecl *Fun = 12045 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12046 if (!functionHasPassObjectSizeParams(Fun)) 12047 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12048 /*TakingAddress=*/true); 12049 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12050 } 12051 } 12052 12053 bool IsInvalidFormOfPointerToMemberFunction() const { 12054 return TargetTypeIsNonStaticMemberFunction && 12055 !OvlExprInfo.HasFormOfMemberPointer; 12056 } 12057 12058 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12059 // TODO: Should we condition this on whether any functions might 12060 // have matched, or is it more appropriate to do that in callers? 12061 // TODO: a fixit wouldn't hurt. 12062 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12063 << TargetType << OvlExpr->getSourceRange(); 12064 } 12065 12066 bool IsStaticMemberFunctionFromBoundPointer() const { 12067 return StaticMemberFunctionFromBoundPointer; 12068 } 12069 12070 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12071 S.Diag(OvlExpr->getBeginLoc(), 12072 diag::err_invalid_form_pointer_member_function) 12073 << OvlExpr->getSourceRange(); 12074 } 12075 12076 void ComplainOfInvalidConversion() const { 12077 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12078 << OvlExpr->getName() << TargetType; 12079 } 12080 12081 void ComplainMultipleMatchesFound() const { 12082 assert(Matches.size() > 1); 12083 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12084 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12085 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12086 /*TakingAddress=*/true); 12087 } 12088 12089 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12090 12091 int getNumMatches() const { return Matches.size(); } 12092 12093 FunctionDecl* getMatchingFunctionDecl() const { 12094 if (Matches.size() != 1) return nullptr; 12095 return Matches[0].second; 12096 } 12097 12098 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12099 if (Matches.size() != 1) return nullptr; 12100 return &Matches[0].first; 12101 } 12102 }; 12103 } 12104 12105 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12106 /// an overloaded function (C++ [over.over]), where @p From is an 12107 /// expression with overloaded function type and @p ToType is the type 12108 /// we're trying to resolve to. For example: 12109 /// 12110 /// @code 12111 /// int f(double); 12112 /// int f(int); 12113 /// 12114 /// int (*pfd)(double) = f; // selects f(double) 12115 /// @endcode 12116 /// 12117 /// This routine returns the resulting FunctionDecl if it could be 12118 /// resolved, and NULL otherwise. When @p Complain is true, this 12119 /// routine will emit diagnostics if there is an error. 12120 FunctionDecl * 12121 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12122 QualType TargetType, 12123 bool Complain, 12124 DeclAccessPair &FoundResult, 12125 bool *pHadMultipleCandidates) { 12126 assert(AddressOfExpr->getType() == Context.OverloadTy); 12127 12128 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12129 Complain); 12130 int NumMatches = Resolver.getNumMatches(); 12131 FunctionDecl *Fn = nullptr; 12132 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12133 if (NumMatches == 0 && ShouldComplain) { 12134 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12135 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12136 else 12137 Resolver.ComplainNoMatchesFound(); 12138 } 12139 else if (NumMatches > 1 && ShouldComplain) 12140 Resolver.ComplainMultipleMatchesFound(); 12141 else if (NumMatches == 1) { 12142 Fn = Resolver.getMatchingFunctionDecl(); 12143 assert(Fn); 12144 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12145 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12146 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12147 if (Complain) { 12148 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12149 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12150 else 12151 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12152 } 12153 } 12154 12155 if (pHadMultipleCandidates) 12156 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12157 return Fn; 12158 } 12159 12160 /// Given an expression that refers to an overloaded function, try to 12161 /// resolve that function to a single function that can have its address taken. 12162 /// This will modify `Pair` iff it returns non-null. 12163 /// 12164 /// This routine can only succeed if from all of the candidates in the overload 12165 /// set for SrcExpr that can have their addresses taken, there is one candidate 12166 /// that is more constrained than the rest. 12167 FunctionDecl * 12168 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12169 OverloadExpr::FindResult R = OverloadExpr::find(E); 12170 OverloadExpr *Ovl = R.Expression; 12171 bool IsResultAmbiguous = false; 12172 FunctionDecl *Result = nullptr; 12173 DeclAccessPair DAP; 12174 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12175 12176 auto CheckMoreConstrained = 12177 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12178 SmallVector<const Expr *, 1> AC1, AC2; 12179 FD1->getAssociatedConstraints(AC1); 12180 FD2->getAssociatedConstraints(AC2); 12181 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12182 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12183 return None; 12184 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12185 return None; 12186 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12187 return None; 12188 return AtLeastAsConstrained1; 12189 }; 12190 12191 // Don't use the AddressOfResolver because we're specifically looking for 12192 // cases where we have one overload candidate that lacks 12193 // enable_if/pass_object_size/... 12194 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12195 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12196 if (!FD) 12197 return nullptr; 12198 12199 if (!checkAddressOfFunctionIsAvailable(FD)) 12200 continue; 12201 12202 // We have more than one result - see if it is more constrained than the 12203 // previous one. 12204 if (Result) { 12205 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12206 Result); 12207 if (!MoreConstrainedThanPrevious) { 12208 IsResultAmbiguous = true; 12209 AmbiguousDecls.push_back(FD); 12210 continue; 12211 } 12212 if (!*MoreConstrainedThanPrevious) 12213 continue; 12214 // FD is more constrained - replace Result with it. 12215 } 12216 IsResultAmbiguous = false; 12217 DAP = I.getPair(); 12218 Result = FD; 12219 } 12220 12221 if (IsResultAmbiguous) 12222 return nullptr; 12223 12224 if (Result) { 12225 SmallVector<const Expr *, 1> ResultAC; 12226 // We skipped over some ambiguous declarations which might be ambiguous with 12227 // the selected result. 12228 for (FunctionDecl *Skipped : AmbiguousDecls) 12229 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12230 return nullptr; 12231 Pair = DAP; 12232 } 12233 return Result; 12234 } 12235 12236 /// Given an overloaded function, tries to turn it into a non-overloaded 12237 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12238 /// will perform access checks, diagnose the use of the resultant decl, and, if 12239 /// requested, potentially perform a function-to-pointer decay. 12240 /// 12241 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12242 /// Otherwise, returns true. This may emit diagnostics and return true. 12243 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12244 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12245 Expr *E = SrcExpr.get(); 12246 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12247 12248 DeclAccessPair DAP; 12249 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12250 if (!Found || Found->isCPUDispatchMultiVersion() || 12251 Found->isCPUSpecificMultiVersion()) 12252 return false; 12253 12254 // Emitting multiple diagnostics for a function that is both inaccessible and 12255 // unavailable is consistent with our behavior elsewhere. So, always check 12256 // for both. 12257 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12258 CheckAddressOfMemberAccess(E, DAP); 12259 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12260 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12261 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12262 else 12263 SrcExpr = Fixed; 12264 return true; 12265 } 12266 12267 /// Given an expression that refers to an overloaded function, try to 12268 /// resolve that overloaded function expression down to a single function. 12269 /// 12270 /// This routine can only resolve template-ids that refer to a single function 12271 /// template, where that template-id refers to a single template whose template 12272 /// arguments are either provided by the template-id or have defaults, 12273 /// as described in C++0x [temp.arg.explicit]p3. 12274 /// 12275 /// If no template-ids are found, no diagnostics are emitted and NULL is 12276 /// returned. 12277 FunctionDecl * 12278 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12279 bool Complain, 12280 DeclAccessPair *FoundResult) { 12281 // C++ [over.over]p1: 12282 // [...] [Note: any redundant set of parentheses surrounding the 12283 // overloaded function name is ignored (5.1). ] 12284 // C++ [over.over]p1: 12285 // [...] The overloaded function name can be preceded by the & 12286 // operator. 12287 12288 // If we didn't actually find any template-ids, we're done. 12289 if (!ovl->hasExplicitTemplateArgs()) 12290 return nullptr; 12291 12292 TemplateArgumentListInfo ExplicitTemplateArgs; 12293 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12294 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12295 12296 // Look through all of the overloaded functions, searching for one 12297 // whose type matches exactly. 12298 FunctionDecl *Matched = nullptr; 12299 for (UnresolvedSetIterator I = ovl->decls_begin(), 12300 E = ovl->decls_end(); I != E; ++I) { 12301 // C++0x [temp.arg.explicit]p3: 12302 // [...] In contexts where deduction is done and fails, or in contexts 12303 // where deduction is not done, if a template argument list is 12304 // specified and it, along with any default template arguments, 12305 // identifies a single function template specialization, then the 12306 // template-id is an lvalue for the function template specialization. 12307 FunctionTemplateDecl *FunctionTemplate 12308 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12309 12310 // C++ [over.over]p2: 12311 // If the name is a function template, template argument deduction is 12312 // done (14.8.2.2), and if the argument deduction succeeds, the 12313 // resulting template argument list is used to generate a single 12314 // function template specialization, which is added to the set of 12315 // overloaded functions considered. 12316 FunctionDecl *Specialization = nullptr; 12317 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12318 if (TemplateDeductionResult Result 12319 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12320 Specialization, Info, 12321 /*IsAddressOfFunction*/true)) { 12322 // Make a note of the failed deduction for diagnostics. 12323 // TODO: Actually use the failed-deduction info? 12324 FailedCandidates.addCandidate() 12325 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12326 MakeDeductionFailureInfo(Context, Result, Info)); 12327 continue; 12328 } 12329 12330 assert(Specialization && "no specialization and no error?"); 12331 12332 // Multiple matches; we can't resolve to a single declaration. 12333 if (Matched) { 12334 if (Complain) { 12335 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12336 << ovl->getName(); 12337 NoteAllOverloadCandidates(ovl); 12338 } 12339 return nullptr; 12340 } 12341 12342 Matched = Specialization; 12343 if (FoundResult) *FoundResult = I.getPair(); 12344 } 12345 12346 if (Matched && 12347 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12348 return nullptr; 12349 12350 return Matched; 12351 } 12352 12353 // Resolve and fix an overloaded expression that can be resolved 12354 // because it identifies a single function template specialization. 12355 // 12356 // Last three arguments should only be supplied if Complain = true 12357 // 12358 // Return true if it was logically possible to so resolve the 12359 // expression, regardless of whether or not it succeeded. Always 12360 // returns true if 'complain' is set. 12361 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12362 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12363 bool complain, SourceRange OpRangeForComplaining, 12364 QualType DestTypeForComplaining, 12365 unsigned DiagIDForComplaining) { 12366 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12367 12368 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12369 12370 DeclAccessPair found; 12371 ExprResult SingleFunctionExpression; 12372 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12373 ovl.Expression, /*complain*/ false, &found)) { 12374 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12375 SrcExpr = ExprError(); 12376 return true; 12377 } 12378 12379 // It is only correct to resolve to an instance method if we're 12380 // resolving a form that's permitted to be a pointer to member. 12381 // Otherwise we'll end up making a bound member expression, which 12382 // is illegal in all the contexts we resolve like this. 12383 if (!ovl.HasFormOfMemberPointer && 12384 isa<CXXMethodDecl>(fn) && 12385 cast<CXXMethodDecl>(fn)->isInstance()) { 12386 if (!complain) return false; 12387 12388 Diag(ovl.Expression->getExprLoc(), 12389 diag::err_bound_member_function) 12390 << 0 << ovl.Expression->getSourceRange(); 12391 12392 // TODO: I believe we only end up here if there's a mix of 12393 // static and non-static candidates (otherwise the expression 12394 // would have 'bound member' type, not 'overload' type). 12395 // Ideally we would note which candidate was chosen and why 12396 // the static candidates were rejected. 12397 SrcExpr = ExprError(); 12398 return true; 12399 } 12400 12401 // Fix the expression to refer to 'fn'. 12402 SingleFunctionExpression = 12403 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12404 12405 // If desired, do function-to-pointer decay. 12406 if (doFunctionPointerConverion) { 12407 SingleFunctionExpression = 12408 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12409 if (SingleFunctionExpression.isInvalid()) { 12410 SrcExpr = ExprError(); 12411 return true; 12412 } 12413 } 12414 } 12415 12416 if (!SingleFunctionExpression.isUsable()) { 12417 if (complain) { 12418 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12419 << ovl.Expression->getName() 12420 << DestTypeForComplaining 12421 << OpRangeForComplaining 12422 << ovl.Expression->getQualifierLoc().getSourceRange(); 12423 NoteAllOverloadCandidates(SrcExpr.get()); 12424 12425 SrcExpr = ExprError(); 12426 return true; 12427 } 12428 12429 return false; 12430 } 12431 12432 SrcExpr = SingleFunctionExpression; 12433 return true; 12434 } 12435 12436 /// Add a single candidate to the overload set. 12437 static void AddOverloadedCallCandidate(Sema &S, 12438 DeclAccessPair FoundDecl, 12439 TemplateArgumentListInfo *ExplicitTemplateArgs, 12440 ArrayRef<Expr *> Args, 12441 OverloadCandidateSet &CandidateSet, 12442 bool PartialOverloading, 12443 bool KnownValid) { 12444 NamedDecl *Callee = FoundDecl.getDecl(); 12445 if (isa<UsingShadowDecl>(Callee)) 12446 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12447 12448 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12449 if (ExplicitTemplateArgs) { 12450 assert(!KnownValid && "Explicit template arguments?"); 12451 return; 12452 } 12453 // Prevent ill-formed function decls to be added as overload candidates. 12454 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12455 return; 12456 12457 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12458 /*SuppressUserConversions=*/false, 12459 PartialOverloading); 12460 return; 12461 } 12462 12463 if (FunctionTemplateDecl *FuncTemplate 12464 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12465 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12466 ExplicitTemplateArgs, Args, CandidateSet, 12467 /*SuppressUserConversions=*/false, 12468 PartialOverloading); 12469 return; 12470 } 12471 12472 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12473 } 12474 12475 /// Add the overload candidates named by callee and/or found by argument 12476 /// dependent lookup to the given overload set. 12477 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12478 ArrayRef<Expr *> Args, 12479 OverloadCandidateSet &CandidateSet, 12480 bool PartialOverloading) { 12481 12482 #ifndef NDEBUG 12483 // Verify that ArgumentDependentLookup is consistent with the rules 12484 // in C++0x [basic.lookup.argdep]p3: 12485 // 12486 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12487 // and let Y be the lookup set produced by argument dependent 12488 // lookup (defined as follows). If X contains 12489 // 12490 // -- a declaration of a class member, or 12491 // 12492 // -- a block-scope function declaration that is not a 12493 // using-declaration, or 12494 // 12495 // -- a declaration that is neither a function or a function 12496 // template 12497 // 12498 // then Y is empty. 12499 12500 if (ULE->requiresADL()) { 12501 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12502 E = ULE->decls_end(); I != E; ++I) { 12503 assert(!(*I)->getDeclContext()->isRecord()); 12504 assert(isa<UsingShadowDecl>(*I) || 12505 !(*I)->getDeclContext()->isFunctionOrMethod()); 12506 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12507 } 12508 } 12509 #endif 12510 12511 // It would be nice to avoid this copy. 12512 TemplateArgumentListInfo TABuffer; 12513 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12514 if (ULE->hasExplicitTemplateArgs()) { 12515 ULE->copyTemplateArgumentsInto(TABuffer); 12516 ExplicitTemplateArgs = &TABuffer; 12517 } 12518 12519 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12520 E = ULE->decls_end(); I != E; ++I) 12521 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12522 CandidateSet, PartialOverloading, 12523 /*KnownValid*/ true); 12524 12525 if (ULE->requiresADL()) 12526 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12527 Args, ExplicitTemplateArgs, 12528 CandidateSet, PartialOverloading); 12529 } 12530 12531 /// Determine whether a declaration with the specified name could be moved into 12532 /// a different namespace. 12533 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12534 switch (Name.getCXXOverloadedOperator()) { 12535 case OO_New: case OO_Array_New: 12536 case OO_Delete: case OO_Array_Delete: 12537 return false; 12538 12539 default: 12540 return true; 12541 } 12542 } 12543 12544 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12545 /// template, where the non-dependent name was declared after the template 12546 /// was defined. This is common in code written for a compilers which do not 12547 /// correctly implement two-stage name lookup. 12548 /// 12549 /// Returns true if a viable candidate was found and a diagnostic was issued. 12550 static bool 12551 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12552 const CXXScopeSpec &SS, LookupResult &R, 12553 OverloadCandidateSet::CandidateSetKind CSK, 12554 TemplateArgumentListInfo *ExplicitTemplateArgs, 12555 ArrayRef<Expr *> Args, 12556 bool *DoDiagnoseEmptyLookup = nullptr) { 12557 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12558 return false; 12559 12560 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12561 if (DC->isTransparentContext()) 12562 continue; 12563 12564 SemaRef.LookupQualifiedName(R, DC); 12565 12566 if (!R.empty()) { 12567 R.suppressDiagnostics(); 12568 12569 if (isa<CXXRecordDecl>(DC)) { 12570 // Don't diagnose names we find in classes; we get much better 12571 // diagnostics for these from DiagnoseEmptyLookup. 12572 R.clear(); 12573 if (DoDiagnoseEmptyLookup) 12574 *DoDiagnoseEmptyLookup = true; 12575 return false; 12576 } 12577 12578 OverloadCandidateSet Candidates(FnLoc, CSK); 12579 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12580 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12581 ExplicitTemplateArgs, Args, 12582 Candidates, false, /*KnownValid*/ false); 12583 12584 OverloadCandidateSet::iterator Best; 12585 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12586 // No viable functions. Don't bother the user with notes for functions 12587 // which don't work and shouldn't be found anyway. 12588 R.clear(); 12589 return false; 12590 } 12591 12592 // Find the namespaces where ADL would have looked, and suggest 12593 // declaring the function there instead. 12594 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12595 Sema::AssociatedClassSet AssociatedClasses; 12596 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12597 AssociatedNamespaces, 12598 AssociatedClasses); 12599 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12600 if (canBeDeclaredInNamespace(R.getLookupName())) { 12601 DeclContext *Std = SemaRef.getStdNamespace(); 12602 for (Sema::AssociatedNamespaceSet::iterator 12603 it = AssociatedNamespaces.begin(), 12604 end = AssociatedNamespaces.end(); it != end; ++it) { 12605 // Never suggest declaring a function within namespace 'std'. 12606 if (Std && Std->Encloses(*it)) 12607 continue; 12608 12609 // Never suggest declaring a function within a namespace with a 12610 // reserved name, like __gnu_cxx. 12611 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12612 if (NS && 12613 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12614 continue; 12615 12616 SuggestedNamespaces.insert(*it); 12617 } 12618 } 12619 12620 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12621 << R.getLookupName(); 12622 if (SuggestedNamespaces.empty()) { 12623 SemaRef.Diag(Best->Function->getLocation(), 12624 diag::note_not_found_by_two_phase_lookup) 12625 << R.getLookupName() << 0; 12626 } else if (SuggestedNamespaces.size() == 1) { 12627 SemaRef.Diag(Best->Function->getLocation(), 12628 diag::note_not_found_by_two_phase_lookup) 12629 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12630 } else { 12631 // FIXME: It would be useful to list the associated namespaces here, 12632 // but the diagnostics infrastructure doesn't provide a way to produce 12633 // a localized representation of a list of items. 12634 SemaRef.Diag(Best->Function->getLocation(), 12635 diag::note_not_found_by_two_phase_lookup) 12636 << R.getLookupName() << 2; 12637 } 12638 12639 // Try to recover by calling this function. 12640 return true; 12641 } 12642 12643 R.clear(); 12644 } 12645 12646 return false; 12647 } 12648 12649 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12650 /// template, where the non-dependent operator was declared after the template 12651 /// was defined. 12652 /// 12653 /// Returns true if a viable candidate was found and a diagnostic was issued. 12654 static bool 12655 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12656 SourceLocation OpLoc, 12657 ArrayRef<Expr *> Args) { 12658 DeclarationName OpName = 12659 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12660 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12661 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12662 OverloadCandidateSet::CSK_Operator, 12663 /*ExplicitTemplateArgs=*/nullptr, Args); 12664 } 12665 12666 namespace { 12667 class BuildRecoveryCallExprRAII { 12668 Sema &SemaRef; 12669 public: 12670 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12671 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12672 SemaRef.IsBuildingRecoveryCallExpr = true; 12673 } 12674 12675 ~BuildRecoveryCallExprRAII() { 12676 SemaRef.IsBuildingRecoveryCallExpr = false; 12677 } 12678 }; 12679 12680 } 12681 12682 /// Attempts to recover from a call where no functions were found. 12683 /// 12684 /// Returns true if new candidates were found. 12685 static ExprResult 12686 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12687 UnresolvedLookupExpr *ULE, 12688 SourceLocation LParenLoc, 12689 MutableArrayRef<Expr *> Args, 12690 SourceLocation RParenLoc, 12691 bool EmptyLookup, bool AllowTypoCorrection) { 12692 // Do not try to recover if it is already building a recovery call. 12693 // This stops infinite loops for template instantiations like 12694 // 12695 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12696 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12697 // 12698 if (SemaRef.IsBuildingRecoveryCallExpr) 12699 return ExprError(); 12700 BuildRecoveryCallExprRAII RCE(SemaRef); 12701 12702 CXXScopeSpec SS; 12703 SS.Adopt(ULE->getQualifierLoc()); 12704 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12705 12706 TemplateArgumentListInfo TABuffer; 12707 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12708 if (ULE->hasExplicitTemplateArgs()) { 12709 ULE->copyTemplateArgumentsInto(TABuffer); 12710 ExplicitTemplateArgs = &TABuffer; 12711 } 12712 12713 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12714 Sema::LookupOrdinaryName); 12715 bool DoDiagnoseEmptyLookup = EmptyLookup; 12716 if (!DiagnoseTwoPhaseLookup( 12717 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12718 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12719 NoTypoCorrectionCCC NoTypoValidator{}; 12720 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12721 ExplicitTemplateArgs != nullptr, 12722 dyn_cast<MemberExpr>(Fn)); 12723 CorrectionCandidateCallback &Validator = 12724 AllowTypoCorrection 12725 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12726 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12727 if (!DoDiagnoseEmptyLookup || 12728 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12729 Args)) 12730 return ExprError(); 12731 } 12732 12733 assert(!R.empty() && "lookup results empty despite recovery"); 12734 12735 // If recovery created an ambiguity, just bail out. 12736 if (R.isAmbiguous()) { 12737 R.suppressDiagnostics(); 12738 return ExprError(); 12739 } 12740 12741 // Build an implicit member call if appropriate. Just drop the 12742 // casts and such from the call, we don't really care. 12743 ExprResult NewFn = ExprError(); 12744 if ((*R.begin())->isCXXClassMember()) 12745 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12746 ExplicitTemplateArgs, S); 12747 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12748 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12749 ExplicitTemplateArgs); 12750 else 12751 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12752 12753 if (NewFn.isInvalid()) 12754 return ExprError(); 12755 12756 // This shouldn't cause an infinite loop because we're giving it 12757 // an expression with viable lookup results, which should never 12758 // end up here. 12759 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12760 MultiExprArg(Args.data(), Args.size()), 12761 RParenLoc); 12762 } 12763 12764 /// Constructs and populates an OverloadedCandidateSet from 12765 /// the given function. 12766 /// \returns true when an the ExprResult output parameter has been set. 12767 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12768 UnresolvedLookupExpr *ULE, 12769 MultiExprArg Args, 12770 SourceLocation RParenLoc, 12771 OverloadCandidateSet *CandidateSet, 12772 ExprResult *Result) { 12773 #ifndef NDEBUG 12774 if (ULE->requiresADL()) { 12775 // To do ADL, we must have found an unqualified name. 12776 assert(!ULE->getQualifier() && "qualified name with ADL"); 12777 12778 // We don't perform ADL for implicit declarations of builtins. 12779 // Verify that this was correctly set up. 12780 FunctionDecl *F; 12781 if (ULE->decls_begin() != ULE->decls_end() && 12782 ULE->decls_begin() + 1 == ULE->decls_end() && 12783 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12784 F->getBuiltinID() && F->isImplicit()) 12785 llvm_unreachable("performing ADL for builtin"); 12786 12787 // We don't perform ADL in C. 12788 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12789 } 12790 #endif 12791 12792 UnbridgedCastsSet UnbridgedCasts; 12793 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12794 *Result = ExprError(); 12795 return true; 12796 } 12797 12798 // Add the functions denoted by the callee to the set of candidate 12799 // functions, including those from argument-dependent lookup. 12800 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12801 12802 if (getLangOpts().MSVCCompat && 12803 CurContext->isDependentContext() && !isSFINAEContext() && 12804 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12805 12806 OverloadCandidateSet::iterator Best; 12807 if (CandidateSet->empty() || 12808 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12809 OR_No_Viable_Function) { 12810 // In Microsoft mode, if we are inside a template class member function 12811 // then create a type dependent CallExpr. The goal is to postpone name 12812 // lookup to instantiation time to be able to search into type dependent 12813 // base classes. 12814 CallExpr *CE = 12815 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue, 12816 RParenLoc, CurFPFeatureOverrides()); 12817 CE->markDependentForPostponedNameLookup(); 12818 *Result = CE; 12819 return true; 12820 } 12821 } 12822 12823 if (CandidateSet->empty()) 12824 return false; 12825 12826 UnbridgedCasts.restore(); 12827 return false; 12828 } 12829 12830 // Guess at what the return type for an unresolvable overload should be. 12831 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12832 OverloadCandidateSet::iterator *Best) { 12833 llvm::Optional<QualType> Result; 12834 // Adjust Type after seeing a candidate. 12835 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12836 if (!Candidate.Function) 12837 return; 12838 if (Candidate.Function->isInvalidDecl()) 12839 return; 12840 QualType T = Candidate.Function->getReturnType(); 12841 if (T.isNull()) 12842 return; 12843 if (!Result) 12844 Result = T; 12845 else if (Result != T) 12846 Result = QualType(); 12847 }; 12848 12849 // Look for an unambiguous type from a progressively larger subset. 12850 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12851 // 12852 // First, consider only the best candidate. 12853 if (Best && *Best != CS.end()) 12854 ConsiderCandidate(**Best); 12855 // Next, consider only viable candidates. 12856 if (!Result) 12857 for (const auto &C : CS) 12858 if (C.Viable) 12859 ConsiderCandidate(C); 12860 // Finally, consider all candidates. 12861 if (!Result) 12862 for (const auto &C : CS) 12863 ConsiderCandidate(C); 12864 12865 return Result.getValueOr(QualType()); 12866 } 12867 12868 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12869 /// the completed call expression. If overload resolution fails, emits 12870 /// diagnostics and returns ExprError() 12871 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12872 UnresolvedLookupExpr *ULE, 12873 SourceLocation LParenLoc, 12874 MultiExprArg Args, 12875 SourceLocation RParenLoc, 12876 Expr *ExecConfig, 12877 OverloadCandidateSet *CandidateSet, 12878 OverloadCandidateSet::iterator *Best, 12879 OverloadingResult OverloadResult, 12880 bool AllowTypoCorrection) { 12881 if (CandidateSet->empty()) 12882 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12883 RParenLoc, /*EmptyLookup=*/true, 12884 AllowTypoCorrection); 12885 12886 switch (OverloadResult) { 12887 case OR_Success: { 12888 FunctionDecl *FDecl = (*Best)->Function; 12889 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12890 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12891 return ExprError(); 12892 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12893 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12894 ExecConfig, /*IsExecConfig=*/false, 12895 (*Best)->IsADLCandidate); 12896 } 12897 12898 case OR_No_Viable_Function: { 12899 // Try to recover by looking for viable functions which the user might 12900 // have meant to call. 12901 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12902 Args, RParenLoc, 12903 /*EmptyLookup=*/false, 12904 AllowTypoCorrection); 12905 if (!Recovery.isInvalid()) 12906 return Recovery; 12907 12908 // If the user passes in a function that we can't take the address of, we 12909 // generally end up emitting really bad error messages. Here, we attempt to 12910 // emit better ones. 12911 for (const Expr *Arg : Args) { 12912 if (!Arg->getType()->isFunctionType()) 12913 continue; 12914 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12915 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12916 if (FD && 12917 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12918 Arg->getExprLoc())) 12919 return ExprError(); 12920 } 12921 } 12922 12923 CandidateSet->NoteCandidates( 12924 PartialDiagnosticAt( 12925 Fn->getBeginLoc(), 12926 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12927 << ULE->getName() << Fn->getSourceRange()), 12928 SemaRef, OCD_AllCandidates, Args); 12929 break; 12930 } 12931 12932 case OR_Ambiguous: 12933 CandidateSet->NoteCandidates( 12934 PartialDiagnosticAt(Fn->getBeginLoc(), 12935 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12936 << ULE->getName() << Fn->getSourceRange()), 12937 SemaRef, OCD_AmbiguousCandidates, Args); 12938 break; 12939 12940 case OR_Deleted: { 12941 CandidateSet->NoteCandidates( 12942 PartialDiagnosticAt(Fn->getBeginLoc(), 12943 SemaRef.PDiag(diag::err_ovl_deleted_call) 12944 << ULE->getName() << Fn->getSourceRange()), 12945 SemaRef, OCD_AllCandidates, Args); 12946 12947 // We emitted an error for the unavailable/deleted function call but keep 12948 // the call in the AST. 12949 FunctionDecl *FDecl = (*Best)->Function; 12950 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12951 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12952 ExecConfig, /*IsExecConfig=*/false, 12953 (*Best)->IsADLCandidate); 12954 } 12955 } 12956 12957 // Overload resolution failed, try to recover. 12958 SmallVector<Expr *, 8> SubExprs = {Fn}; 12959 SubExprs.append(Args.begin(), Args.end()); 12960 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 12961 chooseRecoveryType(*CandidateSet, Best)); 12962 } 12963 12964 static void markUnaddressableCandidatesUnviable(Sema &S, 12965 OverloadCandidateSet &CS) { 12966 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12967 if (I->Viable && 12968 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12969 I->Viable = false; 12970 I->FailureKind = ovl_fail_addr_not_available; 12971 } 12972 } 12973 } 12974 12975 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12976 /// (which eventually refers to the declaration Func) and the call 12977 /// arguments Args/NumArgs, attempt to resolve the function call down 12978 /// to a specific function. If overload resolution succeeds, returns 12979 /// the call expression produced by overload resolution. 12980 /// Otherwise, emits diagnostics and returns ExprError. 12981 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12982 UnresolvedLookupExpr *ULE, 12983 SourceLocation LParenLoc, 12984 MultiExprArg Args, 12985 SourceLocation RParenLoc, 12986 Expr *ExecConfig, 12987 bool AllowTypoCorrection, 12988 bool CalleesAddressIsTaken) { 12989 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12990 OverloadCandidateSet::CSK_Normal); 12991 ExprResult result; 12992 12993 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12994 &result)) 12995 return result; 12996 12997 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12998 // functions that aren't addressible are considered unviable. 12999 if (CalleesAddressIsTaken) 13000 markUnaddressableCandidatesUnviable(*this, CandidateSet); 13001 13002 OverloadCandidateSet::iterator Best; 13003 OverloadingResult OverloadResult = 13004 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 13005 13006 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 13007 ExecConfig, &CandidateSet, &Best, 13008 OverloadResult, AllowTypoCorrection); 13009 } 13010 13011 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 13012 return Functions.size() > 1 || 13013 (Functions.size() == 1 && 13014 isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl())); 13015 } 13016 13017 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 13018 NestedNameSpecifierLoc NNSLoc, 13019 DeclarationNameInfo DNI, 13020 const UnresolvedSetImpl &Fns, 13021 bool PerformADL) { 13022 return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI, 13023 PerformADL, IsOverloaded(Fns), 13024 Fns.begin(), Fns.end()); 13025 } 13026 13027 /// Create a unary operation that may resolve to an overloaded 13028 /// operator. 13029 /// 13030 /// \param OpLoc The location of the operator itself (e.g., '*'). 13031 /// 13032 /// \param Opc The UnaryOperatorKind that describes this operator. 13033 /// 13034 /// \param Fns The set of non-member functions that will be 13035 /// considered by overload resolution. The caller needs to build this 13036 /// set based on the context using, e.g., 13037 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13038 /// set should not contain any member functions; those will be added 13039 /// by CreateOverloadedUnaryOp(). 13040 /// 13041 /// \param Input The input argument. 13042 ExprResult 13043 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13044 const UnresolvedSetImpl &Fns, 13045 Expr *Input, bool PerformADL) { 13046 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13047 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13048 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13049 // TODO: provide better source location info. 13050 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13051 13052 if (checkPlaceholderForOverload(*this, Input)) 13053 return ExprError(); 13054 13055 Expr *Args[2] = { Input, nullptr }; 13056 unsigned NumArgs = 1; 13057 13058 // For post-increment and post-decrement, add the implicit '0' as 13059 // the second argument, so that we know this is a post-increment or 13060 // post-decrement. 13061 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13062 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13063 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13064 SourceLocation()); 13065 NumArgs = 2; 13066 } 13067 13068 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13069 13070 if (Input->isTypeDependent()) { 13071 if (Fns.empty()) 13072 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13073 VK_RValue, OK_Ordinary, OpLoc, false, 13074 CurFPFeatureOverrides()); 13075 13076 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13077 ExprResult Fn = CreateUnresolvedLookupExpr( 13078 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns); 13079 if (Fn.isInvalid()) 13080 return ExprError(); 13081 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray, 13082 Context.DependentTy, VK_RValue, OpLoc, 13083 CurFPFeatureOverrides()); 13084 } 13085 13086 // Build an empty overload set. 13087 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13088 13089 // Add the candidates from the given function set. 13090 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13091 13092 // Add operator candidates that are member functions. 13093 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13094 13095 // Add candidates from ADL. 13096 if (PerformADL) { 13097 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13098 /*ExplicitTemplateArgs*/nullptr, 13099 CandidateSet); 13100 } 13101 13102 // Add builtin operator candidates. 13103 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13104 13105 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13106 13107 // Perform overload resolution. 13108 OverloadCandidateSet::iterator Best; 13109 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13110 case OR_Success: { 13111 // We found a built-in operator or an overloaded operator. 13112 FunctionDecl *FnDecl = Best->Function; 13113 13114 if (FnDecl) { 13115 Expr *Base = nullptr; 13116 // We matched an overloaded operator. Build a call to that 13117 // operator. 13118 13119 // Convert the arguments. 13120 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13121 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13122 13123 ExprResult InputRes = 13124 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13125 Best->FoundDecl, Method); 13126 if (InputRes.isInvalid()) 13127 return ExprError(); 13128 Base = Input = InputRes.get(); 13129 } else { 13130 // Convert the arguments. 13131 ExprResult InputInit 13132 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13133 Context, 13134 FnDecl->getParamDecl(0)), 13135 SourceLocation(), 13136 Input); 13137 if (InputInit.isInvalid()) 13138 return ExprError(); 13139 Input = InputInit.get(); 13140 } 13141 13142 // Build the actual expression node. 13143 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13144 Base, HadMultipleCandidates, 13145 OpLoc); 13146 if (FnExpr.isInvalid()) 13147 return ExprError(); 13148 13149 // Determine the result type. 13150 QualType ResultTy = FnDecl->getReturnType(); 13151 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13152 ResultTy = ResultTy.getNonLValueExprType(Context); 13153 13154 Args[0] = Input; 13155 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13156 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13157 CurFPFeatureOverrides(), Best->IsADLCandidate); 13158 13159 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13160 return ExprError(); 13161 13162 if (CheckFunctionCall(FnDecl, TheCall, 13163 FnDecl->getType()->castAs<FunctionProtoType>())) 13164 return ExprError(); 13165 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13166 } else { 13167 // We matched a built-in operator. Convert the arguments, then 13168 // break out so that we will build the appropriate built-in 13169 // operator node. 13170 ExprResult InputRes = PerformImplicitConversion( 13171 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13172 CCK_ForBuiltinOverloadedOp); 13173 if (InputRes.isInvalid()) 13174 return ExprError(); 13175 Input = InputRes.get(); 13176 break; 13177 } 13178 } 13179 13180 case OR_No_Viable_Function: 13181 // This is an erroneous use of an operator which can be overloaded by 13182 // a non-member function. Check for non-member operators which were 13183 // defined too late to be candidates. 13184 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13185 // FIXME: Recover by calling the found function. 13186 return ExprError(); 13187 13188 // No viable function; fall through to handling this as a 13189 // built-in operator, which will produce an error message for us. 13190 break; 13191 13192 case OR_Ambiguous: 13193 CandidateSet.NoteCandidates( 13194 PartialDiagnosticAt(OpLoc, 13195 PDiag(diag::err_ovl_ambiguous_oper_unary) 13196 << UnaryOperator::getOpcodeStr(Opc) 13197 << Input->getType() << Input->getSourceRange()), 13198 *this, OCD_AmbiguousCandidates, ArgsArray, 13199 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13200 return ExprError(); 13201 13202 case OR_Deleted: 13203 CandidateSet.NoteCandidates( 13204 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13205 << UnaryOperator::getOpcodeStr(Opc) 13206 << Input->getSourceRange()), 13207 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13208 OpLoc); 13209 return ExprError(); 13210 } 13211 13212 // Either we found no viable overloaded operator or we matched a 13213 // built-in operator. In either case, fall through to trying to 13214 // build a built-in operation. 13215 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13216 } 13217 13218 /// Perform lookup for an overloaded binary operator. 13219 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13220 OverloadedOperatorKind Op, 13221 const UnresolvedSetImpl &Fns, 13222 ArrayRef<Expr *> Args, bool PerformADL) { 13223 SourceLocation OpLoc = CandidateSet.getLocation(); 13224 13225 OverloadedOperatorKind ExtraOp = 13226 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13227 ? getRewrittenOverloadedOperator(Op) 13228 : OO_None; 13229 13230 // Add the candidates from the given function set. This also adds the 13231 // rewritten candidates using these functions if necessary. 13232 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13233 13234 // Add operator candidates that are member functions. 13235 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13236 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13237 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13238 OverloadCandidateParamOrder::Reversed); 13239 13240 // In C++20, also add any rewritten member candidates. 13241 if (ExtraOp) { 13242 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13243 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13244 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13245 CandidateSet, 13246 OverloadCandidateParamOrder::Reversed); 13247 } 13248 13249 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13250 // performed for an assignment operator (nor for operator[] nor operator->, 13251 // which don't get here). 13252 if (Op != OO_Equal && PerformADL) { 13253 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13254 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13255 /*ExplicitTemplateArgs*/ nullptr, 13256 CandidateSet); 13257 if (ExtraOp) { 13258 DeclarationName ExtraOpName = 13259 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13260 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13261 /*ExplicitTemplateArgs*/ nullptr, 13262 CandidateSet); 13263 } 13264 } 13265 13266 // Add builtin operator candidates. 13267 // 13268 // FIXME: We don't add any rewritten candidates here. This is strictly 13269 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13270 // resulting in our selecting a rewritten builtin candidate. For example: 13271 // 13272 // enum class E { e }; 13273 // bool operator!=(E, E) requires false; 13274 // bool k = E::e != E::e; 13275 // 13276 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13277 // it seems unreasonable to consider rewritten builtin candidates. A core 13278 // issue has been filed proposing to removed this requirement. 13279 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13280 } 13281 13282 /// Create a binary operation that may resolve to an overloaded 13283 /// operator. 13284 /// 13285 /// \param OpLoc The location of the operator itself (e.g., '+'). 13286 /// 13287 /// \param Opc The BinaryOperatorKind that describes this operator. 13288 /// 13289 /// \param Fns The set of non-member functions that will be 13290 /// considered by overload resolution. The caller needs to build this 13291 /// set based on the context using, e.g., 13292 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13293 /// set should not contain any member functions; those will be added 13294 /// by CreateOverloadedBinOp(). 13295 /// 13296 /// \param LHS Left-hand argument. 13297 /// \param RHS Right-hand argument. 13298 /// \param PerformADL Whether to consider operator candidates found by ADL. 13299 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13300 /// C++20 operator rewrites. 13301 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13302 /// the function in question. Such a function is never a candidate in 13303 /// our overload resolution. This also enables synthesizing a three-way 13304 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13305 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13306 BinaryOperatorKind Opc, 13307 const UnresolvedSetImpl &Fns, Expr *LHS, 13308 Expr *RHS, bool PerformADL, 13309 bool AllowRewrittenCandidates, 13310 FunctionDecl *DefaultedFn) { 13311 Expr *Args[2] = { LHS, RHS }; 13312 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13313 13314 if (!getLangOpts().CPlusPlus20) 13315 AllowRewrittenCandidates = false; 13316 13317 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13318 13319 // If either side is type-dependent, create an appropriate dependent 13320 // expression. 13321 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13322 if (Fns.empty()) { 13323 // If there are no functions to store, just build a dependent 13324 // BinaryOperator or CompoundAssignment. 13325 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13326 return BinaryOperator::Create( 13327 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, 13328 OK_Ordinary, OpLoc, CurFPFeatureOverrides()); 13329 return CompoundAssignOperator::Create( 13330 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13331 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy, 13332 Context.DependentTy); 13333 } 13334 13335 // FIXME: save results of ADL from here? 13336 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13337 // TODO: provide better source location info in DNLoc component. 13338 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13339 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13340 ExprResult Fn = CreateUnresolvedLookupExpr( 13341 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL); 13342 if (Fn.isInvalid()) 13343 return ExprError(); 13344 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args, 13345 Context.DependentTy, VK_RValue, OpLoc, 13346 CurFPFeatureOverrides()); 13347 } 13348 13349 // Always do placeholder-like conversions on the RHS. 13350 if (checkPlaceholderForOverload(*this, Args[1])) 13351 return ExprError(); 13352 13353 // Do placeholder-like conversion on the LHS; note that we should 13354 // not get here with a PseudoObject LHS. 13355 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13356 if (checkPlaceholderForOverload(*this, Args[0])) 13357 return ExprError(); 13358 13359 // If this is the assignment operator, we only perform overload resolution 13360 // if the left-hand side is a class or enumeration type. This is actually 13361 // a hack. The standard requires that we do overload resolution between the 13362 // various built-in candidates, but as DR507 points out, this can lead to 13363 // problems. So we do it this way, which pretty much follows what GCC does. 13364 // Note that we go the traditional code path for compound assignment forms. 13365 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13366 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13367 13368 // If this is the .* operator, which is not overloadable, just 13369 // create a built-in binary operator. 13370 if (Opc == BO_PtrMemD) 13371 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13372 13373 // Build the overload set. 13374 OverloadCandidateSet CandidateSet( 13375 OpLoc, OverloadCandidateSet::CSK_Operator, 13376 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13377 if (DefaultedFn) 13378 CandidateSet.exclude(DefaultedFn); 13379 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13380 13381 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13382 13383 // Perform overload resolution. 13384 OverloadCandidateSet::iterator Best; 13385 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13386 case OR_Success: { 13387 // We found a built-in operator or an overloaded operator. 13388 FunctionDecl *FnDecl = Best->Function; 13389 13390 bool IsReversed = Best->isReversed(); 13391 if (IsReversed) 13392 std::swap(Args[0], Args[1]); 13393 13394 if (FnDecl) { 13395 Expr *Base = nullptr; 13396 // We matched an overloaded operator. Build a call to that 13397 // operator. 13398 13399 OverloadedOperatorKind ChosenOp = 13400 FnDecl->getDeclName().getCXXOverloadedOperator(); 13401 13402 // C++2a [over.match.oper]p9: 13403 // If a rewritten operator== candidate is selected by overload 13404 // resolution for an operator@, its return type shall be cv bool 13405 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13406 !FnDecl->getReturnType()->isBooleanType()) { 13407 bool IsExtension = 13408 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13409 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13410 : diag::err_ovl_rewrite_equalequal_not_bool) 13411 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13412 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13413 Diag(FnDecl->getLocation(), diag::note_declared_at); 13414 if (!IsExtension) 13415 return ExprError(); 13416 } 13417 13418 if (AllowRewrittenCandidates && !IsReversed && 13419 CandidateSet.getRewriteInfo().isReversible()) { 13420 // We could have reversed this operator, but didn't. Check if some 13421 // reversed form was a viable candidate, and if so, if it had a 13422 // better conversion for either parameter. If so, this call is 13423 // formally ambiguous, and allowing it is an extension. 13424 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13425 for (OverloadCandidate &Cand : CandidateSet) { 13426 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13427 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13428 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13429 if (CompareImplicitConversionSequences( 13430 *this, OpLoc, Cand.Conversions[ArgIdx], 13431 Best->Conversions[ArgIdx]) == 13432 ImplicitConversionSequence::Better) { 13433 AmbiguousWith.push_back(Cand.Function); 13434 break; 13435 } 13436 } 13437 } 13438 } 13439 13440 if (!AmbiguousWith.empty()) { 13441 bool AmbiguousWithSelf = 13442 AmbiguousWith.size() == 1 && 13443 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13444 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13445 << BinaryOperator::getOpcodeStr(Opc) 13446 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13447 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13448 if (AmbiguousWithSelf) { 13449 Diag(FnDecl->getLocation(), 13450 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13451 } else { 13452 Diag(FnDecl->getLocation(), 13453 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13454 for (auto *F : AmbiguousWith) 13455 Diag(F->getLocation(), 13456 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13457 } 13458 } 13459 } 13460 13461 // Convert the arguments. 13462 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13463 // Best->Access is only meaningful for class members. 13464 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13465 13466 ExprResult Arg1 = 13467 PerformCopyInitialization( 13468 InitializedEntity::InitializeParameter(Context, 13469 FnDecl->getParamDecl(0)), 13470 SourceLocation(), Args[1]); 13471 if (Arg1.isInvalid()) 13472 return ExprError(); 13473 13474 ExprResult Arg0 = 13475 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13476 Best->FoundDecl, Method); 13477 if (Arg0.isInvalid()) 13478 return ExprError(); 13479 Base = Args[0] = Arg0.getAs<Expr>(); 13480 Args[1] = RHS = Arg1.getAs<Expr>(); 13481 } else { 13482 // Convert the arguments. 13483 ExprResult Arg0 = PerformCopyInitialization( 13484 InitializedEntity::InitializeParameter(Context, 13485 FnDecl->getParamDecl(0)), 13486 SourceLocation(), Args[0]); 13487 if (Arg0.isInvalid()) 13488 return ExprError(); 13489 13490 ExprResult Arg1 = 13491 PerformCopyInitialization( 13492 InitializedEntity::InitializeParameter(Context, 13493 FnDecl->getParamDecl(1)), 13494 SourceLocation(), Args[1]); 13495 if (Arg1.isInvalid()) 13496 return ExprError(); 13497 Args[0] = LHS = Arg0.getAs<Expr>(); 13498 Args[1] = RHS = Arg1.getAs<Expr>(); 13499 } 13500 13501 // Build the actual expression node. 13502 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13503 Best->FoundDecl, Base, 13504 HadMultipleCandidates, OpLoc); 13505 if (FnExpr.isInvalid()) 13506 return ExprError(); 13507 13508 // Determine the result type. 13509 QualType ResultTy = FnDecl->getReturnType(); 13510 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13511 ResultTy = ResultTy.getNonLValueExprType(Context); 13512 13513 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13514 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13515 CurFPFeatureOverrides(), Best->IsADLCandidate); 13516 13517 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13518 FnDecl)) 13519 return ExprError(); 13520 13521 ArrayRef<const Expr *> ArgsArray(Args, 2); 13522 const Expr *ImplicitThis = nullptr; 13523 // Cut off the implicit 'this'. 13524 if (isa<CXXMethodDecl>(FnDecl)) { 13525 ImplicitThis = ArgsArray[0]; 13526 ArgsArray = ArgsArray.slice(1); 13527 } 13528 13529 // Check for a self move. 13530 if (Op == OO_Equal) 13531 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13532 13533 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13534 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13535 VariadicDoesNotApply); 13536 13537 ExprResult R = MaybeBindToTemporary(TheCall); 13538 if (R.isInvalid()) 13539 return ExprError(); 13540 13541 R = CheckForImmediateInvocation(R, FnDecl); 13542 if (R.isInvalid()) 13543 return ExprError(); 13544 13545 // For a rewritten candidate, we've already reversed the arguments 13546 // if needed. Perform the rest of the rewrite now. 13547 if ((Best->RewriteKind & CRK_DifferentOperator) || 13548 (Op == OO_Spaceship && IsReversed)) { 13549 if (Op == OO_ExclaimEqual) { 13550 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13551 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13552 } else { 13553 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13554 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13555 Expr *ZeroLiteral = 13556 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13557 13558 Sema::CodeSynthesisContext Ctx; 13559 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13560 Ctx.Entity = FnDecl; 13561 pushCodeSynthesisContext(Ctx); 13562 13563 R = CreateOverloadedBinOp( 13564 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13565 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13566 /*AllowRewrittenCandidates=*/false); 13567 13568 popCodeSynthesisContext(); 13569 } 13570 if (R.isInvalid()) 13571 return ExprError(); 13572 } else { 13573 assert(ChosenOp == Op && "unexpected operator name"); 13574 } 13575 13576 // Make a note in the AST if we did any rewriting. 13577 if (Best->RewriteKind != CRK_None) 13578 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13579 13580 return R; 13581 } else { 13582 // We matched a built-in operator. Convert the arguments, then 13583 // break out so that we will build the appropriate built-in 13584 // operator node. 13585 ExprResult ArgsRes0 = PerformImplicitConversion( 13586 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13587 AA_Passing, CCK_ForBuiltinOverloadedOp); 13588 if (ArgsRes0.isInvalid()) 13589 return ExprError(); 13590 Args[0] = ArgsRes0.get(); 13591 13592 ExprResult ArgsRes1 = PerformImplicitConversion( 13593 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13594 AA_Passing, CCK_ForBuiltinOverloadedOp); 13595 if (ArgsRes1.isInvalid()) 13596 return ExprError(); 13597 Args[1] = ArgsRes1.get(); 13598 break; 13599 } 13600 } 13601 13602 case OR_No_Viable_Function: { 13603 // C++ [over.match.oper]p9: 13604 // If the operator is the operator , [...] and there are no 13605 // viable functions, then the operator is assumed to be the 13606 // built-in operator and interpreted according to clause 5. 13607 if (Opc == BO_Comma) 13608 break; 13609 13610 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13611 // compare result using '==' and '<'. 13612 if (DefaultedFn && Opc == BO_Cmp) { 13613 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13614 Args[1], DefaultedFn); 13615 if (E.isInvalid() || E.isUsable()) 13616 return E; 13617 } 13618 13619 // For class as left operand for assignment or compound assignment 13620 // operator do not fall through to handling in built-in, but report that 13621 // no overloaded assignment operator found 13622 ExprResult Result = ExprError(); 13623 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13624 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13625 Args, OpLoc); 13626 if (Args[0]->getType()->isRecordType() && 13627 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13628 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13629 << BinaryOperator::getOpcodeStr(Opc) 13630 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13631 if (Args[0]->getType()->isIncompleteType()) { 13632 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13633 << Args[0]->getType() 13634 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13635 } 13636 } else { 13637 // This is an erroneous use of an operator which can be overloaded by 13638 // a non-member function. Check for non-member operators which were 13639 // defined too late to be candidates. 13640 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13641 // FIXME: Recover by calling the found function. 13642 return ExprError(); 13643 13644 // No viable function; try to create a built-in operation, which will 13645 // produce an error. Then, show the non-viable candidates. 13646 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13647 } 13648 assert(Result.isInvalid() && 13649 "C++ binary operator overloading is missing candidates!"); 13650 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13651 return Result; 13652 } 13653 13654 case OR_Ambiguous: 13655 CandidateSet.NoteCandidates( 13656 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13657 << BinaryOperator::getOpcodeStr(Opc) 13658 << Args[0]->getType() 13659 << Args[1]->getType() 13660 << Args[0]->getSourceRange() 13661 << Args[1]->getSourceRange()), 13662 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13663 OpLoc); 13664 return ExprError(); 13665 13666 case OR_Deleted: 13667 if (isImplicitlyDeleted(Best->Function)) { 13668 FunctionDecl *DeletedFD = Best->Function; 13669 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13670 if (DFK.isSpecialMember()) { 13671 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13672 << Args[0]->getType() << DFK.asSpecialMember(); 13673 } else { 13674 assert(DFK.isComparison()); 13675 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13676 << Args[0]->getType() << DeletedFD; 13677 } 13678 13679 // The user probably meant to call this special member. Just 13680 // explain why it's deleted. 13681 NoteDeletedFunction(DeletedFD); 13682 return ExprError(); 13683 } 13684 CandidateSet.NoteCandidates( 13685 PartialDiagnosticAt( 13686 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13687 << getOperatorSpelling(Best->Function->getDeclName() 13688 .getCXXOverloadedOperator()) 13689 << Args[0]->getSourceRange() 13690 << Args[1]->getSourceRange()), 13691 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13692 OpLoc); 13693 return ExprError(); 13694 } 13695 13696 // We matched a built-in operator; build it. 13697 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13698 } 13699 13700 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13701 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13702 FunctionDecl *DefaultedFn) { 13703 const ComparisonCategoryInfo *Info = 13704 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13705 // If we're not producing a known comparison category type, we can't 13706 // synthesize a three-way comparison. Let the caller diagnose this. 13707 if (!Info) 13708 return ExprResult((Expr*)nullptr); 13709 13710 // If we ever want to perform this synthesis more generally, we will need to 13711 // apply the temporary materialization conversion to the operands. 13712 assert(LHS->isGLValue() && RHS->isGLValue() && 13713 "cannot use prvalue expressions more than once"); 13714 Expr *OrigLHS = LHS; 13715 Expr *OrigRHS = RHS; 13716 13717 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13718 // each of them multiple times below. 13719 LHS = new (Context) 13720 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13721 LHS->getObjectKind(), LHS); 13722 RHS = new (Context) 13723 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13724 RHS->getObjectKind(), RHS); 13725 13726 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13727 DefaultedFn); 13728 if (Eq.isInvalid()) 13729 return ExprError(); 13730 13731 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13732 true, DefaultedFn); 13733 if (Less.isInvalid()) 13734 return ExprError(); 13735 13736 ExprResult Greater; 13737 if (Info->isPartial()) { 13738 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13739 DefaultedFn); 13740 if (Greater.isInvalid()) 13741 return ExprError(); 13742 } 13743 13744 // Form the list of comparisons we're going to perform. 13745 struct Comparison { 13746 ExprResult Cmp; 13747 ComparisonCategoryResult Result; 13748 } Comparisons[4] = 13749 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13750 : ComparisonCategoryResult::Equivalent}, 13751 {Less, ComparisonCategoryResult::Less}, 13752 {Greater, ComparisonCategoryResult::Greater}, 13753 {ExprResult(), ComparisonCategoryResult::Unordered}, 13754 }; 13755 13756 int I = Info->isPartial() ? 3 : 2; 13757 13758 // Combine the comparisons with suitable conditional expressions. 13759 ExprResult Result; 13760 for (; I >= 0; --I) { 13761 // Build a reference to the comparison category constant. 13762 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13763 // FIXME: Missing a constant for a comparison category. Diagnose this? 13764 if (!VI) 13765 return ExprResult((Expr*)nullptr); 13766 ExprResult ThisResult = 13767 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13768 if (ThisResult.isInvalid()) 13769 return ExprError(); 13770 13771 // Build a conditional unless this is the final case. 13772 if (Result.get()) { 13773 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13774 ThisResult.get(), Result.get()); 13775 if (Result.isInvalid()) 13776 return ExprError(); 13777 } else { 13778 Result = ThisResult; 13779 } 13780 } 13781 13782 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13783 // bind the OpaqueValueExprs before they're (repeatedly) used. 13784 Expr *SyntacticForm = BinaryOperator::Create( 13785 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13786 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13787 CurFPFeatureOverrides()); 13788 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13789 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13790 } 13791 13792 ExprResult 13793 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13794 SourceLocation RLoc, 13795 Expr *Base, Expr *Idx) { 13796 Expr *Args[2] = { Base, Idx }; 13797 DeclarationName OpName = 13798 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13799 13800 // If either side is type-dependent, create an appropriate dependent 13801 // expression. 13802 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13803 13804 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13805 // CHECKME: no 'operator' keyword? 13806 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13807 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13808 ExprResult Fn = CreateUnresolvedLookupExpr( 13809 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>()); 13810 if (Fn.isInvalid()) 13811 return ExprError(); 13812 // Can't add any actual overloads yet 13813 13814 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args, 13815 Context.DependentTy, VK_RValue, RLoc, 13816 CurFPFeatureOverrides()); 13817 } 13818 13819 // Handle placeholders on both operands. 13820 if (checkPlaceholderForOverload(*this, Args[0])) 13821 return ExprError(); 13822 if (checkPlaceholderForOverload(*this, Args[1])) 13823 return ExprError(); 13824 13825 // Build an empty overload set. 13826 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13827 13828 // Subscript can only be overloaded as a member function. 13829 13830 // Add operator candidates that are member functions. 13831 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13832 13833 // Add builtin operator candidates. 13834 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13835 13836 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13837 13838 // Perform overload resolution. 13839 OverloadCandidateSet::iterator Best; 13840 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13841 case OR_Success: { 13842 // We found a built-in operator or an overloaded operator. 13843 FunctionDecl *FnDecl = Best->Function; 13844 13845 if (FnDecl) { 13846 // We matched an overloaded operator. Build a call to that 13847 // operator. 13848 13849 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13850 13851 // Convert the arguments. 13852 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13853 ExprResult Arg0 = 13854 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13855 Best->FoundDecl, Method); 13856 if (Arg0.isInvalid()) 13857 return ExprError(); 13858 Args[0] = Arg0.get(); 13859 13860 // Convert the arguments. 13861 ExprResult InputInit 13862 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13863 Context, 13864 FnDecl->getParamDecl(0)), 13865 SourceLocation(), 13866 Args[1]); 13867 if (InputInit.isInvalid()) 13868 return ExprError(); 13869 13870 Args[1] = InputInit.getAs<Expr>(); 13871 13872 // Build the actual expression node. 13873 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13874 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13875 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13876 Best->FoundDecl, 13877 Base, 13878 HadMultipleCandidates, 13879 OpLocInfo.getLoc(), 13880 OpLocInfo.getInfo()); 13881 if (FnExpr.isInvalid()) 13882 return ExprError(); 13883 13884 // Determine the result type 13885 QualType ResultTy = FnDecl->getReturnType(); 13886 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13887 ResultTy = ResultTy.getNonLValueExprType(Context); 13888 13889 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13890 Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc, 13891 CurFPFeatureOverrides()); 13892 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13893 return ExprError(); 13894 13895 if (CheckFunctionCall(Method, TheCall, 13896 Method->getType()->castAs<FunctionProtoType>())) 13897 return ExprError(); 13898 13899 return MaybeBindToTemporary(TheCall); 13900 } else { 13901 // We matched a built-in operator. Convert the arguments, then 13902 // break out so that we will build the appropriate built-in 13903 // operator node. 13904 ExprResult ArgsRes0 = PerformImplicitConversion( 13905 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13906 AA_Passing, CCK_ForBuiltinOverloadedOp); 13907 if (ArgsRes0.isInvalid()) 13908 return ExprError(); 13909 Args[0] = ArgsRes0.get(); 13910 13911 ExprResult ArgsRes1 = PerformImplicitConversion( 13912 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13913 AA_Passing, CCK_ForBuiltinOverloadedOp); 13914 if (ArgsRes1.isInvalid()) 13915 return ExprError(); 13916 Args[1] = ArgsRes1.get(); 13917 13918 break; 13919 } 13920 } 13921 13922 case OR_No_Viable_Function: { 13923 PartialDiagnostic PD = CandidateSet.empty() 13924 ? (PDiag(diag::err_ovl_no_oper) 13925 << Args[0]->getType() << /*subscript*/ 0 13926 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13927 : (PDiag(diag::err_ovl_no_viable_subscript) 13928 << Args[0]->getType() << Args[0]->getSourceRange() 13929 << Args[1]->getSourceRange()); 13930 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13931 OCD_AllCandidates, Args, "[]", LLoc); 13932 return ExprError(); 13933 } 13934 13935 case OR_Ambiguous: 13936 CandidateSet.NoteCandidates( 13937 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13938 << "[]" << Args[0]->getType() 13939 << Args[1]->getType() 13940 << Args[0]->getSourceRange() 13941 << Args[1]->getSourceRange()), 13942 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13943 return ExprError(); 13944 13945 case OR_Deleted: 13946 CandidateSet.NoteCandidates( 13947 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13948 << "[]" << Args[0]->getSourceRange() 13949 << Args[1]->getSourceRange()), 13950 *this, OCD_AllCandidates, Args, "[]", LLoc); 13951 return ExprError(); 13952 } 13953 13954 // We matched a built-in operator; build it. 13955 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13956 } 13957 13958 /// BuildCallToMemberFunction - Build a call to a member 13959 /// function. MemExpr is the expression that refers to the member 13960 /// function (and includes the object parameter), Args/NumArgs are the 13961 /// arguments to the function call (not including the object 13962 /// parameter). The caller needs to validate that the member 13963 /// expression refers to a non-static member function or an overloaded 13964 /// member function. 13965 ExprResult 13966 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13967 SourceLocation LParenLoc, 13968 MultiExprArg Args, 13969 SourceLocation RParenLoc) { 13970 assert(MemExprE->getType() == Context.BoundMemberTy || 13971 MemExprE->getType() == Context.OverloadTy); 13972 13973 // Dig out the member expression. This holds both the object 13974 // argument and the member function we're referring to. 13975 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13976 13977 // Determine whether this is a call to a pointer-to-member function. 13978 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13979 assert(op->getType() == Context.BoundMemberTy); 13980 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13981 13982 QualType fnType = 13983 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13984 13985 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13986 QualType resultType = proto->getCallResultType(Context); 13987 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13988 13989 // Check that the object type isn't more qualified than the 13990 // member function we're calling. 13991 Qualifiers funcQuals = proto->getMethodQuals(); 13992 13993 QualType objectType = op->getLHS()->getType(); 13994 if (op->getOpcode() == BO_PtrMemI) 13995 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13996 Qualifiers objectQuals = objectType.getQualifiers(); 13997 13998 Qualifiers difference = objectQuals - funcQuals; 13999 difference.removeObjCGCAttr(); 14000 difference.removeAddressSpace(); 14001 if (difference) { 14002 std::string qualsString = difference.getAsString(); 14003 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 14004 << fnType.getUnqualifiedType() 14005 << qualsString 14006 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 14007 } 14008 14009 CXXMemberCallExpr *call = CXXMemberCallExpr::Create( 14010 Context, MemExprE, Args, resultType, valueKind, RParenLoc, 14011 CurFPFeatureOverrides(), proto->getNumParams()); 14012 14013 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 14014 call, nullptr)) 14015 return ExprError(); 14016 14017 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 14018 return ExprError(); 14019 14020 if (CheckOtherCall(call, proto)) 14021 return ExprError(); 14022 14023 return MaybeBindToTemporary(call); 14024 } 14025 14026 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 14027 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 14028 RParenLoc, CurFPFeatureOverrides()); 14029 14030 UnbridgedCastsSet UnbridgedCasts; 14031 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14032 return ExprError(); 14033 14034 MemberExpr *MemExpr; 14035 CXXMethodDecl *Method = nullptr; 14036 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14037 NestedNameSpecifier *Qualifier = nullptr; 14038 if (isa<MemberExpr>(NakedMemExpr)) { 14039 MemExpr = cast<MemberExpr>(NakedMemExpr); 14040 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14041 FoundDecl = MemExpr->getFoundDecl(); 14042 Qualifier = MemExpr->getQualifier(); 14043 UnbridgedCasts.restore(); 14044 } else { 14045 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14046 Qualifier = UnresExpr->getQualifier(); 14047 14048 QualType ObjectType = UnresExpr->getBaseType(); 14049 Expr::Classification ObjectClassification 14050 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14051 : UnresExpr->getBase()->Classify(Context); 14052 14053 // Add overload candidates 14054 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14055 OverloadCandidateSet::CSK_Normal); 14056 14057 // FIXME: avoid copy. 14058 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14059 if (UnresExpr->hasExplicitTemplateArgs()) { 14060 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14061 TemplateArgs = &TemplateArgsBuffer; 14062 } 14063 14064 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14065 E = UnresExpr->decls_end(); I != E; ++I) { 14066 14067 NamedDecl *Func = *I; 14068 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14069 if (isa<UsingShadowDecl>(Func)) 14070 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14071 14072 14073 // Microsoft supports direct constructor calls. 14074 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14075 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14076 CandidateSet, 14077 /*SuppressUserConversions*/ false); 14078 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14079 // If explicit template arguments were provided, we can't call a 14080 // non-template member function. 14081 if (TemplateArgs) 14082 continue; 14083 14084 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14085 ObjectClassification, Args, CandidateSet, 14086 /*SuppressUserConversions=*/false); 14087 } else { 14088 AddMethodTemplateCandidate( 14089 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14090 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14091 /*SuppressUserConversions=*/false); 14092 } 14093 } 14094 14095 DeclarationName DeclName = UnresExpr->getMemberName(); 14096 14097 UnbridgedCasts.restore(); 14098 14099 OverloadCandidateSet::iterator Best; 14100 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14101 Best)) { 14102 case OR_Success: 14103 Method = cast<CXXMethodDecl>(Best->Function); 14104 FoundDecl = Best->FoundDecl; 14105 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14106 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14107 return ExprError(); 14108 // If FoundDecl is different from Method (such as if one is a template 14109 // and the other a specialization), make sure DiagnoseUseOfDecl is 14110 // called on both. 14111 // FIXME: This would be more comprehensively addressed by modifying 14112 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14113 // being used. 14114 if (Method != FoundDecl.getDecl() && 14115 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14116 return ExprError(); 14117 break; 14118 14119 case OR_No_Viable_Function: 14120 CandidateSet.NoteCandidates( 14121 PartialDiagnosticAt( 14122 UnresExpr->getMemberLoc(), 14123 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14124 << DeclName << MemExprE->getSourceRange()), 14125 *this, OCD_AllCandidates, Args); 14126 // FIXME: Leaking incoming expressions! 14127 return ExprError(); 14128 14129 case OR_Ambiguous: 14130 CandidateSet.NoteCandidates( 14131 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14132 PDiag(diag::err_ovl_ambiguous_member_call) 14133 << DeclName << MemExprE->getSourceRange()), 14134 *this, OCD_AmbiguousCandidates, Args); 14135 // FIXME: Leaking incoming expressions! 14136 return ExprError(); 14137 14138 case OR_Deleted: 14139 CandidateSet.NoteCandidates( 14140 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14141 PDiag(diag::err_ovl_deleted_member_call) 14142 << DeclName << MemExprE->getSourceRange()), 14143 *this, OCD_AllCandidates, Args); 14144 // FIXME: Leaking incoming expressions! 14145 return ExprError(); 14146 } 14147 14148 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14149 14150 // If overload resolution picked a static member, build a 14151 // non-member call based on that function. 14152 if (Method->isStatic()) { 14153 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14154 RParenLoc); 14155 } 14156 14157 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14158 } 14159 14160 QualType ResultType = Method->getReturnType(); 14161 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14162 ResultType = ResultType.getNonLValueExprType(Context); 14163 14164 assert(Method && "Member call to something that isn't a method?"); 14165 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14166 CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create( 14167 Context, MemExprE, Args, ResultType, VK, RParenLoc, 14168 CurFPFeatureOverrides(), Proto->getNumParams()); 14169 14170 // Check for a valid return type. 14171 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14172 TheCall, Method)) 14173 return ExprError(); 14174 14175 // Convert the object argument (for a non-static member function call). 14176 // We only need to do this if there was actually an overload; otherwise 14177 // it was done at lookup. 14178 if (!Method->isStatic()) { 14179 ExprResult ObjectArg = 14180 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14181 FoundDecl, Method); 14182 if (ObjectArg.isInvalid()) 14183 return ExprError(); 14184 MemExpr->setBase(ObjectArg.get()); 14185 } 14186 14187 // Convert the rest of the arguments 14188 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14189 RParenLoc)) 14190 return ExprError(); 14191 14192 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14193 14194 if (CheckFunctionCall(Method, TheCall, Proto)) 14195 return ExprError(); 14196 14197 // In the case the method to call was not selected by the overloading 14198 // resolution process, we still need to handle the enable_if attribute. Do 14199 // that here, so it will not hide previous -- and more relevant -- errors. 14200 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14201 if (const EnableIfAttr *Attr = 14202 CheckEnableIf(Method, LParenLoc, Args, true)) { 14203 Diag(MemE->getMemberLoc(), 14204 diag::err_ovl_no_viable_member_function_in_call) 14205 << Method << Method->getSourceRange(); 14206 Diag(Method->getLocation(), 14207 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14208 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14209 return ExprError(); 14210 } 14211 } 14212 14213 if ((isa<CXXConstructorDecl>(CurContext) || 14214 isa<CXXDestructorDecl>(CurContext)) && 14215 TheCall->getMethodDecl()->isPure()) { 14216 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14217 14218 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14219 MemExpr->performsVirtualDispatch(getLangOpts())) { 14220 Diag(MemExpr->getBeginLoc(), 14221 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14222 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14223 << MD->getParent(); 14224 14225 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14226 if (getLangOpts().AppleKext) 14227 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14228 << MD->getParent() << MD->getDeclName(); 14229 } 14230 } 14231 14232 if (CXXDestructorDecl *DD = 14233 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14234 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14235 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14236 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14237 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14238 MemExpr->getMemberLoc()); 14239 } 14240 14241 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14242 TheCall->getMethodDecl()); 14243 } 14244 14245 /// BuildCallToObjectOfClassType - Build a call to an object of class 14246 /// type (C++ [over.call.object]), which can end up invoking an 14247 /// overloaded function call operator (@c operator()) or performing a 14248 /// user-defined conversion on the object argument. 14249 ExprResult 14250 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14251 SourceLocation LParenLoc, 14252 MultiExprArg Args, 14253 SourceLocation RParenLoc) { 14254 if (checkPlaceholderForOverload(*this, Obj)) 14255 return ExprError(); 14256 ExprResult Object = Obj; 14257 14258 UnbridgedCastsSet UnbridgedCasts; 14259 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14260 return ExprError(); 14261 14262 assert(Object.get()->getType()->isRecordType() && 14263 "Requires object type argument"); 14264 14265 // C++ [over.call.object]p1: 14266 // If the primary-expression E in the function call syntax 14267 // evaluates to a class object of type "cv T", then the set of 14268 // candidate functions includes at least the function call 14269 // operators of T. The function call operators of T are obtained by 14270 // ordinary lookup of the name operator() in the context of 14271 // (E).operator(). 14272 OverloadCandidateSet CandidateSet(LParenLoc, 14273 OverloadCandidateSet::CSK_Operator); 14274 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14275 14276 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14277 diag::err_incomplete_object_call, Object.get())) 14278 return true; 14279 14280 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14281 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14282 LookupQualifiedName(R, Record->getDecl()); 14283 R.suppressDiagnostics(); 14284 14285 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14286 Oper != OperEnd; ++Oper) { 14287 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14288 Object.get()->Classify(Context), Args, CandidateSet, 14289 /*SuppressUserConversion=*/false); 14290 } 14291 14292 // C++ [over.call.object]p2: 14293 // In addition, for each (non-explicit in C++0x) conversion function 14294 // declared in T of the form 14295 // 14296 // operator conversion-type-id () cv-qualifier; 14297 // 14298 // where cv-qualifier is the same cv-qualification as, or a 14299 // greater cv-qualification than, cv, and where conversion-type-id 14300 // denotes the type "pointer to function of (P1,...,Pn) returning 14301 // R", or the type "reference to pointer to function of 14302 // (P1,...,Pn) returning R", or the type "reference to function 14303 // of (P1,...,Pn) returning R", a surrogate call function [...] 14304 // is also considered as a candidate function. Similarly, 14305 // surrogate call functions are added to the set of candidate 14306 // functions for each conversion function declared in an 14307 // accessible base class provided the function is not hidden 14308 // within T by another intervening declaration. 14309 const auto &Conversions = 14310 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14311 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14312 NamedDecl *D = *I; 14313 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14314 if (isa<UsingShadowDecl>(D)) 14315 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14316 14317 // Skip over templated conversion functions; they aren't 14318 // surrogates. 14319 if (isa<FunctionTemplateDecl>(D)) 14320 continue; 14321 14322 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14323 if (!Conv->isExplicit()) { 14324 // Strip the reference type (if any) and then the pointer type (if 14325 // any) to get down to what might be a function type. 14326 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14327 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14328 ConvType = ConvPtrType->getPointeeType(); 14329 14330 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14331 { 14332 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14333 Object.get(), Args, CandidateSet); 14334 } 14335 } 14336 } 14337 14338 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14339 14340 // Perform overload resolution. 14341 OverloadCandidateSet::iterator Best; 14342 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14343 Best)) { 14344 case OR_Success: 14345 // Overload resolution succeeded; we'll build the appropriate call 14346 // below. 14347 break; 14348 14349 case OR_No_Viable_Function: { 14350 PartialDiagnostic PD = 14351 CandidateSet.empty() 14352 ? (PDiag(diag::err_ovl_no_oper) 14353 << Object.get()->getType() << /*call*/ 1 14354 << Object.get()->getSourceRange()) 14355 : (PDiag(diag::err_ovl_no_viable_object_call) 14356 << Object.get()->getType() << Object.get()->getSourceRange()); 14357 CandidateSet.NoteCandidates( 14358 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14359 OCD_AllCandidates, Args); 14360 break; 14361 } 14362 case OR_Ambiguous: 14363 CandidateSet.NoteCandidates( 14364 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14365 PDiag(diag::err_ovl_ambiguous_object_call) 14366 << Object.get()->getType() 14367 << Object.get()->getSourceRange()), 14368 *this, OCD_AmbiguousCandidates, Args); 14369 break; 14370 14371 case OR_Deleted: 14372 CandidateSet.NoteCandidates( 14373 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14374 PDiag(diag::err_ovl_deleted_object_call) 14375 << Object.get()->getType() 14376 << Object.get()->getSourceRange()), 14377 *this, OCD_AllCandidates, Args); 14378 break; 14379 } 14380 14381 if (Best == CandidateSet.end()) 14382 return true; 14383 14384 UnbridgedCasts.restore(); 14385 14386 if (Best->Function == nullptr) { 14387 // Since there is no function declaration, this is one of the 14388 // surrogate candidates. Dig out the conversion function. 14389 CXXConversionDecl *Conv 14390 = cast<CXXConversionDecl>( 14391 Best->Conversions[0].UserDefined.ConversionFunction); 14392 14393 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14394 Best->FoundDecl); 14395 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14396 return ExprError(); 14397 assert(Conv == Best->FoundDecl.getDecl() && 14398 "Found Decl & conversion-to-functionptr should be same, right?!"); 14399 // We selected one of the surrogate functions that converts the 14400 // object parameter to a function pointer. Perform the conversion 14401 // on the object argument, then let BuildCallExpr finish the job. 14402 14403 // Create an implicit member expr to refer to the conversion operator. 14404 // and then call it. 14405 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14406 Conv, HadMultipleCandidates); 14407 if (Call.isInvalid()) 14408 return ExprError(); 14409 // Record usage of conversion in an implicit cast. 14410 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14411 CK_UserDefinedConversion, Call.get(), 14412 nullptr, VK_RValue); 14413 14414 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14415 } 14416 14417 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14418 14419 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14420 // that calls this method, using Object for the implicit object 14421 // parameter and passing along the remaining arguments. 14422 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14423 14424 // An error diagnostic has already been printed when parsing the declaration. 14425 if (Method->isInvalidDecl()) 14426 return ExprError(); 14427 14428 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14429 unsigned NumParams = Proto->getNumParams(); 14430 14431 DeclarationNameInfo OpLocInfo( 14432 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14433 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14434 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14435 Obj, HadMultipleCandidates, 14436 OpLocInfo.getLoc(), 14437 OpLocInfo.getInfo()); 14438 if (NewFn.isInvalid()) 14439 return true; 14440 14441 // The number of argument slots to allocate in the call. If we have default 14442 // arguments we need to allocate space for them as well. We additionally 14443 // need one more slot for the object parameter. 14444 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14445 14446 // Build the full argument list for the method call (the implicit object 14447 // parameter is placed at the beginning of the list). 14448 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14449 14450 bool IsError = false; 14451 14452 // Initialize the implicit object parameter. 14453 ExprResult ObjRes = 14454 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14455 Best->FoundDecl, Method); 14456 if (ObjRes.isInvalid()) 14457 IsError = true; 14458 else 14459 Object = ObjRes; 14460 MethodArgs[0] = Object.get(); 14461 14462 // Check the argument types. 14463 for (unsigned i = 0; i != NumParams; i++) { 14464 Expr *Arg; 14465 if (i < Args.size()) { 14466 Arg = Args[i]; 14467 14468 // Pass the argument. 14469 14470 ExprResult InputInit 14471 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14472 Context, 14473 Method->getParamDecl(i)), 14474 SourceLocation(), Arg); 14475 14476 IsError |= InputInit.isInvalid(); 14477 Arg = InputInit.getAs<Expr>(); 14478 } else { 14479 ExprResult DefArg 14480 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14481 if (DefArg.isInvalid()) { 14482 IsError = true; 14483 break; 14484 } 14485 14486 Arg = DefArg.getAs<Expr>(); 14487 } 14488 14489 MethodArgs[i + 1] = Arg; 14490 } 14491 14492 // If this is a variadic call, handle args passed through "...". 14493 if (Proto->isVariadic()) { 14494 // Promote the arguments (C99 6.5.2.2p7). 14495 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14496 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14497 nullptr); 14498 IsError |= Arg.isInvalid(); 14499 MethodArgs[i + 1] = Arg.get(); 14500 } 14501 } 14502 14503 if (IsError) 14504 return true; 14505 14506 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14507 14508 // Once we've built TheCall, all of the expressions are properly owned. 14509 QualType ResultTy = Method->getReturnType(); 14510 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14511 ResultTy = ResultTy.getNonLValueExprType(Context); 14512 14513 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14514 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc, 14515 CurFPFeatureOverrides()); 14516 14517 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14518 return true; 14519 14520 if (CheckFunctionCall(Method, TheCall, Proto)) 14521 return true; 14522 14523 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14524 } 14525 14526 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14527 /// (if one exists), where @c Base is an expression of class type and 14528 /// @c Member is the name of the member we're trying to find. 14529 ExprResult 14530 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14531 bool *NoArrowOperatorFound) { 14532 assert(Base->getType()->isRecordType() && 14533 "left-hand side must have class type"); 14534 14535 if (checkPlaceholderForOverload(*this, Base)) 14536 return ExprError(); 14537 14538 SourceLocation Loc = Base->getExprLoc(); 14539 14540 // C++ [over.ref]p1: 14541 // 14542 // [...] An expression x->m is interpreted as (x.operator->())->m 14543 // for a class object x of type T if T::operator->() exists and if 14544 // the operator is selected as the best match function by the 14545 // overload resolution mechanism (13.3). 14546 DeclarationName OpName = 14547 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14548 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14549 14550 if (RequireCompleteType(Loc, Base->getType(), 14551 diag::err_typecheck_incomplete_tag, Base)) 14552 return ExprError(); 14553 14554 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14555 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14556 R.suppressDiagnostics(); 14557 14558 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14559 Oper != OperEnd; ++Oper) { 14560 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14561 None, CandidateSet, /*SuppressUserConversion=*/false); 14562 } 14563 14564 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14565 14566 // Perform overload resolution. 14567 OverloadCandidateSet::iterator Best; 14568 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14569 case OR_Success: 14570 // Overload resolution succeeded; we'll build the call below. 14571 break; 14572 14573 case OR_No_Viable_Function: { 14574 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14575 if (CandidateSet.empty()) { 14576 QualType BaseType = Base->getType(); 14577 if (NoArrowOperatorFound) { 14578 // Report this specific error to the caller instead of emitting a 14579 // diagnostic, as requested. 14580 *NoArrowOperatorFound = true; 14581 return ExprError(); 14582 } 14583 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14584 << BaseType << Base->getSourceRange(); 14585 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14586 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14587 << FixItHint::CreateReplacement(OpLoc, "."); 14588 } 14589 } else 14590 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14591 << "operator->" << Base->getSourceRange(); 14592 CandidateSet.NoteCandidates(*this, Base, Cands); 14593 return ExprError(); 14594 } 14595 case OR_Ambiguous: 14596 CandidateSet.NoteCandidates( 14597 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14598 << "->" << Base->getType() 14599 << Base->getSourceRange()), 14600 *this, OCD_AmbiguousCandidates, Base); 14601 return ExprError(); 14602 14603 case OR_Deleted: 14604 CandidateSet.NoteCandidates( 14605 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14606 << "->" << Base->getSourceRange()), 14607 *this, OCD_AllCandidates, Base); 14608 return ExprError(); 14609 } 14610 14611 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14612 14613 // Convert the object parameter. 14614 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14615 ExprResult BaseResult = 14616 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14617 Best->FoundDecl, Method); 14618 if (BaseResult.isInvalid()) 14619 return ExprError(); 14620 Base = BaseResult.get(); 14621 14622 // Build the operator call. 14623 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14624 Base, HadMultipleCandidates, OpLoc); 14625 if (FnExpr.isInvalid()) 14626 return ExprError(); 14627 14628 QualType ResultTy = Method->getReturnType(); 14629 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14630 ResultTy = ResultTy.getNonLValueExprType(Context); 14631 CXXOperatorCallExpr *TheCall = 14632 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base, 14633 ResultTy, VK, OpLoc, CurFPFeatureOverrides()); 14634 14635 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14636 return ExprError(); 14637 14638 if (CheckFunctionCall(Method, TheCall, 14639 Method->getType()->castAs<FunctionProtoType>())) 14640 return ExprError(); 14641 14642 return MaybeBindToTemporary(TheCall); 14643 } 14644 14645 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14646 /// a literal operator described by the provided lookup results. 14647 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14648 DeclarationNameInfo &SuffixInfo, 14649 ArrayRef<Expr*> Args, 14650 SourceLocation LitEndLoc, 14651 TemplateArgumentListInfo *TemplateArgs) { 14652 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14653 14654 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14655 OverloadCandidateSet::CSK_Normal); 14656 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14657 TemplateArgs); 14658 14659 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14660 14661 // Perform overload resolution. This will usually be trivial, but might need 14662 // to perform substitutions for a literal operator template. 14663 OverloadCandidateSet::iterator Best; 14664 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14665 case OR_Success: 14666 case OR_Deleted: 14667 break; 14668 14669 case OR_No_Viable_Function: 14670 CandidateSet.NoteCandidates( 14671 PartialDiagnosticAt(UDSuffixLoc, 14672 PDiag(diag::err_ovl_no_viable_function_in_call) 14673 << R.getLookupName()), 14674 *this, OCD_AllCandidates, Args); 14675 return ExprError(); 14676 14677 case OR_Ambiguous: 14678 CandidateSet.NoteCandidates( 14679 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14680 << R.getLookupName()), 14681 *this, OCD_AmbiguousCandidates, Args); 14682 return ExprError(); 14683 } 14684 14685 FunctionDecl *FD = Best->Function; 14686 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14687 nullptr, HadMultipleCandidates, 14688 SuffixInfo.getLoc(), 14689 SuffixInfo.getInfo()); 14690 if (Fn.isInvalid()) 14691 return true; 14692 14693 // Check the argument types. This should almost always be a no-op, except 14694 // that array-to-pointer decay is applied to string literals. 14695 Expr *ConvArgs[2]; 14696 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14697 ExprResult InputInit = PerformCopyInitialization( 14698 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14699 SourceLocation(), Args[ArgIdx]); 14700 if (InputInit.isInvalid()) 14701 return true; 14702 ConvArgs[ArgIdx] = InputInit.get(); 14703 } 14704 14705 QualType ResultTy = FD->getReturnType(); 14706 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14707 ResultTy = ResultTy.getNonLValueExprType(Context); 14708 14709 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14710 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14711 VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides()); 14712 14713 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14714 return ExprError(); 14715 14716 if (CheckFunctionCall(FD, UDL, nullptr)) 14717 return ExprError(); 14718 14719 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14720 } 14721 14722 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14723 /// given LookupResult is non-empty, it is assumed to describe a member which 14724 /// will be invoked. Otherwise, the function will be found via argument 14725 /// dependent lookup. 14726 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14727 /// otherwise CallExpr is set to ExprError() and some non-success value 14728 /// is returned. 14729 Sema::ForRangeStatus 14730 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14731 SourceLocation RangeLoc, 14732 const DeclarationNameInfo &NameInfo, 14733 LookupResult &MemberLookup, 14734 OverloadCandidateSet *CandidateSet, 14735 Expr *Range, ExprResult *CallExpr) { 14736 Scope *S = nullptr; 14737 14738 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14739 if (!MemberLookup.empty()) { 14740 ExprResult MemberRef = 14741 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14742 /*IsPtr=*/false, CXXScopeSpec(), 14743 /*TemplateKWLoc=*/SourceLocation(), 14744 /*FirstQualifierInScope=*/nullptr, 14745 MemberLookup, 14746 /*TemplateArgs=*/nullptr, S); 14747 if (MemberRef.isInvalid()) { 14748 *CallExpr = ExprError(); 14749 return FRS_DiagnosticIssued; 14750 } 14751 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14752 if (CallExpr->isInvalid()) { 14753 *CallExpr = ExprError(); 14754 return FRS_DiagnosticIssued; 14755 } 14756 } else { 14757 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr, 14758 NestedNameSpecifierLoc(), 14759 NameInfo, UnresolvedSet<0>()); 14760 if (FnR.isInvalid()) 14761 return FRS_DiagnosticIssued; 14762 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get()); 14763 14764 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14765 CandidateSet, CallExpr); 14766 if (CandidateSet->empty() || CandidateSetError) { 14767 *CallExpr = ExprError(); 14768 return FRS_NoViableFunction; 14769 } 14770 OverloadCandidateSet::iterator Best; 14771 OverloadingResult OverloadResult = 14772 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14773 14774 if (OverloadResult == OR_No_Viable_Function) { 14775 *CallExpr = ExprError(); 14776 return FRS_NoViableFunction; 14777 } 14778 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14779 Loc, nullptr, CandidateSet, &Best, 14780 OverloadResult, 14781 /*AllowTypoCorrection=*/false); 14782 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14783 *CallExpr = ExprError(); 14784 return FRS_DiagnosticIssued; 14785 } 14786 } 14787 return FRS_Success; 14788 } 14789 14790 14791 /// FixOverloadedFunctionReference - E is an expression that refers to 14792 /// a C++ overloaded function (possibly with some parentheses and 14793 /// perhaps a '&' around it). We have resolved the overloaded function 14794 /// to the function declaration Fn, so patch up the expression E to 14795 /// refer (possibly indirectly) to Fn. Returns the new expr. 14796 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14797 FunctionDecl *Fn) { 14798 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14799 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14800 Found, Fn); 14801 if (SubExpr == PE->getSubExpr()) 14802 return PE; 14803 14804 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14805 } 14806 14807 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14808 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14809 Found, Fn); 14810 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14811 SubExpr->getType()) && 14812 "Implicit cast type cannot be determined from overload"); 14813 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14814 if (SubExpr == ICE->getSubExpr()) 14815 return ICE; 14816 14817 return ImplicitCastExpr::Create(Context, ICE->getType(), 14818 ICE->getCastKind(), 14819 SubExpr, nullptr, 14820 ICE->getValueKind()); 14821 } 14822 14823 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14824 if (!GSE->isResultDependent()) { 14825 Expr *SubExpr = 14826 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14827 if (SubExpr == GSE->getResultExpr()) 14828 return GSE; 14829 14830 // Replace the resulting type information before rebuilding the generic 14831 // selection expression. 14832 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14833 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14834 unsigned ResultIdx = GSE->getResultIndex(); 14835 AssocExprs[ResultIdx] = SubExpr; 14836 14837 return GenericSelectionExpr::Create( 14838 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14839 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14840 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14841 ResultIdx); 14842 } 14843 // Rather than fall through to the unreachable, return the original generic 14844 // selection expression. 14845 return GSE; 14846 } 14847 14848 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14849 assert(UnOp->getOpcode() == UO_AddrOf && 14850 "Can only take the address of an overloaded function"); 14851 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14852 if (Method->isStatic()) { 14853 // Do nothing: static member functions aren't any different 14854 // from non-member functions. 14855 } else { 14856 // Fix the subexpression, which really has to be an 14857 // UnresolvedLookupExpr holding an overloaded member function 14858 // or template. 14859 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14860 Found, Fn); 14861 if (SubExpr == UnOp->getSubExpr()) 14862 return UnOp; 14863 14864 assert(isa<DeclRefExpr>(SubExpr) 14865 && "fixed to something other than a decl ref"); 14866 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14867 && "fixed to a member ref with no nested name qualifier"); 14868 14869 // We have taken the address of a pointer to member 14870 // function. Perform the computation here so that we get the 14871 // appropriate pointer to member type. 14872 QualType ClassType 14873 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14874 QualType MemPtrType 14875 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14876 // Under the MS ABI, lock down the inheritance model now. 14877 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14878 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14879 14880 return UnaryOperator::Create( 14881 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 14882 UnOp->getOperatorLoc(), false, CurFPFeatureOverrides()); 14883 } 14884 } 14885 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14886 Found, Fn); 14887 if (SubExpr == UnOp->getSubExpr()) 14888 return UnOp; 14889 14890 return UnaryOperator::Create(Context, SubExpr, UO_AddrOf, 14891 Context.getPointerType(SubExpr->getType()), 14892 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), 14893 false, CurFPFeatureOverrides()); 14894 } 14895 14896 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14897 // FIXME: avoid copy. 14898 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14899 if (ULE->hasExplicitTemplateArgs()) { 14900 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14901 TemplateArgs = &TemplateArgsBuffer; 14902 } 14903 14904 DeclRefExpr *DRE = 14905 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14906 ULE->getQualifierLoc(), Found.getDecl(), 14907 ULE->getTemplateKeywordLoc(), TemplateArgs); 14908 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14909 return DRE; 14910 } 14911 14912 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14913 // FIXME: avoid copy. 14914 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14915 if (MemExpr->hasExplicitTemplateArgs()) { 14916 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14917 TemplateArgs = &TemplateArgsBuffer; 14918 } 14919 14920 Expr *Base; 14921 14922 // If we're filling in a static method where we used to have an 14923 // implicit member access, rewrite to a simple decl ref. 14924 if (MemExpr->isImplicitAccess()) { 14925 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14926 DeclRefExpr *DRE = BuildDeclRefExpr( 14927 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14928 MemExpr->getQualifierLoc(), Found.getDecl(), 14929 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14930 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14931 return DRE; 14932 } else { 14933 SourceLocation Loc = MemExpr->getMemberLoc(); 14934 if (MemExpr->getQualifier()) 14935 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14936 Base = 14937 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14938 } 14939 } else 14940 Base = MemExpr->getBase(); 14941 14942 ExprValueKind valueKind; 14943 QualType type; 14944 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14945 valueKind = VK_LValue; 14946 type = Fn->getType(); 14947 } else { 14948 valueKind = VK_RValue; 14949 type = Context.BoundMemberTy; 14950 } 14951 14952 return BuildMemberExpr( 14953 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14954 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14955 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14956 type, valueKind, OK_Ordinary, TemplateArgs); 14957 } 14958 14959 llvm_unreachable("Invalid reference to overloaded function"); 14960 } 14961 14962 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14963 DeclAccessPair Found, 14964 FunctionDecl *Fn) { 14965 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14966 } 14967