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 llvm::APSInt IntConstantValue; 350 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 351 assert(Initializer && "Unknown conversion expression"); 352 353 // If it's value-dependent, we can't tell whether it's narrowing. 354 if (Initializer->isValueDependent()) 355 return NK_Dependent_Narrowing; 356 357 if (Initializer->isIntegerConstantExpr(IntConstantValue, 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 llvm::APSInt InitializerValue; 434 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted); 435 436 // If it's value-dependent, we can't tell whether it's narrowing. 437 if (Initializer->isValueDependent()) 438 return NK_Dependent_Narrowing; 439 440 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 441 // Such conversions on variables are always narrowing. 442 return NK_Variable_Narrowing; 443 } 444 bool Narrowing = false; 445 if (FromWidth < ToWidth) { 446 // Negative -> unsigned is narrowing. Otherwise, more bits is never 447 // narrowing. 448 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 449 Narrowing = true; 450 } else { 451 // Add a bit to the InitializerValue so we don't have to worry about 452 // signed vs. unsigned comparisons. 453 InitializerValue = InitializerValue.extend( 454 InitializerValue.getBitWidth() + 1); 455 // Convert the initializer to and from the target width and signed-ness. 456 llvm::APSInt ConvertedValue = InitializerValue; 457 ConvertedValue = ConvertedValue.trunc(ToWidth); 458 ConvertedValue.setIsSigned(ToSigned); 459 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 460 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 461 // If the result is different, this was a narrowing conversion. 462 if (ConvertedValue != InitializerValue) 463 Narrowing = true; 464 } 465 if (Narrowing) { 466 ConstantType = Initializer->getType(); 467 ConstantValue = APValue(InitializerValue); 468 return NK_Constant_Narrowing; 469 } 470 } 471 return NK_Not_Narrowing; 472 } 473 474 default: 475 // Other kinds of conversions are not narrowings. 476 return NK_Not_Narrowing; 477 } 478 } 479 480 /// dump - Print this standard conversion sequence to standard 481 /// error. Useful for debugging overloading issues. 482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 483 raw_ostream &OS = llvm::errs(); 484 bool PrintedSomething = false; 485 if (First != ICK_Identity) { 486 OS << GetImplicitConversionName(First); 487 PrintedSomething = true; 488 } 489 490 if (Second != ICK_Identity) { 491 if (PrintedSomething) { 492 OS << " -> "; 493 } 494 OS << GetImplicitConversionName(Second); 495 496 if (CopyConstructor) { 497 OS << " (by copy constructor)"; 498 } else if (DirectBinding) { 499 OS << " (direct reference binding)"; 500 } else if (ReferenceBinding) { 501 OS << " (reference binding)"; 502 } 503 PrintedSomething = true; 504 } 505 506 if (Third != ICK_Identity) { 507 if (PrintedSomething) { 508 OS << " -> "; 509 } 510 OS << GetImplicitConversionName(Third); 511 PrintedSomething = true; 512 } 513 514 if (!PrintedSomething) { 515 OS << "No conversions required"; 516 } 517 } 518 519 /// dump - Print this user-defined conversion sequence to standard 520 /// error. Useful for debugging overloading issues. 521 void UserDefinedConversionSequence::dump() const { 522 raw_ostream &OS = llvm::errs(); 523 if (Before.First || Before.Second || Before.Third) { 524 Before.dump(); 525 OS << " -> "; 526 } 527 if (ConversionFunction) 528 OS << '\'' << *ConversionFunction << '\''; 529 else 530 OS << "aggregate initialization"; 531 if (After.First || After.Second || After.Third) { 532 OS << " -> "; 533 After.dump(); 534 } 535 } 536 537 /// dump - Print this implicit conversion sequence to standard 538 /// error. Useful for debugging overloading issues. 539 void ImplicitConversionSequence::dump() const { 540 raw_ostream &OS = llvm::errs(); 541 if (isStdInitializerListElement()) 542 OS << "Worst std::initializer_list element conversion: "; 543 switch (ConversionKind) { 544 case StandardConversion: 545 OS << "Standard conversion: "; 546 Standard.dump(); 547 break; 548 case UserDefinedConversion: 549 OS << "User-defined conversion: "; 550 UserDefined.dump(); 551 break; 552 case EllipsisConversion: 553 OS << "Ellipsis conversion"; 554 break; 555 case AmbiguousConversion: 556 OS << "Ambiguous conversion"; 557 break; 558 case BadConversion: 559 OS << "Bad conversion"; 560 break; 561 } 562 563 OS << "\n"; 564 } 565 566 void AmbiguousConversionSequence::construct() { 567 new (&conversions()) ConversionSet(); 568 } 569 570 void AmbiguousConversionSequence::destruct() { 571 conversions().~ConversionSet(); 572 } 573 574 void 575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 576 FromTypePtr = O.FromTypePtr; 577 ToTypePtr = O.ToTypePtr; 578 new (&conversions()) ConversionSet(O.conversions()); 579 } 580 581 namespace { 582 // Structure used by DeductionFailureInfo to store 583 // template argument information. 584 struct DFIArguments { 585 TemplateArgument FirstArg; 586 TemplateArgument SecondArg; 587 }; 588 // Structure used by DeductionFailureInfo to store 589 // template parameter and template argument information. 590 struct DFIParamWithArguments : DFIArguments { 591 TemplateParameter Param; 592 }; 593 // Structure used by DeductionFailureInfo to store template argument 594 // information and the index of the problematic call argument. 595 struct DFIDeducedMismatchArgs : DFIArguments { 596 TemplateArgumentList *TemplateArgs; 597 unsigned CallArgIndex; 598 }; 599 // Structure used by DeductionFailureInfo to store information about 600 // unsatisfied constraints. 601 struct CNSInfo { 602 TemplateArgumentList *TemplateArgs; 603 ConstraintSatisfaction Satisfaction; 604 }; 605 } 606 607 /// Convert from Sema's representation of template deduction information 608 /// to the form used in overload-candidate information. 609 DeductionFailureInfo 610 clang::MakeDeductionFailureInfo(ASTContext &Context, 611 Sema::TemplateDeductionResult TDK, 612 TemplateDeductionInfo &Info) { 613 DeductionFailureInfo Result; 614 Result.Result = static_cast<unsigned>(TDK); 615 Result.HasDiagnostic = false; 616 switch (TDK) { 617 case Sema::TDK_Invalid: 618 case Sema::TDK_InstantiationDepth: 619 case Sema::TDK_TooManyArguments: 620 case Sema::TDK_TooFewArguments: 621 case Sema::TDK_MiscellaneousDeductionFailure: 622 case Sema::TDK_CUDATargetMismatch: 623 Result.Data = nullptr; 624 break; 625 626 case Sema::TDK_Incomplete: 627 case Sema::TDK_InvalidExplicitArguments: 628 Result.Data = Info.Param.getOpaqueValue(); 629 break; 630 631 case Sema::TDK_DeducedMismatch: 632 case Sema::TDK_DeducedMismatchNested: { 633 // FIXME: Should allocate from normal heap so that we can free this later. 634 auto *Saved = new (Context) DFIDeducedMismatchArgs; 635 Saved->FirstArg = Info.FirstArg; 636 Saved->SecondArg = Info.SecondArg; 637 Saved->TemplateArgs = Info.take(); 638 Saved->CallArgIndex = Info.CallArgIndex; 639 Result.Data = Saved; 640 break; 641 } 642 643 case Sema::TDK_NonDeducedMismatch: { 644 // FIXME: Should allocate from normal heap so that we can free this later. 645 DFIArguments *Saved = new (Context) DFIArguments; 646 Saved->FirstArg = Info.FirstArg; 647 Saved->SecondArg = Info.SecondArg; 648 Result.Data = Saved; 649 break; 650 } 651 652 case Sema::TDK_IncompletePack: 653 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: { 656 // FIXME: Should allocate from normal heap so that we can free this later. 657 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 658 Saved->Param = Info.Param; 659 Saved->FirstArg = Info.FirstArg; 660 Saved->SecondArg = Info.SecondArg; 661 Result.Data = Saved; 662 break; 663 } 664 665 case Sema::TDK_SubstitutionFailure: 666 Result.Data = Info.take(); 667 if (Info.hasSFINAEDiagnostic()) { 668 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 669 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 670 Info.takeSFINAEDiagnostic(*Diag); 671 Result.HasDiagnostic = true; 672 } 673 break; 674 675 case Sema::TDK_ConstraintsNotSatisfied: { 676 CNSInfo *Saved = new (Context) CNSInfo; 677 Saved->TemplateArgs = Info.take(); 678 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction; 679 Result.Data = Saved; 680 break; 681 } 682 683 case Sema::TDK_Success: 684 case Sema::TDK_NonDependentConversionFailure: 685 llvm_unreachable("not a deduction failure"); 686 } 687 688 return Result; 689 } 690 691 void DeductionFailureInfo::Destroy() { 692 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 693 case Sema::TDK_Success: 694 case Sema::TDK_Invalid: 695 case Sema::TDK_InstantiationDepth: 696 case Sema::TDK_Incomplete: 697 case Sema::TDK_TooManyArguments: 698 case Sema::TDK_TooFewArguments: 699 case Sema::TDK_InvalidExplicitArguments: 700 case Sema::TDK_CUDATargetMismatch: 701 case Sema::TDK_NonDependentConversionFailure: 702 break; 703 704 case Sema::TDK_IncompletePack: 705 case Sema::TDK_Inconsistent: 706 case Sema::TDK_Underqualified: 707 case Sema::TDK_DeducedMismatch: 708 case Sema::TDK_DeducedMismatchNested: 709 case Sema::TDK_NonDeducedMismatch: 710 // FIXME: Destroy the data? 711 Data = nullptr; 712 break; 713 714 case Sema::TDK_SubstitutionFailure: 715 // FIXME: Destroy the template argument list? 716 Data = nullptr; 717 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 718 Diag->~PartialDiagnosticAt(); 719 HasDiagnostic = false; 720 } 721 break; 722 723 case Sema::TDK_ConstraintsNotSatisfied: 724 // FIXME: Destroy the template argument list? 725 Data = nullptr; 726 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 727 Diag->~PartialDiagnosticAt(); 728 HasDiagnostic = false; 729 } 730 break; 731 732 // Unhandled 733 case Sema::TDK_MiscellaneousDeductionFailure: 734 break; 735 } 736 } 737 738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 739 if (HasDiagnostic) 740 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 741 return nullptr; 742 } 743 744 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 745 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 746 case Sema::TDK_Success: 747 case Sema::TDK_Invalid: 748 case Sema::TDK_InstantiationDepth: 749 case Sema::TDK_TooManyArguments: 750 case Sema::TDK_TooFewArguments: 751 case Sema::TDK_SubstitutionFailure: 752 case Sema::TDK_DeducedMismatch: 753 case Sema::TDK_DeducedMismatchNested: 754 case Sema::TDK_NonDeducedMismatch: 755 case Sema::TDK_CUDATargetMismatch: 756 case Sema::TDK_NonDependentConversionFailure: 757 case Sema::TDK_ConstraintsNotSatisfied: 758 return TemplateParameter(); 759 760 case Sema::TDK_Incomplete: 761 case Sema::TDK_InvalidExplicitArguments: 762 return TemplateParameter::getFromOpaqueValue(Data); 763 764 case Sema::TDK_IncompletePack: 765 case Sema::TDK_Inconsistent: 766 case Sema::TDK_Underqualified: 767 return static_cast<DFIParamWithArguments*>(Data)->Param; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return TemplateParameter(); 775 } 776 777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 778 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 779 case Sema::TDK_Success: 780 case Sema::TDK_Invalid: 781 case Sema::TDK_InstantiationDepth: 782 case Sema::TDK_TooManyArguments: 783 case Sema::TDK_TooFewArguments: 784 case Sema::TDK_Incomplete: 785 case Sema::TDK_IncompletePack: 786 case Sema::TDK_InvalidExplicitArguments: 787 case Sema::TDK_Inconsistent: 788 case Sema::TDK_Underqualified: 789 case Sema::TDK_NonDeducedMismatch: 790 case Sema::TDK_CUDATargetMismatch: 791 case Sema::TDK_NonDependentConversionFailure: 792 return nullptr; 793 794 case Sema::TDK_DeducedMismatch: 795 case Sema::TDK_DeducedMismatchNested: 796 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 797 798 case Sema::TDK_SubstitutionFailure: 799 return static_cast<TemplateArgumentList*>(Data); 800 801 case Sema::TDK_ConstraintsNotSatisfied: 802 return static_cast<CNSInfo*>(Data)->TemplateArgs; 803 804 // Unhandled 805 case Sema::TDK_MiscellaneousDeductionFailure: 806 break; 807 } 808 809 return nullptr; 810 } 811 812 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 813 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 814 case Sema::TDK_Success: 815 case Sema::TDK_Invalid: 816 case Sema::TDK_InstantiationDepth: 817 case Sema::TDK_Incomplete: 818 case Sema::TDK_TooManyArguments: 819 case Sema::TDK_TooFewArguments: 820 case Sema::TDK_InvalidExplicitArguments: 821 case Sema::TDK_SubstitutionFailure: 822 case Sema::TDK_CUDATargetMismatch: 823 case Sema::TDK_NonDependentConversionFailure: 824 case Sema::TDK_ConstraintsNotSatisfied: 825 return nullptr; 826 827 case Sema::TDK_IncompletePack: 828 case Sema::TDK_Inconsistent: 829 case Sema::TDK_Underqualified: 830 case Sema::TDK_DeducedMismatch: 831 case Sema::TDK_DeducedMismatchNested: 832 case Sema::TDK_NonDeducedMismatch: 833 return &static_cast<DFIArguments*>(Data)->FirstArg; 834 835 // Unhandled 836 case Sema::TDK_MiscellaneousDeductionFailure: 837 break; 838 } 839 840 return nullptr; 841 } 842 843 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 844 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 845 case Sema::TDK_Success: 846 case Sema::TDK_Invalid: 847 case Sema::TDK_InstantiationDepth: 848 case Sema::TDK_Incomplete: 849 case Sema::TDK_IncompletePack: 850 case Sema::TDK_TooManyArguments: 851 case Sema::TDK_TooFewArguments: 852 case Sema::TDK_InvalidExplicitArguments: 853 case Sema::TDK_SubstitutionFailure: 854 case Sema::TDK_CUDATargetMismatch: 855 case Sema::TDK_NonDependentConversionFailure: 856 case Sema::TDK_ConstraintsNotSatisfied: 857 return nullptr; 858 859 case Sema::TDK_Inconsistent: 860 case Sema::TDK_Underqualified: 861 case Sema::TDK_DeducedMismatch: 862 case Sema::TDK_DeducedMismatchNested: 863 case Sema::TDK_NonDeducedMismatch: 864 return &static_cast<DFIArguments*>(Data)->SecondArg; 865 866 // Unhandled 867 case Sema::TDK_MiscellaneousDeductionFailure: 868 break; 869 } 870 871 return nullptr; 872 } 873 874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 875 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 876 case Sema::TDK_DeducedMismatch: 877 case Sema::TDK_DeducedMismatchNested: 878 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 879 880 default: 881 return llvm::None; 882 } 883 } 884 885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 886 OverloadedOperatorKind Op) { 887 if (!AllowRewrittenCandidates) 888 return false; 889 return Op == OO_EqualEqual || Op == OO_Spaceship; 890 } 891 892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed( 893 ASTContext &Ctx, const FunctionDecl *FD) { 894 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator())) 895 return false; 896 // Don't bother adding a reversed candidate that can never be a better 897 // match than the non-reversed version. 898 return FD->getNumParams() != 2 || 899 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(), 900 FD->getParamDecl(1)->getType()) || 901 FD->hasAttr<EnableIfAttr>(); 902 } 903 904 void OverloadCandidateSet::destroyCandidates() { 905 for (iterator i = begin(), e = end(); i != e; ++i) { 906 for (auto &C : i->Conversions) 907 C.~ImplicitConversionSequence(); 908 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 909 i->DeductionFailure.Destroy(); 910 } 911 } 912 913 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 914 destroyCandidates(); 915 SlabAllocator.Reset(); 916 NumInlineBytesUsed = 0; 917 Candidates.clear(); 918 Functions.clear(); 919 Kind = CSK; 920 } 921 922 namespace { 923 class UnbridgedCastsSet { 924 struct Entry { 925 Expr **Addr; 926 Expr *Saved; 927 }; 928 SmallVector<Entry, 2> Entries; 929 930 public: 931 void save(Sema &S, Expr *&E) { 932 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 933 Entry entry = { &E, E }; 934 Entries.push_back(entry); 935 E = S.stripARCUnbridgedCast(E); 936 } 937 938 void restore() { 939 for (SmallVectorImpl<Entry>::iterator 940 i = Entries.begin(), e = Entries.end(); i != e; ++i) 941 *i->Addr = i->Saved; 942 } 943 }; 944 } 945 946 /// checkPlaceholderForOverload - Do any interesting placeholder-like 947 /// preprocessing on the given expression. 948 /// 949 /// \param unbridgedCasts a collection to which to add unbridged casts; 950 /// without this, they will be immediately diagnosed as errors 951 /// 952 /// Return true on unrecoverable error. 953 static bool 954 checkPlaceholderForOverload(Sema &S, Expr *&E, 955 UnbridgedCastsSet *unbridgedCasts = nullptr) { 956 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 957 // We can't handle overloaded expressions here because overload 958 // resolution might reasonably tweak them. 959 if (placeholder->getKind() == BuiltinType::Overload) return false; 960 961 // If the context potentially accepts unbridged ARC casts, strip 962 // the unbridged cast and add it to the collection for later restoration. 963 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 964 unbridgedCasts) { 965 unbridgedCasts->save(S, E); 966 return false; 967 } 968 969 // Go ahead and check everything else. 970 ExprResult result = S.CheckPlaceholderExpr(E); 971 if (result.isInvalid()) 972 return true; 973 974 E = result.get(); 975 return false; 976 } 977 978 // Nothing to do. 979 return false; 980 } 981 982 /// checkArgPlaceholdersForOverload - Check a set of call operands for 983 /// placeholders. 984 static bool checkArgPlaceholdersForOverload(Sema &S, 985 MultiExprArg Args, 986 UnbridgedCastsSet &unbridged) { 987 for (unsigned i = 0, e = Args.size(); i != e; ++i) 988 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 989 return true; 990 991 return false; 992 } 993 994 /// Determine whether the given New declaration is an overload of the 995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 996 /// New and Old cannot be overloaded, e.g., if New has the same signature as 997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 998 /// functions (or function templates) at all. When it does return Ovl_Match or 999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 1001 /// declaration. 1002 /// 1003 /// Example: Given the following input: 1004 /// 1005 /// void f(int, float); // #1 1006 /// void f(int, int); // #2 1007 /// int f(int, int); // #3 1008 /// 1009 /// When we process #1, there is no previous declaration of "f", so IsOverload 1010 /// will not be used. 1011 /// 1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have 1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 1015 /// unchanged. 1016 /// 1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare 1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and 1021 /// MatchedDecl will be set to point to the FunctionDecl for #2. 1022 /// 1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 1024 /// by a using declaration. The rules for whether to hide shadow declarations 1025 /// ignore some properties which otherwise figure into a function template's 1026 /// signature. 1027 Sema::OverloadKind 1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 1029 NamedDecl *&Match, bool NewIsUsingDecl) { 1030 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 1031 I != E; ++I) { 1032 NamedDecl *OldD = *I; 1033 1034 bool OldIsUsingDecl = false; 1035 if (isa<UsingShadowDecl>(OldD)) { 1036 OldIsUsingDecl = true; 1037 1038 // We can always introduce two using declarations into the same 1039 // context, even if they have identical signatures. 1040 if (NewIsUsingDecl) continue; 1041 1042 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1043 } 1044 1045 // A using-declaration does not conflict with another declaration 1046 // if one of them is hidden. 1047 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 1048 continue; 1049 1050 // If either declaration was introduced by a using declaration, 1051 // we'll need to use slightly different rules for matching. 1052 // Essentially, these rules are the normal rules, except that 1053 // function templates hide function templates with different 1054 // return types or template parameter lists. 1055 bool UseMemberUsingDeclRules = 1056 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 1057 !New->getFriendObjectKind(); 1058 1059 if (FunctionDecl *OldF = OldD->getAsFunction()) { 1060 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 1061 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 1062 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1063 continue; 1064 } 1065 1066 if (!isa<FunctionTemplateDecl>(OldD) && 1067 !shouldLinkPossiblyHiddenDecl(*I, New)) 1068 continue; 1069 1070 Match = *I; 1071 return Ovl_Match; 1072 } 1073 1074 // Builtins that have custom typechecking or have a reference should 1075 // not be overloadable or redeclarable. 1076 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1077 Match = *I; 1078 return Ovl_NonFunction; 1079 } 1080 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1081 // We can overload with these, which can show up when doing 1082 // redeclaration checks for UsingDecls. 1083 assert(Old.getLookupKind() == LookupUsingDeclName); 1084 } else if (isa<TagDecl>(OldD)) { 1085 // We can always overload with tags by hiding them. 1086 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1087 // Optimistically assume that an unresolved using decl will 1088 // overload; if it doesn't, we'll have to diagnose during 1089 // template instantiation. 1090 // 1091 // Exception: if the scope is dependent and this is not a class 1092 // member, the using declaration can only introduce an enumerator. 1093 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1094 Match = *I; 1095 return Ovl_NonFunction; 1096 } 1097 } else { 1098 // (C++ 13p1): 1099 // Only function declarations can be overloaded; object and type 1100 // declarations cannot be overloaded. 1101 Match = *I; 1102 return Ovl_NonFunction; 1103 } 1104 } 1105 1106 // C++ [temp.friend]p1: 1107 // For a friend function declaration that is not a template declaration: 1108 // -- if the name of the friend is a qualified or unqualified template-id, 1109 // [...], otherwise 1110 // -- if the name of the friend is a qualified-id and a matching 1111 // non-template function is found in the specified class or namespace, 1112 // the friend declaration refers to that function, otherwise, 1113 // -- if the name of the friend is a qualified-id and a matching function 1114 // template is found in the specified class or namespace, the friend 1115 // declaration refers to the deduced specialization of that function 1116 // template, otherwise 1117 // -- the name shall be an unqualified-id [...] 1118 // If we get here for a qualified friend declaration, we've just reached the 1119 // third bullet. If the type of the friend is dependent, skip this lookup 1120 // until instantiation. 1121 if (New->getFriendObjectKind() && New->getQualifier() && 1122 !New->getDescribedFunctionTemplate() && 1123 !New->getDependentSpecializationInfo() && 1124 !New->getType()->isDependentType()) { 1125 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1126 TemplateSpecResult.addAllDecls(Old); 1127 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1128 /*QualifiedFriend*/true)) { 1129 New->setInvalidDecl(); 1130 return Ovl_Overload; 1131 } 1132 1133 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1134 return Ovl_Match; 1135 } 1136 1137 return Ovl_Overload; 1138 } 1139 1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1141 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, 1142 bool ConsiderRequiresClauses) { 1143 // C++ [basic.start.main]p2: This function shall not be overloaded. 1144 if (New->isMain()) 1145 return false; 1146 1147 // MSVCRT user defined entry points cannot be overloaded. 1148 if (New->isMSVCRTEntryPoint()) 1149 return false; 1150 1151 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1152 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1153 1154 // C++ [temp.fct]p2: 1155 // A function template can be overloaded with other function templates 1156 // and with normal (non-template) functions. 1157 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1158 return true; 1159 1160 // Is the function New an overload of the function Old? 1161 QualType OldQType = Context.getCanonicalType(Old->getType()); 1162 QualType NewQType = Context.getCanonicalType(New->getType()); 1163 1164 // Compare the signatures (C++ 1.3.10) of the two functions to 1165 // determine whether they are overloads. If we find any mismatch 1166 // in the signature, they are overloads. 1167 1168 // If either of these functions is a K&R-style function (no 1169 // prototype), then we consider them to have matching signatures. 1170 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1171 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1172 return false; 1173 1174 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1175 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1176 1177 // The signature of a function includes the types of its 1178 // parameters (C++ 1.3.10), which includes the presence or absence 1179 // of the ellipsis; see C++ DR 357). 1180 if (OldQType != NewQType && 1181 (OldType->getNumParams() != NewType->getNumParams() || 1182 OldType->isVariadic() != NewType->isVariadic() || 1183 !FunctionParamTypesAreEqual(OldType, NewType))) 1184 return true; 1185 1186 // C++ [temp.over.link]p4: 1187 // The signature of a function template consists of its function 1188 // signature, its return type and its template parameter list. The names 1189 // of the template parameters are significant only for establishing the 1190 // relationship between the template parameters and the rest of the 1191 // signature. 1192 // 1193 // We check the return type and template parameter lists for function 1194 // templates first; the remaining checks follow. 1195 // 1196 // However, we don't consider either of these when deciding whether 1197 // a member introduced by a shadow declaration is hidden. 1198 if (!UseMemberUsingDeclRules && NewTemplate && 1199 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1200 OldTemplate->getTemplateParameters(), 1201 false, TPL_TemplateMatch) || 1202 !Context.hasSameType(Old->getDeclaredReturnType(), 1203 New->getDeclaredReturnType()))) 1204 return true; 1205 1206 // If the function is a class member, its signature includes the 1207 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1208 // 1209 // As part of this, also check whether one of the member functions 1210 // is static, in which case they are not overloads (C++ 1211 // 13.1p2). While not part of the definition of the signature, 1212 // this check is important to determine whether these functions 1213 // can be overloaded. 1214 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1215 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1216 if (OldMethod && NewMethod && 1217 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1218 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1219 if (!UseMemberUsingDeclRules && 1220 (OldMethod->getRefQualifier() == RQ_None || 1221 NewMethod->getRefQualifier() == RQ_None)) { 1222 // C++0x [over.load]p2: 1223 // - Member function declarations with the same name and the same 1224 // parameter-type-list as well as member function template 1225 // declarations with the same name, the same parameter-type-list, and 1226 // the same template parameter lists cannot be overloaded if any of 1227 // them, but not all, have a ref-qualifier (8.3.5). 1228 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1229 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1230 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1231 } 1232 return true; 1233 } 1234 1235 // We may not have applied the implicit const for a constexpr member 1236 // function yet (because we haven't yet resolved whether this is a static 1237 // or non-static member function). Add it now, on the assumption that this 1238 // is a redeclaration of OldMethod. 1239 auto OldQuals = OldMethod->getMethodQualifiers(); 1240 auto NewQuals = NewMethod->getMethodQualifiers(); 1241 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1242 !isa<CXXConstructorDecl>(NewMethod)) 1243 NewQuals.addConst(); 1244 // We do not allow overloading based off of '__restrict'. 1245 OldQuals.removeRestrict(); 1246 NewQuals.removeRestrict(); 1247 if (OldQuals != NewQuals) 1248 return true; 1249 } 1250 1251 // Though pass_object_size is placed on parameters and takes an argument, we 1252 // consider it to be a function-level modifier for the sake of function 1253 // identity. Either the function has one or more parameters with 1254 // pass_object_size or it doesn't. 1255 if (functionHasPassObjectSizeParams(New) != 1256 functionHasPassObjectSizeParams(Old)) 1257 return true; 1258 1259 // enable_if attributes are an order-sensitive part of the signature. 1260 for (specific_attr_iterator<EnableIfAttr> 1261 NewI = New->specific_attr_begin<EnableIfAttr>(), 1262 NewE = New->specific_attr_end<EnableIfAttr>(), 1263 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1264 OldE = Old->specific_attr_end<EnableIfAttr>(); 1265 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1266 if (NewI == NewE || OldI == OldE) 1267 return true; 1268 llvm::FoldingSetNodeID NewID, OldID; 1269 NewI->getCond()->Profile(NewID, Context, true); 1270 OldI->getCond()->Profile(OldID, Context, true); 1271 if (NewID != OldID) 1272 return true; 1273 } 1274 1275 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1276 // Don't allow overloading of destructors. (In theory we could, but it 1277 // would be a giant change to clang.) 1278 if (!isa<CXXDestructorDecl>(New)) { 1279 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1280 OldTarget = IdentifyCUDATarget(Old); 1281 if (NewTarget != CFT_InvalidTarget) { 1282 assert((OldTarget != CFT_InvalidTarget) && 1283 "Unexpected invalid target."); 1284 1285 // Allow overloading of functions with same signature and different CUDA 1286 // target attributes. 1287 if (NewTarget != OldTarget) 1288 return true; 1289 } 1290 } 1291 } 1292 1293 if (ConsiderRequiresClauses) { 1294 Expr *NewRC = New->getTrailingRequiresClause(), 1295 *OldRC = Old->getTrailingRequiresClause(); 1296 if ((NewRC != nullptr) != (OldRC != nullptr)) 1297 // RC are most certainly different - these are overloads. 1298 return true; 1299 1300 if (NewRC) { 1301 llvm::FoldingSetNodeID NewID, OldID; 1302 NewRC->Profile(NewID, Context, /*Canonical=*/true); 1303 OldRC->Profile(OldID, Context, /*Canonical=*/true); 1304 if (NewID != OldID) 1305 // RCs are not equivalent - these are overloads. 1306 return true; 1307 } 1308 } 1309 1310 // The signatures match; this is not an overload. 1311 return false; 1312 } 1313 1314 /// Tries a user-defined conversion from From to ToType. 1315 /// 1316 /// Produces an implicit conversion sequence for when a standard conversion 1317 /// is not an option. See TryImplicitConversion for more information. 1318 static ImplicitConversionSequence 1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1320 bool SuppressUserConversions, 1321 AllowedExplicit AllowExplicit, 1322 bool InOverloadResolution, 1323 bool CStyle, 1324 bool AllowObjCWritebackConversion, 1325 bool AllowObjCConversionOnExplicit) { 1326 ImplicitConversionSequence ICS; 1327 1328 if (SuppressUserConversions) { 1329 // We're not in the case above, so there is no conversion that 1330 // we can perform. 1331 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1332 return ICS; 1333 } 1334 1335 // Attempt user-defined conversion. 1336 OverloadCandidateSet Conversions(From->getExprLoc(), 1337 OverloadCandidateSet::CSK_Normal); 1338 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1339 Conversions, AllowExplicit, 1340 AllowObjCConversionOnExplicit)) { 1341 case OR_Success: 1342 case OR_Deleted: 1343 ICS.setUserDefined(); 1344 // C++ [over.ics.user]p4: 1345 // A conversion of an expression of class type to the same class 1346 // type is given Exact Match rank, and a conversion of an 1347 // expression of class type to a base class of that type is 1348 // given Conversion rank, in spite of the fact that a copy 1349 // constructor (i.e., a user-defined conversion function) is 1350 // called for those cases. 1351 if (CXXConstructorDecl *Constructor 1352 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1353 QualType FromCanon 1354 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1355 QualType ToCanon 1356 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1357 if (Constructor->isCopyConstructor() && 1358 (FromCanon == ToCanon || 1359 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1360 // Turn this into a "standard" conversion sequence, so that it 1361 // gets ranked with standard conversion sequences. 1362 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1363 ICS.setStandard(); 1364 ICS.Standard.setAsIdentityConversion(); 1365 ICS.Standard.setFromType(From->getType()); 1366 ICS.Standard.setAllToTypes(ToType); 1367 ICS.Standard.CopyConstructor = Constructor; 1368 ICS.Standard.FoundCopyConstructor = Found; 1369 if (ToCanon != FromCanon) 1370 ICS.Standard.Second = ICK_Derived_To_Base; 1371 } 1372 } 1373 break; 1374 1375 case OR_Ambiguous: 1376 ICS.setAmbiguous(); 1377 ICS.Ambiguous.setFromType(From->getType()); 1378 ICS.Ambiguous.setToType(ToType); 1379 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1380 Cand != Conversions.end(); ++Cand) 1381 if (Cand->Best) 1382 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1383 break; 1384 1385 // Fall through. 1386 case OR_No_Viable_Function: 1387 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1388 break; 1389 } 1390 1391 return ICS; 1392 } 1393 1394 /// TryImplicitConversion - Attempt to perform an implicit conversion 1395 /// from the given expression (Expr) to the given type (ToType). This 1396 /// function returns an implicit conversion sequence that can be used 1397 /// to perform the initialization. Given 1398 /// 1399 /// void f(float f); 1400 /// void g(int i) { f(i); } 1401 /// 1402 /// this routine would produce an implicit conversion sequence to 1403 /// describe the initialization of f from i, which will be a standard 1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1406 // 1407 /// Note that this routine only determines how the conversion can be 1408 /// performed; it does not actually perform the conversion. As such, 1409 /// it will not produce any diagnostics if no conversion is available, 1410 /// but will instead return an implicit conversion sequence of kind 1411 /// "BadConversion". 1412 /// 1413 /// If @p SuppressUserConversions, then user-defined conversions are 1414 /// not permitted. 1415 /// If @p AllowExplicit, then explicit user-defined conversions are 1416 /// permitted. 1417 /// 1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1419 /// writeback conversion, which allows __autoreleasing id* parameters to 1420 /// be initialized with __strong id* or __weak id* arguments. 1421 static ImplicitConversionSequence 1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1423 bool SuppressUserConversions, 1424 AllowedExplicit AllowExplicit, 1425 bool InOverloadResolution, 1426 bool CStyle, 1427 bool AllowObjCWritebackConversion, 1428 bool AllowObjCConversionOnExplicit) { 1429 ImplicitConversionSequence ICS; 1430 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1431 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1432 ICS.setStandard(); 1433 return ICS; 1434 } 1435 1436 if (!S.getLangOpts().CPlusPlus) { 1437 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1438 return ICS; 1439 } 1440 1441 // C++ [over.ics.user]p4: 1442 // A conversion of an expression of class type to the same class 1443 // type is given Exact Match rank, and a conversion of an 1444 // expression of class type to a base class of that type is 1445 // given Conversion rank, in spite of the fact that a copy/move 1446 // constructor (i.e., a user-defined conversion function) is 1447 // called for those cases. 1448 QualType FromType = From->getType(); 1449 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1450 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1451 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1452 ICS.setStandard(); 1453 ICS.Standard.setAsIdentityConversion(); 1454 ICS.Standard.setFromType(FromType); 1455 ICS.Standard.setAllToTypes(ToType); 1456 1457 // We don't actually check at this point whether there is a valid 1458 // copy/move constructor, since overloading just assumes that it 1459 // exists. When we actually perform initialization, we'll find the 1460 // appropriate constructor to copy the returned object, if needed. 1461 ICS.Standard.CopyConstructor = nullptr; 1462 1463 // Determine whether this is considered a derived-to-base conversion. 1464 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1465 ICS.Standard.Second = ICK_Derived_To_Base; 1466 1467 return ICS; 1468 } 1469 1470 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1471 AllowExplicit, InOverloadResolution, CStyle, 1472 AllowObjCWritebackConversion, 1473 AllowObjCConversionOnExplicit); 1474 } 1475 1476 ImplicitConversionSequence 1477 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1478 bool SuppressUserConversions, 1479 AllowedExplicit AllowExplicit, 1480 bool InOverloadResolution, 1481 bool CStyle, 1482 bool AllowObjCWritebackConversion) { 1483 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions, 1484 AllowExplicit, InOverloadResolution, CStyle, 1485 AllowObjCWritebackConversion, 1486 /*AllowObjCConversionOnExplicit=*/false); 1487 } 1488 1489 /// PerformImplicitConversion - Perform an implicit conversion of the 1490 /// expression From to the type ToType. Returns the 1491 /// converted expression. Flavor is the kind of conversion we're 1492 /// performing, used in the error message. If @p AllowExplicit, 1493 /// explicit user-defined conversions are permitted. 1494 ExprResult 1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1496 AssignmentAction Action, bool AllowExplicit) { 1497 ImplicitConversionSequence ICS; 1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1499 } 1500 1501 ExprResult 1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1503 AssignmentAction Action, bool AllowExplicit, 1504 ImplicitConversionSequence& ICS) { 1505 if (checkPlaceholderForOverload(*this, From)) 1506 return ExprError(); 1507 1508 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1509 bool AllowObjCWritebackConversion 1510 = getLangOpts().ObjCAutoRefCount && 1511 (Action == AA_Passing || Action == AA_Sending); 1512 if (getLangOpts().ObjC) 1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1514 From->getType(), From); 1515 ICS = ::TryImplicitConversion(*this, From, ToType, 1516 /*SuppressUserConversions=*/false, 1517 AllowExplicit ? AllowedExplicit::All 1518 : AllowedExplicit::None, 1519 /*InOverloadResolution=*/false, 1520 /*CStyle=*/false, AllowObjCWritebackConversion, 1521 /*AllowObjCConversionOnExplicit=*/false); 1522 return PerformImplicitConversion(From, ToType, ICS, Action); 1523 } 1524 1525 /// Determine whether the conversion from FromType to ToType is a valid 1526 /// conversion that strips "noexcept" or "noreturn" off the nested function 1527 /// type. 1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1529 QualType &ResultTy) { 1530 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1531 return false; 1532 1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1534 // or F(t noexcept) -> F(t) 1535 // where F adds one of the following at most once: 1536 // - a pointer 1537 // - a member pointer 1538 // - a block pointer 1539 // Changes here need matching changes in FindCompositePointerType. 1540 CanQualType CanTo = Context.getCanonicalType(ToType); 1541 CanQualType CanFrom = Context.getCanonicalType(FromType); 1542 Type::TypeClass TyClass = CanTo->getTypeClass(); 1543 if (TyClass != CanFrom->getTypeClass()) return false; 1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1545 if (TyClass == Type::Pointer) { 1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType(); 1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType(); 1548 } else if (TyClass == Type::BlockPointer) { 1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType(); 1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType(); 1551 } else if (TyClass == Type::MemberPointer) { 1552 auto ToMPT = CanTo.castAs<MemberPointerType>(); 1553 auto FromMPT = CanFrom.castAs<MemberPointerType>(); 1554 // A function pointer conversion cannot change the class of the function. 1555 if (ToMPT->getClass() != FromMPT->getClass()) 1556 return false; 1557 CanTo = ToMPT->getPointeeType(); 1558 CanFrom = FromMPT->getPointeeType(); 1559 } else { 1560 return false; 1561 } 1562 1563 TyClass = CanTo->getTypeClass(); 1564 if (TyClass != CanFrom->getTypeClass()) return false; 1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1566 return false; 1567 } 1568 1569 const auto *FromFn = cast<FunctionType>(CanFrom); 1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1571 1572 const auto *ToFn = cast<FunctionType>(CanTo); 1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1574 1575 bool Changed = false; 1576 1577 // Drop 'noreturn' if not present in target type. 1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1580 Changed = true; 1581 } 1582 1583 // Drop 'noexcept' if not present in target type. 1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1587 FromFn = cast<FunctionType>( 1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1589 EST_None) 1590 .getTypePtr()); 1591 Changed = true; 1592 } 1593 1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1595 // only if the ExtParameterInfo lists of the two function prototypes can be 1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1598 bool CanUseToFPT, CanUseFromFPT; 1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1600 CanUseFromFPT, NewParamInfos) && 1601 CanUseToFPT && !CanUseFromFPT) { 1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1603 ExtInfo.ExtParameterInfos = 1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1606 FromFPT->getParamTypes(), ExtInfo); 1607 FromFn = QT->getAs<FunctionType>(); 1608 Changed = true; 1609 } 1610 } 1611 1612 if (!Changed) 1613 return false; 1614 1615 assert(QualType(FromFn, 0).isCanonical()); 1616 if (QualType(FromFn, 0) != CanTo) return false; 1617 1618 ResultTy = ToType; 1619 return true; 1620 } 1621 1622 /// Determine whether the conversion from FromType to ToType is a valid 1623 /// vector conversion. 1624 /// 1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1626 /// conversion. 1627 static bool IsVectorConversion(Sema &S, QualType FromType, 1628 QualType ToType, ImplicitConversionKind &ICK) { 1629 // We need at least one of these types to be a vector type to have a vector 1630 // conversion. 1631 if (!ToType->isVectorType() && !FromType->isVectorType()) 1632 return false; 1633 1634 // Identical types require no conversions. 1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1636 return false; 1637 1638 // There are no conversions between extended vector types, only identity. 1639 if (ToType->isExtVectorType()) { 1640 // There are no conversions between extended vector types other than the 1641 // identity conversion. 1642 if (FromType->isExtVectorType()) 1643 return false; 1644 1645 // Vector splat from any arithmetic type to a vector. 1646 if (FromType->isArithmeticType()) { 1647 ICK = ICK_Vector_Splat; 1648 return true; 1649 } 1650 } 1651 1652 // We can perform the conversion between vector types in the following cases: 1653 // 1)vector types are equivalent AltiVec and GCC vector types 1654 // 2)lax vector conversions are permitted and the vector types are of the 1655 // same size 1656 // 3)the destination type does not have the ARM MVE strict-polymorphism 1657 // attribute, which inhibits lax vector conversion for overload resolution 1658 // only 1659 if (ToType->isVectorType() && FromType->isVectorType()) { 1660 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1661 (S.isLaxVectorConversion(FromType, ToType) && 1662 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) { 1663 ICK = ICK_Vector_Conversion; 1664 return true; 1665 } 1666 } 1667 1668 return false; 1669 } 1670 1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1672 bool InOverloadResolution, 1673 StandardConversionSequence &SCS, 1674 bool CStyle); 1675 1676 /// IsStandardConversion - Determines whether there is a standard 1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1678 /// expression From to the type ToType. Standard conversion sequences 1679 /// only consider non-class types; for conversions that involve class 1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1681 /// contain the standard conversion sequence required to perform this 1682 /// conversion and this routine will return true. Otherwise, this 1683 /// routine will return false and the value of SCS is unspecified. 1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1685 bool InOverloadResolution, 1686 StandardConversionSequence &SCS, 1687 bool CStyle, 1688 bool AllowObjCWritebackConversion) { 1689 QualType FromType = From->getType(); 1690 1691 // Standard conversions (C++ [conv]) 1692 SCS.setAsIdentityConversion(); 1693 SCS.IncompatibleObjC = false; 1694 SCS.setFromType(FromType); 1695 SCS.CopyConstructor = nullptr; 1696 1697 // There are no standard conversions for class types in C++, so 1698 // abort early. When overloading in C, however, we do permit them. 1699 if (S.getLangOpts().CPlusPlus && 1700 (FromType->isRecordType() || ToType->isRecordType())) 1701 return false; 1702 1703 // The first conversion can be an lvalue-to-rvalue conversion, 1704 // array-to-pointer conversion, or function-to-pointer conversion 1705 // (C++ 4p1). 1706 1707 if (FromType == S.Context.OverloadTy) { 1708 DeclAccessPair AccessPair; 1709 if (FunctionDecl *Fn 1710 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1711 AccessPair)) { 1712 // We were able to resolve the address of the overloaded function, 1713 // so we can convert to the type of that function. 1714 FromType = Fn->getType(); 1715 SCS.setFromType(FromType); 1716 1717 // we can sometimes resolve &foo<int> regardless of ToType, so check 1718 // if the type matches (identity) or we are converting to bool 1719 if (!S.Context.hasSameUnqualifiedType( 1720 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1721 QualType resultTy; 1722 // if the function type matches except for [[noreturn]], it's ok 1723 if (!S.IsFunctionConversion(FromType, 1724 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1725 // otherwise, only a boolean conversion is standard 1726 if (!ToType->isBooleanType()) 1727 return false; 1728 } 1729 1730 // Check if the "from" expression is taking the address of an overloaded 1731 // function and recompute the FromType accordingly. Take advantage of the 1732 // fact that non-static member functions *must* have such an address-of 1733 // expression. 1734 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1735 if (Method && !Method->isStatic()) { 1736 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1737 "Non-unary operator on non-static member address"); 1738 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1739 == UO_AddrOf && 1740 "Non-address-of operator on non-static member address"); 1741 const Type *ClassType 1742 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1743 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1744 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1745 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1746 UO_AddrOf && 1747 "Non-address-of operator for overloaded function expression"); 1748 FromType = S.Context.getPointerType(FromType); 1749 } 1750 1751 // Check that we've computed the proper type after overload resolution. 1752 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1753 // be calling it from within an NDEBUG block. 1754 assert(S.Context.hasSameType( 1755 FromType, 1756 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1757 } else { 1758 return false; 1759 } 1760 } 1761 // Lvalue-to-rvalue conversion (C++11 4.1): 1762 // A glvalue (3.10) of a non-function, non-array type T can 1763 // be converted to a prvalue. 1764 bool argIsLValue = From->isGLValue(); 1765 if (argIsLValue && 1766 !FromType->isFunctionType() && !FromType->isArrayType() && 1767 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1768 SCS.First = ICK_Lvalue_To_Rvalue; 1769 1770 // C11 6.3.2.1p2: 1771 // ... if the lvalue has atomic type, the value has the non-atomic version 1772 // of the type of the lvalue ... 1773 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1774 FromType = Atomic->getValueType(); 1775 1776 // If T is a non-class type, the type of the rvalue is the 1777 // cv-unqualified version of T. Otherwise, the type of the rvalue 1778 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1779 // just strip the qualifiers because they don't matter. 1780 FromType = FromType.getUnqualifiedType(); 1781 } else if (FromType->isArrayType()) { 1782 // Array-to-pointer conversion (C++ 4.2) 1783 SCS.First = ICK_Array_To_Pointer; 1784 1785 // An lvalue or rvalue of type "array of N T" or "array of unknown 1786 // bound of T" can be converted to an rvalue of type "pointer to 1787 // T" (C++ 4.2p1). 1788 FromType = S.Context.getArrayDecayedType(FromType); 1789 1790 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1791 // This conversion is deprecated in C++03 (D.4) 1792 SCS.DeprecatedStringLiteralToCharPtr = true; 1793 1794 // For the purpose of ranking in overload resolution 1795 // (13.3.3.1.1), this conversion is considered an 1796 // array-to-pointer conversion followed by a qualification 1797 // conversion (4.4). (C++ 4.2p2) 1798 SCS.Second = ICK_Identity; 1799 SCS.Third = ICK_Qualification; 1800 SCS.QualificationIncludesObjCLifetime = false; 1801 SCS.setAllToTypes(FromType); 1802 return true; 1803 } 1804 } else if (FromType->isFunctionType() && argIsLValue) { 1805 // Function-to-pointer conversion (C++ 4.3). 1806 SCS.First = ICK_Function_To_Pointer; 1807 1808 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1809 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1810 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1811 return false; 1812 1813 // An lvalue of function type T can be converted to an rvalue of 1814 // type "pointer to T." The result is a pointer to the 1815 // function. (C++ 4.3p1). 1816 FromType = S.Context.getPointerType(FromType); 1817 } else { 1818 // We don't require any conversions for the first step. 1819 SCS.First = ICK_Identity; 1820 } 1821 SCS.setToType(0, FromType); 1822 1823 // The second conversion can be an integral promotion, floating 1824 // point promotion, integral conversion, floating point conversion, 1825 // floating-integral conversion, pointer conversion, 1826 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1827 // For overloading in C, this can also be a "compatible-type" 1828 // conversion. 1829 bool IncompatibleObjC = false; 1830 ImplicitConversionKind SecondICK = ICK_Identity; 1831 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1832 // The unqualified versions of the types are the same: there's no 1833 // conversion to do. 1834 SCS.Second = ICK_Identity; 1835 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1836 // Integral promotion (C++ 4.5). 1837 SCS.Second = ICK_Integral_Promotion; 1838 FromType = ToType.getUnqualifiedType(); 1839 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1840 // Floating point promotion (C++ 4.6). 1841 SCS.Second = ICK_Floating_Promotion; 1842 FromType = ToType.getUnqualifiedType(); 1843 } else if (S.IsComplexPromotion(FromType, ToType)) { 1844 // Complex promotion (Clang extension) 1845 SCS.Second = ICK_Complex_Promotion; 1846 FromType = ToType.getUnqualifiedType(); 1847 } else if (ToType->isBooleanType() && 1848 (FromType->isArithmeticType() || 1849 FromType->isAnyPointerType() || 1850 FromType->isBlockPointerType() || 1851 FromType->isMemberPointerType())) { 1852 // Boolean conversions (C++ 4.12). 1853 SCS.Second = ICK_Boolean_Conversion; 1854 FromType = S.Context.BoolTy; 1855 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1856 ToType->isIntegralType(S.Context)) { 1857 // Integral conversions (C++ 4.7). 1858 SCS.Second = ICK_Integral_Conversion; 1859 FromType = ToType.getUnqualifiedType(); 1860 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1861 // Complex conversions (C99 6.3.1.6) 1862 SCS.Second = ICK_Complex_Conversion; 1863 FromType = ToType.getUnqualifiedType(); 1864 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1865 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1866 // Complex-real conversions (C99 6.3.1.7) 1867 SCS.Second = ICK_Complex_Real; 1868 FromType = ToType.getUnqualifiedType(); 1869 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1870 // FIXME: disable conversions between long double and __float128 if 1871 // their representation is different until there is back end support 1872 // We of course allow this conversion if long double is really double. 1873 if (&S.Context.getFloatTypeSemantics(FromType) != 1874 &S.Context.getFloatTypeSemantics(ToType)) { 1875 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1876 ToType == S.Context.LongDoubleTy) || 1877 (FromType == S.Context.LongDoubleTy && 1878 ToType == S.Context.Float128Ty)); 1879 if (Float128AndLongDouble && 1880 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1881 &llvm::APFloat::PPCDoubleDouble())) 1882 return false; 1883 } 1884 // Floating point conversions (C++ 4.8). 1885 SCS.Second = ICK_Floating_Conversion; 1886 FromType = ToType.getUnqualifiedType(); 1887 } else if ((FromType->isRealFloatingType() && 1888 ToType->isIntegralType(S.Context)) || 1889 (FromType->isIntegralOrUnscopedEnumerationType() && 1890 ToType->isRealFloatingType())) { 1891 // Floating-integral conversions (C++ 4.9). 1892 SCS.Second = ICK_Floating_Integral; 1893 FromType = ToType.getUnqualifiedType(); 1894 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1895 SCS.Second = ICK_Block_Pointer_Conversion; 1896 } else if (AllowObjCWritebackConversion && 1897 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1898 SCS.Second = ICK_Writeback_Conversion; 1899 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1900 FromType, IncompatibleObjC)) { 1901 // Pointer conversions (C++ 4.10). 1902 SCS.Second = ICK_Pointer_Conversion; 1903 SCS.IncompatibleObjC = IncompatibleObjC; 1904 FromType = FromType.getUnqualifiedType(); 1905 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1906 InOverloadResolution, FromType)) { 1907 // Pointer to member conversions (4.11). 1908 SCS.Second = ICK_Pointer_Member; 1909 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1910 SCS.Second = SecondICK; 1911 FromType = ToType.getUnqualifiedType(); 1912 } else if (!S.getLangOpts().CPlusPlus && 1913 S.Context.typesAreCompatible(ToType, FromType)) { 1914 // Compatible conversions (Clang extension for C function overloading) 1915 SCS.Second = ICK_Compatible_Conversion; 1916 FromType = ToType.getUnqualifiedType(); 1917 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1918 InOverloadResolution, 1919 SCS, CStyle)) { 1920 SCS.Second = ICK_TransparentUnionConversion; 1921 FromType = ToType; 1922 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1923 CStyle)) { 1924 // tryAtomicConversion has updated the standard conversion sequence 1925 // appropriately. 1926 return true; 1927 } else if (ToType->isEventT() && 1928 From->isIntegerConstantExpr(S.getASTContext()) && 1929 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1930 SCS.Second = ICK_Zero_Event_Conversion; 1931 FromType = ToType; 1932 } else if (ToType->isQueueT() && 1933 From->isIntegerConstantExpr(S.getASTContext()) && 1934 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1935 SCS.Second = ICK_Zero_Queue_Conversion; 1936 FromType = ToType; 1937 } else if (ToType->isSamplerT() && 1938 From->isIntegerConstantExpr(S.getASTContext())) { 1939 SCS.Second = ICK_Compatible_Conversion; 1940 FromType = ToType; 1941 } else { 1942 // No second conversion required. 1943 SCS.Second = ICK_Identity; 1944 } 1945 SCS.setToType(1, FromType); 1946 1947 // The third conversion can be a function pointer conversion or a 1948 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1949 bool ObjCLifetimeConversion; 1950 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1951 // Function pointer conversions (removing 'noexcept') including removal of 1952 // 'noreturn' (Clang extension). 1953 SCS.Third = ICK_Function_Conversion; 1954 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1955 ObjCLifetimeConversion)) { 1956 SCS.Third = ICK_Qualification; 1957 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1958 FromType = ToType; 1959 } else { 1960 // No conversion required 1961 SCS.Third = ICK_Identity; 1962 } 1963 1964 // C++ [over.best.ics]p6: 1965 // [...] Any difference in top-level cv-qualification is 1966 // subsumed by the initialization itself and does not constitute 1967 // a conversion. [...] 1968 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1969 QualType CanonTo = S.Context.getCanonicalType(ToType); 1970 if (CanonFrom.getLocalUnqualifiedType() 1971 == CanonTo.getLocalUnqualifiedType() && 1972 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1973 FromType = ToType; 1974 CanonFrom = CanonTo; 1975 } 1976 1977 SCS.setToType(2, FromType); 1978 1979 if (CanonFrom == CanonTo) 1980 return true; 1981 1982 // If we have not converted the argument type to the parameter type, 1983 // this is a bad conversion sequence, unless we're resolving an overload in C. 1984 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1985 return false; 1986 1987 ExprResult ER = ExprResult{From}; 1988 Sema::AssignConvertType Conv = 1989 S.CheckSingleAssignmentConstraints(ToType, ER, 1990 /*Diagnose=*/false, 1991 /*DiagnoseCFAudited=*/false, 1992 /*ConvertRHS=*/false); 1993 ImplicitConversionKind SecondConv; 1994 switch (Conv) { 1995 case Sema::Compatible: 1996 SecondConv = ICK_C_Only_Conversion; 1997 break; 1998 // For our purposes, discarding qualifiers is just as bad as using an 1999 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 2000 // qualifiers, as well. 2001 case Sema::CompatiblePointerDiscardsQualifiers: 2002 case Sema::IncompatiblePointer: 2003 case Sema::IncompatiblePointerSign: 2004 SecondConv = ICK_Incompatible_Pointer_Conversion; 2005 break; 2006 default: 2007 return false; 2008 } 2009 2010 // First can only be an lvalue conversion, so we pretend that this was the 2011 // second conversion. First should already be valid from earlier in the 2012 // function. 2013 SCS.Second = SecondConv; 2014 SCS.setToType(1, ToType); 2015 2016 // Third is Identity, because Second should rank us worse than any other 2017 // conversion. This could also be ICK_Qualification, but it's simpler to just 2018 // lump everything in with the second conversion, and we don't gain anything 2019 // from making this ICK_Qualification. 2020 SCS.Third = ICK_Identity; 2021 SCS.setToType(2, ToType); 2022 return true; 2023 } 2024 2025 static bool 2026 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 2027 QualType &ToType, 2028 bool InOverloadResolution, 2029 StandardConversionSequence &SCS, 2030 bool CStyle) { 2031 2032 const RecordType *UT = ToType->getAsUnionType(); 2033 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 2034 return false; 2035 // The field to initialize within the transparent union. 2036 RecordDecl *UD = UT->getDecl(); 2037 // It's compatible if the expression matches any of the fields. 2038 for (const auto *it : UD->fields()) { 2039 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 2040 CStyle, /*AllowObjCWritebackConversion=*/false)) { 2041 ToType = it->getType(); 2042 return true; 2043 } 2044 } 2045 return false; 2046 } 2047 2048 /// IsIntegralPromotion - Determines whether the conversion from the 2049 /// expression From (whose potentially-adjusted type is FromType) to 2050 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 2051 /// sets PromotedType to the promoted type. 2052 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 2053 const BuiltinType *To = ToType->getAs<BuiltinType>(); 2054 // All integers are built-in. 2055 if (!To) { 2056 return false; 2057 } 2058 2059 // An rvalue of type char, signed char, unsigned char, short int, or 2060 // unsigned short int can be converted to an rvalue of type int if 2061 // int can represent all the values of the source type; otherwise, 2062 // the source rvalue can be converted to an rvalue of type unsigned 2063 // int (C++ 4.5p1). 2064 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 2065 !FromType->isEnumeralType()) { 2066 if (// We can promote any signed, promotable integer type to an int 2067 (FromType->isSignedIntegerType() || 2068 // We can promote any unsigned integer type whose size is 2069 // less than int to an int. 2070 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2071 return To->getKind() == BuiltinType::Int; 2072 } 2073 2074 return To->getKind() == BuiltinType::UInt; 2075 } 2076 2077 // C++11 [conv.prom]p3: 2078 // A prvalue of an unscoped enumeration type whose underlying type is not 2079 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2080 // following types that can represent all the values of the enumeration 2081 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2082 // unsigned int, long int, unsigned long int, long long int, or unsigned 2083 // long long int. If none of the types in that list can represent all the 2084 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2085 // type can be converted to an rvalue a prvalue of the extended integer type 2086 // with lowest integer conversion rank (4.13) greater than the rank of long 2087 // long in which all the values of the enumeration can be represented. If 2088 // there are two such extended types, the signed one is chosen. 2089 // C++11 [conv.prom]p4: 2090 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2091 // can be converted to a prvalue of its underlying type. Moreover, if 2092 // integral promotion can be applied to its underlying type, a prvalue of an 2093 // unscoped enumeration type whose underlying type is fixed can also be 2094 // converted to a prvalue of the promoted underlying type. 2095 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2096 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2097 // provided for a scoped enumeration. 2098 if (FromEnumType->getDecl()->isScoped()) 2099 return false; 2100 2101 // We can perform an integral promotion to the underlying type of the enum, 2102 // even if that's not the promoted type. Note that the check for promoting 2103 // the underlying type is based on the type alone, and does not consider 2104 // the bitfield-ness of the actual source expression. 2105 if (FromEnumType->getDecl()->isFixed()) { 2106 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2107 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2108 IsIntegralPromotion(nullptr, Underlying, ToType); 2109 } 2110 2111 // We have already pre-calculated the promotion type, so this is trivial. 2112 if (ToType->isIntegerType() && 2113 isCompleteType(From->getBeginLoc(), FromType)) 2114 return Context.hasSameUnqualifiedType( 2115 ToType, FromEnumType->getDecl()->getPromotionType()); 2116 2117 // C++ [conv.prom]p5: 2118 // If the bit-field has an enumerated type, it is treated as any other 2119 // value of that type for promotion purposes. 2120 // 2121 // ... so do not fall through into the bit-field checks below in C++. 2122 if (getLangOpts().CPlusPlus) 2123 return false; 2124 } 2125 2126 // C++0x [conv.prom]p2: 2127 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2128 // to an rvalue a prvalue of the first of the following types that can 2129 // represent all the values of its underlying type: int, unsigned int, 2130 // long int, unsigned long int, long long int, or unsigned long long int. 2131 // If none of the types in that list can represent all the values of its 2132 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2133 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2134 // type. 2135 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2136 ToType->isIntegerType()) { 2137 // Determine whether the type we're converting from is signed or 2138 // unsigned. 2139 bool FromIsSigned = FromType->isSignedIntegerType(); 2140 uint64_t FromSize = Context.getTypeSize(FromType); 2141 2142 // The types we'll try to promote to, in the appropriate 2143 // order. Try each of these types. 2144 QualType PromoteTypes[6] = { 2145 Context.IntTy, Context.UnsignedIntTy, 2146 Context.LongTy, Context.UnsignedLongTy , 2147 Context.LongLongTy, Context.UnsignedLongLongTy 2148 }; 2149 for (int Idx = 0; Idx < 6; ++Idx) { 2150 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2151 if (FromSize < ToSize || 2152 (FromSize == ToSize && 2153 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2154 // We found the type that we can promote to. If this is the 2155 // type we wanted, we have a promotion. Otherwise, no 2156 // promotion. 2157 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2158 } 2159 } 2160 } 2161 2162 // An rvalue for an integral bit-field (9.6) can be converted to an 2163 // rvalue of type int if int can represent all the values of the 2164 // bit-field; otherwise, it can be converted to unsigned int if 2165 // unsigned int can represent all the values of the bit-field. If 2166 // the bit-field is larger yet, no integral promotion applies to 2167 // it. If the bit-field has an enumerated type, it is treated as any 2168 // other value of that type for promotion purposes (C++ 4.5p3). 2169 // FIXME: We should delay checking of bit-fields until we actually perform the 2170 // conversion. 2171 // 2172 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2173 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2174 // bit-fields and those whose underlying type is larger than int) for GCC 2175 // compatibility. 2176 if (From) { 2177 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2178 llvm::APSInt BitWidth; 2179 if (FromType->isIntegralType(Context) && 2180 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2181 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2182 ToSize = Context.getTypeSize(ToType); 2183 2184 // Are we promoting to an int from a bitfield that fits in an int? 2185 if (BitWidth < ToSize || 2186 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2187 return To->getKind() == BuiltinType::Int; 2188 } 2189 2190 // Are we promoting to an unsigned int from an unsigned bitfield 2191 // that fits into an unsigned int? 2192 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2193 return To->getKind() == BuiltinType::UInt; 2194 } 2195 2196 return false; 2197 } 2198 } 2199 } 2200 2201 // An rvalue of type bool can be converted to an rvalue of type int, 2202 // with false becoming zero and true becoming one (C++ 4.5p4). 2203 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2204 return true; 2205 } 2206 2207 return false; 2208 } 2209 2210 /// IsFloatingPointPromotion - Determines whether the conversion from 2211 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2212 /// returns true and sets PromotedType to the promoted type. 2213 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2214 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2215 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2216 /// An rvalue of type float can be converted to an rvalue of type 2217 /// double. (C++ 4.6p1). 2218 if (FromBuiltin->getKind() == BuiltinType::Float && 2219 ToBuiltin->getKind() == BuiltinType::Double) 2220 return true; 2221 2222 // C99 6.3.1.5p1: 2223 // When a float is promoted to double or long double, or a 2224 // double is promoted to long double [...]. 2225 if (!getLangOpts().CPlusPlus && 2226 (FromBuiltin->getKind() == BuiltinType::Float || 2227 FromBuiltin->getKind() == BuiltinType::Double) && 2228 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2229 ToBuiltin->getKind() == BuiltinType::Float128)) 2230 return true; 2231 2232 // Half can be promoted to float. 2233 if (!getLangOpts().NativeHalfType && 2234 FromBuiltin->getKind() == BuiltinType::Half && 2235 ToBuiltin->getKind() == BuiltinType::Float) 2236 return true; 2237 } 2238 2239 return false; 2240 } 2241 2242 /// Determine if a conversion is a complex promotion. 2243 /// 2244 /// A complex promotion is defined as a complex -> complex conversion 2245 /// where the conversion between the underlying real types is a 2246 /// floating-point or integral promotion. 2247 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2248 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2249 if (!FromComplex) 2250 return false; 2251 2252 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2253 if (!ToComplex) 2254 return false; 2255 2256 return IsFloatingPointPromotion(FromComplex->getElementType(), 2257 ToComplex->getElementType()) || 2258 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2259 ToComplex->getElementType()); 2260 } 2261 2262 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2263 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2264 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2265 /// if non-empty, will be a pointer to ToType that may or may not have 2266 /// the right set of qualifiers on its pointee. 2267 /// 2268 static QualType 2269 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2270 QualType ToPointee, QualType ToType, 2271 ASTContext &Context, 2272 bool StripObjCLifetime = false) { 2273 assert((FromPtr->getTypeClass() == Type::Pointer || 2274 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2275 "Invalid similarly-qualified pointer type"); 2276 2277 /// Conversions to 'id' subsume cv-qualifier conversions. 2278 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2279 return ToType.getUnqualifiedType(); 2280 2281 QualType CanonFromPointee 2282 = Context.getCanonicalType(FromPtr->getPointeeType()); 2283 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2284 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2285 2286 if (StripObjCLifetime) 2287 Quals.removeObjCLifetime(); 2288 2289 // Exact qualifier match -> return the pointer type we're converting to. 2290 if (CanonToPointee.getLocalQualifiers() == Quals) { 2291 // ToType is exactly what we need. Return it. 2292 if (!ToType.isNull()) 2293 return ToType.getUnqualifiedType(); 2294 2295 // Build a pointer to ToPointee. It has the right qualifiers 2296 // already. 2297 if (isa<ObjCObjectPointerType>(ToType)) 2298 return Context.getObjCObjectPointerType(ToPointee); 2299 return Context.getPointerType(ToPointee); 2300 } 2301 2302 // Just build a canonical type that has the right qualifiers. 2303 QualType QualifiedCanonToPointee 2304 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2305 2306 if (isa<ObjCObjectPointerType>(ToType)) 2307 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2308 return Context.getPointerType(QualifiedCanonToPointee); 2309 } 2310 2311 static bool isNullPointerConstantForConversion(Expr *Expr, 2312 bool InOverloadResolution, 2313 ASTContext &Context) { 2314 // Handle value-dependent integral null pointer constants correctly. 2315 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2316 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2317 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2318 return !InOverloadResolution; 2319 2320 return Expr->isNullPointerConstant(Context, 2321 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2322 : Expr::NPC_ValueDependentIsNull); 2323 } 2324 2325 /// IsPointerConversion - Determines whether the conversion of the 2326 /// expression From, which has the (possibly adjusted) type FromType, 2327 /// can be converted to the type ToType via a pointer conversion (C++ 2328 /// 4.10). If so, returns true and places the converted type (that 2329 /// might differ from ToType in its cv-qualifiers at some level) into 2330 /// ConvertedType. 2331 /// 2332 /// This routine also supports conversions to and from block pointers 2333 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2334 /// pointers to interfaces. FIXME: Once we've determined the 2335 /// appropriate overloading rules for Objective-C, we may want to 2336 /// split the Objective-C checks into a different routine; however, 2337 /// GCC seems to consider all of these conversions to be pointer 2338 /// conversions, so for now they live here. IncompatibleObjC will be 2339 /// set if the conversion is an allowed Objective-C conversion that 2340 /// should result in a warning. 2341 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2342 bool InOverloadResolution, 2343 QualType& ConvertedType, 2344 bool &IncompatibleObjC) { 2345 IncompatibleObjC = false; 2346 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2347 IncompatibleObjC)) 2348 return true; 2349 2350 // Conversion from a null pointer constant to any Objective-C pointer type. 2351 if (ToType->isObjCObjectPointerType() && 2352 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2353 ConvertedType = ToType; 2354 return true; 2355 } 2356 2357 // Blocks: Block pointers can be converted to void*. 2358 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2359 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 2360 ConvertedType = ToType; 2361 return true; 2362 } 2363 // Blocks: A null pointer constant can be converted to a block 2364 // pointer type. 2365 if (ToType->isBlockPointerType() && 2366 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2367 ConvertedType = ToType; 2368 return true; 2369 } 2370 2371 // If the left-hand-side is nullptr_t, the right side can be a null 2372 // pointer constant. 2373 if (ToType->isNullPtrType() && 2374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2375 ConvertedType = ToType; 2376 return true; 2377 } 2378 2379 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2380 if (!ToTypePtr) 2381 return false; 2382 2383 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2384 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2385 ConvertedType = ToType; 2386 return true; 2387 } 2388 2389 // Beyond this point, both types need to be pointers 2390 // , including objective-c pointers. 2391 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2392 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2393 !getLangOpts().ObjCAutoRefCount) { 2394 ConvertedType = BuildSimilarlyQualifiedPointerType( 2395 FromType->getAs<ObjCObjectPointerType>(), 2396 ToPointeeType, 2397 ToType, Context); 2398 return true; 2399 } 2400 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2401 if (!FromTypePtr) 2402 return false; 2403 2404 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2405 2406 // If the unqualified pointee types are the same, this can't be a 2407 // pointer conversion, so don't do all of the work below. 2408 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2409 return false; 2410 2411 // An rvalue of type "pointer to cv T," where T is an object type, 2412 // can be converted to an rvalue of type "pointer to cv void" (C++ 2413 // 4.10p2). 2414 if (FromPointeeType->isIncompleteOrObjectType() && 2415 ToPointeeType->isVoidType()) { 2416 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2417 ToPointeeType, 2418 ToType, Context, 2419 /*StripObjCLifetime=*/true); 2420 return true; 2421 } 2422 2423 // MSVC allows implicit function to void* type conversion. 2424 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2425 ToPointeeType->isVoidType()) { 2426 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2427 ToPointeeType, 2428 ToType, Context); 2429 return true; 2430 } 2431 2432 // When we're overloading in C, we allow a special kind of pointer 2433 // conversion for compatible-but-not-identical pointee types. 2434 if (!getLangOpts().CPlusPlus && 2435 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2436 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2437 ToPointeeType, 2438 ToType, Context); 2439 return true; 2440 } 2441 2442 // C++ [conv.ptr]p3: 2443 // 2444 // An rvalue of type "pointer to cv D," where D is a class type, 2445 // can be converted to an rvalue of type "pointer to cv B," where 2446 // B is a base class (clause 10) of D. If B is an inaccessible 2447 // (clause 11) or ambiguous (10.2) base class of D, a program that 2448 // necessitates this conversion is ill-formed. The result of the 2449 // conversion is a pointer to the base class sub-object of the 2450 // derived class object. The null pointer value is converted to 2451 // the null pointer value of the destination type. 2452 // 2453 // Note that we do not check for ambiguity or inaccessibility 2454 // here. That is handled by CheckPointerConversion. 2455 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2456 ToPointeeType->isRecordType() && 2457 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2458 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2459 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2460 ToPointeeType, 2461 ToType, Context); 2462 return true; 2463 } 2464 2465 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2466 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2467 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2468 ToPointeeType, 2469 ToType, Context); 2470 return true; 2471 } 2472 2473 return false; 2474 } 2475 2476 /// Adopt the given qualifiers for the given type. 2477 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2478 Qualifiers TQs = T.getQualifiers(); 2479 2480 // Check whether qualifiers already match. 2481 if (TQs == Qs) 2482 return T; 2483 2484 if (Qs.compatiblyIncludes(TQs)) 2485 return Context.getQualifiedType(T, Qs); 2486 2487 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2488 } 2489 2490 /// isObjCPointerConversion - Determines whether this is an 2491 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2492 /// with the same arguments and return values. 2493 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2494 QualType& ConvertedType, 2495 bool &IncompatibleObjC) { 2496 if (!getLangOpts().ObjC) 2497 return false; 2498 2499 // The set of qualifiers on the type we're converting from. 2500 Qualifiers FromQualifiers = FromType.getQualifiers(); 2501 2502 // First, we handle all conversions on ObjC object pointer types. 2503 const ObjCObjectPointerType* ToObjCPtr = 2504 ToType->getAs<ObjCObjectPointerType>(); 2505 const ObjCObjectPointerType *FromObjCPtr = 2506 FromType->getAs<ObjCObjectPointerType>(); 2507 2508 if (ToObjCPtr && FromObjCPtr) { 2509 // If the pointee types are the same (ignoring qualifications), 2510 // then this is not a pointer conversion. 2511 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2512 FromObjCPtr->getPointeeType())) 2513 return false; 2514 2515 // Conversion between Objective-C pointers. 2516 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2517 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2518 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2519 if (getLangOpts().CPlusPlus && LHS && RHS && 2520 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2521 FromObjCPtr->getPointeeType())) 2522 return false; 2523 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2524 ToObjCPtr->getPointeeType(), 2525 ToType, Context); 2526 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2527 return true; 2528 } 2529 2530 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2531 // Okay: this is some kind of implicit downcast of Objective-C 2532 // interfaces, which is permitted. However, we're going to 2533 // complain about it. 2534 IncompatibleObjC = true; 2535 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2536 ToObjCPtr->getPointeeType(), 2537 ToType, Context); 2538 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2539 return true; 2540 } 2541 } 2542 // Beyond this point, both types need to be C pointers or block pointers. 2543 QualType ToPointeeType; 2544 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2545 ToPointeeType = ToCPtr->getPointeeType(); 2546 else if (const BlockPointerType *ToBlockPtr = 2547 ToType->getAs<BlockPointerType>()) { 2548 // Objective C++: We're able to convert from a pointer to any object 2549 // to a block pointer type. 2550 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2551 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2552 return true; 2553 } 2554 ToPointeeType = ToBlockPtr->getPointeeType(); 2555 } 2556 else if (FromType->getAs<BlockPointerType>() && 2557 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2558 // Objective C++: We're able to convert from a block pointer type to a 2559 // pointer to any object. 2560 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2561 return true; 2562 } 2563 else 2564 return false; 2565 2566 QualType FromPointeeType; 2567 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2568 FromPointeeType = FromCPtr->getPointeeType(); 2569 else if (const BlockPointerType *FromBlockPtr = 2570 FromType->getAs<BlockPointerType>()) 2571 FromPointeeType = FromBlockPtr->getPointeeType(); 2572 else 2573 return false; 2574 2575 // If we have pointers to pointers, recursively check whether this 2576 // is an Objective-C conversion. 2577 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2578 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2579 IncompatibleObjC)) { 2580 // We always complain about this conversion. 2581 IncompatibleObjC = true; 2582 ConvertedType = Context.getPointerType(ConvertedType); 2583 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2584 return true; 2585 } 2586 // Allow conversion of pointee being objective-c pointer to another one; 2587 // as in I* to id. 2588 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2589 ToPointeeType->getAs<ObjCObjectPointerType>() && 2590 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2591 IncompatibleObjC)) { 2592 2593 ConvertedType = Context.getPointerType(ConvertedType); 2594 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2595 return true; 2596 } 2597 2598 // If we have pointers to functions or blocks, check whether the only 2599 // differences in the argument and result types are in Objective-C 2600 // pointer conversions. If so, we permit the conversion (but 2601 // complain about it). 2602 const FunctionProtoType *FromFunctionType 2603 = FromPointeeType->getAs<FunctionProtoType>(); 2604 const FunctionProtoType *ToFunctionType 2605 = ToPointeeType->getAs<FunctionProtoType>(); 2606 if (FromFunctionType && ToFunctionType) { 2607 // If the function types are exactly the same, this isn't an 2608 // Objective-C pointer conversion. 2609 if (Context.getCanonicalType(FromPointeeType) 2610 == Context.getCanonicalType(ToPointeeType)) 2611 return false; 2612 2613 // Perform the quick checks that will tell us whether these 2614 // function types are obviously different. 2615 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2616 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2617 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2618 return false; 2619 2620 bool HasObjCConversion = false; 2621 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2622 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2623 // Okay, the types match exactly. Nothing to do. 2624 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2625 ToFunctionType->getReturnType(), 2626 ConvertedType, IncompatibleObjC)) { 2627 // Okay, we have an Objective-C pointer conversion. 2628 HasObjCConversion = true; 2629 } else { 2630 // Function types are too different. Abort. 2631 return false; 2632 } 2633 2634 // Check argument types. 2635 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2636 ArgIdx != NumArgs; ++ArgIdx) { 2637 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2638 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2639 if (Context.getCanonicalType(FromArgType) 2640 == Context.getCanonicalType(ToArgType)) { 2641 // Okay, the types match exactly. Nothing to do. 2642 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2643 ConvertedType, IncompatibleObjC)) { 2644 // Okay, we have an Objective-C pointer conversion. 2645 HasObjCConversion = true; 2646 } else { 2647 // Argument types are too different. Abort. 2648 return false; 2649 } 2650 } 2651 2652 if (HasObjCConversion) { 2653 // We had an Objective-C conversion. Allow this pointer 2654 // conversion, but complain about it. 2655 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2656 IncompatibleObjC = true; 2657 return true; 2658 } 2659 } 2660 2661 return false; 2662 } 2663 2664 /// Determine whether this is an Objective-C writeback conversion, 2665 /// used for parameter passing when performing automatic reference counting. 2666 /// 2667 /// \param FromType The type we're converting form. 2668 /// 2669 /// \param ToType The type we're converting to. 2670 /// 2671 /// \param ConvertedType The type that will be produced after applying 2672 /// this conversion. 2673 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2674 QualType &ConvertedType) { 2675 if (!getLangOpts().ObjCAutoRefCount || 2676 Context.hasSameUnqualifiedType(FromType, ToType)) 2677 return false; 2678 2679 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2680 QualType ToPointee; 2681 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2682 ToPointee = ToPointer->getPointeeType(); 2683 else 2684 return false; 2685 2686 Qualifiers ToQuals = ToPointee.getQualifiers(); 2687 if (!ToPointee->isObjCLifetimeType() || 2688 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2689 !ToQuals.withoutObjCLifetime().empty()) 2690 return false; 2691 2692 // Argument must be a pointer to __strong to __weak. 2693 QualType FromPointee; 2694 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2695 FromPointee = FromPointer->getPointeeType(); 2696 else 2697 return false; 2698 2699 Qualifiers FromQuals = FromPointee.getQualifiers(); 2700 if (!FromPointee->isObjCLifetimeType() || 2701 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2702 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2703 return false; 2704 2705 // Make sure that we have compatible qualifiers. 2706 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2707 if (!ToQuals.compatiblyIncludes(FromQuals)) 2708 return false; 2709 2710 // Remove qualifiers from the pointee type we're converting from; they 2711 // aren't used in the compatibility check belong, and we'll be adding back 2712 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2713 FromPointee = FromPointee.getUnqualifiedType(); 2714 2715 // The unqualified form of the pointee types must be compatible. 2716 ToPointee = ToPointee.getUnqualifiedType(); 2717 bool IncompatibleObjC; 2718 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2719 FromPointee = ToPointee; 2720 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2721 IncompatibleObjC)) 2722 return false; 2723 2724 /// Construct the type we're converting to, which is a pointer to 2725 /// __autoreleasing pointee. 2726 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2727 ConvertedType = Context.getPointerType(FromPointee); 2728 return true; 2729 } 2730 2731 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2732 QualType& ConvertedType) { 2733 QualType ToPointeeType; 2734 if (const BlockPointerType *ToBlockPtr = 2735 ToType->getAs<BlockPointerType>()) 2736 ToPointeeType = ToBlockPtr->getPointeeType(); 2737 else 2738 return false; 2739 2740 QualType FromPointeeType; 2741 if (const BlockPointerType *FromBlockPtr = 2742 FromType->getAs<BlockPointerType>()) 2743 FromPointeeType = FromBlockPtr->getPointeeType(); 2744 else 2745 return false; 2746 // We have pointer to blocks, check whether the only 2747 // differences in the argument and result types are in Objective-C 2748 // pointer conversions. If so, we permit the conversion. 2749 2750 const FunctionProtoType *FromFunctionType 2751 = FromPointeeType->getAs<FunctionProtoType>(); 2752 const FunctionProtoType *ToFunctionType 2753 = ToPointeeType->getAs<FunctionProtoType>(); 2754 2755 if (!FromFunctionType || !ToFunctionType) 2756 return false; 2757 2758 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2759 return true; 2760 2761 // Perform the quick checks that will tell us whether these 2762 // function types are obviously different. 2763 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2764 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2765 return false; 2766 2767 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2768 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2769 if (FromEInfo != ToEInfo) 2770 return false; 2771 2772 bool IncompatibleObjC = false; 2773 if (Context.hasSameType(FromFunctionType->getReturnType(), 2774 ToFunctionType->getReturnType())) { 2775 // Okay, the types match exactly. Nothing to do. 2776 } else { 2777 QualType RHS = FromFunctionType->getReturnType(); 2778 QualType LHS = ToFunctionType->getReturnType(); 2779 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2780 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2781 LHS = LHS.getUnqualifiedType(); 2782 2783 if (Context.hasSameType(RHS,LHS)) { 2784 // OK exact match. 2785 } else if (isObjCPointerConversion(RHS, LHS, 2786 ConvertedType, IncompatibleObjC)) { 2787 if (IncompatibleObjC) 2788 return false; 2789 // Okay, we have an Objective-C pointer conversion. 2790 } 2791 else 2792 return false; 2793 } 2794 2795 // Check argument types. 2796 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2797 ArgIdx != NumArgs; ++ArgIdx) { 2798 IncompatibleObjC = false; 2799 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2800 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2801 if (Context.hasSameType(FromArgType, ToArgType)) { 2802 // Okay, the types match exactly. Nothing to do. 2803 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2804 ConvertedType, IncompatibleObjC)) { 2805 if (IncompatibleObjC) 2806 return false; 2807 // Okay, we have an Objective-C pointer conversion. 2808 } else 2809 // Argument types are too different. Abort. 2810 return false; 2811 } 2812 2813 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2814 bool CanUseToFPT, CanUseFromFPT; 2815 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2816 CanUseToFPT, CanUseFromFPT, 2817 NewParamInfos)) 2818 return false; 2819 2820 ConvertedType = ToType; 2821 return true; 2822 } 2823 2824 enum { 2825 ft_default, 2826 ft_different_class, 2827 ft_parameter_arity, 2828 ft_parameter_mismatch, 2829 ft_return_type, 2830 ft_qualifer_mismatch, 2831 ft_noexcept 2832 }; 2833 2834 /// Attempts to get the FunctionProtoType from a Type. Handles 2835 /// MemberFunctionPointers properly. 2836 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2837 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2838 return FPT; 2839 2840 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2841 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2842 2843 return nullptr; 2844 } 2845 2846 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2847 /// function types. Catches different number of parameter, mismatch in 2848 /// parameter types, and different return types. 2849 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2850 QualType FromType, QualType ToType) { 2851 // If either type is not valid, include no extra info. 2852 if (FromType.isNull() || ToType.isNull()) { 2853 PDiag << ft_default; 2854 return; 2855 } 2856 2857 // Get the function type from the pointers. 2858 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2859 const auto *FromMember = FromType->castAs<MemberPointerType>(), 2860 *ToMember = ToType->castAs<MemberPointerType>(); 2861 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2862 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2863 << QualType(FromMember->getClass(), 0); 2864 return; 2865 } 2866 FromType = FromMember->getPointeeType(); 2867 ToType = ToMember->getPointeeType(); 2868 } 2869 2870 if (FromType->isPointerType()) 2871 FromType = FromType->getPointeeType(); 2872 if (ToType->isPointerType()) 2873 ToType = ToType->getPointeeType(); 2874 2875 // Remove references. 2876 FromType = FromType.getNonReferenceType(); 2877 ToType = ToType.getNonReferenceType(); 2878 2879 // Don't print extra info for non-specialized template functions. 2880 if (FromType->isInstantiationDependentType() && 2881 !FromType->getAs<TemplateSpecializationType>()) { 2882 PDiag << ft_default; 2883 return; 2884 } 2885 2886 // No extra info for same types. 2887 if (Context.hasSameType(FromType, ToType)) { 2888 PDiag << ft_default; 2889 return; 2890 } 2891 2892 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2893 *ToFunction = tryGetFunctionProtoType(ToType); 2894 2895 // Both types need to be function types. 2896 if (!FromFunction || !ToFunction) { 2897 PDiag << ft_default; 2898 return; 2899 } 2900 2901 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2902 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2903 << FromFunction->getNumParams(); 2904 return; 2905 } 2906 2907 // Handle different parameter types. 2908 unsigned ArgPos; 2909 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2910 PDiag << ft_parameter_mismatch << ArgPos + 1 2911 << ToFunction->getParamType(ArgPos) 2912 << FromFunction->getParamType(ArgPos); 2913 return; 2914 } 2915 2916 // Handle different return type. 2917 if (!Context.hasSameType(FromFunction->getReturnType(), 2918 ToFunction->getReturnType())) { 2919 PDiag << ft_return_type << ToFunction->getReturnType() 2920 << FromFunction->getReturnType(); 2921 return; 2922 } 2923 2924 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2925 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2926 << FromFunction->getMethodQuals(); 2927 return; 2928 } 2929 2930 // Handle exception specification differences on canonical type (in C++17 2931 // onwards). 2932 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2933 ->isNothrow() != 2934 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2935 ->isNothrow()) { 2936 PDiag << ft_noexcept; 2937 return; 2938 } 2939 2940 // Unable to find a difference, so add no extra info. 2941 PDiag << ft_default; 2942 } 2943 2944 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2945 /// for equality of their argument types. Caller has already checked that 2946 /// they have same number of arguments. If the parameters are different, 2947 /// ArgPos will have the parameter index of the first different parameter. 2948 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2949 const FunctionProtoType *NewType, 2950 unsigned *ArgPos) { 2951 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2952 N = NewType->param_type_begin(), 2953 E = OldType->param_type_end(); 2954 O && (O != E); ++O, ++N) { 2955 // Ignore address spaces in pointee type. This is to disallow overloading 2956 // on __ptr32/__ptr64 address spaces. 2957 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType()); 2958 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType()); 2959 2960 if (!Context.hasSameType(Old, New)) { 2961 if (ArgPos) 2962 *ArgPos = O - OldType->param_type_begin(); 2963 return false; 2964 } 2965 } 2966 return true; 2967 } 2968 2969 /// CheckPointerConversion - Check the pointer conversion from the 2970 /// expression From to the type ToType. This routine checks for 2971 /// ambiguous or inaccessible derived-to-base pointer 2972 /// conversions for which IsPointerConversion has already returned 2973 /// true. It returns true and produces a diagnostic if there was an 2974 /// error, or returns false otherwise. 2975 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2976 CastKind &Kind, 2977 CXXCastPath& BasePath, 2978 bool IgnoreBaseAccess, 2979 bool Diagnose) { 2980 QualType FromType = From->getType(); 2981 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2982 2983 Kind = CK_BitCast; 2984 2985 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2986 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2987 Expr::NPCK_ZeroExpression) { 2988 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2989 DiagRuntimeBehavior(From->getExprLoc(), From, 2990 PDiag(diag::warn_impcast_bool_to_null_pointer) 2991 << ToType << From->getSourceRange()); 2992 else if (!isUnevaluatedContext()) 2993 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2994 << ToType << From->getSourceRange(); 2995 } 2996 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2997 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2998 QualType FromPointeeType = FromPtrType->getPointeeType(), 2999 ToPointeeType = ToPtrType->getPointeeType(); 3000 3001 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 3002 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 3003 // We must have a derived-to-base conversion. Check an 3004 // ambiguous or inaccessible conversion. 3005 unsigned InaccessibleID = 0; 3006 unsigned AmbiguousID = 0; 3007 if (Diagnose) { 3008 InaccessibleID = diag::err_upcast_to_inaccessible_base; 3009 AmbiguousID = diag::err_ambiguous_derived_to_base_conv; 3010 } 3011 if (CheckDerivedToBaseConversion( 3012 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID, 3013 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 3014 &BasePath, IgnoreBaseAccess)) 3015 return true; 3016 3017 // The conversion was successful. 3018 Kind = CK_DerivedToBase; 3019 } 3020 3021 if (Diagnose && !IsCStyleOrFunctionalCast && 3022 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 3023 assert(getLangOpts().MSVCCompat && 3024 "this should only be possible with MSVCCompat!"); 3025 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 3026 << From->getSourceRange(); 3027 } 3028 } 3029 } else if (const ObjCObjectPointerType *ToPtrType = 3030 ToType->getAs<ObjCObjectPointerType>()) { 3031 if (const ObjCObjectPointerType *FromPtrType = 3032 FromType->getAs<ObjCObjectPointerType>()) { 3033 // Objective-C++ conversions are always okay. 3034 // FIXME: We should have a different class of conversions for the 3035 // Objective-C++ implicit conversions. 3036 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 3037 return false; 3038 } else if (FromType->isBlockPointerType()) { 3039 Kind = CK_BlockPointerToObjCPointerCast; 3040 } else { 3041 Kind = CK_CPointerToObjCPointerCast; 3042 } 3043 } else if (ToType->isBlockPointerType()) { 3044 if (!FromType->isBlockPointerType()) 3045 Kind = CK_AnyPointerToBlockPointerCast; 3046 } 3047 3048 // We shouldn't fall into this case unless it's valid for other 3049 // reasons. 3050 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 3051 Kind = CK_NullToPointer; 3052 3053 return false; 3054 } 3055 3056 /// IsMemberPointerConversion - Determines whether the conversion of the 3057 /// expression From, which has the (possibly adjusted) type FromType, can be 3058 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 3059 /// If so, returns true and places the converted type (that might differ from 3060 /// ToType in its cv-qualifiers at some level) into ConvertedType. 3061 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 3062 QualType ToType, 3063 bool InOverloadResolution, 3064 QualType &ConvertedType) { 3065 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 3066 if (!ToTypePtr) 3067 return false; 3068 3069 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 3070 if (From->isNullPointerConstant(Context, 3071 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 3072 : Expr::NPC_ValueDependentIsNull)) { 3073 ConvertedType = ToType; 3074 return true; 3075 } 3076 3077 // Otherwise, both types have to be member pointers. 3078 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3079 if (!FromTypePtr) 3080 return false; 3081 3082 // A pointer to member of B can be converted to a pointer to member of D, 3083 // where D is derived from B (C++ 4.11p2). 3084 QualType FromClass(FromTypePtr->getClass(), 0); 3085 QualType ToClass(ToTypePtr->getClass(), 0); 3086 3087 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3088 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3089 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3090 ToClass.getTypePtr()); 3091 return true; 3092 } 3093 3094 return false; 3095 } 3096 3097 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3098 /// expression From to the type ToType. This routine checks for ambiguous or 3099 /// virtual or inaccessible base-to-derived member pointer conversions 3100 /// for which IsMemberPointerConversion has already returned true. It returns 3101 /// true and produces a diagnostic if there was an error, or returns false 3102 /// otherwise. 3103 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3104 CastKind &Kind, 3105 CXXCastPath &BasePath, 3106 bool IgnoreBaseAccess) { 3107 QualType FromType = From->getType(); 3108 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3109 if (!FromPtrType) { 3110 // This must be a null pointer to member pointer conversion 3111 assert(From->isNullPointerConstant(Context, 3112 Expr::NPC_ValueDependentIsNull) && 3113 "Expr must be null pointer constant!"); 3114 Kind = CK_NullToMemberPointer; 3115 return false; 3116 } 3117 3118 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3119 assert(ToPtrType && "No member pointer cast has a target type " 3120 "that is not a member pointer."); 3121 3122 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3123 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3124 3125 // FIXME: What about dependent types? 3126 assert(FromClass->isRecordType() && "Pointer into non-class."); 3127 assert(ToClass->isRecordType() && "Pointer into non-class."); 3128 3129 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3130 /*DetectVirtual=*/true); 3131 bool DerivationOkay = 3132 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3133 assert(DerivationOkay && 3134 "Should not have been called if derivation isn't OK."); 3135 (void)DerivationOkay; 3136 3137 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3138 getUnqualifiedType())) { 3139 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3140 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3141 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3142 return true; 3143 } 3144 3145 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3146 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3147 << FromClass << ToClass << QualType(VBase, 0) 3148 << From->getSourceRange(); 3149 return true; 3150 } 3151 3152 if (!IgnoreBaseAccess) 3153 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3154 Paths.front(), 3155 diag::err_downcast_from_inaccessible_base); 3156 3157 // Must be a base to derived member conversion. 3158 BuildBasePathArray(Paths, BasePath); 3159 Kind = CK_BaseToDerivedMemberPointer; 3160 return false; 3161 } 3162 3163 /// Determine whether the lifetime conversion between the two given 3164 /// qualifiers sets is nontrivial. 3165 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3166 Qualifiers ToQuals) { 3167 // Converting anything to const __unsafe_unretained is trivial. 3168 if (ToQuals.hasConst() && 3169 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3170 return false; 3171 3172 return true; 3173 } 3174 3175 /// Perform a single iteration of the loop for checking if a qualification 3176 /// conversion is valid. 3177 /// 3178 /// Specifically, check whether any change between the qualifiers of \p 3179 /// FromType and \p ToType is permissible, given knowledge about whether every 3180 /// outer layer is const-qualified. 3181 static bool isQualificationConversionStep(QualType FromType, QualType ToType, 3182 bool CStyle, bool IsTopLevel, 3183 bool &PreviousToQualsIncludeConst, 3184 bool &ObjCLifetimeConversion) { 3185 Qualifiers FromQuals = FromType.getQualifiers(); 3186 Qualifiers ToQuals = ToType.getQualifiers(); 3187 3188 // Ignore __unaligned qualifier if this type is void. 3189 if (ToType.getUnqualifiedType()->isVoidType()) 3190 FromQuals.removeUnaligned(); 3191 3192 // Objective-C ARC: 3193 // Check Objective-C lifetime conversions. 3194 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) { 3195 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3196 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3197 ObjCLifetimeConversion = true; 3198 FromQuals.removeObjCLifetime(); 3199 ToQuals.removeObjCLifetime(); 3200 } else { 3201 // Qualification conversions cannot cast between different 3202 // Objective-C lifetime qualifiers. 3203 return false; 3204 } 3205 } 3206 3207 // Allow addition/removal of GC attributes but not changing GC attributes. 3208 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3209 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3210 FromQuals.removeObjCGCAttr(); 3211 ToQuals.removeObjCGCAttr(); 3212 } 3213 3214 // -- for every j > 0, if const is in cv 1,j then const is in cv 3215 // 2,j, and similarly for volatile. 3216 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3217 return false; 3218 3219 // If address spaces mismatch: 3220 // - in top level it is only valid to convert to addr space that is a 3221 // superset in all cases apart from C-style casts where we allow 3222 // conversions between overlapping address spaces. 3223 // - in non-top levels it is not a valid conversion. 3224 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() && 3225 (!IsTopLevel || 3226 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) || 3227 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals))))) 3228 return false; 3229 3230 // -- if the cv 1,j and cv 2,j are different, then const is in 3231 // every cv for 0 < k < j. 3232 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() && 3233 !PreviousToQualsIncludeConst) 3234 return false; 3235 3236 // Keep track of whether all prior cv-qualifiers in the "to" type 3237 // include const. 3238 PreviousToQualsIncludeConst = 3239 PreviousToQualsIncludeConst && ToQuals.hasConst(); 3240 return true; 3241 } 3242 3243 /// IsQualificationConversion - Determines whether the conversion from 3244 /// an rvalue of type FromType to ToType is a qualification conversion 3245 /// (C++ 4.4). 3246 /// 3247 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3248 /// when the qualification conversion involves a change in the Objective-C 3249 /// object lifetime. 3250 bool 3251 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3252 bool CStyle, bool &ObjCLifetimeConversion) { 3253 FromType = Context.getCanonicalType(FromType); 3254 ToType = Context.getCanonicalType(ToType); 3255 ObjCLifetimeConversion = false; 3256 3257 // If FromType and ToType are the same type, this is not a 3258 // qualification conversion. 3259 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3260 return false; 3261 3262 // (C++ 4.4p4): 3263 // A conversion can add cv-qualifiers at levels other than the first 3264 // in multi-level pointers, subject to the following rules: [...] 3265 bool PreviousToQualsIncludeConst = true; 3266 bool UnwrappedAnyPointer = false; 3267 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3268 if (!isQualificationConversionStep( 3269 FromType, ToType, CStyle, !UnwrappedAnyPointer, 3270 PreviousToQualsIncludeConst, ObjCLifetimeConversion)) 3271 return false; 3272 UnwrappedAnyPointer = true; 3273 } 3274 3275 // We are left with FromType and ToType being the pointee types 3276 // after unwrapping the original FromType and ToType the same number 3277 // of times. If we unwrapped any pointers, and if FromType and 3278 // ToType have the same unqualified type (since we checked 3279 // qualifiers above), then this is a qualification conversion. 3280 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3281 } 3282 3283 /// - Determine whether this is a conversion from a scalar type to an 3284 /// atomic type. 3285 /// 3286 /// If successful, updates \c SCS's second and third steps in the conversion 3287 /// sequence to finish the conversion. 3288 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3289 bool InOverloadResolution, 3290 StandardConversionSequence &SCS, 3291 bool CStyle) { 3292 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3293 if (!ToAtomic) 3294 return false; 3295 3296 StandardConversionSequence InnerSCS; 3297 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3298 InOverloadResolution, InnerSCS, 3299 CStyle, /*AllowObjCWritebackConversion=*/false)) 3300 return false; 3301 3302 SCS.Second = InnerSCS.Second; 3303 SCS.setToType(1, InnerSCS.getToType(1)); 3304 SCS.Third = InnerSCS.Third; 3305 SCS.QualificationIncludesObjCLifetime 3306 = InnerSCS.QualificationIncludesObjCLifetime; 3307 SCS.setToType(2, InnerSCS.getToType(2)); 3308 return true; 3309 } 3310 3311 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3312 CXXConstructorDecl *Constructor, 3313 QualType Type) { 3314 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>(); 3315 if (CtorType->getNumParams() > 0) { 3316 QualType FirstArg = CtorType->getParamType(0); 3317 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3318 return true; 3319 } 3320 return false; 3321 } 3322 3323 static OverloadingResult 3324 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3325 CXXRecordDecl *To, 3326 UserDefinedConversionSequence &User, 3327 OverloadCandidateSet &CandidateSet, 3328 bool AllowExplicit) { 3329 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3330 for (auto *D : S.LookupConstructors(To)) { 3331 auto Info = getConstructorInfo(D); 3332 if (!Info) 3333 continue; 3334 3335 bool Usable = !Info.Constructor->isInvalidDecl() && 3336 S.isInitListConstructor(Info.Constructor); 3337 if (Usable) { 3338 // If the first argument is (a reference to) the target type, 3339 // suppress conversions. 3340 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3341 S.Context, Info.Constructor, ToType); 3342 if (Info.ConstructorTmpl) 3343 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3344 /*ExplicitArgs*/ nullptr, From, 3345 CandidateSet, SuppressUserConversions, 3346 /*PartialOverloading*/ false, 3347 AllowExplicit); 3348 else 3349 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3350 CandidateSet, SuppressUserConversions, 3351 /*PartialOverloading*/ false, AllowExplicit); 3352 } 3353 } 3354 3355 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3356 3357 OverloadCandidateSet::iterator Best; 3358 switch (auto Result = 3359 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3360 case OR_Deleted: 3361 case OR_Success: { 3362 // Record the standard conversion we used and the conversion function. 3363 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3364 QualType ThisType = Constructor->getThisType(); 3365 // Initializer lists don't have conversions as such. 3366 User.Before.setAsIdentityConversion(); 3367 User.HadMultipleCandidates = HadMultipleCandidates; 3368 User.ConversionFunction = Constructor; 3369 User.FoundConversionFunction = Best->FoundDecl; 3370 User.After.setAsIdentityConversion(); 3371 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3372 User.After.setAllToTypes(ToType); 3373 return Result; 3374 } 3375 3376 case OR_No_Viable_Function: 3377 return OR_No_Viable_Function; 3378 case OR_Ambiguous: 3379 return OR_Ambiguous; 3380 } 3381 3382 llvm_unreachable("Invalid OverloadResult!"); 3383 } 3384 3385 /// Determines whether there is a user-defined conversion sequence 3386 /// (C++ [over.ics.user]) that converts expression From to the type 3387 /// ToType. If such a conversion exists, User will contain the 3388 /// user-defined conversion sequence that performs such a conversion 3389 /// and this routine will return true. Otherwise, this routine returns 3390 /// false and User is unspecified. 3391 /// 3392 /// \param AllowExplicit true if the conversion should consider C++0x 3393 /// "explicit" conversion functions as well as non-explicit conversion 3394 /// functions (C++0x [class.conv.fct]p2). 3395 /// 3396 /// \param AllowObjCConversionOnExplicit true if the conversion should 3397 /// allow an extra Objective-C pointer conversion on uses of explicit 3398 /// constructors. Requires \c AllowExplicit to also be set. 3399 static OverloadingResult 3400 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3401 UserDefinedConversionSequence &User, 3402 OverloadCandidateSet &CandidateSet, 3403 AllowedExplicit AllowExplicit, 3404 bool AllowObjCConversionOnExplicit) { 3405 assert(AllowExplicit != AllowedExplicit::None || 3406 !AllowObjCConversionOnExplicit); 3407 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3408 3409 // Whether we will only visit constructors. 3410 bool ConstructorsOnly = false; 3411 3412 // If the type we are conversion to is a class type, enumerate its 3413 // constructors. 3414 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3415 // C++ [over.match.ctor]p1: 3416 // When objects of class type are direct-initialized (8.5), or 3417 // copy-initialized from an expression of the same or a 3418 // derived class type (8.5), overload resolution selects the 3419 // constructor. [...] For copy-initialization, the candidate 3420 // functions are all the converting constructors (12.3.1) of 3421 // that class. The argument list is the expression-list within 3422 // the parentheses of the initializer. 3423 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3424 (From->getType()->getAs<RecordType>() && 3425 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3426 ConstructorsOnly = true; 3427 3428 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3429 // We're not going to find any constructors. 3430 } else if (CXXRecordDecl *ToRecordDecl 3431 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3432 3433 Expr **Args = &From; 3434 unsigned NumArgs = 1; 3435 bool ListInitializing = false; 3436 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3437 // But first, see if there is an init-list-constructor that will work. 3438 OverloadingResult Result = IsInitializerListConstructorConversion( 3439 S, From, ToType, ToRecordDecl, User, CandidateSet, 3440 AllowExplicit == AllowedExplicit::All); 3441 if (Result != OR_No_Viable_Function) 3442 return Result; 3443 // Never mind. 3444 CandidateSet.clear( 3445 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3446 3447 // If we're list-initializing, we pass the individual elements as 3448 // arguments, not the entire list. 3449 Args = InitList->getInits(); 3450 NumArgs = InitList->getNumInits(); 3451 ListInitializing = true; 3452 } 3453 3454 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3455 auto Info = getConstructorInfo(D); 3456 if (!Info) 3457 continue; 3458 3459 bool Usable = !Info.Constructor->isInvalidDecl(); 3460 if (!ListInitializing) 3461 Usable = Usable && Info.Constructor->isConvertingConstructor( 3462 /*AllowExplicit*/ true); 3463 if (Usable) { 3464 bool SuppressUserConversions = !ConstructorsOnly; 3465 if (SuppressUserConversions && ListInitializing) { 3466 SuppressUserConversions = false; 3467 if (NumArgs == 1) { 3468 // If the first argument is (a reference to) the target type, 3469 // suppress conversions. 3470 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3471 S.Context, Info.Constructor, ToType); 3472 } 3473 } 3474 if (Info.ConstructorTmpl) 3475 S.AddTemplateOverloadCandidate( 3476 Info.ConstructorTmpl, Info.FoundDecl, 3477 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3478 CandidateSet, SuppressUserConversions, 3479 /*PartialOverloading*/ false, 3480 AllowExplicit == AllowedExplicit::All); 3481 else 3482 // Allow one user-defined conversion when user specifies a 3483 // From->ToType conversion via an static cast (c-style, etc). 3484 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3485 llvm::makeArrayRef(Args, NumArgs), 3486 CandidateSet, SuppressUserConversions, 3487 /*PartialOverloading*/ false, 3488 AllowExplicit == AllowedExplicit::All); 3489 } 3490 } 3491 } 3492 } 3493 3494 // Enumerate conversion functions, if we're allowed to. 3495 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3496 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3497 // No conversion functions from incomplete types. 3498 } else if (const RecordType *FromRecordType = 3499 From->getType()->getAs<RecordType>()) { 3500 if (CXXRecordDecl *FromRecordDecl 3501 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3502 // Add all of the conversion functions as candidates. 3503 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3504 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3505 DeclAccessPair FoundDecl = I.getPair(); 3506 NamedDecl *D = FoundDecl.getDecl(); 3507 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3508 if (isa<UsingShadowDecl>(D)) 3509 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3510 3511 CXXConversionDecl *Conv; 3512 FunctionTemplateDecl *ConvTemplate; 3513 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3514 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3515 else 3516 Conv = cast<CXXConversionDecl>(D); 3517 3518 if (ConvTemplate) 3519 S.AddTemplateConversionCandidate( 3520 ConvTemplate, FoundDecl, ActingContext, From, ToType, 3521 CandidateSet, AllowObjCConversionOnExplicit, 3522 AllowExplicit != AllowedExplicit::None); 3523 else 3524 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType, 3525 CandidateSet, AllowObjCConversionOnExplicit, 3526 AllowExplicit != AllowedExplicit::None); 3527 } 3528 } 3529 } 3530 3531 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3532 3533 OverloadCandidateSet::iterator Best; 3534 switch (auto Result = 3535 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3536 case OR_Success: 3537 case OR_Deleted: 3538 // Record the standard conversion we used and the conversion function. 3539 if (CXXConstructorDecl *Constructor 3540 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3541 // C++ [over.ics.user]p1: 3542 // If the user-defined conversion is specified by a 3543 // constructor (12.3.1), the initial standard conversion 3544 // sequence converts the source type to the type required by 3545 // the argument of the constructor. 3546 // 3547 QualType ThisType = Constructor->getThisType(); 3548 if (isa<InitListExpr>(From)) { 3549 // Initializer lists don't have conversions as such. 3550 User.Before.setAsIdentityConversion(); 3551 } else { 3552 if (Best->Conversions[0].isEllipsis()) 3553 User.EllipsisConversion = true; 3554 else { 3555 User.Before = Best->Conversions[0].Standard; 3556 User.EllipsisConversion = false; 3557 } 3558 } 3559 User.HadMultipleCandidates = HadMultipleCandidates; 3560 User.ConversionFunction = Constructor; 3561 User.FoundConversionFunction = Best->FoundDecl; 3562 User.After.setAsIdentityConversion(); 3563 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType()); 3564 User.After.setAllToTypes(ToType); 3565 return Result; 3566 } 3567 if (CXXConversionDecl *Conversion 3568 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3569 // C++ [over.ics.user]p1: 3570 // 3571 // [...] If the user-defined conversion is specified by a 3572 // conversion function (12.3.2), the initial standard 3573 // conversion sequence converts the source type to the 3574 // implicit object parameter of the conversion function. 3575 User.Before = Best->Conversions[0].Standard; 3576 User.HadMultipleCandidates = HadMultipleCandidates; 3577 User.ConversionFunction = Conversion; 3578 User.FoundConversionFunction = Best->FoundDecl; 3579 User.EllipsisConversion = false; 3580 3581 // C++ [over.ics.user]p2: 3582 // The second standard conversion sequence converts the 3583 // result of the user-defined conversion to the target type 3584 // for the sequence. Since an implicit conversion sequence 3585 // is an initialization, the special rules for 3586 // initialization by user-defined conversion apply when 3587 // selecting the best user-defined conversion for a 3588 // user-defined conversion sequence (see 13.3.3 and 3589 // 13.3.3.1). 3590 User.After = Best->FinalConversion; 3591 return Result; 3592 } 3593 llvm_unreachable("Not a constructor or conversion function?"); 3594 3595 case OR_No_Viable_Function: 3596 return OR_No_Viable_Function; 3597 3598 case OR_Ambiguous: 3599 return OR_Ambiguous; 3600 } 3601 3602 llvm_unreachable("Invalid OverloadResult!"); 3603 } 3604 3605 bool 3606 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3607 ImplicitConversionSequence ICS; 3608 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3609 OverloadCandidateSet::CSK_Normal); 3610 OverloadingResult OvResult = 3611 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3612 CandidateSet, AllowedExplicit::None, false); 3613 3614 if (!(OvResult == OR_Ambiguous || 3615 (OvResult == OR_No_Viable_Function && !CandidateSet.empty()))) 3616 return false; 3617 3618 auto Cands = CandidateSet.CompleteCandidates( 3619 *this, 3620 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates, 3621 From); 3622 if (OvResult == OR_Ambiguous) 3623 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3624 << From->getType() << ToType << From->getSourceRange(); 3625 else { // OR_No_Viable_Function && !CandidateSet.empty() 3626 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3627 diag::err_typecheck_nonviable_condition_incomplete, 3628 From->getType(), From->getSourceRange())) 3629 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3630 << false << From->getType() << From->getSourceRange() << ToType; 3631 } 3632 3633 CandidateSet.NoteCandidates( 3634 *this, From, Cands); 3635 return true; 3636 } 3637 3638 /// Compare the user-defined conversion functions or constructors 3639 /// of two user-defined conversion sequences to determine whether any ordering 3640 /// is possible. 3641 static ImplicitConversionSequence::CompareKind 3642 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3643 FunctionDecl *Function2) { 3644 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3645 return ImplicitConversionSequence::Indistinguishable; 3646 3647 // Objective-C++: 3648 // If both conversion functions are implicitly-declared conversions from 3649 // a lambda closure type to a function pointer and a block pointer, 3650 // respectively, always prefer the conversion to a function pointer, 3651 // because the function pointer is more lightweight and is more likely 3652 // to keep code working. 3653 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3654 if (!Conv1) 3655 return ImplicitConversionSequence::Indistinguishable; 3656 3657 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3658 if (!Conv2) 3659 return ImplicitConversionSequence::Indistinguishable; 3660 3661 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3662 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3663 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3664 if (Block1 != Block2) 3665 return Block1 ? ImplicitConversionSequence::Worse 3666 : ImplicitConversionSequence::Better; 3667 } 3668 3669 return ImplicitConversionSequence::Indistinguishable; 3670 } 3671 3672 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3673 const ImplicitConversionSequence &ICS) { 3674 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3675 (ICS.isUserDefined() && 3676 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3677 } 3678 3679 /// CompareImplicitConversionSequences - Compare two implicit 3680 /// conversion sequences to determine whether one is better than the 3681 /// other or if they are indistinguishable (C++ 13.3.3.2). 3682 static ImplicitConversionSequence::CompareKind 3683 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3684 const ImplicitConversionSequence& ICS1, 3685 const ImplicitConversionSequence& ICS2) 3686 { 3687 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3688 // conversion sequences (as defined in 13.3.3.1) 3689 // -- a standard conversion sequence (13.3.3.1.1) is a better 3690 // conversion sequence than a user-defined conversion sequence or 3691 // an ellipsis conversion sequence, and 3692 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3693 // conversion sequence than an ellipsis conversion sequence 3694 // (13.3.3.1.3). 3695 // 3696 // C++0x [over.best.ics]p10: 3697 // For the purpose of ranking implicit conversion sequences as 3698 // described in 13.3.3.2, the ambiguous conversion sequence is 3699 // treated as a user-defined sequence that is indistinguishable 3700 // from any other user-defined conversion sequence. 3701 3702 // String literal to 'char *' conversion has been deprecated in C++03. It has 3703 // been removed from C++11. We still accept this conversion, if it happens at 3704 // the best viable function. Otherwise, this conversion is considered worse 3705 // than ellipsis conversion. Consider this as an extension; this is not in the 3706 // standard. For example: 3707 // 3708 // int &f(...); // #1 3709 // void f(char*); // #2 3710 // void g() { int &r = f("foo"); } 3711 // 3712 // In C++03, we pick #2 as the best viable function. 3713 // In C++11, we pick #1 as the best viable function, because ellipsis 3714 // conversion is better than string-literal to char* conversion (since there 3715 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3716 // convert arguments, #2 would be the best viable function in C++11. 3717 // If the best viable function has this conversion, a warning will be issued 3718 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3719 3720 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3721 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3722 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3723 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3724 ? ImplicitConversionSequence::Worse 3725 : ImplicitConversionSequence::Better; 3726 3727 if (ICS1.getKindRank() < ICS2.getKindRank()) 3728 return ImplicitConversionSequence::Better; 3729 if (ICS2.getKindRank() < ICS1.getKindRank()) 3730 return ImplicitConversionSequence::Worse; 3731 3732 // The following checks require both conversion sequences to be of 3733 // the same kind. 3734 if (ICS1.getKind() != ICS2.getKind()) 3735 return ImplicitConversionSequence::Indistinguishable; 3736 3737 ImplicitConversionSequence::CompareKind Result = 3738 ImplicitConversionSequence::Indistinguishable; 3739 3740 // Two implicit conversion sequences of the same form are 3741 // indistinguishable conversion sequences unless one of the 3742 // following rules apply: (C++ 13.3.3.2p3): 3743 3744 // List-initialization sequence L1 is a better conversion sequence than 3745 // list-initialization sequence L2 if: 3746 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3747 // if not that, 3748 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3749 // and N1 is smaller than N2., 3750 // even if one of the other rules in this paragraph would otherwise apply. 3751 if (!ICS1.isBad()) { 3752 if (ICS1.isStdInitializerListElement() && 3753 !ICS2.isStdInitializerListElement()) 3754 return ImplicitConversionSequence::Better; 3755 if (!ICS1.isStdInitializerListElement() && 3756 ICS2.isStdInitializerListElement()) 3757 return ImplicitConversionSequence::Worse; 3758 } 3759 3760 if (ICS1.isStandard()) 3761 // Standard conversion sequence S1 is a better conversion sequence than 3762 // standard conversion sequence S2 if [...] 3763 Result = CompareStandardConversionSequences(S, Loc, 3764 ICS1.Standard, ICS2.Standard); 3765 else if (ICS1.isUserDefined()) { 3766 // User-defined conversion sequence U1 is a better conversion 3767 // sequence than another user-defined conversion sequence U2 if 3768 // they contain the same user-defined conversion function or 3769 // constructor and if the second standard conversion sequence of 3770 // U1 is better than the second standard conversion sequence of 3771 // U2 (C++ 13.3.3.2p3). 3772 if (ICS1.UserDefined.ConversionFunction == 3773 ICS2.UserDefined.ConversionFunction) 3774 Result = CompareStandardConversionSequences(S, Loc, 3775 ICS1.UserDefined.After, 3776 ICS2.UserDefined.After); 3777 else 3778 Result = compareConversionFunctions(S, 3779 ICS1.UserDefined.ConversionFunction, 3780 ICS2.UserDefined.ConversionFunction); 3781 } 3782 3783 return Result; 3784 } 3785 3786 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3787 // determine if one is a proper subset of the other. 3788 static ImplicitConversionSequence::CompareKind 3789 compareStandardConversionSubsets(ASTContext &Context, 3790 const StandardConversionSequence& SCS1, 3791 const StandardConversionSequence& SCS2) { 3792 ImplicitConversionSequence::CompareKind Result 3793 = ImplicitConversionSequence::Indistinguishable; 3794 3795 // the identity conversion sequence is considered to be a subsequence of 3796 // any non-identity conversion sequence 3797 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3798 return ImplicitConversionSequence::Better; 3799 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3800 return ImplicitConversionSequence::Worse; 3801 3802 if (SCS1.Second != SCS2.Second) { 3803 if (SCS1.Second == ICK_Identity) 3804 Result = ImplicitConversionSequence::Better; 3805 else if (SCS2.Second == ICK_Identity) 3806 Result = ImplicitConversionSequence::Worse; 3807 else 3808 return ImplicitConversionSequence::Indistinguishable; 3809 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3810 return ImplicitConversionSequence::Indistinguishable; 3811 3812 if (SCS1.Third == SCS2.Third) { 3813 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3814 : ImplicitConversionSequence::Indistinguishable; 3815 } 3816 3817 if (SCS1.Third == ICK_Identity) 3818 return Result == ImplicitConversionSequence::Worse 3819 ? ImplicitConversionSequence::Indistinguishable 3820 : ImplicitConversionSequence::Better; 3821 3822 if (SCS2.Third == ICK_Identity) 3823 return Result == ImplicitConversionSequence::Better 3824 ? ImplicitConversionSequence::Indistinguishable 3825 : ImplicitConversionSequence::Worse; 3826 3827 return ImplicitConversionSequence::Indistinguishable; 3828 } 3829 3830 /// Determine whether one of the given reference bindings is better 3831 /// than the other based on what kind of bindings they are. 3832 static bool 3833 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3834 const StandardConversionSequence &SCS2) { 3835 // C++0x [over.ics.rank]p3b4: 3836 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3837 // implicit object parameter of a non-static member function declared 3838 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3839 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3840 // lvalue reference to a function lvalue and S2 binds an rvalue 3841 // reference*. 3842 // 3843 // FIXME: Rvalue references. We're going rogue with the above edits, 3844 // because the semantics in the current C++0x working paper (N3225 at the 3845 // time of this writing) break the standard definition of std::forward 3846 // and std::reference_wrapper when dealing with references to functions. 3847 // Proposed wording changes submitted to CWG for consideration. 3848 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3849 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3850 return false; 3851 3852 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3853 SCS2.IsLvalueReference) || 3854 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3855 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3856 } 3857 3858 enum class FixedEnumPromotion { 3859 None, 3860 ToUnderlyingType, 3861 ToPromotedUnderlyingType 3862 }; 3863 3864 /// Returns kind of fixed enum promotion the \a SCS uses. 3865 static FixedEnumPromotion 3866 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) { 3867 3868 if (SCS.Second != ICK_Integral_Promotion) 3869 return FixedEnumPromotion::None; 3870 3871 QualType FromType = SCS.getFromType(); 3872 if (!FromType->isEnumeralType()) 3873 return FixedEnumPromotion::None; 3874 3875 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl(); 3876 if (!Enum->isFixed()) 3877 return FixedEnumPromotion::None; 3878 3879 QualType UnderlyingType = Enum->getIntegerType(); 3880 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType)) 3881 return FixedEnumPromotion::ToUnderlyingType; 3882 3883 return FixedEnumPromotion::ToPromotedUnderlyingType; 3884 } 3885 3886 /// CompareStandardConversionSequences - Compare two standard 3887 /// conversion sequences to determine whether one is better than the 3888 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3889 static ImplicitConversionSequence::CompareKind 3890 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3891 const StandardConversionSequence& SCS1, 3892 const StandardConversionSequence& SCS2) 3893 { 3894 // Standard conversion sequence S1 is a better conversion sequence 3895 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3896 3897 // -- S1 is a proper subsequence of S2 (comparing the conversion 3898 // sequences in the canonical form defined by 13.3.3.1.1, 3899 // excluding any Lvalue Transformation; the identity conversion 3900 // sequence is considered to be a subsequence of any 3901 // non-identity conversion sequence) or, if not that, 3902 if (ImplicitConversionSequence::CompareKind CK 3903 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3904 return CK; 3905 3906 // -- the rank of S1 is better than the rank of S2 (by the rules 3907 // defined below), or, if not that, 3908 ImplicitConversionRank Rank1 = SCS1.getRank(); 3909 ImplicitConversionRank Rank2 = SCS2.getRank(); 3910 if (Rank1 < Rank2) 3911 return ImplicitConversionSequence::Better; 3912 else if (Rank2 < Rank1) 3913 return ImplicitConversionSequence::Worse; 3914 3915 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3916 // are indistinguishable unless one of the following rules 3917 // applies: 3918 3919 // A conversion that is not a conversion of a pointer, or 3920 // pointer to member, to bool is better than another conversion 3921 // that is such a conversion. 3922 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3923 return SCS2.isPointerConversionToBool() 3924 ? ImplicitConversionSequence::Better 3925 : ImplicitConversionSequence::Worse; 3926 3927 // C++14 [over.ics.rank]p4b2: 3928 // This is retroactively applied to C++11 by CWG 1601. 3929 // 3930 // A conversion that promotes an enumeration whose underlying type is fixed 3931 // to its underlying type is better than one that promotes to the promoted 3932 // underlying type, if the two are different. 3933 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1); 3934 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2); 3935 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None && 3936 FEP1 != FEP2) 3937 return FEP1 == FixedEnumPromotion::ToUnderlyingType 3938 ? ImplicitConversionSequence::Better 3939 : ImplicitConversionSequence::Worse; 3940 3941 // C++ [over.ics.rank]p4b2: 3942 // 3943 // If class B is derived directly or indirectly from class A, 3944 // conversion of B* to A* is better than conversion of B* to 3945 // void*, and conversion of A* to void* is better than conversion 3946 // of B* to void*. 3947 bool SCS1ConvertsToVoid 3948 = SCS1.isPointerConversionToVoidPointer(S.Context); 3949 bool SCS2ConvertsToVoid 3950 = SCS2.isPointerConversionToVoidPointer(S.Context); 3951 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3952 // Exactly one of the conversion sequences is a conversion to 3953 // a void pointer; it's the worse conversion. 3954 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3955 : ImplicitConversionSequence::Worse; 3956 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3957 // Neither conversion sequence converts to a void pointer; compare 3958 // their derived-to-base conversions. 3959 if (ImplicitConversionSequence::CompareKind DerivedCK 3960 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3961 return DerivedCK; 3962 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3963 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3964 // Both conversion sequences are conversions to void 3965 // pointers. Compare the source types to determine if there's an 3966 // inheritance relationship in their sources. 3967 QualType FromType1 = SCS1.getFromType(); 3968 QualType FromType2 = SCS2.getFromType(); 3969 3970 // Adjust the types we're converting from via the array-to-pointer 3971 // conversion, if we need to. 3972 if (SCS1.First == ICK_Array_To_Pointer) 3973 FromType1 = S.Context.getArrayDecayedType(FromType1); 3974 if (SCS2.First == ICK_Array_To_Pointer) 3975 FromType2 = S.Context.getArrayDecayedType(FromType2); 3976 3977 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3978 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3979 3980 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3981 return ImplicitConversionSequence::Better; 3982 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3983 return ImplicitConversionSequence::Worse; 3984 3985 // Objective-C++: If one interface is more specific than the 3986 // other, it is the better one. 3987 const ObjCObjectPointerType* FromObjCPtr1 3988 = FromType1->getAs<ObjCObjectPointerType>(); 3989 const ObjCObjectPointerType* FromObjCPtr2 3990 = FromType2->getAs<ObjCObjectPointerType>(); 3991 if (FromObjCPtr1 && FromObjCPtr2) { 3992 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3993 FromObjCPtr2); 3994 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3995 FromObjCPtr1); 3996 if (AssignLeft != AssignRight) { 3997 return AssignLeft? ImplicitConversionSequence::Better 3998 : ImplicitConversionSequence::Worse; 3999 } 4000 } 4001 } 4002 4003 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4004 // Check for a better reference binding based on the kind of bindings. 4005 if (isBetterReferenceBindingKind(SCS1, SCS2)) 4006 return ImplicitConversionSequence::Better; 4007 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 4008 return ImplicitConversionSequence::Worse; 4009 } 4010 4011 // Compare based on qualification conversions (C++ 13.3.3.2p3, 4012 // bullet 3). 4013 if (ImplicitConversionSequence::CompareKind QualCK 4014 = CompareQualificationConversions(S, SCS1, SCS2)) 4015 return QualCK; 4016 4017 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 4018 // C++ [over.ics.rank]p3b4: 4019 // -- S1 and S2 are reference bindings (8.5.3), and the types to 4020 // which the references refer are the same type except for 4021 // top-level cv-qualifiers, and the type to which the reference 4022 // initialized by S2 refers is more cv-qualified than the type 4023 // to which the reference initialized by S1 refers. 4024 QualType T1 = SCS1.getToType(2); 4025 QualType T2 = SCS2.getToType(2); 4026 T1 = S.Context.getCanonicalType(T1); 4027 T2 = S.Context.getCanonicalType(T2); 4028 Qualifiers T1Quals, T2Quals; 4029 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4030 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4031 if (UnqualT1 == UnqualT2) { 4032 // Objective-C++ ARC: If the references refer to objects with different 4033 // lifetimes, prefer bindings that don't change lifetime. 4034 if (SCS1.ObjCLifetimeConversionBinding != 4035 SCS2.ObjCLifetimeConversionBinding) { 4036 return SCS1.ObjCLifetimeConversionBinding 4037 ? ImplicitConversionSequence::Worse 4038 : ImplicitConversionSequence::Better; 4039 } 4040 4041 // If the type is an array type, promote the element qualifiers to the 4042 // type for comparison. 4043 if (isa<ArrayType>(T1) && T1Quals) 4044 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 4045 if (isa<ArrayType>(T2) && T2Quals) 4046 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 4047 if (T2.isMoreQualifiedThan(T1)) 4048 return ImplicitConversionSequence::Better; 4049 if (T1.isMoreQualifiedThan(T2)) 4050 return ImplicitConversionSequence::Worse; 4051 } 4052 } 4053 4054 // In Microsoft mode, prefer an integral conversion to a 4055 // floating-to-integral conversion if the integral conversion 4056 // is between types of the same size. 4057 // For example: 4058 // void f(float); 4059 // void f(int); 4060 // int main { 4061 // long a; 4062 // f(a); 4063 // } 4064 // Here, MSVC will call f(int) instead of generating a compile error 4065 // as clang will do in standard mode. 4066 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 4067 SCS2.Second == ICK_Floating_Integral && 4068 S.Context.getTypeSize(SCS1.getFromType()) == 4069 S.Context.getTypeSize(SCS1.getToType(2))) 4070 return ImplicitConversionSequence::Better; 4071 4072 // Prefer a compatible vector conversion over a lax vector conversion 4073 // For example: 4074 // 4075 // typedef float __v4sf __attribute__((__vector_size__(16))); 4076 // void f(vector float); 4077 // void f(vector signed int); 4078 // int main() { 4079 // __v4sf a; 4080 // f(a); 4081 // } 4082 // Here, we'd like to choose f(vector float) and not 4083 // report an ambiguous call error 4084 if (SCS1.Second == ICK_Vector_Conversion && 4085 SCS2.Second == ICK_Vector_Conversion) { 4086 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4087 SCS1.getFromType(), SCS1.getToType(2)); 4088 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 4089 SCS2.getFromType(), SCS2.getToType(2)); 4090 4091 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 4092 return SCS1IsCompatibleVectorConversion 4093 ? ImplicitConversionSequence::Better 4094 : ImplicitConversionSequence::Worse; 4095 } 4096 4097 return ImplicitConversionSequence::Indistinguishable; 4098 } 4099 4100 /// CompareQualificationConversions - Compares two standard conversion 4101 /// sequences to determine whether they can be ranked based on their 4102 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 4103 static ImplicitConversionSequence::CompareKind 4104 CompareQualificationConversions(Sema &S, 4105 const StandardConversionSequence& SCS1, 4106 const StandardConversionSequence& SCS2) { 4107 // C++ 13.3.3.2p3: 4108 // -- S1 and S2 differ only in their qualification conversion and 4109 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 4110 // cv-qualification signature of type T1 is a proper subset of 4111 // the cv-qualification signature of type T2, and S1 is not the 4112 // deprecated string literal array-to-pointer conversion (4.2). 4113 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 4114 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 4115 return ImplicitConversionSequence::Indistinguishable; 4116 4117 // FIXME: the example in the standard doesn't use a qualification 4118 // conversion (!) 4119 QualType T1 = SCS1.getToType(2); 4120 QualType T2 = SCS2.getToType(2); 4121 T1 = S.Context.getCanonicalType(T1); 4122 T2 = S.Context.getCanonicalType(T2); 4123 assert(!T1->isReferenceType() && !T2->isReferenceType()); 4124 Qualifiers T1Quals, T2Quals; 4125 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 4126 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 4127 4128 // If the types are the same, we won't learn anything by unwrapping 4129 // them. 4130 if (UnqualT1 == UnqualT2) 4131 return ImplicitConversionSequence::Indistinguishable; 4132 4133 ImplicitConversionSequence::CompareKind Result 4134 = ImplicitConversionSequence::Indistinguishable; 4135 4136 // Objective-C++ ARC: 4137 // Prefer qualification conversions not involving a change in lifetime 4138 // to qualification conversions that do not change lifetime. 4139 if (SCS1.QualificationIncludesObjCLifetime != 4140 SCS2.QualificationIncludesObjCLifetime) { 4141 Result = SCS1.QualificationIncludesObjCLifetime 4142 ? ImplicitConversionSequence::Worse 4143 : ImplicitConversionSequence::Better; 4144 } 4145 4146 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4147 // Within each iteration of the loop, we check the qualifiers to 4148 // determine if this still looks like a qualification 4149 // conversion. Then, if all is well, we unwrap one more level of 4150 // pointers or pointers-to-members and do it all again 4151 // until there are no more pointers or pointers-to-members left 4152 // to unwrap. This essentially mimics what 4153 // IsQualificationConversion does, but here we're checking for a 4154 // strict subset of qualifiers. 4155 if (T1.getQualifiers().withoutObjCLifetime() == 4156 T2.getQualifiers().withoutObjCLifetime()) 4157 // The qualifiers are the same, so this doesn't tell us anything 4158 // about how the sequences rank. 4159 // ObjC ownership quals are omitted above as they interfere with 4160 // the ARC overload rule. 4161 ; 4162 else if (T2.isMoreQualifiedThan(T1)) { 4163 // T1 has fewer qualifiers, so it could be the better sequence. 4164 if (Result == ImplicitConversionSequence::Worse) 4165 // Neither has qualifiers that are a subset of the other's 4166 // qualifiers. 4167 return ImplicitConversionSequence::Indistinguishable; 4168 4169 Result = ImplicitConversionSequence::Better; 4170 } else if (T1.isMoreQualifiedThan(T2)) { 4171 // T2 has fewer qualifiers, so it could be the better sequence. 4172 if (Result == ImplicitConversionSequence::Better) 4173 // Neither has qualifiers that are a subset of the other's 4174 // qualifiers. 4175 return ImplicitConversionSequence::Indistinguishable; 4176 4177 Result = ImplicitConversionSequence::Worse; 4178 } else { 4179 // Qualifiers are disjoint. 4180 return ImplicitConversionSequence::Indistinguishable; 4181 } 4182 4183 // If the types after this point are equivalent, we're done. 4184 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4185 break; 4186 } 4187 4188 // Check that the winning standard conversion sequence isn't using 4189 // the deprecated string literal array to pointer conversion. 4190 switch (Result) { 4191 case ImplicitConversionSequence::Better: 4192 if (SCS1.DeprecatedStringLiteralToCharPtr) 4193 Result = ImplicitConversionSequence::Indistinguishable; 4194 break; 4195 4196 case ImplicitConversionSequence::Indistinguishable: 4197 break; 4198 4199 case ImplicitConversionSequence::Worse: 4200 if (SCS2.DeprecatedStringLiteralToCharPtr) 4201 Result = ImplicitConversionSequence::Indistinguishable; 4202 break; 4203 } 4204 4205 return Result; 4206 } 4207 4208 /// CompareDerivedToBaseConversions - Compares two standard conversion 4209 /// sequences to determine whether they can be ranked based on their 4210 /// various kinds of derived-to-base conversions (C++ 4211 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4212 /// conversions between Objective-C interface types. 4213 static ImplicitConversionSequence::CompareKind 4214 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4215 const StandardConversionSequence& SCS1, 4216 const StandardConversionSequence& SCS2) { 4217 QualType FromType1 = SCS1.getFromType(); 4218 QualType ToType1 = SCS1.getToType(1); 4219 QualType FromType2 = SCS2.getFromType(); 4220 QualType ToType2 = SCS2.getToType(1); 4221 4222 // Adjust the types we're converting from via the array-to-pointer 4223 // conversion, if we need to. 4224 if (SCS1.First == ICK_Array_To_Pointer) 4225 FromType1 = S.Context.getArrayDecayedType(FromType1); 4226 if (SCS2.First == ICK_Array_To_Pointer) 4227 FromType2 = S.Context.getArrayDecayedType(FromType2); 4228 4229 // Canonicalize all of the types. 4230 FromType1 = S.Context.getCanonicalType(FromType1); 4231 ToType1 = S.Context.getCanonicalType(ToType1); 4232 FromType2 = S.Context.getCanonicalType(FromType2); 4233 ToType2 = S.Context.getCanonicalType(ToType2); 4234 4235 // C++ [over.ics.rank]p4b3: 4236 // 4237 // If class B is derived directly or indirectly from class A and 4238 // class C is derived directly or indirectly from B, 4239 // 4240 // Compare based on pointer conversions. 4241 if (SCS1.Second == ICK_Pointer_Conversion && 4242 SCS2.Second == ICK_Pointer_Conversion && 4243 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4244 FromType1->isPointerType() && FromType2->isPointerType() && 4245 ToType1->isPointerType() && ToType2->isPointerType()) { 4246 QualType FromPointee1 = 4247 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4248 QualType ToPointee1 = 4249 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4250 QualType FromPointee2 = 4251 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4252 QualType ToPointee2 = 4253 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4254 4255 // -- conversion of C* to B* is better than conversion of C* to A*, 4256 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4257 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4258 return ImplicitConversionSequence::Better; 4259 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4260 return ImplicitConversionSequence::Worse; 4261 } 4262 4263 // -- conversion of B* to A* is better than conversion of C* to A*, 4264 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4265 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4266 return ImplicitConversionSequence::Better; 4267 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4268 return ImplicitConversionSequence::Worse; 4269 } 4270 } else if (SCS1.Second == ICK_Pointer_Conversion && 4271 SCS2.Second == ICK_Pointer_Conversion) { 4272 const ObjCObjectPointerType *FromPtr1 4273 = FromType1->getAs<ObjCObjectPointerType>(); 4274 const ObjCObjectPointerType *FromPtr2 4275 = FromType2->getAs<ObjCObjectPointerType>(); 4276 const ObjCObjectPointerType *ToPtr1 4277 = ToType1->getAs<ObjCObjectPointerType>(); 4278 const ObjCObjectPointerType *ToPtr2 4279 = ToType2->getAs<ObjCObjectPointerType>(); 4280 4281 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4282 // Apply the same conversion ranking rules for Objective-C pointer types 4283 // that we do for C++ pointers to class types. However, we employ the 4284 // Objective-C pseudo-subtyping relationship used for assignment of 4285 // Objective-C pointer types. 4286 bool FromAssignLeft 4287 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4288 bool FromAssignRight 4289 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4290 bool ToAssignLeft 4291 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4292 bool ToAssignRight 4293 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4294 4295 // A conversion to an a non-id object pointer type or qualified 'id' 4296 // type is better than a conversion to 'id'. 4297 if (ToPtr1->isObjCIdType() && 4298 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4299 return ImplicitConversionSequence::Worse; 4300 if (ToPtr2->isObjCIdType() && 4301 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4302 return ImplicitConversionSequence::Better; 4303 4304 // A conversion to a non-id object pointer type is better than a 4305 // conversion to a qualified 'id' type 4306 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4307 return ImplicitConversionSequence::Worse; 4308 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4309 return ImplicitConversionSequence::Better; 4310 4311 // A conversion to an a non-Class object pointer type or qualified 'Class' 4312 // type is better than a conversion to 'Class'. 4313 if (ToPtr1->isObjCClassType() && 4314 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4315 return ImplicitConversionSequence::Worse; 4316 if (ToPtr2->isObjCClassType() && 4317 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4318 return ImplicitConversionSequence::Better; 4319 4320 // A conversion to a non-Class object pointer type is better than a 4321 // conversion to a qualified 'Class' type. 4322 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4323 return ImplicitConversionSequence::Worse; 4324 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4325 return ImplicitConversionSequence::Better; 4326 4327 // -- "conversion of C* to B* is better than conversion of C* to A*," 4328 if (S.Context.hasSameType(FromType1, FromType2) && 4329 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4330 (ToAssignLeft != ToAssignRight)) { 4331 if (FromPtr1->isSpecialized()) { 4332 // "conversion of B<A> * to B * is better than conversion of B * to 4333 // C *. 4334 bool IsFirstSame = 4335 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4336 bool IsSecondSame = 4337 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4338 if (IsFirstSame) { 4339 if (!IsSecondSame) 4340 return ImplicitConversionSequence::Better; 4341 } else if (IsSecondSame) 4342 return ImplicitConversionSequence::Worse; 4343 } 4344 return ToAssignLeft? ImplicitConversionSequence::Worse 4345 : ImplicitConversionSequence::Better; 4346 } 4347 4348 // -- "conversion of B* to A* is better than conversion of C* to A*," 4349 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4350 (FromAssignLeft != FromAssignRight)) 4351 return FromAssignLeft? ImplicitConversionSequence::Better 4352 : ImplicitConversionSequence::Worse; 4353 } 4354 } 4355 4356 // Ranking of member-pointer types. 4357 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4358 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4359 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4360 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>(); 4361 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>(); 4362 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>(); 4363 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>(); 4364 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4365 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4366 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4367 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4368 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4369 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4370 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4371 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4372 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4373 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4374 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4375 return ImplicitConversionSequence::Worse; 4376 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4377 return ImplicitConversionSequence::Better; 4378 } 4379 // conversion of B::* to C::* is better than conversion of A::* to C::* 4380 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4381 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4382 return ImplicitConversionSequence::Better; 4383 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4384 return ImplicitConversionSequence::Worse; 4385 } 4386 } 4387 4388 if (SCS1.Second == ICK_Derived_To_Base) { 4389 // -- conversion of C to B is better than conversion of C to A, 4390 // -- binding of an expression of type C to a reference of type 4391 // B& is better than binding an expression of type C to a 4392 // reference of type A&, 4393 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4394 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4395 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4396 return ImplicitConversionSequence::Better; 4397 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4398 return ImplicitConversionSequence::Worse; 4399 } 4400 4401 // -- conversion of B to A is better than conversion of C to A. 4402 // -- binding of an expression of type B to a reference of type 4403 // A& is better than binding an expression of type C to a 4404 // reference of type A&, 4405 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4406 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4407 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4408 return ImplicitConversionSequence::Better; 4409 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4410 return ImplicitConversionSequence::Worse; 4411 } 4412 } 4413 4414 return ImplicitConversionSequence::Indistinguishable; 4415 } 4416 4417 /// Determine whether the given type is valid, e.g., it is not an invalid 4418 /// C++ class. 4419 static bool isTypeValid(QualType T) { 4420 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4421 return !Record->isInvalidDecl(); 4422 4423 return true; 4424 } 4425 4426 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) { 4427 if (!T.getQualifiers().hasUnaligned()) 4428 return T; 4429 4430 Qualifiers Q; 4431 T = Ctx.getUnqualifiedArrayType(T, Q); 4432 Q.removeUnaligned(); 4433 return Ctx.getQualifiedType(T, Q); 4434 } 4435 4436 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4437 /// determine whether they are reference-compatible, 4438 /// reference-related, or incompatible, for use in C++ initialization by 4439 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4440 /// type, and the first type (T1) is the pointee type of the reference 4441 /// type being initialized. 4442 Sema::ReferenceCompareResult 4443 Sema::CompareReferenceRelationship(SourceLocation Loc, 4444 QualType OrigT1, QualType OrigT2, 4445 ReferenceConversions *ConvOut) { 4446 assert(!OrigT1->isReferenceType() && 4447 "T1 must be the pointee type of the reference type"); 4448 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4449 4450 QualType T1 = Context.getCanonicalType(OrigT1); 4451 QualType T2 = Context.getCanonicalType(OrigT2); 4452 Qualifiers T1Quals, T2Quals; 4453 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4454 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4455 4456 ReferenceConversions ConvTmp; 4457 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp; 4458 Conv = ReferenceConversions(); 4459 4460 // C++2a [dcl.init.ref]p4: 4461 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4462 // reference-related to "cv2 T2" if T1 is similar to T2, or 4463 // T1 is a base class of T2. 4464 // "cv1 T1" is reference-compatible with "cv2 T2" if 4465 // a prvalue of type "pointer to cv2 T2" can be converted to the type 4466 // "pointer to cv1 T1" via a standard conversion sequence. 4467 4468 // Check for standard conversions we can apply to pointers: derived-to-base 4469 // conversions, ObjC pointer conversions, and function pointer conversions. 4470 // (Qualification conversions are checked last.) 4471 QualType ConvertedT2; 4472 if (UnqualT1 == UnqualT2) { 4473 // Nothing to do. 4474 } else if (isCompleteType(Loc, OrigT2) && 4475 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4476 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4477 Conv |= ReferenceConversions::DerivedToBase; 4478 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4479 UnqualT2->isObjCObjectOrInterfaceType() && 4480 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4481 Conv |= ReferenceConversions::ObjC; 4482 else if (UnqualT2->isFunctionType() && 4483 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) { 4484 Conv |= ReferenceConversions::Function; 4485 // No need to check qualifiers; function types don't have them. 4486 return Ref_Compatible; 4487 } 4488 bool ConvertedReferent = Conv != 0; 4489 4490 // We can have a qualification conversion. Compute whether the types are 4491 // similar at the same time. 4492 bool PreviousToQualsIncludeConst = true; 4493 bool TopLevel = true; 4494 do { 4495 if (T1 == T2) 4496 break; 4497 4498 // We will need a qualification conversion. 4499 Conv |= ReferenceConversions::Qualification; 4500 4501 // Track whether we performed a qualification conversion anywhere other 4502 // than the top level. This matters for ranking reference bindings in 4503 // overload resolution. 4504 if (!TopLevel) 4505 Conv |= ReferenceConversions::NestedQualification; 4506 4507 // MS compiler ignores __unaligned qualifier for references; do the same. 4508 T1 = withoutUnaligned(Context, T1); 4509 T2 = withoutUnaligned(Context, T2); 4510 4511 // If we find a qualifier mismatch, the types are not reference-compatible, 4512 // but are still be reference-related if they're similar. 4513 bool ObjCLifetimeConversion = false; 4514 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel, 4515 PreviousToQualsIncludeConst, 4516 ObjCLifetimeConversion)) 4517 return (ConvertedReferent || Context.hasSimilarType(T1, T2)) 4518 ? Ref_Related 4519 : Ref_Incompatible; 4520 4521 // FIXME: Should we track this for any level other than the first? 4522 if (ObjCLifetimeConversion) 4523 Conv |= ReferenceConversions::ObjCLifetime; 4524 4525 TopLevel = false; 4526 } while (Context.UnwrapSimilarTypes(T1, T2)); 4527 4528 // At this point, if the types are reference-related, we must either have the 4529 // same inner type (ignoring qualifiers), or must have already worked out how 4530 // to convert the referent. 4531 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2)) 4532 ? Ref_Compatible 4533 : Ref_Incompatible; 4534 } 4535 4536 /// Look for a user-defined conversion to a value reference-compatible 4537 /// with DeclType. Return true if something definite is found. 4538 static bool 4539 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4540 QualType DeclType, SourceLocation DeclLoc, 4541 Expr *Init, QualType T2, bool AllowRvalues, 4542 bool AllowExplicit) { 4543 assert(T2->isRecordType() && "Can only find conversions of record types."); 4544 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl()); 4545 4546 OverloadCandidateSet CandidateSet( 4547 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4548 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4549 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4550 NamedDecl *D = *I; 4551 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4552 if (isa<UsingShadowDecl>(D)) 4553 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4554 4555 FunctionTemplateDecl *ConvTemplate 4556 = dyn_cast<FunctionTemplateDecl>(D); 4557 CXXConversionDecl *Conv; 4558 if (ConvTemplate) 4559 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4560 else 4561 Conv = cast<CXXConversionDecl>(D); 4562 4563 if (AllowRvalues) { 4564 // If we are initializing an rvalue reference, don't permit conversion 4565 // functions that return lvalues. 4566 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4567 const ReferenceType *RefType 4568 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4569 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4570 continue; 4571 } 4572 4573 if (!ConvTemplate && 4574 S.CompareReferenceRelationship( 4575 DeclLoc, 4576 Conv->getConversionType() 4577 .getNonReferenceType() 4578 .getUnqualifiedType(), 4579 DeclType.getNonReferenceType().getUnqualifiedType()) == 4580 Sema::Ref_Incompatible) 4581 continue; 4582 } else { 4583 // If the conversion function doesn't return a reference type, 4584 // it can't be considered for this conversion. An rvalue reference 4585 // is only acceptable if its referencee is a function type. 4586 4587 const ReferenceType *RefType = 4588 Conv->getConversionType()->getAs<ReferenceType>(); 4589 if (!RefType || 4590 (!RefType->isLValueReferenceType() && 4591 !RefType->getPointeeType()->isFunctionType())) 4592 continue; 4593 } 4594 4595 if (ConvTemplate) 4596 S.AddTemplateConversionCandidate( 4597 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4598 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4599 else 4600 S.AddConversionCandidate( 4601 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet, 4602 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit); 4603 } 4604 4605 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4606 4607 OverloadCandidateSet::iterator Best; 4608 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4609 case OR_Success: 4610 // C++ [over.ics.ref]p1: 4611 // 4612 // [...] If the parameter binds directly to the result of 4613 // applying a conversion function to the argument 4614 // expression, the implicit conversion sequence is a 4615 // user-defined conversion sequence (13.3.3.1.2), with the 4616 // second standard conversion sequence either an identity 4617 // conversion or, if the conversion function returns an 4618 // entity of a type that is a derived class of the parameter 4619 // type, a derived-to-base Conversion. 4620 if (!Best->FinalConversion.DirectBinding) 4621 return false; 4622 4623 ICS.setUserDefined(); 4624 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4625 ICS.UserDefined.After = Best->FinalConversion; 4626 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4627 ICS.UserDefined.ConversionFunction = Best->Function; 4628 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4629 ICS.UserDefined.EllipsisConversion = false; 4630 assert(ICS.UserDefined.After.ReferenceBinding && 4631 ICS.UserDefined.After.DirectBinding && 4632 "Expected a direct reference binding!"); 4633 return true; 4634 4635 case OR_Ambiguous: 4636 ICS.setAmbiguous(); 4637 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4638 Cand != CandidateSet.end(); ++Cand) 4639 if (Cand->Best) 4640 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4641 return true; 4642 4643 case OR_No_Viable_Function: 4644 case OR_Deleted: 4645 // There was no suitable conversion, or we found a deleted 4646 // conversion; continue with other checks. 4647 return false; 4648 } 4649 4650 llvm_unreachable("Invalid OverloadResult!"); 4651 } 4652 4653 /// Compute an implicit conversion sequence for reference 4654 /// initialization. 4655 static ImplicitConversionSequence 4656 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4657 SourceLocation DeclLoc, 4658 bool SuppressUserConversions, 4659 bool AllowExplicit) { 4660 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4661 4662 // Most paths end in a failed conversion. 4663 ImplicitConversionSequence ICS; 4664 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4665 4666 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType(); 4667 QualType T2 = Init->getType(); 4668 4669 // If the initializer is the address of an overloaded function, try 4670 // to resolve the overloaded function. If all goes well, T2 is the 4671 // type of the resulting function. 4672 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4673 DeclAccessPair Found; 4674 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4675 false, Found)) 4676 T2 = Fn->getType(); 4677 } 4678 4679 // Compute some basic properties of the types and the initializer. 4680 bool isRValRef = DeclType->isRValueReferenceType(); 4681 Expr::Classification InitCategory = Init->Classify(S.Context); 4682 4683 Sema::ReferenceConversions RefConv; 4684 Sema::ReferenceCompareResult RefRelationship = 4685 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv); 4686 4687 auto SetAsReferenceBinding = [&](bool BindsDirectly) { 4688 ICS.setStandard(); 4689 ICS.Standard.First = ICK_Identity; 4690 // FIXME: A reference binding can be a function conversion too. We should 4691 // consider that when ordering reference-to-function bindings. 4692 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase) 4693 ? ICK_Derived_To_Base 4694 : (RefConv & Sema::ReferenceConversions::ObjC) 4695 ? ICK_Compatible_Conversion 4696 : ICK_Identity; 4697 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank 4698 // a reference binding that performs a non-top-level qualification 4699 // conversion as a qualification conversion, not as an identity conversion. 4700 ICS.Standard.Third = (RefConv & 4701 Sema::ReferenceConversions::NestedQualification) 4702 ? ICK_Qualification 4703 : ICK_Identity; 4704 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4705 ICS.Standard.setToType(0, T2); 4706 ICS.Standard.setToType(1, T1); 4707 ICS.Standard.setToType(2, T1); 4708 ICS.Standard.ReferenceBinding = true; 4709 ICS.Standard.DirectBinding = BindsDirectly; 4710 ICS.Standard.IsLvalueReference = !isRValRef; 4711 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4712 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4713 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4714 ICS.Standard.ObjCLifetimeConversionBinding = 4715 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0; 4716 ICS.Standard.CopyConstructor = nullptr; 4717 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4718 }; 4719 4720 // C++0x [dcl.init.ref]p5: 4721 // A reference to type "cv1 T1" is initialized by an expression 4722 // of type "cv2 T2" as follows: 4723 4724 // -- If reference is an lvalue reference and the initializer expression 4725 if (!isRValRef) { 4726 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4727 // reference-compatible with "cv2 T2," or 4728 // 4729 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4730 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4731 // C++ [over.ics.ref]p1: 4732 // When a parameter of reference type binds directly (8.5.3) 4733 // to an argument expression, the implicit conversion sequence 4734 // is the identity conversion, unless the argument expression 4735 // has a type that is a derived class of the parameter type, 4736 // in which case the implicit conversion sequence is a 4737 // derived-to-base Conversion (13.3.3.1). 4738 SetAsReferenceBinding(/*BindsDirectly=*/true); 4739 4740 // Nothing more to do: the inaccessibility/ambiguity check for 4741 // derived-to-base conversions is suppressed when we're 4742 // computing the implicit conversion sequence (C++ 4743 // [over.best.ics]p2). 4744 return ICS; 4745 } 4746 4747 // -- has a class type (i.e., T2 is a class type), where T1 is 4748 // not reference-related to T2, and can be implicitly 4749 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4750 // is reference-compatible with "cv3 T3" 92) (this 4751 // conversion is selected by enumerating the applicable 4752 // conversion functions (13.3.1.6) and choosing the best 4753 // one through overload resolution (13.3)), 4754 if (!SuppressUserConversions && T2->isRecordType() && 4755 S.isCompleteType(DeclLoc, T2) && 4756 RefRelationship == Sema::Ref_Incompatible) { 4757 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4758 Init, T2, /*AllowRvalues=*/false, 4759 AllowExplicit)) 4760 return ICS; 4761 } 4762 } 4763 4764 // -- Otherwise, the reference shall be an lvalue reference to a 4765 // non-volatile const type (i.e., cv1 shall be const), or the reference 4766 // shall be an rvalue reference. 4767 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4768 return ICS; 4769 4770 // -- If the initializer expression 4771 // 4772 // -- is an xvalue, class prvalue, array prvalue or function 4773 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4774 if (RefRelationship == Sema::Ref_Compatible && 4775 (InitCategory.isXValue() || 4776 (InitCategory.isPRValue() && 4777 (T2->isRecordType() || T2->isArrayType())) || 4778 (InitCategory.isLValue() && T2->isFunctionType()))) { 4779 // In C++11, this is always a direct binding. In C++98/03, it's a direct 4780 // binding unless we're binding to a class prvalue. 4781 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4782 // allow the use of rvalue references in C++98/03 for the benefit of 4783 // standard library implementors; therefore, we need the xvalue check here. 4784 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 || 4785 !(InitCategory.isPRValue() || T2->isRecordType())); 4786 return ICS; 4787 } 4788 4789 // -- has a class type (i.e., T2 is a class type), where T1 is not 4790 // reference-related to T2, and can be implicitly converted to 4791 // an xvalue, class prvalue, or function lvalue of type 4792 // "cv3 T3", where "cv1 T1" is reference-compatible with 4793 // "cv3 T3", 4794 // 4795 // then the reference is bound to the value of the initializer 4796 // expression in the first case and to the result of the conversion 4797 // in the second case (or, in either case, to an appropriate base 4798 // class subobject). 4799 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4800 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4801 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4802 Init, T2, /*AllowRvalues=*/true, 4803 AllowExplicit)) { 4804 // In the second case, if the reference is an rvalue reference 4805 // and the second standard conversion sequence of the 4806 // user-defined conversion sequence includes an lvalue-to-rvalue 4807 // conversion, the program is ill-formed. 4808 if (ICS.isUserDefined() && isRValRef && 4809 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4810 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4811 4812 return ICS; 4813 } 4814 4815 // A temporary of function type cannot be created; don't even try. 4816 if (T1->isFunctionType()) 4817 return ICS; 4818 4819 // -- Otherwise, a temporary of type "cv1 T1" is created and 4820 // initialized from the initializer expression using the 4821 // rules for a non-reference copy initialization (8.5). The 4822 // reference is then bound to the temporary. If T1 is 4823 // reference-related to T2, cv1 must be the same 4824 // cv-qualification as, or greater cv-qualification than, 4825 // cv2; otherwise, the program is ill-formed. 4826 if (RefRelationship == Sema::Ref_Related) { 4827 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4828 // we would be reference-compatible or reference-compatible with 4829 // added qualification. But that wasn't the case, so the reference 4830 // initialization fails. 4831 // 4832 // Note that we only want to check address spaces and cvr-qualifiers here. 4833 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4834 Qualifiers T1Quals = T1.getQualifiers(); 4835 Qualifiers T2Quals = T2.getQualifiers(); 4836 T1Quals.removeObjCGCAttr(); 4837 T1Quals.removeObjCLifetime(); 4838 T2Quals.removeObjCGCAttr(); 4839 T2Quals.removeObjCLifetime(); 4840 // MS compiler ignores __unaligned qualifier for references; do the same. 4841 T1Quals.removeUnaligned(); 4842 T2Quals.removeUnaligned(); 4843 if (!T1Quals.compatiblyIncludes(T2Quals)) 4844 return ICS; 4845 } 4846 4847 // If at least one of the types is a class type, the types are not 4848 // related, and we aren't allowed any user conversions, the 4849 // reference binding fails. This case is important for breaking 4850 // recursion, since TryImplicitConversion below will attempt to 4851 // create a temporary through the use of a copy constructor. 4852 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4853 (T1->isRecordType() || T2->isRecordType())) 4854 return ICS; 4855 4856 // If T1 is reference-related to T2 and the reference is an rvalue 4857 // reference, the initializer expression shall not be an lvalue. 4858 if (RefRelationship >= Sema::Ref_Related && 4859 isRValRef && Init->Classify(S.Context).isLValue()) 4860 return ICS; 4861 4862 // C++ [over.ics.ref]p2: 4863 // When a parameter of reference type is not bound directly to 4864 // an argument expression, the conversion sequence is the one 4865 // required to convert the argument expression to the 4866 // underlying type of the reference according to 4867 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4868 // to copy-initializing a temporary of the underlying type with 4869 // the argument expression. Any difference in top-level 4870 // cv-qualification is subsumed by the initialization itself 4871 // and does not constitute a conversion. 4872 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4873 AllowedExplicit::None, 4874 /*InOverloadResolution=*/false, 4875 /*CStyle=*/false, 4876 /*AllowObjCWritebackConversion=*/false, 4877 /*AllowObjCConversionOnExplicit=*/false); 4878 4879 // Of course, that's still a reference binding. 4880 if (ICS.isStandard()) { 4881 ICS.Standard.ReferenceBinding = true; 4882 ICS.Standard.IsLvalueReference = !isRValRef; 4883 ICS.Standard.BindsToFunctionLvalue = false; 4884 ICS.Standard.BindsToRvalue = true; 4885 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4886 ICS.Standard.ObjCLifetimeConversionBinding = false; 4887 } else if (ICS.isUserDefined()) { 4888 const ReferenceType *LValRefType = 4889 ICS.UserDefined.ConversionFunction->getReturnType() 4890 ->getAs<LValueReferenceType>(); 4891 4892 // C++ [over.ics.ref]p3: 4893 // Except for an implicit object parameter, for which see 13.3.1, a 4894 // standard conversion sequence cannot be formed if it requires [...] 4895 // binding an rvalue reference to an lvalue other than a function 4896 // lvalue. 4897 // Note that the function case is not possible here. 4898 if (DeclType->isRValueReferenceType() && LValRefType) { 4899 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4900 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4901 // reference to an rvalue! 4902 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4903 return ICS; 4904 } 4905 4906 ICS.UserDefined.After.ReferenceBinding = true; 4907 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4908 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4909 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4910 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4911 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4912 } 4913 4914 return ICS; 4915 } 4916 4917 static ImplicitConversionSequence 4918 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4919 bool SuppressUserConversions, 4920 bool InOverloadResolution, 4921 bool AllowObjCWritebackConversion, 4922 bool AllowExplicit = false); 4923 4924 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4925 /// initializer list From. 4926 static ImplicitConversionSequence 4927 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4928 bool SuppressUserConversions, 4929 bool InOverloadResolution, 4930 bool AllowObjCWritebackConversion) { 4931 // C++11 [over.ics.list]p1: 4932 // When an argument is an initializer list, it is not an expression and 4933 // special rules apply for converting it to a parameter type. 4934 4935 ImplicitConversionSequence Result; 4936 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4937 4938 // We need a complete type for what follows. Incomplete types can never be 4939 // initialized from init lists. 4940 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4941 return Result; 4942 4943 // Per DR1467: 4944 // If the parameter type is a class X and the initializer list has a single 4945 // element of type cv U, where U is X or a class derived from X, the 4946 // implicit conversion sequence is the one required to convert the element 4947 // to the parameter type. 4948 // 4949 // Otherwise, if the parameter type is a character array [... ] 4950 // and the initializer list has a single element that is an 4951 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4952 // implicit conversion sequence is the identity conversion. 4953 if (From->getNumInits() == 1) { 4954 if (ToType->isRecordType()) { 4955 QualType InitType = From->getInit(0)->getType(); 4956 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4957 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4958 return TryCopyInitialization(S, From->getInit(0), ToType, 4959 SuppressUserConversions, 4960 InOverloadResolution, 4961 AllowObjCWritebackConversion); 4962 } 4963 // FIXME: Check the other conditions here: array of character type, 4964 // initializer is a string literal. 4965 if (ToType->isArrayType()) { 4966 InitializedEntity Entity = 4967 InitializedEntity::InitializeParameter(S.Context, ToType, 4968 /*Consumed=*/false); 4969 if (S.CanPerformCopyInitialization(Entity, From)) { 4970 Result.setStandard(); 4971 Result.Standard.setAsIdentityConversion(); 4972 Result.Standard.setFromType(ToType); 4973 Result.Standard.setAllToTypes(ToType); 4974 return Result; 4975 } 4976 } 4977 } 4978 4979 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4980 // C++11 [over.ics.list]p2: 4981 // If the parameter type is std::initializer_list<X> or "array of X" and 4982 // all the elements can be implicitly converted to X, the implicit 4983 // conversion sequence is the worst conversion necessary to convert an 4984 // element of the list to X. 4985 // 4986 // C++14 [over.ics.list]p3: 4987 // Otherwise, if the parameter type is "array of N X", if the initializer 4988 // list has exactly N elements or if it has fewer than N elements and X is 4989 // default-constructible, and if all the elements of the initializer list 4990 // can be implicitly converted to X, the implicit conversion sequence is 4991 // the worst conversion necessary to convert an element of the list to X. 4992 // 4993 // FIXME: We're missing a lot of these checks. 4994 bool toStdInitializerList = false; 4995 QualType X; 4996 if (ToType->isArrayType()) 4997 X = S.Context.getAsArrayType(ToType)->getElementType(); 4998 else 4999 toStdInitializerList = S.isStdInitializerList(ToType, &X); 5000 if (!X.isNull()) { 5001 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 5002 Expr *Init = From->getInit(i); 5003 ImplicitConversionSequence ICS = 5004 TryCopyInitialization(S, Init, X, SuppressUserConversions, 5005 InOverloadResolution, 5006 AllowObjCWritebackConversion); 5007 // If a single element isn't convertible, fail. 5008 if (ICS.isBad()) { 5009 Result = ICS; 5010 break; 5011 } 5012 // Otherwise, look for the worst conversion. 5013 if (Result.isBad() || CompareImplicitConversionSequences( 5014 S, From->getBeginLoc(), ICS, Result) == 5015 ImplicitConversionSequence::Worse) 5016 Result = ICS; 5017 } 5018 5019 // For an empty list, we won't have computed any conversion sequence. 5020 // Introduce the identity conversion sequence. 5021 if (From->getNumInits() == 0) { 5022 Result.setStandard(); 5023 Result.Standard.setAsIdentityConversion(); 5024 Result.Standard.setFromType(ToType); 5025 Result.Standard.setAllToTypes(ToType); 5026 } 5027 5028 Result.setStdInitializerListElement(toStdInitializerList); 5029 return Result; 5030 } 5031 5032 // C++14 [over.ics.list]p4: 5033 // C++11 [over.ics.list]p3: 5034 // Otherwise, if the parameter is a non-aggregate class X and overload 5035 // resolution chooses a single best constructor [...] the implicit 5036 // conversion sequence is a user-defined conversion sequence. If multiple 5037 // constructors are viable but none is better than the others, the 5038 // implicit conversion sequence is a user-defined conversion sequence. 5039 if (ToType->isRecordType() && !ToType->isAggregateType()) { 5040 // This function can deal with initializer lists. 5041 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 5042 AllowedExplicit::None, 5043 InOverloadResolution, /*CStyle=*/false, 5044 AllowObjCWritebackConversion, 5045 /*AllowObjCConversionOnExplicit=*/false); 5046 } 5047 5048 // C++14 [over.ics.list]p5: 5049 // C++11 [over.ics.list]p4: 5050 // Otherwise, if the parameter has an aggregate type which can be 5051 // initialized from the initializer list [...] the implicit conversion 5052 // sequence is a user-defined conversion sequence. 5053 if (ToType->isAggregateType()) { 5054 // Type is an aggregate, argument is an init list. At this point it comes 5055 // down to checking whether the initialization works. 5056 // FIXME: Find out whether this parameter is consumed or not. 5057 InitializedEntity Entity = 5058 InitializedEntity::InitializeParameter(S.Context, ToType, 5059 /*Consumed=*/false); 5060 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity, 5061 From)) { 5062 Result.setUserDefined(); 5063 Result.UserDefined.Before.setAsIdentityConversion(); 5064 // Initializer lists don't have a type. 5065 Result.UserDefined.Before.setFromType(QualType()); 5066 Result.UserDefined.Before.setAllToTypes(QualType()); 5067 5068 Result.UserDefined.After.setAsIdentityConversion(); 5069 Result.UserDefined.After.setFromType(ToType); 5070 Result.UserDefined.After.setAllToTypes(ToType); 5071 Result.UserDefined.ConversionFunction = nullptr; 5072 } 5073 return Result; 5074 } 5075 5076 // C++14 [over.ics.list]p6: 5077 // C++11 [over.ics.list]p5: 5078 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 5079 if (ToType->isReferenceType()) { 5080 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 5081 // mention initializer lists in any way. So we go by what list- 5082 // initialization would do and try to extrapolate from that. 5083 5084 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType(); 5085 5086 // If the initializer list has a single element that is reference-related 5087 // to the parameter type, we initialize the reference from that. 5088 if (From->getNumInits() == 1) { 5089 Expr *Init = From->getInit(0); 5090 5091 QualType T2 = Init->getType(); 5092 5093 // If the initializer is the address of an overloaded function, try 5094 // to resolve the overloaded function. If all goes well, T2 is the 5095 // type of the resulting function. 5096 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 5097 DeclAccessPair Found; 5098 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 5099 Init, ToType, false, Found)) 5100 T2 = Fn->getType(); 5101 } 5102 5103 // Compute some basic properties of the types and the initializer. 5104 Sema::ReferenceCompareResult RefRelationship = 5105 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2); 5106 5107 if (RefRelationship >= Sema::Ref_Related) { 5108 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 5109 SuppressUserConversions, 5110 /*AllowExplicit=*/false); 5111 } 5112 } 5113 5114 // Otherwise, we bind the reference to a temporary created from the 5115 // initializer list. 5116 Result = TryListConversion(S, From, T1, SuppressUserConversions, 5117 InOverloadResolution, 5118 AllowObjCWritebackConversion); 5119 if (Result.isFailure()) 5120 return Result; 5121 assert(!Result.isEllipsis() && 5122 "Sub-initialization cannot result in ellipsis conversion."); 5123 5124 // Can we even bind to a temporary? 5125 if (ToType->isRValueReferenceType() || 5126 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5127 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5128 Result.UserDefined.After; 5129 SCS.ReferenceBinding = true; 5130 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5131 SCS.BindsToRvalue = true; 5132 SCS.BindsToFunctionLvalue = false; 5133 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5134 SCS.ObjCLifetimeConversionBinding = false; 5135 } else 5136 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5137 From, ToType); 5138 return Result; 5139 } 5140 5141 // C++14 [over.ics.list]p7: 5142 // C++11 [over.ics.list]p6: 5143 // Otherwise, if the parameter type is not a class: 5144 if (!ToType->isRecordType()) { 5145 // - if the initializer list has one element that is not itself an 5146 // initializer list, the implicit conversion sequence is the one 5147 // required to convert the element to the parameter type. 5148 unsigned NumInits = From->getNumInits(); 5149 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5150 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5151 SuppressUserConversions, 5152 InOverloadResolution, 5153 AllowObjCWritebackConversion); 5154 // - if the initializer list has no elements, the implicit conversion 5155 // sequence is the identity conversion. 5156 else if (NumInits == 0) { 5157 Result.setStandard(); 5158 Result.Standard.setAsIdentityConversion(); 5159 Result.Standard.setFromType(ToType); 5160 Result.Standard.setAllToTypes(ToType); 5161 } 5162 return Result; 5163 } 5164 5165 // C++14 [over.ics.list]p8: 5166 // C++11 [over.ics.list]p7: 5167 // In all cases other than those enumerated above, no conversion is possible 5168 return Result; 5169 } 5170 5171 /// TryCopyInitialization - Try to copy-initialize a value of type 5172 /// ToType from the expression From. Return the implicit conversion 5173 /// sequence required to pass this argument, which may be a bad 5174 /// conversion sequence (meaning that the argument cannot be passed to 5175 /// a parameter of this type). If @p SuppressUserConversions, then we 5176 /// do not permit any user-defined conversion sequences. 5177 static ImplicitConversionSequence 5178 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5179 bool SuppressUserConversions, 5180 bool InOverloadResolution, 5181 bool AllowObjCWritebackConversion, 5182 bool AllowExplicit) { 5183 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5184 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5185 InOverloadResolution,AllowObjCWritebackConversion); 5186 5187 if (ToType->isReferenceType()) 5188 return TryReferenceInit(S, From, ToType, 5189 /*FIXME:*/ From->getBeginLoc(), 5190 SuppressUserConversions, AllowExplicit); 5191 5192 return TryImplicitConversion(S, From, ToType, 5193 SuppressUserConversions, 5194 AllowedExplicit::None, 5195 InOverloadResolution, 5196 /*CStyle=*/false, 5197 AllowObjCWritebackConversion, 5198 /*AllowObjCConversionOnExplicit=*/false); 5199 } 5200 5201 static bool TryCopyInitialization(const CanQualType FromQTy, 5202 const CanQualType ToQTy, 5203 Sema &S, 5204 SourceLocation Loc, 5205 ExprValueKind FromVK) { 5206 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5207 ImplicitConversionSequence ICS = 5208 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5209 5210 return !ICS.isBad(); 5211 } 5212 5213 /// TryObjectArgumentInitialization - Try to initialize the object 5214 /// parameter of the given member function (@c Method) from the 5215 /// expression @p From. 5216 static ImplicitConversionSequence 5217 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5218 Expr::Classification FromClassification, 5219 CXXMethodDecl *Method, 5220 CXXRecordDecl *ActingContext) { 5221 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5222 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5223 // const volatile object. 5224 Qualifiers Quals = Method->getMethodQualifiers(); 5225 if (isa<CXXDestructorDecl>(Method)) { 5226 Quals.addConst(); 5227 Quals.addVolatile(); 5228 } 5229 5230 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5231 5232 // Set up the conversion sequence as a "bad" conversion, to allow us 5233 // to exit early. 5234 ImplicitConversionSequence ICS; 5235 5236 // We need to have an object of class type. 5237 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5238 FromType = PT->getPointeeType(); 5239 5240 // When we had a pointer, it's implicitly dereferenced, so we 5241 // better have an lvalue. 5242 assert(FromClassification.isLValue()); 5243 } 5244 5245 assert(FromType->isRecordType()); 5246 5247 // C++0x [over.match.funcs]p4: 5248 // For non-static member functions, the type of the implicit object 5249 // parameter is 5250 // 5251 // - "lvalue reference to cv X" for functions declared without a 5252 // ref-qualifier or with the & ref-qualifier 5253 // - "rvalue reference to cv X" for functions declared with the && 5254 // ref-qualifier 5255 // 5256 // where X is the class of which the function is a member and cv is the 5257 // cv-qualification on the member function declaration. 5258 // 5259 // However, when finding an implicit conversion sequence for the argument, we 5260 // are not allowed to perform user-defined conversions 5261 // (C++ [over.match.funcs]p5). We perform a simplified version of 5262 // reference binding here, that allows class rvalues to bind to 5263 // non-constant references. 5264 5265 // First check the qualifiers. 5266 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5267 if (ImplicitParamType.getCVRQualifiers() 5268 != FromTypeCanon.getLocalCVRQualifiers() && 5269 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5270 ICS.setBad(BadConversionSequence::bad_qualifiers, 5271 FromType, ImplicitParamType); 5272 return ICS; 5273 } 5274 5275 if (FromTypeCanon.hasAddressSpace()) { 5276 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5277 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5278 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5279 ICS.setBad(BadConversionSequence::bad_qualifiers, 5280 FromType, ImplicitParamType); 5281 return ICS; 5282 } 5283 } 5284 5285 // Check that we have either the same type or a derived type. It 5286 // affects the conversion rank. 5287 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5288 ImplicitConversionKind SecondKind; 5289 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5290 SecondKind = ICK_Identity; 5291 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5292 SecondKind = ICK_Derived_To_Base; 5293 else { 5294 ICS.setBad(BadConversionSequence::unrelated_class, 5295 FromType, ImplicitParamType); 5296 return ICS; 5297 } 5298 5299 // Check the ref-qualifier. 5300 switch (Method->getRefQualifier()) { 5301 case RQ_None: 5302 // Do nothing; we don't care about lvalueness or rvalueness. 5303 break; 5304 5305 case RQ_LValue: 5306 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5307 // non-const lvalue reference cannot bind to an rvalue 5308 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5309 ImplicitParamType); 5310 return ICS; 5311 } 5312 break; 5313 5314 case RQ_RValue: 5315 if (!FromClassification.isRValue()) { 5316 // rvalue reference cannot bind to an lvalue 5317 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5318 ImplicitParamType); 5319 return ICS; 5320 } 5321 break; 5322 } 5323 5324 // Success. Mark this as a reference binding. 5325 ICS.setStandard(); 5326 ICS.Standard.setAsIdentityConversion(); 5327 ICS.Standard.Second = SecondKind; 5328 ICS.Standard.setFromType(FromType); 5329 ICS.Standard.setAllToTypes(ImplicitParamType); 5330 ICS.Standard.ReferenceBinding = true; 5331 ICS.Standard.DirectBinding = true; 5332 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5333 ICS.Standard.BindsToFunctionLvalue = false; 5334 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5335 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5336 = (Method->getRefQualifier() == RQ_None); 5337 return ICS; 5338 } 5339 5340 /// PerformObjectArgumentInitialization - Perform initialization of 5341 /// the implicit object parameter for the given Method with the given 5342 /// expression. 5343 ExprResult 5344 Sema::PerformObjectArgumentInitialization(Expr *From, 5345 NestedNameSpecifier *Qualifier, 5346 NamedDecl *FoundDecl, 5347 CXXMethodDecl *Method) { 5348 QualType FromRecordType, DestType; 5349 QualType ImplicitParamRecordType = 5350 Method->getThisType()->castAs<PointerType>()->getPointeeType(); 5351 5352 Expr::Classification FromClassification; 5353 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5354 FromRecordType = PT->getPointeeType(); 5355 DestType = Method->getThisType(); 5356 FromClassification = Expr::Classification::makeSimpleLValue(); 5357 } else { 5358 FromRecordType = From->getType(); 5359 DestType = ImplicitParamRecordType; 5360 FromClassification = From->Classify(Context); 5361 5362 // When performing member access on an rvalue, materialize a temporary. 5363 if (From->isRValue()) { 5364 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5365 Method->getRefQualifier() != 5366 RefQualifierKind::RQ_RValue); 5367 } 5368 } 5369 5370 // Note that we always use the true parent context when performing 5371 // the actual argument initialization. 5372 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5373 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5374 Method->getParent()); 5375 if (ICS.isBad()) { 5376 switch (ICS.Bad.Kind) { 5377 case BadConversionSequence::bad_qualifiers: { 5378 Qualifiers FromQs = FromRecordType.getQualifiers(); 5379 Qualifiers ToQs = DestType.getQualifiers(); 5380 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5381 if (CVR) { 5382 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5383 << Method->getDeclName() << FromRecordType << (CVR - 1) 5384 << From->getSourceRange(); 5385 Diag(Method->getLocation(), diag::note_previous_decl) 5386 << Method->getDeclName(); 5387 return ExprError(); 5388 } 5389 break; 5390 } 5391 5392 case BadConversionSequence::lvalue_ref_to_rvalue: 5393 case BadConversionSequence::rvalue_ref_to_lvalue: { 5394 bool IsRValueQualified = 5395 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5396 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5397 << Method->getDeclName() << FromClassification.isRValue() 5398 << IsRValueQualified; 5399 Diag(Method->getLocation(), diag::note_previous_decl) 5400 << Method->getDeclName(); 5401 return ExprError(); 5402 } 5403 5404 case BadConversionSequence::no_conversion: 5405 case BadConversionSequence::unrelated_class: 5406 break; 5407 } 5408 5409 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5410 << ImplicitParamRecordType << FromRecordType 5411 << From->getSourceRange(); 5412 } 5413 5414 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5415 ExprResult FromRes = 5416 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5417 if (FromRes.isInvalid()) 5418 return ExprError(); 5419 From = FromRes.get(); 5420 } 5421 5422 if (!Context.hasSameType(From->getType(), DestType)) { 5423 CastKind CK; 5424 QualType PteeTy = DestType->getPointeeType(); 5425 LangAS DestAS = 5426 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace(); 5427 if (FromRecordType.getAddressSpace() != DestAS) 5428 CK = CK_AddressSpaceConversion; 5429 else 5430 CK = CK_NoOp; 5431 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get(); 5432 } 5433 return From; 5434 } 5435 5436 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5437 /// expression From to bool (C++0x [conv]p3). 5438 static ImplicitConversionSequence 5439 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5440 // C++ [dcl.init]/17.8: 5441 // - Otherwise, if the initialization is direct-initialization, the source 5442 // type is std::nullptr_t, and the destination type is bool, the initial 5443 // value of the object being initialized is false. 5444 if (From->getType()->isNullPtrType()) 5445 return ImplicitConversionSequence::getNullptrToBool(From->getType(), 5446 S.Context.BoolTy, 5447 From->isGLValue()); 5448 5449 // All other direct-initialization of bool is equivalent to an implicit 5450 // conversion to bool in which explicit conversions are permitted. 5451 return TryImplicitConversion(S, From, S.Context.BoolTy, 5452 /*SuppressUserConversions=*/false, 5453 AllowedExplicit::Conversions, 5454 /*InOverloadResolution=*/false, 5455 /*CStyle=*/false, 5456 /*AllowObjCWritebackConversion=*/false, 5457 /*AllowObjCConversionOnExplicit=*/false); 5458 } 5459 5460 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5461 /// of the expression From to bool (C++0x [conv]p3). 5462 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5463 if (checkPlaceholderForOverload(*this, From)) 5464 return ExprError(); 5465 5466 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5467 if (!ICS.isBad()) 5468 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5469 5470 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5471 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5472 << From->getType() << From->getSourceRange(); 5473 return ExprError(); 5474 } 5475 5476 /// Check that the specified conversion is permitted in a converted constant 5477 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5478 /// is acceptable. 5479 static bool CheckConvertedConstantConversions(Sema &S, 5480 StandardConversionSequence &SCS) { 5481 // Since we know that the target type is an integral or unscoped enumeration 5482 // type, most conversion kinds are impossible. All possible First and Third 5483 // conversions are fine. 5484 switch (SCS.Second) { 5485 case ICK_Identity: 5486 case ICK_Function_Conversion: 5487 case ICK_Integral_Promotion: 5488 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5489 case ICK_Zero_Queue_Conversion: 5490 return true; 5491 5492 case ICK_Boolean_Conversion: 5493 // Conversion from an integral or unscoped enumeration type to bool is 5494 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5495 // conversion, so we allow it in a converted constant expression. 5496 // 5497 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5498 // a lot of popular code. We should at least add a warning for this 5499 // (non-conforming) extension. 5500 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5501 SCS.getToType(2)->isBooleanType(); 5502 5503 case ICK_Pointer_Conversion: 5504 case ICK_Pointer_Member: 5505 // C++1z: null pointer conversions and null member pointer conversions are 5506 // only permitted if the source type is std::nullptr_t. 5507 return SCS.getFromType()->isNullPtrType(); 5508 5509 case ICK_Floating_Promotion: 5510 case ICK_Complex_Promotion: 5511 case ICK_Floating_Conversion: 5512 case ICK_Complex_Conversion: 5513 case ICK_Floating_Integral: 5514 case ICK_Compatible_Conversion: 5515 case ICK_Derived_To_Base: 5516 case ICK_Vector_Conversion: 5517 case ICK_Vector_Splat: 5518 case ICK_Complex_Real: 5519 case ICK_Block_Pointer_Conversion: 5520 case ICK_TransparentUnionConversion: 5521 case ICK_Writeback_Conversion: 5522 case ICK_Zero_Event_Conversion: 5523 case ICK_C_Only_Conversion: 5524 case ICK_Incompatible_Pointer_Conversion: 5525 return false; 5526 5527 case ICK_Lvalue_To_Rvalue: 5528 case ICK_Array_To_Pointer: 5529 case ICK_Function_To_Pointer: 5530 llvm_unreachable("found a first conversion kind in Second"); 5531 5532 case ICK_Qualification: 5533 llvm_unreachable("found a third conversion kind in Second"); 5534 5535 case ICK_Num_Conversion_Kinds: 5536 break; 5537 } 5538 5539 llvm_unreachable("unknown conversion kind"); 5540 } 5541 5542 /// CheckConvertedConstantExpression - Check that the expression From is a 5543 /// converted constant expression of type T, perform the conversion and produce 5544 /// the converted expression, per C++11 [expr.const]p3. 5545 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5546 QualType T, APValue &Value, 5547 Sema::CCEKind CCE, 5548 bool RequireInt) { 5549 assert(S.getLangOpts().CPlusPlus11 && 5550 "converted constant expression outside C++11"); 5551 5552 if (checkPlaceholderForOverload(S, From)) 5553 return ExprError(); 5554 5555 // C++1z [expr.const]p3: 5556 // A converted constant expression of type T is an expression, 5557 // implicitly converted to type T, where the converted 5558 // expression is a constant expression and the implicit conversion 5559 // sequence contains only [... list of conversions ...]. 5560 // C++1z [stmt.if]p2: 5561 // If the if statement is of the form if constexpr, the value of the 5562 // condition shall be a contextually converted constant expression of type 5563 // bool. 5564 ImplicitConversionSequence ICS = 5565 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool 5566 ? TryContextuallyConvertToBool(S, From) 5567 : TryCopyInitialization(S, From, T, 5568 /*SuppressUserConversions=*/false, 5569 /*InOverloadResolution=*/false, 5570 /*AllowObjCWritebackConversion=*/false, 5571 /*AllowExplicit=*/false); 5572 StandardConversionSequence *SCS = nullptr; 5573 switch (ICS.getKind()) { 5574 case ImplicitConversionSequence::StandardConversion: 5575 SCS = &ICS.Standard; 5576 break; 5577 case ImplicitConversionSequence::UserDefinedConversion: 5578 // We are converting to a non-class type, so the Before sequence 5579 // must be trivial. 5580 SCS = &ICS.UserDefined.After; 5581 break; 5582 case ImplicitConversionSequence::AmbiguousConversion: 5583 case ImplicitConversionSequence::BadConversion: 5584 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5585 return S.Diag(From->getBeginLoc(), 5586 diag::err_typecheck_converted_constant_expression) 5587 << From->getType() << From->getSourceRange() << T; 5588 return ExprError(); 5589 5590 case ImplicitConversionSequence::EllipsisConversion: 5591 llvm_unreachable("ellipsis conversion in converted constant expression"); 5592 } 5593 5594 // Check that we would only use permitted conversions. 5595 if (!CheckConvertedConstantConversions(S, *SCS)) { 5596 return S.Diag(From->getBeginLoc(), 5597 diag::err_typecheck_converted_constant_expression_disallowed) 5598 << From->getType() << From->getSourceRange() << T; 5599 } 5600 // [...] and where the reference binding (if any) binds directly. 5601 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5602 return S.Diag(From->getBeginLoc(), 5603 diag::err_typecheck_converted_constant_expression_indirect) 5604 << From->getType() << From->getSourceRange() << T; 5605 } 5606 5607 ExprResult Result = 5608 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5609 if (Result.isInvalid()) 5610 return Result; 5611 5612 // C++2a [intro.execution]p5: 5613 // A full-expression is [...] a constant-expression [...] 5614 Result = 5615 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(), 5616 /*DiscardedValue=*/false, /*IsConstexpr=*/true); 5617 if (Result.isInvalid()) 5618 return Result; 5619 5620 // Check for a narrowing implicit conversion. 5621 APValue PreNarrowingValue; 5622 QualType PreNarrowingType; 5623 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5624 PreNarrowingType)) { 5625 case NK_Dependent_Narrowing: 5626 // Implicit conversion to a narrower type, but the expression is 5627 // value-dependent so we can't tell whether it's actually narrowing. 5628 case NK_Variable_Narrowing: 5629 // Implicit conversion to a narrower type, and the value is not a constant 5630 // expression. We'll diagnose this in a moment. 5631 case NK_Not_Narrowing: 5632 break; 5633 5634 case NK_Constant_Narrowing: 5635 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5636 << CCE << /*Constant*/ 1 5637 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5638 break; 5639 5640 case NK_Type_Narrowing: 5641 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5642 << CCE << /*Constant*/ 0 << From->getType() << T; 5643 break; 5644 } 5645 5646 if (Result.get()->isValueDependent()) { 5647 Value = APValue(); 5648 return Result; 5649 } 5650 5651 // Check the expression is a constant expression. 5652 SmallVector<PartialDiagnosticAt, 8> Notes; 5653 Expr::EvalResult Eval; 5654 Eval.Diag = &Notes; 5655 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5656 ? Expr::EvaluateForMangling 5657 : Expr::EvaluateForCodeGen; 5658 5659 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5660 (RequireInt && !Eval.Val.isInt())) { 5661 // The expression can't be folded, so we can't keep it at this position in 5662 // the AST. 5663 Result = ExprError(); 5664 } else { 5665 Value = Eval.Val; 5666 5667 if (Notes.empty()) { 5668 // It's a constant expression. 5669 return ConstantExpr::Create(S.Context, Result.get(), Value); 5670 } 5671 } 5672 5673 // It's not a constant expression. Produce an appropriate diagnostic. 5674 if (Notes.size() == 1 && 5675 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5676 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5677 else { 5678 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5679 << CCE << From->getSourceRange(); 5680 for (unsigned I = 0; I < Notes.size(); ++I) 5681 S.Diag(Notes[I].first, Notes[I].second); 5682 } 5683 return ExprError(); 5684 } 5685 5686 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5687 APValue &Value, CCEKind CCE) { 5688 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5689 } 5690 5691 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5692 llvm::APSInt &Value, 5693 CCEKind CCE) { 5694 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5695 5696 APValue V; 5697 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5698 if (!R.isInvalid() && !R.get()->isValueDependent()) 5699 Value = V.getInt(); 5700 return R; 5701 } 5702 5703 5704 /// dropPointerConversions - If the given standard conversion sequence 5705 /// involves any pointer conversions, remove them. This may change 5706 /// the result type of the conversion sequence. 5707 static void dropPointerConversion(StandardConversionSequence &SCS) { 5708 if (SCS.Second == ICK_Pointer_Conversion) { 5709 SCS.Second = ICK_Identity; 5710 SCS.Third = ICK_Identity; 5711 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5712 } 5713 } 5714 5715 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5716 /// convert the expression From to an Objective-C pointer type. 5717 static ImplicitConversionSequence 5718 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5719 // Do an implicit conversion to 'id'. 5720 QualType Ty = S.Context.getObjCIdType(); 5721 ImplicitConversionSequence ICS 5722 = TryImplicitConversion(S, From, Ty, 5723 // FIXME: Are these flags correct? 5724 /*SuppressUserConversions=*/false, 5725 AllowedExplicit::Conversions, 5726 /*InOverloadResolution=*/false, 5727 /*CStyle=*/false, 5728 /*AllowObjCWritebackConversion=*/false, 5729 /*AllowObjCConversionOnExplicit=*/true); 5730 5731 // Strip off any final conversions to 'id'. 5732 switch (ICS.getKind()) { 5733 case ImplicitConversionSequence::BadConversion: 5734 case ImplicitConversionSequence::AmbiguousConversion: 5735 case ImplicitConversionSequence::EllipsisConversion: 5736 break; 5737 5738 case ImplicitConversionSequence::UserDefinedConversion: 5739 dropPointerConversion(ICS.UserDefined.After); 5740 break; 5741 5742 case ImplicitConversionSequence::StandardConversion: 5743 dropPointerConversion(ICS.Standard); 5744 break; 5745 } 5746 5747 return ICS; 5748 } 5749 5750 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5751 /// conversion of the expression From to an Objective-C pointer type. 5752 /// Returns a valid but null ExprResult if no conversion sequence exists. 5753 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5754 if (checkPlaceholderForOverload(*this, From)) 5755 return ExprError(); 5756 5757 QualType Ty = Context.getObjCIdType(); 5758 ImplicitConversionSequence ICS = 5759 TryContextuallyConvertToObjCPointer(*this, From); 5760 if (!ICS.isBad()) 5761 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5762 return ExprResult(); 5763 } 5764 5765 /// Determine whether the provided type is an integral type, or an enumeration 5766 /// type of a permitted flavor. 5767 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5768 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5769 : T->isIntegralOrUnscopedEnumerationType(); 5770 } 5771 5772 static ExprResult 5773 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5774 Sema::ContextualImplicitConverter &Converter, 5775 QualType T, UnresolvedSetImpl &ViableConversions) { 5776 5777 if (Converter.Suppress) 5778 return ExprError(); 5779 5780 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5781 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5782 CXXConversionDecl *Conv = 5783 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5784 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5785 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5786 } 5787 return From; 5788 } 5789 5790 static bool 5791 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5792 Sema::ContextualImplicitConverter &Converter, 5793 QualType T, bool HadMultipleCandidates, 5794 UnresolvedSetImpl &ExplicitConversions) { 5795 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5796 DeclAccessPair Found = ExplicitConversions[0]; 5797 CXXConversionDecl *Conversion = 5798 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5799 5800 // The user probably meant to invoke the given explicit 5801 // conversion; use it. 5802 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5803 std::string TypeStr; 5804 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5805 5806 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5807 << FixItHint::CreateInsertion(From->getBeginLoc(), 5808 "static_cast<" + TypeStr + ">(") 5809 << FixItHint::CreateInsertion( 5810 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5811 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5812 5813 // If we aren't in a SFINAE context, build a call to the 5814 // explicit conversion function. 5815 if (SemaRef.isSFINAEContext()) 5816 return true; 5817 5818 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5819 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5820 HadMultipleCandidates); 5821 if (Result.isInvalid()) 5822 return true; 5823 // Record usage of conversion in an implicit cast. 5824 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5825 CK_UserDefinedConversion, Result.get(), 5826 nullptr, Result.get()->getValueKind()); 5827 } 5828 return false; 5829 } 5830 5831 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5832 Sema::ContextualImplicitConverter &Converter, 5833 QualType T, bool HadMultipleCandidates, 5834 DeclAccessPair &Found) { 5835 CXXConversionDecl *Conversion = 5836 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5837 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5838 5839 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5840 if (!Converter.SuppressConversion) { 5841 if (SemaRef.isSFINAEContext()) 5842 return true; 5843 5844 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5845 << From->getSourceRange(); 5846 } 5847 5848 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5849 HadMultipleCandidates); 5850 if (Result.isInvalid()) 5851 return true; 5852 // Record usage of conversion in an implicit cast. 5853 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5854 CK_UserDefinedConversion, Result.get(), 5855 nullptr, Result.get()->getValueKind()); 5856 return false; 5857 } 5858 5859 static ExprResult finishContextualImplicitConversion( 5860 Sema &SemaRef, SourceLocation Loc, Expr *From, 5861 Sema::ContextualImplicitConverter &Converter) { 5862 if (!Converter.match(From->getType()) && !Converter.Suppress) 5863 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5864 << From->getSourceRange(); 5865 5866 return SemaRef.DefaultLvalueConversion(From); 5867 } 5868 5869 static void 5870 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5871 UnresolvedSetImpl &ViableConversions, 5872 OverloadCandidateSet &CandidateSet) { 5873 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5874 DeclAccessPair FoundDecl = ViableConversions[I]; 5875 NamedDecl *D = FoundDecl.getDecl(); 5876 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5877 if (isa<UsingShadowDecl>(D)) 5878 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5879 5880 CXXConversionDecl *Conv; 5881 FunctionTemplateDecl *ConvTemplate; 5882 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5883 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5884 else 5885 Conv = cast<CXXConversionDecl>(D); 5886 5887 if (ConvTemplate) 5888 SemaRef.AddTemplateConversionCandidate( 5889 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5890 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true); 5891 else 5892 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5893 ToType, CandidateSet, 5894 /*AllowObjCConversionOnExplicit=*/false, 5895 /*AllowExplicit*/ true); 5896 } 5897 } 5898 5899 /// Attempt to convert the given expression to a type which is accepted 5900 /// by the given converter. 5901 /// 5902 /// This routine will attempt to convert an expression of class type to a 5903 /// type accepted by the specified converter. In C++11 and before, the class 5904 /// must have a single non-explicit conversion function converting to a matching 5905 /// type. In C++1y, there can be multiple such conversion functions, but only 5906 /// one target type. 5907 /// 5908 /// \param Loc The source location of the construct that requires the 5909 /// conversion. 5910 /// 5911 /// \param From The expression we're converting from. 5912 /// 5913 /// \param Converter Used to control and diagnose the conversion process. 5914 /// 5915 /// \returns The expression, converted to an integral or enumeration type if 5916 /// successful. 5917 ExprResult Sema::PerformContextualImplicitConversion( 5918 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5919 // We can't perform any more checking for type-dependent expressions. 5920 if (From->isTypeDependent()) 5921 return From; 5922 5923 // Process placeholders immediately. 5924 if (From->hasPlaceholderType()) { 5925 ExprResult result = CheckPlaceholderExpr(From); 5926 if (result.isInvalid()) 5927 return result; 5928 From = result.get(); 5929 } 5930 5931 // If the expression already has a matching type, we're golden. 5932 QualType T = From->getType(); 5933 if (Converter.match(T)) 5934 return DefaultLvalueConversion(From); 5935 5936 // FIXME: Check for missing '()' if T is a function type? 5937 5938 // We can only perform contextual implicit conversions on objects of class 5939 // type. 5940 const RecordType *RecordTy = T->getAs<RecordType>(); 5941 if (!RecordTy || !getLangOpts().CPlusPlus) { 5942 if (!Converter.Suppress) 5943 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5944 return From; 5945 } 5946 5947 // We must have a complete class type. 5948 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5949 ContextualImplicitConverter &Converter; 5950 Expr *From; 5951 5952 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5953 : Converter(Converter), From(From) {} 5954 5955 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5956 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5957 } 5958 } IncompleteDiagnoser(Converter, From); 5959 5960 if (Converter.Suppress ? !isCompleteType(Loc, T) 5961 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5962 return From; 5963 5964 // Look for a conversion to an integral or enumeration type. 5965 UnresolvedSet<4> 5966 ViableConversions; // These are *potentially* viable in C++1y. 5967 UnresolvedSet<4> ExplicitConversions; 5968 const auto &Conversions = 5969 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5970 5971 bool HadMultipleCandidates = 5972 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5973 5974 // To check that there is only one target type, in C++1y: 5975 QualType ToType; 5976 bool HasUniqueTargetType = true; 5977 5978 // Collect explicit or viable (potentially in C++1y) conversions. 5979 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5980 NamedDecl *D = (*I)->getUnderlyingDecl(); 5981 CXXConversionDecl *Conversion; 5982 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5983 if (ConvTemplate) { 5984 if (getLangOpts().CPlusPlus14) 5985 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5986 else 5987 continue; // C++11 does not consider conversion operator templates(?). 5988 } else 5989 Conversion = cast<CXXConversionDecl>(D); 5990 5991 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5992 "Conversion operator templates are considered potentially " 5993 "viable in C++1y"); 5994 5995 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5996 if (Converter.match(CurToType) || ConvTemplate) { 5997 5998 if (Conversion->isExplicit()) { 5999 // FIXME: For C++1y, do we need this restriction? 6000 // cf. diagnoseNoViableConversion() 6001 if (!ConvTemplate) 6002 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 6003 } else { 6004 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 6005 if (ToType.isNull()) 6006 ToType = CurToType.getUnqualifiedType(); 6007 else if (HasUniqueTargetType && 6008 (CurToType.getUnqualifiedType() != ToType)) 6009 HasUniqueTargetType = false; 6010 } 6011 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 6012 } 6013 } 6014 } 6015 6016 if (getLangOpts().CPlusPlus14) { 6017 // C++1y [conv]p6: 6018 // ... An expression e of class type E appearing in such a context 6019 // is said to be contextually implicitly converted to a specified 6020 // type T and is well-formed if and only if e can be implicitly 6021 // converted to a type T that is determined as follows: E is searched 6022 // for conversion functions whose return type is cv T or reference to 6023 // cv T such that T is allowed by the context. There shall be 6024 // exactly one such T. 6025 6026 // If no unique T is found: 6027 if (ToType.isNull()) { 6028 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6029 HadMultipleCandidates, 6030 ExplicitConversions)) 6031 return ExprError(); 6032 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6033 } 6034 6035 // If more than one unique Ts are found: 6036 if (!HasUniqueTargetType) 6037 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6038 ViableConversions); 6039 6040 // If one unique T is found: 6041 // First, build a candidate set from the previously recorded 6042 // potentially viable conversions. 6043 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6044 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 6045 CandidateSet); 6046 6047 // Then, perform overload resolution over the candidate set. 6048 OverloadCandidateSet::iterator Best; 6049 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 6050 case OR_Success: { 6051 // Apply this conversion. 6052 DeclAccessPair Found = 6053 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 6054 if (recordConversion(*this, Loc, From, Converter, T, 6055 HadMultipleCandidates, Found)) 6056 return ExprError(); 6057 break; 6058 } 6059 case OR_Ambiguous: 6060 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6061 ViableConversions); 6062 case OR_No_Viable_Function: 6063 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6064 HadMultipleCandidates, 6065 ExplicitConversions)) 6066 return ExprError(); 6067 LLVM_FALLTHROUGH; 6068 case OR_Deleted: 6069 // We'll complain below about a non-integral condition type. 6070 break; 6071 } 6072 } else { 6073 switch (ViableConversions.size()) { 6074 case 0: { 6075 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 6076 HadMultipleCandidates, 6077 ExplicitConversions)) 6078 return ExprError(); 6079 6080 // We'll complain below about a non-integral condition type. 6081 break; 6082 } 6083 case 1: { 6084 // Apply this conversion. 6085 DeclAccessPair Found = ViableConversions[0]; 6086 if (recordConversion(*this, Loc, From, Converter, T, 6087 HadMultipleCandidates, Found)) 6088 return ExprError(); 6089 break; 6090 } 6091 default: 6092 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 6093 ViableConversions); 6094 } 6095 } 6096 6097 return finishContextualImplicitConversion(*this, Loc, From, Converter); 6098 } 6099 6100 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 6101 /// an acceptable non-member overloaded operator for a call whose 6102 /// arguments have types T1 (and, if non-empty, T2). This routine 6103 /// implements the check in C++ [over.match.oper]p3b2 concerning 6104 /// enumeration types. 6105 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 6106 FunctionDecl *Fn, 6107 ArrayRef<Expr *> Args) { 6108 QualType T1 = Args[0]->getType(); 6109 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 6110 6111 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 6112 return true; 6113 6114 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 6115 return true; 6116 6117 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>(); 6118 if (Proto->getNumParams() < 1) 6119 return false; 6120 6121 if (T1->isEnumeralType()) { 6122 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 6123 if (Context.hasSameUnqualifiedType(T1, ArgType)) 6124 return true; 6125 } 6126 6127 if (Proto->getNumParams() < 2) 6128 return false; 6129 6130 if (!T2.isNull() && T2->isEnumeralType()) { 6131 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 6132 if (Context.hasSameUnqualifiedType(T2, ArgType)) 6133 return true; 6134 } 6135 6136 return false; 6137 } 6138 6139 /// AddOverloadCandidate - Adds the given function to the set of 6140 /// candidate functions, using the given function call arguments. If 6141 /// @p SuppressUserConversions, then don't allow user-defined 6142 /// conversions via constructors or conversion operators. 6143 /// 6144 /// \param PartialOverloading true if we are performing "partial" overloading 6145 /// based on an incomplete set of function arguments. This feature is used by 6146 /// code completion. 6147 void Sema::AddOverloadCandidate( 6148 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6149 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6150 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions, 6151 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions, 6152 OverloadCandidateParamOrder PO) { 6153 const FunctionProtoType *Proto 6154 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6155 assert(Proto && "Functions without a prototype cannot be overloaded"); 6156 assert(!Function->getDescribedFunctionTemplate() && 6157 "Use AddTemplateOverloadCandidate for function templates"); 6158 6159 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6160 if (!isa<CXXConstructorDecl>(Method)) { 6161 // If we get here, it's because we're calling a member function 6162 // that is named without a member access expression (e.g., 6163 // "this->f") that was either written explicitly or created 6164 // implicitly. This can happen with a qualified call to a member 6165 // function, e.g., X::f(). We use an empty type for the implied 6166 // object argument (C++ [over.call.func]p3), and the acting context 6167 // is irrelevant. 6168 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6169 Expr::Classification::makeSimpleLValue(), Args, 6170 CandidateSet, SuppressUserConversions, 6171 PartialOverloading, EarlyConversions, PO); 6172 return; 6173 } 6174 // We treat a constructor like a non-member function, since its object 6175 // argument doesn't participate in overload resolution. 6176 } 6177 6178 if (!CandidateSet.isNewCandidate(Function, PO)) 6179 return; 6180 6181 // C++11 [class.copy]p11: [DR1402] 6182 // A defaulted move constructor that is defined as deleted is ignored by 6183 // overload resolution. 6184 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6185 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6186 Constructor->isMoveConstructor()) 6187 return; 6188 6189 // Overload resolution is always an unevaluated context. 6190 EnterExpressionEvaluationContext Unevaluated( 6191 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6192 6193 // C++ [over.match.oper]p3: 6194 // if no operand has a class type, only those non-member functions in the 6195 // lookup set that have a first parameter of type T1 or "reference to 6196 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6197 // is a right operand) a second parameter of type T2 or "reference to 6198 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6199 // candidate functions. 6200 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6201 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6202 return; 6203 6204 // Add this candidate 6205 OverloadCandidate &Candidate = 6206 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6207 Candidate.FoundDecl = FoundDecl; 6208 Candidate.Function = Function; 6209 Candidate.Viable = true; 6210 Candidate.RewriteKind = 6211 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO); 6212 Candidate.IsSurrogate = false; 6213 Candidate.IsADLCandidate = IsADLCandidate; 6214 Candidate.IgnoreObjectArgument = false; 6215 Candidate.ExplicitCallArguments = Args.size(); 6216 6217 // Explicit functions are not actually candidates at all if we're not 6218 // allowing them in this context, but keep them around so we can point 6219 // to them in diagnostics. 6220 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) { 6221 Candidate.Viable = false; 6222 Candidate.FailureKind = ovl_fail_explicit; 6223 return; 6224 } 6225 6226 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6227 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6228 Candidate.Viable = false; 6229 Candidate.FailureKind = ovl_non_default_multiversion_function; 6230 return; 6231 } 6232 6233 if (Constructor) { 6234 // C++ [class.copy]p3: 6235 // A member function template is never instantiated to perform the copy 6236 // of a class object to an object of its class type. 6237 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6238 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6239 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6240 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6241 ClassType))) { 6242 Candidate.Viable = false; 6243 Candidate.FailureKind = ovl_fail_illegal_constructor; 6244 return; 6245 } 6246 6247 // C++ [over.match.funcs]p8: (proposed DR resolution) 6248 // A constructor inherited from class type C that has a first parameter 6249 // of type "reference to P" (including such a constructor instantiated 6250 // from a template) is excluded from the set of candidate functions when 6251 // constructing an object of type cv D if the argument list has exactly 6252 // one argument and D is reference-related to P and P is reference-related 6253 // to C. 6254 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6255 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6256 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6257 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6258 QualType C = Context.getRecordType(Constructor->getParent()); 6259 QualType D = Context.getRecordType(Shadow->getParent()); 6260 SourceLocation Loc = Args.front()->getExprLoc(); 6261 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6262 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6263 Candidate.Viable = false; 6264 Candidate.FailureKind = ovl_fail_inhctor_slice; 6265 return; 6266 } 6267 } 6268 6269 // Check that the constructor is capable of constructing an object in the 6270 // destination address space. 6271 if (!Qualifiers::isAddressSpaceSupersetOf( 6272 Constructor->getMethodQualifiers().getAddressSpace(), 6273 CandidateSet.getDestAS())) { 6274 Candidate.Viable = false; 6275 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch; 6276 } 6277 } 6278 6279 unsigned NumParams = Proto->getNumParams(); 6280 6281 // (C++ 13.3.2p2): A candidate function having fewer than m 6282 // parameters is viable only if it has an ellipsis in its parameter 6283 // list (8.3.5). 6284 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6285 !Proto->isVariadic()) { 6286 Candidate.Viable = false; 6287 Candidate.FailureKind = ovl_fail_too_many_arguments; 6288 return; 6289 } 6290 6291 // (C++ 13.3.2p2): A candidate function having more than m parameters 6292 // is viable only if the (m+1)st parameter has a default argument 6293 // (8.3.6). For the purposes of overload resolution, the 6294 // parameter list is truncated on the right, so that there are 6295 // exactly m parameters. 6296 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6297 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6298 // Not enough arguments. 6299 Candidate.Viable = false; 6300 Candidate.FailureKind = ovl_fail_too_few_arguments; 6301 return; 6302 } 6303 6304 // (CUDA B.1): Check for invalid calls between targets. 6305 if (getLangOpts().CUDA) 6306 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6307 // Skip the check for callers that are implicit members, because in this 6308 // case we may not yet know what the member's target is; the target is 6309 // inferred for the member automatically, based on the bases and fields of 6310 // the class. 6311 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6312 Candidate.Viable = false; 6313 Candidate.FailureKind = ovl_fail_bad_target; 6314 return; 6315 } 6316 6317 if (Function->getTrailingRequiresClause()) { 6318 ConstraintSatisfaction Satisfaction; 6319 if (CheckFunctionConstraints(Function, Satisfaction) || 6320 !Satisfaction.IsSatisfied) { 6321 Candidate.Viable = false; 6322 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6323 return; 6324 } 6325 } 6326 6327 // Determine the implicit conversion sequences for each of the 6328 // arguments. 6329 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6330 unsigned ConvIdx = 6331 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx; 6332 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6333 // We already formed a conversion sequence for this parameter during 6334 // template argument deduction. 6335 } else if (ArgIdx < NumParams) { 6336 // (C++ 13.3.2p3): for F to be a viable function, there shall 6337 // exist for each argument an implicit conversion sequence 6338 // (13.3.3.1) that converts that argument to the corresponding 6339 // parameter of F. 6340 QualType ParamType = Proto->getParamType(ArgIdx); 6341 Candidate.Conversions[ConvIdx] = TryCopyInitialization( 6342 *this, Args[ArgIdx], ParamType, SuppressUserConversions, 6343 /*InOverloadResolution=*/true, 6344 /*AllowObjCWritebackConversion=*/ 6345 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions); 6346 if (Candidate.Conversions[ConvIdx].isBad()) { 6347 Candidate.Viable = false; 6348 Candidate.FailureKind = ovl_fail_bad_conversion; 6349 return; 6350 } 6351 } else { 6352 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6353 // argument for which there is no corresponding parameter is 6354 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6355 Candidate.Conversions[ConvIdx].setEllipsis(); 6356 } 6357 } 6358 6359 if (EnableIfAttr *FailedAttr = 6360 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) { 6361 Candidate.Viable = false; 6362 Candidate.FailureKind = ovl_fail_enable_if; 6363 Candidate.DeductionFailure.Data = FailedAttr; 6364 return; 6365 } 6366 6367 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6368 Candidate.Viable = false; 6369 Candidate.FailureKind = ovl_fail_ext_disabled; 6370 return; 6371 } 6372 } 6373 6374 ObjCMethodDecl * 6375 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6376 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6377 if (Methods.size() <= 1) 6378 return nullptr; 6379 6380 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6381 bool Match = true; 6382 ObjCMethodDecl *Method = Methods[b]; 6383 unsigned NumNamedArgs = Sel.getNumArgs(); 6384 // Method might have more arguments than selector indicates. This is due 6385 // to addition of c-style arguments in method. 6386 if (Method->param_size() > NumNamedArgs) 6387 NumNamedArgs = Method->param_size(); 6388 if (Args.size() < NumNamedArgs) 6389 continue; 6390 6391 for (unsigned i = 0; i < NumNamedArgs; i++) { 6392 // We can't do any type-checking on a type-dependent argument. 6393 if (Args[i]->isTypeDependent()) { 6394 Match = false; 6395 break; 6396 } 6397 6398 ParmVarDecl *param = Method->parameters()[i]; 6399 Expr *argExpr = Args[i]; 6400 assert(argExpr && "SelectBestMethod(): missing expression"); 6401 6402 // Strip the unbridged-cast placeholder expression off unless it's 6403 // a consumed argument. 6404 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6405 !param->hasAttr<CFConsumedAttr>()) 6406 argExpr = stripARCUnbridgedCast(argExpr); 6407 6408 // If the parameter is __unknown_anytype, move on to the next method. 6409 if (param->getType() == Context.UnknownAnyTy) { 6410 Match = false; 6411 break; 6412 } 6413 6414 ImplicitConversionSequence ConversionState 6415 = TryCopyInitialization(*this, argExpr, param->getType(), 6416 /*SuppressUserConversions*/false, 6417 /*InOverloadResolution=*/true, 6418 /*AllowObjCWritebackConversion=*/ 6419 getLangOpts().ObjCAutoRefCount, 6420 /*AllowExplicit*/false); 6421 // This function looks for a reasonably-exact match, so we consider 6422 // incompatible pointer conversions to be a failure here. 6423 if (ConversionState.isBad() || 6424 (ConversionState.isStandard() && 6425 ConversionState.Standard.Second == 6426 ICK_Incompatible_Pointer_Conversion)) { 6427 Match = false; 6428 break; 6429 } 6430 } 6431 // Promote additional arguments to variadic methods. 6432 if (Match && Method->isVariadic()) { 6433 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6434 if (Args[i]->isTypeDependent()) { 6435 Match = false; 6436 break; 6437 } 6438 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6439 nullptr); 6440 if (Arg.isInvalid()) { 6441 Match = false; 6442 break; 6443 } 6444 } 6445 } else { 6446 // Check for extra arguments to non-variadic methods. 6447 if (Args.size() != NumNamedArgs) 6448 Match = false; 6449 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6450 // Special case when selectors have no argument. In this case, select 6451 // one with the most general result type of 'id'. 6452 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6453 QualType ReturnT = Methods[b]->getReturnType(); 6454 if (ReturnT->isObjCIdType()) 6455 return Methods[b]; 6456 } 6457 } 6458 } 6459 6460 if (Match) 6461 return Method; 6462 } 6463 return nullptr; 6464 } 6465 6466 static bool convertArgsForAvailabilityChecks( 6467 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, 6468 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, 6469 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) { 6470 if (ThisArg) { 6471 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6472 assert(!isa<CXXConstructorDecl>(Method) && 6473 "Shouldn't have `this` for ctors!"); 6474 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6475 ExprResult R = S.PerformObjectArgumentInitialization( 6476 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6477 if (R.isInvalid()) 6478 return false; 6479 ConvertedThis = R.get(); 6480 } else { 6481 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6482 (void)MD; 6483 assert((MissingImplicitThis || MD->isStatic() || 6484 isa<CXXConstructorDecl>(MD)) && 6485 "Expected `this` for non-ctor instance methods"); 6486 } 6487 ConvertedThis = nullptr; 6488 } 6489 6490 // Ignore any variadic arguments. Converting them is pointless, since the 6491 // user can't refer to them in the function condition. 6492 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6493 6494 // Convert the arguments. 6495 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6496 ExprResult R; 6497 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6498 S.Context, Function->getParamDecl(I)), 6499 SourceLocation(), Args[I]); 6500 6501 if (R.isInvalid()) 6502 return false; 6503 6504 ConvertedArgs.push_back(R.get()); 6505 } 6506 6507 if (Trap.hasErrorOccurred()) 6508 return false; 6509 6510 // Push default arguments if needed. 6511 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6512 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6513 ParmVarDecl *P = Function->getParamDecl(i); 6514 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P); 6515 if (R.isInvalid()) 6516 return false; 6517 ConvertedArgs.push_back(R.get()); 6518 } 6519 6520 if (Trap.hasErrorOccurred()) 6521 return false; 6522 } 6523 return true; 6524 } 6525 6526 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, 6527 SourceLocation CallLoc, 6528 ArrayRef<Expr *> Args, 6529 bool MissingImplicitThis) { 6530 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6531 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6532 return nullptr; 6533 6534 SFINAETrap Trap(*this); 6535 SmallVector<Expr *, 16> ConvertedArgs; 6536 // FIXME: We should look into making enable_if late-parsed. 6537 Expr *DiscardedThis; 6538 if (!convertArgsForAvailabilityChecks( 6539 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap, 6540 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6541 return *EnableIfAttrs.begin(); 6542 6543 for (auto *EIA : EnableIfAttrs) { 6544 APValue Result; 6545 // FIXME: This doesn't consider value-dependent cases, because doing so is 6546 // very difficult. Ideally, we should handle them more gracefully. 6547 if (EIA->getCond()->isValueDependent() || 6548 !EIA->getCond()->EvaluateWithSubstitution( 6549 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6550 return EIA; 6551 6552 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6553 return EIA; 6554 } 6555 return nullptr; 6556 } 6557 6558 template <typename CheckFn> 6559 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6560 bool ArgDependent, SourceLocation Loc, 6561 CheckFn &&IsSuccessful) { 6562 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6563 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6564 if (ArgDependent == DIA->getArgDependent()) 6565 Attrs.push_back(DIA); 6566 } 6567 6568 // Common case: No diagnose_if attributes, so we can quit early. 6569 if (Attrs.empty()) 6570 return false; 6571 6572 auto WarningBegin = std::stable_partition( 6573 Attrs.begin(), Attrs.end(), 6574 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6575 6576 // Note that diagnose_if attributes are late-parsed, so they appear in the 6577 // correct order (unlike enable_if attributes). 6578 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6579 IsSuccessful); 6580 if (ErrAttr != WarningBegin) { 6581 const DiagnoseIfAttr *DIA = *ErrAttr; 6582 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6583 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6584 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6585 return true; 6586 } 6587 6588 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6589 if (IsSuccessful(DIA)) { 6590 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6591 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6592 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6593 } 6594 6595 return false; 6596 } 6597 6598 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6599 const Expr *ThisArg, 6600 ArrayRef<const Expr *> Args, 6601 SourceLocation Loc) { 6602 return diagnoseDiagnoseIfAttrsWith( 6603 *this, Function, /*ArgDependent=*/true, Loc, 6604 [&](const DiagnoseIfAttr *DIA) { 6605 APValue Result; 6606 // It's sane to use the same Args for any redecl of this function, since 6607 // EvaluateWithSubstitution only cares about the position of each 6608 // argument in the arg list, not the ParmVarDecl* it maps to. 6609 if (!DIA->getCond()->EvaluateWithSubstitution( 6610 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6611 return false; 6612 return Result.isInt() && Result.getInt().getBoolValue(); 6613 }); 6614 } 6615 6616 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6617 SourceLocation Loc) { 6618 return diagnoseDiagnoseIfAttrsWith( 6619 *this, ND, /*ArgDependent=*/false, Loc, 6620 [&](const DiagnoseIfAttr *DIA) { 6621 bool Result; 6622 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6623 Result; 6624 }); 6625 } 6626 6627 /// Add all of the function declarations in the given function set to 6628 /// the overload candidate set. 6629 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6630 ArrayRef<Expr *> Args, 6631 OverloadCandidateSet &CandidateSet, 6632 TemplateArgumentListInfo *ExplicitTemplateArgs, 6633 bool SuppressUserConversions, 6634 bool PartialOverloading, 6635 bool FirstArgumentIsBase) { 6636 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6637 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6638 ArrayRef<Expr *> FunctionArgs = Args; 6639 6640 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6641 FunctionDecl *FD = 6642 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6643 6644 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6645 QualType ObjectType; 6646 Expr::Classification ObjectClassification; 6647 if (Args.size() > 0) { 6648 if (Expr *E = Args[0]) { 6649 // Use the explicit base to restrict the lookup: 6650 ObjectType = E->getType(); 6651 // Pointers in the object arguments are implicitly dereferenced, so we 6652 // always classify them as l-values. 6653 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6654 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6655 else 6656 ObjectClassification = E->Classify(Context); 6657 } // .. else there is an implicit base. 6658 FunctionArgs = Args.slice(1); 6659 } 6660 if (FunTmpl) { 6661 AddMethodTemplateCandidate( 6662 FunTmpl, F.getPair(), 6663 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6664 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6665 FunctionArgs, CandidateSet, SuppressUserConversions, 6666 PartialOverloading); 6667 } else { 6668 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6669 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6670 ObjectClassification, FunctionArgs, CandidateSet, 6671 SuppressUserConversions, PartialOverloading); 6672 } 6673 } else { 6674 // This branch handles both standalone functions and static methods. 6675 6676 // Slice the first argument (which is the base) when we access 6677 // static method as non-static. 6678 if (Args.size() > 0 && 6679 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6680 !isa<CXXConstructorDecl>(FD)))) { 6681 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6682 FunctionArgs = Args.slice(1); 6683 } 6684 if (FunTmpl) { 6685 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6686 ExplicitTemplateArgs, FunctionArgs, 6687 CandidateSet, SuppressUserConversions, 6688 PartialOverloading); 6689 } else { 6690 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6691 SuppressUserConversions, PartialOverloading); 6692 } 6693 } 6694 } 6695 } 6696 6697 /// AddMethodCandidate - Adds a named decl (which is some kind of 6698 /// method) as a method candidate to the given overload set. 6699 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 6700 Expr::Classification ObjectClassification, 6701 ArrayRef<Expr *> Args, 6702 OverloadCandidateSet &CandidateSet, 6703 bool SuppressUserConversions, 6704 OverloadCandidateParamOrder PO) { 6705 NamedDecl *Decl = FoundDecl.getDecl(); 6706 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6707 6708 if (isa<UsingShadowDecl>(Decl)) 6709 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6710 6711 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6712 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6713 "Expected a member function template"); 6714 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6715 /*ExplicitArgs*/ nullptr, ObjectType, 6716 ObjectClassification, Args, CandidateSet, 6717 SuppressUserConversions, false, PO); 6718 } else { 6719 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6720 ObjectType, ObjectClassification, Args, CandidateSet, 6721 SuppressUserConversions, false, None, PO); 6722 } 6723 } 6724 6725 /// AddMethodCandidate - Adds the given C++ member function to the set 6726 /// of candidate functions, using the given function call arguments 6727 /// and the object argument (@c Object). For example, in a call 6728 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6729 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6730 /// allow user-defined conversions via constructors or conversion 6731 /// operators. 6732 void 6733 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6734 CXXRecordDecl *ActingContext, QualType ObjectType, 6735 Expr::Classification ObjectClassification, 6736 ArrayRef<Expr *> Args, 6737 OverloadCandidateSet &CandidateSet, 6738 bool SuppressUserConversions, 6739 bool PartialOverloading, 6740 ConversionSequenceList EarlyConversions, 6741 OverloadCandidateParamOrder PO) { 6742 const FunctionProtoType *Proto 6743 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6744 assert(Proto && "Methods without a prototype cannot be overloaded"); 6745 assert(!isa<CXXConstructorDecl>(Method) && 6746 "Use AddOverloadCandidate for constructors"); 6747 6748 if (!CandidateSet.isNewCandidate(Method, PO)) 6749 return; 6750 6751 // C++11 [class.copy]p23: [DR1402] 6752 // A defaulted move assignment operator that is defined as deleted is 6753 // ignored by overload resolution. 6754 if (Method->isDefaulted() && Method->isDeleted() && 6755 Method->isMoveAssignmentOperator()) 6756 return; 6757 6758 // Overload resolution is always an unevaluated context. 6759 EnterExpressionEvaluationContext Unevaluated( 6760 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6761 6762 // Add this candidate 6763 OverloadCandidate &Candidate = 6764 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6765 Candidate.FoundDecl = FoundDecl; 6766 Candidate.Function = Method; 6767 Candidate.RewriteKind = 6768 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO); 6769 Candidate.IsSurrogate = false; 6770 Candidate.IgnoreObjectArgument = false; 6771 Candidate.ExplicitCallArguments = Args.size(); 6772 6773 unsigned NumParams = Proto->getNumParams(); 6774 6775 // (C++ 13.3.2p2): A candidate function having fewer than m 6776 // parameters is viable only if it has an ellipsis in its parameter 6777 // list (8.3.5). 6778 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6779 !Proto->isVariadic()) { 6780 Candidate.Viable = false; 6781 Candidate.FailureKind = ovl_fail_too_many_arguments; 6782 return; 6783 } 6784 6785 // (C++ 13.3.2p2): A candidate function having more than m parameters 6786 // is viable only if the (m+1)st parameter has a default argument 6787 // (8.3.6). For the purposes of overload resolution, the 6788 // parameter list is truncated on the right, so that there are 6789 // exactly m parameters. 6790 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6791 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6792 // Not enough arguments. 6793 Candidate.Viable = false; 6794 Candidate.FailureKind = ovl_fail_too_few_arguments; 6795 return; 6796 } 6797 6798 Candidate.Viable = true; 6799 6800 if (Method->isStatic() || ObjectType.isNull()) 6801 // The implicit object argument is ignored. 6802 Candidate.IgnoreObjectArgument = true; 6803 else { 6804 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 6805 // Determine the implicit conversion sequence for the object 6806 // parameter. 6807 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization( 6808 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6809 Method, ActingContext); 6810 if (Candidate.Conversions[ConvIdx].isBad()) { 6811 Candidate.Viable = false; 6812 Candidate.FailureKind = ovl_fail_bad_conversion; 6813 return; 6814 } 6815 } 6816 6817 // (CUDA B.1): Check for invalid calls between targets. 6818 if (getLangOpts().CUDA) 6819 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6820 if (!IsAllowedCUDACall(Caller, Method)) { 6821 Candidate.Viable = false; 6822 Candidate.FailureKind = ovl_fail_bad_target; 6823 return; 6824 } 6825 6826 if (Method->getTrailingRequiresClause()) { 6827 ConstraintSatisfaction Satisfaction; 6828 if (CheckFunctionConstraints(Method, Satisfaction) || 6829 !Satisfaction.IsSatisfied) { 6830 Candidate.Viable = false; 6831 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 6832 return; 6833 } 6834 } 6835 6836 // Determine the implicit conversion sequences for each of the 6837 // arguments. 6838 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6839 unsigned ConvIdx = 6840 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1); 6841 if (Candidate.Conversions[ConvIdx].isInitialized()) { 6842 // We already formed a conversion sequence for this parameter during 6843 // template argument deduction. 6844 } else if (ArgIdx < NumParams) { 6845 // (C++ 13.3.2p3): for F to be a viable function, there shall 6846 // exist for each argument an implicit conversion sequence 6847 // (13.3.3.1) that converts that argument to the corresponding 6848 // parameter of F. 6849 QualType ParamType = Proto->getParamType(ArgIdx); 6850 Candidate.Conversions[ConvIdx] 6851 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6852 SuppressUserConversions, 6853 /*InOverloadResolution=*/true, 6854 /*AllowObjCWritebackConversion=*/ 6855 getLangOpts().ObjCAutoRefCount); 6856 if (Candidate.Conversions[ConvIdx].isBad()) { 6857 Candidate.Viable = false; 6858 Candidate.FailureKind = ovl_fail_bad_conversion; 6859 return; 6860 } 6861 } else { 6862 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6863 // argument for which there is no corresponding parameter is 6864 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6865 Candidate.Conversions[ConvIdx].setEllipsis(); 6866 } 6867 } 6868 6869 if (EnableIfAttr *FailedAttr = 6870 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) { 6871 Candidate.Viable = false; 6872 Candidate.FailureKind = ovl_fail_enable_if; 6873 Candidate.DeductionFailure.Data = FailedAttr; 6874 return; 6875 } 6876 6877 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6878 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6879 Candidate.Viable = false; 6880 Candidate.FailureKind = ovl_non_default_multiversion_function; 6881 } 6882 } 6883 6884 /// Add a C++ member function template as a candidate to the candidate 6885 /// set, using template argument deduction to produce an appropriate member 6886 /// function template specialization. 6887 void Sema::AddMethodTemplateCandidate( 6888 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 6889 CXXRecordDecl *ActingContext, 6890 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 6891 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 6892 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6893 bool PartialOverloading, OverloadCandidateParamOrder PO) { 6894 if (!CandidateSet.isNewCandidate(MethodTmpl, PO)) 6895 return; 6896 6897 // C++ [over.match.funcs]p7: 6898 // In each case where a candidate is a function template, candidate 6899 // function template specializations are generated using template argument 6900 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6901 // candidate functions in the usual way.113) A given name can refer to one 6902 // or more function templates and also to a set of overloaded non-template 6903 // functions. In such a case, the candidate functions generated from each 6904 // function template are combined with the set of non-template candidate 6905 // functions. 6906 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6907 FunctionDecl *Specialization = nullptr; 6908 ConversionSequenceList Conversions; 6909 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6910 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6911 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6912 return CheckNonDependentConversions( 6913 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6914 SuppressUserConversions, ActingContext, ObjectType, 6915 ObjectClassification, PO); 6916 })) { 6917 OverloadCandidate &Candidate = 6918 CandidateSet.addCandidate(Conversions.size(), Conversions); 6919 Candidate.FoundDecl = FoundDecl; 6920 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6921 Candidate.Viable = false; 6922 Candidate.RewriteKind = 6923 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 6924 Candidate.IsSurrogate = false; 6925 Candidate.IgnoreObjectArgument = 6926 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6927 ObjectType.isNull(); 6928 Candidate.ExplicitCallArguments = Args.size(); 6929 if (Result == TDK_NonDependentConversionFailure) 6930 Candidate.FailureKind = ovl_fail_bad_conversion; 6931 else { 6932 Candidate.FailureKind = ovl_fail_bad_deduction; 6933 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6934 Info); 6935 } 6936 return; 6937 } 6938 6939 // Add the function template specialization produced by template argument 6940 // deduction as a candidate. 6941 assert(Specialization && "Missing member function template specialization?"); 6942 assert(isa<CXXMethodDecl>(Specialization) && 6943 "Specialization is not a member function?"); 6944 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6945 ActingContext, ObjectType, ObjectClassification, Args, 6946 CandidateSet, SuppressUserConversions, PartialOverloading, 6947 Conversions, PO); 6948 } 6949 6950 /// Determine whether a given function template has a simple explicit specifier 6951 /// or a non-value-dependent explicit-specification that evaluates to true. 6952 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) { 6953 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit(); 6954 } 6955 6956 /// Add a C++ function template specialization as a candidate 6957 /// in the candidate set, using template argument deduction to produce 6958 /// an appropriate function template specialization. 6959 void Sema::AddTemplateOverloadCandidate( 6960 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6961 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6962 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6963 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate, 6964 OverloadCandidateParamOrder PO) { 6965 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO)) 6966 return; 6967 6968 // If the function template has a non-dependent explicit specification, 6969 // exclude it now if appropriate; we are not permitted to perform deduction 6970 // and substitution in this case. 6971 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 6972 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6973 Candidate.FoundDecl = FoundDecl; 6974 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6975 Candidate.Viable = false; 6976 Candidate.FailureKind = ovl_fail_explicit; 6977 return; 6978 } 6979 6980 // C++ [over.match.funcs]p7: 6981 // In each case where a candidate is a function template, candidate 6982 // function template specializations are generated using template argument 6983 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6984 // candidate functions in the usual way.113) A given name can refer to one 6985 // or more function templates and also to a set of overloaded non-template 6986 // functions. In such a case, the candidate functions generated from each 6987 // function template are combined with the set of non-template candidate 6988 // functions. 6989 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6990 FunctionDecl *Specialization = nullptr; 6991 ConversionSequenceList Conversions; 6992 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6993 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6994 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6995 return CheckNonDependentConversions( 6996 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions, 6997 SuppressUserConversions, nullptr, QualType(), {}, PO); 6998 })) { 6999 OverloadCandidate &Candidate = 7000 CandidateSet.addCandidate(Conversions.size(), Conversions); 7001 Candidate.FoundDecl = FoundDecl; 7002 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7003 Candidate.Viable = false; 7004 Candidate.RewriteKind = 7005 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO); 7006 Candidate.IsSurrogate = false; 7007 Candidate.IsADLCandidate = IsADLCandidate; 7008 // Ignore the object argument if there is one, since we don't have an object 7009 // type. 7010 Candidate.IgnoreObjectArgument = 7011 isa<CXXMethodDecl>(Candidate.Function) && 7012 !isa<CXXConstructorDecl>(Candidate.Function); 7013 Candidate.ExplicitCallArguments = Args.size(); 7014 if (Result == TDK_NonDependentConversionFailure) 7015 Candidate.FailureKind = ovl_fail_bad_conversion; 7016 else { 7017 Candidate.FailureKind = ovl_fail_bad_deduction; 7018 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7019 Info); 7020 } 7021 return; 7022 } 7023 7024 // Add the function template specialization produced by template argument 7025 // deduction as a candidate. 7026 assert(Specialization && "Missing function template specialization?"); 7027 AddOverloadCandidate( 7028 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions, 7029 PartialOverloading, AllowExplicit, 7030 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO); 7031 } 7032 7033 /// Check that implicit conversion sequences can be formed for each argument 7034 /// whose corresponding parameter has a non-dependent type, per DR1391's 7035 /// [temp.deduct.call]p10. 7036 bool Sema::CheckNonDependentConversions( 7037 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 7038 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 7039 ConversionSequenceList &Conversions, bool SuppressUserConversions, 7040 CXXRecordDecl *ActingContext, QualType ObjectType, 7041 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) { 7042 // FIXME: The cases in which we allow explicit conversions for constructor 7043 // arguments never consider calling a constructor template. It's not clear 7044 // that is correct. 7045 const bool AllowExplicit = false; 7046 7047 auto *FD = FunctionTemplate->getTemplatedDecl(); 7048 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7049 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 7050 unsigned ThisConversions = HasThisConversion ? 1 : 0; 7051 7052 Conversions = 7053 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 7054 7055 // Overload resolution is always an unevaluated context. 7056 EnterExpressionEvaluationContext Unevaluated( 7057 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7058 7059 // For a method call, check the 'this' conversion here too. DR1391 doesn't 7060 // require that, but this check should never result in a hard error, and 7061 // overload resolution is permitted to sidestep instantiations. 7062 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 7063 !ObjectType.isNull()) { 7064 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0; 7065 Conversions[ConvIdx] = TryObjectArgumentInitialization( 7066 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 7067 Method, ActingContext); 7068 if (Conversions[ConvIdx].isBad()) 7069 return true; 7070 } 7071 7072 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 7073 ++I) { 7074 QualType ParamType = ParamTypes[I]; 7075 if (!ParamType->isDependentType()) { 7076 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed 7077 ? 0 7078 : (ThisConversions + I); 7079 Conversions[ConvIdx] 7080 = TryCopyInitialization(*this, Args[I], ParamType, 7081 SuppressUserConversions, 7082 /*InOverloadResolution=*/true, 7083 /*AllowObjCWritebackConversion=*/ 7084 getLangOpts().ObjCAutoRefCount, 7085 AllowExplicit); 7086 if (Conversions[ConvIdx].isBad()) 7087 return true; 7088 } 7089 } 7090 7091 return false; 7092 } 7093 7094 /// Determine whether this is an allowable conversion from the result 7095 /// of an explicit conversion operator to the expected type, per C++ 7096 /// [over.match.conv]p1 and [over.match.ref]p1. 7097 /// 7098 /// \param ConvType The return type of the conversion function. 7099 /// 7100 /// \param ToType The type we are converting to. 7101 /// 7102 /// \param AllowObjCPointerConversion Allow a conversion from one 7103 /// Objective-C pointer to another. 7104 /// 7105 /// \returns true if the conversion is allowable, false otherwise. 7106 static bool isAllowableExplicitConversion(Sema &S, 7107 QualType ConvType, QualType ToType, 7108 bool AllowObjCPointerConversion) { 7109 QualType ToNonRefType = ToType.getNonReferenceType(); 7110 7111 // Easy case: the types are the same. 7112 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 7113 return true; 7114 7115 // Allow qualification conversions. 7116 bool ObjCLifetimeConversion; 7117 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 7118 ObjCLifetimeConversion)) 7119 return true; 7120 7121 // If we're not allowed to consider Objective-C pointer conversions, 7122 // we're done. 7123 if (!AllowObjCPointerConversion) 7124 return false; 7125 7126 // Is this an Objective-C pointer conversion? 7127 bool IncompatibleObjC = false; 7128 QualType ConvertedType; 7129 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 7130 IncompatibleObjC); 7131 } 7132 7133 /// AddConversionCandidate - Add a C++ conversion function as a 7134 /// candidate in the candidate set (C++ [over.match.conv], 7135 /// C++ [over.match.copy]). From is the expression we're converting from, 7136 /// and ToType is the type that we're eventually trying to convert to 7137 /// (which may or may not be the same type as the type that the 7138 /// conversion function produces). 7139 void Sema::AddConversionCandidate( 7140 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 7141 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 7142 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7143 bool AllowExplicit, bool AllowResultConversion) { 7144 assert(!Conversion->getDescribedFunctionTemplate() && 7145 "Conversion function templates use AddTemplateConversionCandidate"); 7146 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 7147 if (!CandidateSet.isNewCandidate(Conversion)) 7148 return; 7149 7150 // If the conversion function has an undeduced return type, trigger its 7151 // deduction now. 7152 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 7153 if (DeduceReturnType(Conversion, From->getExprLoc())) 7154 return; 7155 ConvType = Conversion->getConversionType().getNonReferenceType(); 7156 } 7157 7158 // If we don't allow any conversion of the result type, ignore conversion 7159 // functions that don't convert to exactly (possibly cv-qualified) T. 7160 if (!AllowResultConversion && 7161 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 7162 return; 7163 7164 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 7165 // operator is only a candidate if its return type is the target type or 7166 // can be converted to the target type with a qualification conversion. 7167 // 7168 // FIXME: Include such functions in the candidate list and explain why we 7169 // can't select them. 7170 if (Conversion->isExplicit() && 7171 !isAllowableExplicitConversion(*this, ConvType, ToType, 7172 AllowObjCConversionOnExplicit)) 7173 return; 7174 7175 // Overload resolution is always an unevaluated context. 7176 EnterExpressionEvaluationContext Unevaluated( 7177 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7178 7179 // Add this candidate 7180 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 7181 Candidate.FoundDecl = FoundDecl; 7182 Candidate.Function = Conversion; 7183 Candidate.IsSurrogate = false; 7184 Candidate.IgnoreObjectArgument = false; 7185 Candidate.FinalConversion.setAsIdentityConversion(); 7186 Candidate.FinalConversion.setFromType(ConvType); 7187 Candidate.FinalConversion.setAllToTypes(ToType); 7188 Candidate.Viable = true; 7189 Candidate.ExplicitCallArguments = 1; 7190 7191 // Explicit functions are not actually candidates at all if we're not 7192 // allowing them in this context, but keep them around so we can point 7193 // to them in diagnostics. 7194 if (!AllowExplicit && Conversion->isExplicit()) { 7195 Candidate.Viable = false; 7196 Candidate.FailureKind = ovl_fail_explicit; 7197 return; 7198 } 7199 7200 // C++ [over.match.funcs]p4: 7201 // For conversion functions, the function is considered to be a member of 7202 // the class of the implicit implied object argument for the purpose of 7203 // defining the type of the implicit object parameter. 7204 // 7205 // Determine the implicit conversion sequence for the implicit 7206 // object parameter. 7207 QualType ImplicitParamType = From->getType(); 7208 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 7209 ImplicitParamType = FromPtrType->getPointeeType(); 7210 CXXRecordDecl *ConversionContext 7211 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl()); 7212 7213 Candidate.Conversions[0] = TryObjectArgumentInitialization( 7214 *this, CandidateSet.getLocation(), From->getType(), 7215 From->Classify(Context), Conversion, ConversionContext); 7216 7217 if (Candidate.Conversions[0].isBad()) { 7218 Candidate.Viable = false; 7219 Candidate.FailureKind = ovl_fail_bad_conversion; 7220 return; 7221 } 7222 7223 if (Conversion->getTrailingRequiresClause()) { 7224 ConstraintSatisfaction Satisfaction; 7225 if (CheckFunctionConstraints(Conversion, Satisfaction) || 7226 !Satisfaction.IsSatisfied) { 7227 Candidate.Viable = false; 7228 Candidate.FailureKind = ovl_fail_constraints_not_satisfied; 7229 return; 7230 } 7231 } 7232 7233 // We won't go through a user-defined type conversion function to convert a 7234 // derived to base as such conversions are given Conversion Rank. They only 7235 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7236 QualType FromCanon 7237 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7238 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7239 if (FromCanon == ToCanon || 7240 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7241 Candidate.Viable = false; 7242 Candidate.FailureKind = ovl_fail_trivial_conversion; 7243 return; 7244 } 7245 7246 // To determine what the conversion from the result of calling the 7247 // conversion function to the type we're eventually trying to 7248 // convert to (ToType), we need to synthesize a call to the 7249 // conversion function and attempt copy initialization from it. This 7250 // makes sure that we get the right semantics with respect to 7251 // lvalues/rvalues and the type. Fortunately, we can allocate this 7252 // call on the stack and we don't need its arguments to be 7253 // well-formed. 7254 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7255 VK_LValue, From->getBeginLoc()); 7256 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7257 Context.getPointerType(Conversion->getType()), 7258 CK_FunctionToPointerDecay, 7259 &ConversionRef, VK_RValue); 7260 7261 QualType ConversionType = Conversion->getConversionType(); 7262 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7263 Candidate.Viable = false; 7264 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7265 return; 7266 } 7267 7268 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7269 7270 // Note that it is safe to allocate CallExpr on the stack here because 7271 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7272 // allocator). 7273 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7274 7275 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)]; 7276 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7277 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7278 7279 ImplicitConversionSequence ICS = 7280 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7281 /*SuppressUserConversions=*/true, 7282 /*InOverloadResolution=*/false, 7283 /*AllowObjCWritebackConversion=*/false); 7284 7285 switch (ICS.getKind()) { 7286 case ImplicitConversionSequence::StandardConversion: 7287 Candidate.FinalConversion = ICS.Standard; 7288 7289 // C++ [over.ics.user]p3: 7290 // If the user-defined conversion is specified by a specialization of a 7291 // conversion function template, the second standard conversion sequence 7292 // shall have exact match rank. 7293 if (Conversion->getPrimaryTemplate() && 7294 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7295 Candidate.Viable = false; 7296 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7297 return; 7298 } 7299 7300 // C++0x [dcl.init.ref]p5: 7301 // In the second case, if the reference is an rvalue reference and 7302 // the second standard conversion sequence of the user-defined 7303 // conversion sequence includes an lvalue-to-rvalue conversion, the 7304 // program is ill-formed. 7305 if (ToType->isRValueReferenceType() && 7306 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7307 Candidate.Viable = false; 7308 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7309 return; 7310 } 7311 break; 7312 7313 case ImplicitConversionSequence::BadConversion: 7314 Candidate.Viable = false; 7315 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7316 return; 7317 7318 default: 7319 llvm_unreachable( 7320 "Can only end up with a standard conversion sequence or failure"); 7321 } 7322 7323 if (EnableIfAttr *FailedAttr = 7324 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7325 Candidate.Viable = false; 7326 Candidate.FailureKind = ovl_fail_enable_if; 7327 Candidate.DeductionFailure.Data = FailedAttr; 7328 return; 7329 } 7330 7331 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7332 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7333 Candidate.Viable = false; 7334 Candidate.FailureKind = ovl_non_default_multiversion_function; 7335 } 7336 } 7337 7338 /// Adds a conversion function template specialization 7339 /// candidate to the overload set, using template argument deduction 7340 /// to deduce the template arguments of the conversion function 7341 /// template from the type that we are converting to (C++ 7342 /// [temp.deduct.conv]). 7343 void Sema::AddTemplateConversionCandidate( 7344 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 7345 CXXRecordDecl *ActingDC, Expr *From, QualType ToType, 7346 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 7347 bool AllowExplicit, bool AllowResultConversion) { 7348 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7349 "Only conversion function templates permitted here"); 7350 7351 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7352 return; 7353 7354 // If the function template has a non-dependent explicit specification, 7355 // exclude it now if appropriate; we are not permitted to perform deduction 7356 // and substitution in this case. 7357 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) { 7358 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7359 Candidate.FoundDecl = FoundDecl; 7360 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7361 Candidate.Viable = false; 7362 Candidate.FailureKind = ovl_fail_explicit; 7363 return; 7364 } 7365 7366 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7367 CXXConversionDecl *Specialization = nullptr; 7368 if (TemplateDeductionResult Result 7369 = DeduceTemplateArguments(FunctionTemplate, ToType, 7370 Specialization, Info)) { 7371 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7372 Candidate.FoundDecl = FoundDecl; 7373 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7374 Candidate.Viable = false; 7375 Candidate.FailureKind = ovl_fail_bad_deduction; 7376 Candidate.IsSurrogate = false; 7377 Candidate.IgnoreObjectArgument = false; 7378 Candidate.ExplicitCallArguments = 1; 7379 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7380 Info); 7381 return; 7382 } 7383 7384 // Add the conversion function template specialization produced by 7385 // template argument deduction as a candidate. 7386 assert(Specialization && "Missing function template specialization?"); 7387 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7388 CandidateSet, AllowObjCConversionOnExplicit, 7389 AllowExplicit, AllowResultConversion); 7390 } 7391 7392 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7393 /// converts the given @c Object to a function pointer via the 7394 /// conversion function @c Conversion, and then attempts to call it 7395 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7396 /// the type of function that we'll eventually be calling. 7397 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7398 DeclAccessPair FoundDecl, 7399 CXXRecordDecl *ActingContext, 7400 const FunctionProtoType *Proto, 7401 Expr *Object, 7402 ArrayRef<Expr *> Args, 7403 OverloadCandidateSet& CandidateSet) { 7404 if (!CandidateSet.isNewCandidate(Conversion)) 7405 return; 7406 7407 // Overload resolution is always an unevaluated context. 7408 EnterExpressionEvaluationContext Unevaluated( 7409 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7410 7411 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7412 Candidate.FoundDecl = FoundDecl; 7413 Candidate.Function = nullptr; 7414 Candidate.Surrogate = Conversion; 7415 Candidate.Viable = true; 7416 Candidate.IsSurrogate = true; 7417 Candidate.IgnoreObjectArgument = false; 7418 Candidate.ExplicitCallArguments = Args.size(); 7419 7420 // Determine the implicit conversion sequence for the implicit 7421 // object parameter. 7422 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7423 *this, CandidateSet.getLocation(), Object->getType(), 7424 Object->Classify(Context), Conversion, ActingContext); 7425 if (ObjectInit.isBad()) { 7426 Candidate.Viable = false; 7427 Candidate.FailureKind = ovl_fail_bad_conversion; 7428 Candidate.Conversions[0] = ObjectInit; 7429 return; 7430 } 7431 7432 // The first conversion is actually a user-defined conversion whose 7433 // first conversion is ObjectInit's standard conversion (which is 7434 // effectively a reference binding). Record it as such. 7435 Candidate.Conversions[0].setUserDefined(); 7436 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7437 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7438 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7439 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7440 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7441 Candidate.Conversions[0].UserDefined.After 7442 = Candidate.Conversions[0].UserDefined.Before; 7443 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7444 7445 // Find the 7446 unsigned NumParams = Proto->getNumParams(); 7447 7448 // (C++ 13.3.2p2): A candidate function having fewer than m 7449 // parameters is viable only if it has an ellipsis in its parameter 7450 // list (8.3.5). 7451 if (Args.size() > NumParams && !Proto->isVariadic()) { 7452 Candidate.Viable = false; 7453 Candidate.FailureKind = ovl_fail_too_many_arguments; 7454 return; 7455 } 7456 7457 // Function types don't have any default arguments, so just check if 7458 // we have enough arguments. 7459 if (Args.size() < NumParams) { 7460 // Not enough arguments. 7461 Candidate.Viable = false; 7462 Candidate.FailureKind = ovl_fail_too_few_arguments; 7463 return; 7464 } 7465 7466 // Determine the implicit conversion sequences for each of the 7467 // arguments. 7468 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7469 if (ArgIdx < NumParams) { 7470 // (C++ 13.3.2p3): for F to be a viable function, there shall 7471 // exist for each argument an implicit conversion sequence 7472 // (13.3.3.1) that converts that argument to the corresponding 7473 // parameter of F. 7474 QualType ParamType = Proto->getParamType(ArgIdx); 7475 Candidate.Conversions[ArgIdx + 1] 7476 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7477 /*SuppressUserConversions=*/false, 7478 /*InOverloadResolution=*/false, 7479 /*AllowObjCWritebackConversion=*/ 7480 getLangOpts().ObjCAutoRefCount); 7481 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7482 Candidate.Viable = false; 7483 Candidate.FailureKind = ovl_fail_bad_conversion; 7484 return; 7485 } 7486 } else { 7487 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7488 // argument for which there is no corresponding parameter is 7489 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7490 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7491 } 7492 } 7493 7494 if (EnableIfAttr *FailedAttr = 7495 CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) { 7496 Candidate.Viable = false; 7497 Candidate.FailureKind = ovl_fail_enable_if; 7498 Candidate.DeductionFailure.Data = FailedAttr; 7499 return; 7500 } 7501 } 7502 7503 /// Add all of the non-member operator function declarations in the given 7504 /// function set to the overload candidate set. 7505 void Sema::AddNonMemberOperatorCandidates( 7506 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, 7507 OverloadCandidateSet &CandidateSet, 7508 TemplateArgumentListInfo *ExplicitTemplateArgs) { 7509 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 7510 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 7511 ArrayRef<Expr *> FunctionArgs = Args; 7512 7513 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 7514 FunctionDecl *FD = 7515 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 7516 7517 // Don't consider rewritten functions if we're not rewriting. 7518 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD)) 7519 continue; 7520 7521 assert(!isa<CXXMethodDecl>(FD) && 7522 "unqualified operator lookup found a member function"); 7523 7524 if (FunTmpl) { 7525 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs, 7526 FunctionArgs, CandidateSet); 7527 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7528 AddTemplateOverloadCandidate( 7529 FunTmpl, F.getPair(), ExplicitTemplateArgs, 7530 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false, 7531 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed); 7532 } else { 7533 if (ExplicitTemplateArgs) 7534 continue; 7535 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet); 7536 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) 7537 AddOverloadCandidate(FD, F.getPair(), 7538 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, 7539 false, false, true, false, ADLCallKind::NotADL, 7540 None, OverloadCandidateParamOrder::Reversed); 7541 } 7542 } 7543 } 7544 7545 /// Add overload candidates for overloaded operators that are 7546 /// member functions. 7547 /// 7548 /// Add the overloaded operator candidates that are member functions 7549 /// for the operator Op that was used in an operator expression such 7550 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7551 /// CandidateSet will store the added overload candidates. (C++ 7552 /// [over.match.oper]). 7553 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7554 SourceLocation OpLoc, 7555 ArrayRef<Expr *> Args, 7556 OverloadCandidateSet &CandidateSet, 7557 OverloadCandidateParamOrder PO) { 7558 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7559 7560 // C++ [over.match.oper]p3: 7561 // For a unary operator @ with an operand of a type whose 7562 // cv-unqualified version is T1, and for a binary operator @ with 7563 // a left operand of a type whose cv-unqualified version is T1 and 7564 // a right operand of a type whose cv-unqualified version is T2, 7565 // three sets of candidate functions, designated member 7566 // candidates, non-member candidates and built-in candidates, are 7567 // constructed as follows: 7568 QualType T1 = Args[0]->getType(); 7569 7570 // -- If T1 is a complete class type or a class currently being 7571 // defined, the set of member candidates is the result of the 7572 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7573 // the set of member candidates is empty. 7574 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7575 // Complete the type if it can be completed. 7576 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7577 return; 7578 // If the type is neither complete nor being defined, bail out now. 7579 if (!T1Rec->getDecl()->getDefinition()) 7580 return; 7581 7582 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7583 LookupQualifiedName(Operators, T1Rec->getDecl()); 7584 Operators.suppressDiagnostics(); 7585 7586 for (LookupResult::iterator Oper = Operators.begin(), 7587 OperEnd = Operators.end(); 7588 Oper != OperEnd; 7589 ++Oper) 7590 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7591 Args[0]->Classify(Context), Args.slice(1), 7592 CandidateSet, /*SuppressUserConversion=*/false, PO); 7593 } 7594 } 7595 7596 /// AddBuiltinCandidate - Add a candidate for a built-in 7597 /// operator. ResultTy and ParamTys are the result and parameter types 7598 /// of the built-in candidate, respectively. Args and NumArgs are the 7599 /// arguments being passed to the candidate. IsAssignmentOperator 7600 /// should be true when this built-in candidate is an assignment 7601 /// operator. NumContextualBoolArguments is the number of arguments 7602 /// (at the beginning of the argument list) that will be contextually 7603 /// converted to bool. 7604 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7605 OverloadCandidateSet& CandidateSet, 7606 bool IsAssignmentOperator, 7607 unsigned NumContextualBoolArguments) { 7608 // Overload resolution is always an unevaluated context. 7609 EnterExpressionEvaluationContext Unevaluated( 7610 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7611 7612 // Add this candidate 7613 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7614 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7615 Candidate.Function = nullptr; 7616 Candidate.IsSurrogate = false; 7617 Candidate.IgnoreObjectArgument = false; 7618 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7619 7620 // Determine the implicit conversion sequences for each of the 7621 // arguments. 7622 Candidate.Viable = true; 7623 Candidate.ExplicitCallArguments = Args.size(); 7624 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7625 // C++ [over.match.oper]p4: 7626 // For the built-in assignment operators, conversions of the 7627 // left operand are restricted as follows: 7628 // -- no temporaries are introduced to hold the left operand, and 7629 // -- no user-defined conversions are applied to the left 7630 // operand to achieve a type match with the left-most 7631 // parameter of a built-in candidate. 7632 // 7633 // We block these conversions by turning off user-defined 7634 // conversions, since that is the only way that initialization of 7635 // a reference to a non-class type can occur from something that 7636 // is not of the same type. 7637 if (ArgIdx < NumContextualBoolArguments) { 7638 assert(ParamTys[ArgIdx] == Context.BoolTy && 7639 "Contextual conversion to bool requires bool type"); 7640 Candidate.Conversions[ArgIdx] 7641 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7642 } else { 7643 Candidate.Conversions[ArgIdx] 7644 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7645 ArgIdx == 0 && IsAssignmentOperator, 7646 /*InOverloadResolution=*/false, 7647 /*AllowObjCWritebackConversion=*/ 7648 getLangOpts().ObjCAutoRefCount); 7649 } 7650 if (Candidate.Conversions[ArgIdx].isBad()) { 7651 Candidate.Viable = false; 7652 Candidate.FailureKind = ovl_fail_bad_conversion; 7653 break; 7654 } 7655 } 7656 } 7657 7658 namespace { 7659 7660 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7661 /// candidate operator functions for built-in operators (C++ 7662 /// [over.built]). The types are separated into pointer types and 7663 /// enumeration types. 7664 class BuiltinCandidateTypeSet { 7665 /// TypeSet - A set of types. 7666 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7667 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7668 7669 /// PointerTypes - The set of pointer types that will be used in the 7670 /// built-in candidates. 7671 TypeSet PointerTypes; 7672 7673 /// MemberPointerTypes - The set of member pointer types that will be 7674 /// used in the built-in candidates. 7675 TypeSet MemberPointerTypes; 7676 7677 /// EnumerationTypes - The set of enumeration types that will be 7678 /// used in the built-in candidates. 7679 TypeSet EnumerationTypes; 7680 7681 /// The set of vector types that will be used in the built-in 7682 /// candidates. 7683 TypeSet VectorTypes; 7684 7685 /// The set of matrix types that will be used in the built-in 7686 /// candidates. 7687 TypeSet MatrixTypes; 7688 7689 /// A flag indicating non-record types are viable candidates 7690 bool HasNonRecordTypes; 7691 7692 /// A flag indicating whether either arithmetic or enumeration types 7693 /// were present in the candidate set. 7694 bool HasArithmeticOrEnumeralTypes; 7695 7696 /// A flag indicating whether the nullptr type was present in the 7697 /// candidate set. 7698 bool HasNullPtrType; 7699 7700 /// Sema - The semantic analysis instance where we are building the 7701 /// candidate type set. 7702 Sema &SemaRef; 7703 7704 /// Context - The AST context in which we will build the type sets. 7705 ASTContext &Context; 7706 7707 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7708 const Qualifiers &VisibleQuals); 7709 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7710 7711 public: 7712 /// iterator - Iterates through the types that are part of the set. 7713 typedef TypeSet::iterator iterator; 7714 7715 BuiltinCandidateTypeSet(Sema &SemaRef) 7716 : HasNonRecordTypes(false), 7717 HasArithmeticOrEnumeralTypes(false), 7718 HasNullPtrType(false), 7719 SemaRef(SemaRef), 7720 Context(SemaRef.Context) { } 7721 7722 void AddTypesConvertedFrom(QualType Ty, 7723 SourceLocation Loc, 7724 bool AllowUserConversions, 7725 bool AllowExplicitConversions, 7726 const Qualifiers &VisibleTypeConversionsQuals); 7727 7728 /// pointer_begin - First pointer type found; 7729 iterator pointer_begin() { return PointerTypes.begin(); } 7730 7731 /// pointer_end - Past the last pointer type found; 7732 iterator pointer_end() { return PointerTypes.end(); } 7733 7734 /// member_pointer_begin - First member pointer type found; 7735 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7736 7737 /// member_pointer_end - Past the last member pointer type found; 7738 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7739 7740 /// enumeration_begin - First enumeration type found; 7741 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7742 7743 /// enumeration_end - Past the last enumeration type found; 7744 iterator enumeration_end() { return EnumerationTypes.end(); } 7745 7746 iterator vector_begin() { return VectorTypes.begin(); } 7747 iterator vector_end() { return VectorTypes.end(); } 7748 7749 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; } 7750 iterator matrix_begin() { return MatrixTypes.begin(); } 7751 iterator matrix_end() { return MatrixTypes.end(); } 7752 7753 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); } 7754 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7755 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7756 bool hasNullPtrType() const { return HasNullPtrType; } 7757 }; 7758 7759 } // end anonymous namespace 7760 7761 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7762 /// the set of pointer types along with any more-qualified variants of 7763 /// that type. For example, if @p Ty is "int const *", this routine 7764 /// will add "int const *", "int const volatile *", "int const 7765 /// restrict *", and "int const volatile restrict *" to the set of 7766 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7767 /// false otherwise. 7768 /// 7769 /// FIXME: what to do about extended qualifiers? 7770 bool 7771 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7772 const Qualifiers &VisibleQuals) { 7773 7774 // Insert this type. 7775 if (!PointerTypes.insert(Ty)) 7776 return false; 7777 7778 QualType PointeeTy; 7779 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7780 bool buildObjCPtr = false; 7781 if (!PointerTy) { 7782 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7783 PointeeTy = PTy->getPointeeType(); 7784 buildObjCPtr = true; 7785 } else { 7786 PointeeTy = PointerTy->getPointeeType(); 7787 } 7788 7789 // Don't add qualified variants of arrays. For one, they're not allowed 7790 // (the qualifier would sink to the element type), and for another, the 7791 // only overload situation where it matters is subscript or pointer +- int, 7792 // and those shouldn't have qualifier variants anyway. 7793 if (PointeeTy->isArrayType()) 7794 return true; 7795 7796 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7797 bool hasVolatile = VisibleQuals.hasVolatile(); 7798 bool hasRestrict = VisibleQuals.hasRestrict(); 7799 7800 // Iterate through all strict supersets of BaseCVR. 7801 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7802 if ((CVR | BaseCVR) != CVR) continue; 7803 // Skip over volatile if no volatile found anywhere in the types. 7804 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7805 7806 // Skip over restrict if no restrict found anywhere in the types, or if 7807 // the type cannot be restrict-qualified. 7808 if ((CVR & Qualifiers::Restrict) && 7809 (!hasRestrict || 7810 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7811 continue; 7812 7813 // Build qualified pointee type. 7814 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7815 7816 // Build qualified pointer type. 7817 QualType QPointerTy; 7818 if (!buildObjCPtr) 7819 QPointerTy = Context.getPointerType(QPointeeTy); 7820 else 7821 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7822 7823 // Insert qualified pointer type. 7824 PointerTypes.insert(QPointerTy); 7825 } 7826 7827 return true; 7828 } 7829 7830 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7831 /// to the set of pointer types along with any more-qualified variants of 7832 /// that type. For example, if @p Ty is "int const *", this routine 7833 /// will add "int const *", "int const volatile *", "int const 7834 /// restrict *", and "int const volatile restrict *" to the set of 7835 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7836 /// false otherwise. 7837 /// 7838 /// FIXME: what to do about extended qualifiers? 7839 bool 7840 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7841 QualType Ty) { 7842 // Insert this type. 7843 if (!MemberPointerTypes.insert(Ty)) 7844 return false; 7845 7846 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7847 assert(PointerTy && "type was not a member pointer type!"); 7848 7849 QualType PointeeTy = PointerTy->getPointeeType(); 7850 // Don't add qualified variants of arrays. For one, they're not allowed 7851 // (the qualifier would sink to the element type), and for another, the 7852 // only overload situation where it matters is subscript or pointer +- int, 7853 // and those shouldn't have qualifier variants anyway. 7854 if (PointeeTy->isArrayType()) 7855 return true; 7856 const Type *ClassTy = PointerTy->getClass(); 7857 7858 // Iterate through all strict supersets of the pointee type's CVR 7859 // qualifiers. 7860 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7861 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7862 if ((CVR | BaseCVR) != CVR) continue; 7863 7864 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7865 MemberPointerTypes.insert( 7866 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7867 } 7868 7869 return true; 7870 } 7871 7872 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7873 /// Ty can be implicit converted to the given set of @p Types. We're 7874 /// primarily interested in pointer types and enumeration types. We also 7875 /// take member pointer types, for the conditional operator. 7876 /// AllowUserConversions is true if we should look at the conversion 7877 /// functions of a class type, and AllowExplicitConversions if we 7878 /// should also include the explicit conversion functions of a class 7879 /// type. 7880 void 7881 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7882 SourceLocation Loc, 7883 bool AllowUserConversions, 7884 bool AllowExplicitConversions, 7885 const Qualifiers &VisibleQuals) { 7886 // Only deal with canonical types. 7887 Ty = Context.getCanonicalType(Ty); 7888 7889 // Look through reference types; they aren't part of the type of an 7890 // expression for the purposes of conversions. 7891 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7892 Ty = RefTy->getPointeeType(); 7893 7894 // If we're dealing with an array type, decay to the pointer. 7895 if (Ty->isArrayType()) 7896 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7897 7898 // Otherwise, we don't care about qualifiers on the type. 7899 Ty = Ty.getLocalUnqualifiedType(); 7900 7901 // Flag if we ever add a non-record type. 7902 const RecordType *TyRec = Ty->getAs<RecordType>(); 7903 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7904 7905 // Flag if we encounter an arithmetic type. 7906 HasArithmeticOrEnumeralTypes = 7907 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7908 7909 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7910 PointerTypes.insert(Ty); 7911 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7912 // Insert our type, and its more-qualified variants, into the set 7913 // of types. 7914 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7915 return; 7916 } else if (Ty->isMemberPointerType()) { 7917 // Member pointers are far easier, since the pointee can't be converted. 7918 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7919 return; 7920 } else if (Ty->isEnumeralType()) { 7921 HasArithmeticOrEnumeralTypes = true; 7922 EnumerationTypes.insert(Ty); 7923 } else if (Ty->isVectorType()) { 7924 // We treat vector types as arithmetic types in many contexts as an 7925 // extension. 7926 HasArithmeticOrEnumeralTypes = true; 7927 VectorTypes.insert(Ty); 7928 } else if (Ty->isMatrixType()) { 7929 // Similar to vector types, we treat vector types as arithmetic types in 7930 // many contexts as an extension. 7931 HasArithmeticOrEnumeralTypes = true; 7932 MatrixTypes.insert(Ty); 7933 } else if (Ty->isNullPtrType()) { 7934 HasNullPtrType = true; 7935 } else if (AllowUserConversions && TyRec) { 7936 // No conversion functions in incomplete types. 7937 if (!SemaRef.isCompleteType(Loc, Ty)) 7938 return; 7939 7940 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7941 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7942 if (isa<UsingShadowDecl>(D)) 7943 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7944 7945 // Skip conversion function templates; they don't tell us anything 7946 // about which builtin types we can convert to. 7947 if (isa<FunctionTemplateDecl>(D)) 7948 continue; 7949 7950 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7951 if (AllowExplicitConversions || !Conv->isExplicit()) { 7952 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7953 VisibleQuals); 7954 } 7955 } 7956 } 7957 } 7958 /// Helper function for adjusting address spaces for the pointer or reference 7959 /// operands of builtin operators depending on the argument. 7960 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7961 Expr *Arg) { 7962 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7963 } 7964 7965 /// Helper function for AddBuiltinOperatorCandidates() that adds 7966 /// the volatile- and non-volatile-qualified assignment operators for the 7967 /// given type to the candidate set. 7968 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7969 QualType T, 7970 ArrayRef<Expr *> Args, 7971 OverloadCandidateSet &CandidateSet) { 7972 QualType ParamTypes[2]; 7973 7974 // T& operator=(T&, T) 7975 ParamTypes[0] = S.Context.getLValueReferenceType( 7976 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7977 ParamTypes[1] = T; 7978 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7979 /*IsAssignmentOperator=*/true); 7980 7981 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7982 // volatile T& operator=(volatile T&, T) 7983 ParamTypes[0] = S.Context.getLValueReferenceType( 7984 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7985 Args[0])); 7986 ParamTypes[1] = T; 7987 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7988 /*IsAssignmentOperator=*/true); 7989 } 7990 } 7991 7992 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7993 /// if any, found in visible type conversion functions found in ArgExpr's type. 7994 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7995 Qualifiers VRQuals; 7996 const RecordType *TyRec; 7997 if (const MemberPointerType *RHSMPType = 7998 ArgExpr->getType()->getAs<MemberPointerType>()) 7999 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 8000 else 8001 TyRec = ArgExpr->getType()->getAs<RecordType>(); 8002 if (!TyRec) { 8003 // Just to be safe, assume the worst case. 8004 VRQuals.addVolatile(); 8005 VRQuals.addRestrict(); 8006 return VRQuals; 8007 } 8008 8009 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 8010 if (!ClassDecl->hasDefinition()) 8011 return VRQuals; 8012 8013 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 8014 if (isa<UsingShadowDecl>(D)) 8015 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 8016 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 8017 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 8018 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 8019 CanTy = ResTypeRef->getPointeeType(); 8020 // Need to go down the pointer/mempointer chain and add qualifiers 8021 // as see them. 8022 bool done = false; 8023 while (!done) { 8024 if (CanTy.isRestrictQualified()) 8025 VRQuals.addRestrict(); 8026 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 8027 CanTy = ResTypePtr->getPointeeType(); 8028 else if (const MemberPointerType *ResTypeMPtr = 8029 CanTy->getAs<MemberPointerType>()) 8030 CanTy = ResTypeMPtr->getPointeeType(); 8031 else 8032 done = true; 8033 if (CanTy.isVolatileQualified()) 8034 VRQuals.addVolatile(); 8035 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 8036 return VRQuals; 8037 } 8038 } 8039 } 8040 return VRQuals; 8041 } 8042 8043 namespace { 8044 8045 /// Helper class to manage the addition of builtin operator overload 8046 /// candidates. It provides shared state and utility methods used throughout 8047 /// the process, as well as a helper method to add each group of builtin 8048 /// operator overloads from the standard to a candidate set. 8049 class BuiltinOperatorOverloadBuilder { 8050 // Common instance state available to all overload candidate addition methods. 8051 Sema &S; 8052 ArrayRef<Expr *> Args; 8053 Qualifiers VisibleTypeConversionsQuals; 8054 bool HasArithmeticOrEnumeralCandidateType; 8055 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 8056 OverloadCandidateSet &CandidateSet; 8057 8058 static constexpr int ArithmeticTypesCap = 24; 8059 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 8060 8061 // Define some indices used to iterate over the arithmetic types in 8062 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 8063 // types are that preserved by promotion (C++ [over.built]p2). 8064 unsigned FirstIntegralType, 8065 LastIntegralType; 8066 unsigned FirstPromotedIntegralType, 8067 LastPromotedIntegralType; 8068 unsigned FirstPromotedArithmeticType, 8069 LastPromotedArithmeticType; 8070 unsigned NumArithmeticTypes; 8071 8072 void InitArithmeticTypes() { 8073 // Start of promoted types. 8074 FirstPromotedArithmeticType = 0; 8075 ArithmeticTypes.push_back(S.Context.FloatTy); 8076 ArithmeticTypes.push_back(S.Context.DoubleTy); 8077 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 8078 if (S.Context.getTargetInfo().hasFloat128Type()) 8079 ArithmeticTypes.push_back(S.Context.Float128Ty); 8080 8081 // Start of integral types. 8082 FirstIntegralType = ArithmeticTypes.size(); 8083 FirstPromotedIntegralType = ArithmeticTypes.size(); 8084 ArithmeticTypes.push_back(S.Context.IntTy); 8085 ArithmeticTypes.push_back(S.Context.LongTy); 8086 ArithmeticTypes.push_back(S.Context.LongLongTy); 8087 if (S.Context.getTargetInfo().hasInt128Type()) 8088 ArithmeticTypes.push_back(S.Context.Int128Ty); 8089 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 8090 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 8091 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 8092 if (S.Context.getTargetInfo().hasInt128Type()) 8093 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 8094 LastPromotedIntegralType = ArithmeticTypes.size(); 8095 LastPromotedArithmeticType = ArithmeticTypes.size(); 8096 // End of promoted types. 8097 8098 ArithmeticTypes.push_back(S.Context.BoolTy); 8099 ArithmeticTypes.push_back(S.Context.CharTy); 8100 ArithmeticTypes.push_back(S.Context.WCharTy); 8101 if (S.Context.getLangOpts().Char8) 8102 ArithmeticTypes.push_back(S.Context.Char8Ty); 8103 ArithmeticTypes.push_back(S.Context.Char16Ty); 8104 ArithmeticTypes.push_back(S.Context.Char32Ty); 8105 ArithmeticTypes.push_back(S.Context.SignedCharTy); 8106 ArithmeticTypes.push_back(S.Context.ShortTy); 8107 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 8108 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 8109 LastIntegralType = ArithmeticTypes.size(); 8110 NumArithmeticTypes = ArithmeticTypes.size(); 8111 // End of integral types. 8112 // FIXME: What about complex? What about half? 8113 8114 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 8115 "Enough inline storage for all arithmetic types."); 8116 } 8117 8118 /// Helper method to factor out the common pattern of adding overloads 8119 /// for '++' and '--' builtin operators. 8120 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 8121 bool HasVolatile, 8122 bool HasRestrict) { 8123 QualType ParamTypes[2] = { 8124 S.Context.getLValueReferenceType(CandidateTy), 8125 S.Context.IntTy 8126 }; 8127 8128 // Non-volatile version. 8129 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8130 8131 // Use a heuristic to reduce number of builtin candidates in the set: 8132 // add volatile version only if there are conversions to a volatile type. 8133 if (HasVolatile) { 8134 ParamTypes[0] = 8135 S.Context.getLValueReferenceType( 8136 S.Context.getVolatileType(CandidateTy)); 8137 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8138 } 8139 8140 // Add restrict version only if there are conversions to a restrict type 8141 // and our candidate type is a non-restrict-qualified pointer. 8142 if (HasRestrict && CandidateTy->isAnyPointerType() && 8143 !CandidateTy.isRestrictQualified()) { 8144 ParamTypes[0] 8145 = S.Context.getLValueReferenceType( 8146 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 8147 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8148 8149 if (HasVolatile) { 8150 ParamTypes[0] 8151 = S.Context.getLValueReferenceType( 8152 S.Context.getCVRQualifiedType(CandidateTy, 8153 (Qualifiers::Volatile | 8154 Qualifiers::Restrict))); 8155 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8156 } 8157 } 8158 8159 } 8160 8161 /// Helper to add an overload candidate for a binary builtin with types \p L 8162 /// and \p R. 8163 void AddCandidate(QualType L, QualType R) { 8164 QualType LandR[2] = {L, R}; 8165 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8166 } 8167 8168 public: 8169 BuiltinOperatorOverloadBuilder( 8170 Sema &S, ArrayRef<Expr *> Args, 8171 Qualifiers VisibleTypeConversionsQuals, 8172 bool HasArithmeticOrEnumeralCandidateType, 8173 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 8174 OverloadCandidateSet &CandidateSet) 8175 : S(S), Args(Args), 8176 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 8177 HasArithmeticOrEnumeralCandidateType( 8178 HasArithmeticOrEnumeralCandidateType), 8179 CandidateTypes(CandidateTypes), 8180 CandidateSet(CandidateSet) { 8181 8182 InitArithmeticTypes(); 8183 } 8184 8185 // Increment is deprecated for bool since C++17. 8186 // 8187 // C++ [over.built]p3: 8188 // 8189 // For every pair (T, VQ), where T is an arithmetic type other 8190 // than bool, and VQ is either volatile or empty, there exist 8191 // candidate operator functions of the form 8192 // 8193 // VQ T& operator++(VQ T&); 8194 // T operator++(VQ T&, int); 8195 // 8196 // C++ [over.built]p4: 8197 // 8198 // For every pair (T, VQ), where T is an arithmetic type other 8199 // than bool, and VQ is either volatile or empty, there exist 8200 // candidate operator functions of the form 8201 // 8202 // VQ T& operator--(VQ T&); 8203 // T operator--(VQ T&, int); 8204 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 8205 if (!HasArithmeticOrEnumeralCandidateType) 8206 return; 8207 8208 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 8209 const auto TypeOfT = ArithmeticTypes[Arith]; 8210 if (TypeOfT == S.Context.BoolTy) { 8211 if (Op == OO_MinusMinus) 8212 continue; 8213 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 8214 continue; 8215 } 8216 addPlusPlusMinusMinusStyleOverloads( 8217 TypeOfT, 8218 VisibleTypeConversionsQuals.hasVolatile(), 8219 VisibleTypeConversionsQuals.hasRestrict()); 8220 } 8221 } 8222 8223 // C++ [over.built]p5: 8224 // 8225 // For every pair (T, VQ), where T is a cv-qualified or 8226 // cv-unqualified object type, and VQ is either volatile or 8227 // empty, there exist candidate operator functions of the form 8228 // 8229 // T*VQ& operator++(T*VQ&); 8230 // T*VQ& operator--(T*VQ&); 8231 // T* operator++(T*VQ&, int); 8232 // T* operator--(T*VQ&, int); 8233 void addPlusPlusMinusMinusPointerOverloads() { 8234 for (BuiltinCandidateTypeSet::iterator 8235 Ptr = CandidateTypes[0].pointer_begin(), 8236 PtrEnd = CandidateTypes[0].pointer_end(); 8237 Ptr != PtrEnd; ++Ptr) { 8238 // Skip pointer types that aren't pointers to object types. 8239 if (!(*Ptr)->getPointeeType()->isObjectType()) 8240 continue; 8241 8242 addPlusPlusMinusMinusStyleOverloads(*Ptr, 8243 (!(*Ptr).isVolatileQualified() && 8244 VisibleTypeConversionsQuals.hasVolatile()), 8245 (!(*Ptr).isRestrictQualified() && 8246 VisibleTypeConversionsQuals.hasRestrict())); 8247 } 8248 } 8249 8250 // C++ [over.built]p6: 8251 // For every cv-qualified or cv-unqualified object type T, there 8252 // exist candidate operator functions of the form 8253 // 8254 // T& operator*(T*); 8255 // 8256 // C++ [over.built]p7: 8257 // For every function type T that does not have cv-qualifiers or a 8258 // ref-qualifier, there exist candidate operator functions of the form 8259 // T& operator*(T*); 8260 void addUnaryStarPointerOverloads() { 8261 for (BuiltinCandidateTypeSet::iterator 8262 Ptr = CandidateTypes[0].pointer_begin(), 8263 PtrEnd = CandidateTypes[0].pointer_end(); 8264 Ptr != PtrEnd; ++Ptr) { 8265 QualType ParamTy = *Ptr; 8266 QualType PointeeTy = ParamTy->getPointeeType(); 8267 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 8268 continue; 8269 8270 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 8271 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 8272 continue; 8273 8274 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8275 } 8276 } 8277 8278 // C++ [over.built]p9: 8279 // For every promoted arithmetic type T, there exist candidate 8280 // operator functions of the form 8281 // 8282 // T operator+(T); 8283 // T operator-(T); 8284 void addUnaryPlusOrMinusArithmeticOverloads() { 8285 if (!HasArithmeticOrEnumeralCandidateType) 8286 return; 8287 8288 for (unsigned Arith = FirstPromotedArithmeticType; 8289 Arith < LastPromotedArithmeticType; ++Arith) { 8290 QualType ArithTy = ArithmeticTypes[Arith]; 8291 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 8292 } 8293 8294 // Extension: We also add these operators for vector types. 8295 for (BuiltinCandidateTypeSet::iterator 8296 Vec = CandidateTypes[0].vector_begin(), 8297 VecEnd = CandidateTypes[0].vector_end(); 8298 Vec != VecEnd; ++Vec) { 8299 QualType VecTy = *Vec; 8300 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8301 } 8302 } 8303 8304 // C++ [over.built]p8: 8305 // For every type T, there exist candidate operator functions of 8306 // the form 8307 // 8308 // T* operator+(T*); 8309 void addUnaryPlusPointerOverloads() { 8310 for (BuiltinCandidateTypeSet::iterator 8311 Ptr = CandidateTypes[0].pointer_begin(), 8312 PtrEnd = CandidateTypes[0].pointer_end(); 8313 Ptr != PtrEnd; ++Ptr) { 8314 QualType ParamTy = *Ptr; 8315 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8316 } 8317 } 8318 8319 // C++ [over.built]p10: 8320 // For every promoted integral type T, there exist candidate 8321 // operator functions of the form 8322 // 8323 // T operator~(T); 8324 void addUnaryTildePromotedIntegralOverloads() { 8325 if (!HasArithmeticOrEnumeralCandidateType) 8326 return; 8327 8328 for (unsigned Int = FirstPromotedIntegralType; 8329 Int < LastPromotedIntegralType; ++Int) { 8330 QualType IntTy = ArithmeticTypes[Int]; 8331 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8332 } 8333 8334 // Extension: We also add this operator for vector types. 8335 for (BuiltinCandidateTypeSet::iterator 8336 Vec = CandidateTypes[0].vector_begin(), 8337 VecEnd = CandidateTypes[0].vector_end(); 8338 Vec != VecEnd; ++Vec) { 8339 QualType VecTy = *Vec; 8340 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8341 } 8342 } 8343 8344 // C++ [over.match.oper]p16: 8345 // For every pointer to member type T or type std::nullptr_t, there 8346 // exist candidate operator functions of the form 8347 // 8348 // bool operator==(T,T); 8349 // bool operator!=(T,T); 8350 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8351 /// Set of (canonical) types that we've already handled. 8352 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8353 8354 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8355 for (BuiltinCandidateTypeSet::iterator 8356 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8357 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8358 MemPtr != MemPtrEnd; 8359 ++MemPtr) { 8360 // Don't add the same builtin candidate twice. 8361 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8362 continue; 8363 8364 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8365 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8366 } 8367 8368 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8369 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8370 if (AddedTypes.insert(NullPtrTy).second) { 8371 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8372 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8373 } 8374 } 8375 } 8376 } 8377 8378 // C++ [over.built]p15: 8379 // 8380 // For every T, where T is an enumeration type or a pointer type, 8381 // there exist candidate operator functions of the form 8382 // 8383 // bool operator<(T, T); 8384 // bool operator>(T, T); 8385 // bool operator<=(T, T); 8386 // bool operator>=(T, T); 8387 // bool operator==(T, T); 8388 // bool operator!=(T, T); 8389 // R operator<=>(T, T) 8390 void addGenericBinaryPointerOrEnumeralOverloads() { 8391 // C++ [over.match.oper]p3: 8392 // [...]the built-in candidates include all of the candidate operator 8393 // functions defined in 13.6 that, compared to the given operator, [...] 8394 // do not have the same parameter-type-list as any non-template non-member 8395 // candidate. 8396 // 8397 // Note that in practice, this only affects enumeration types because there 8398 // aren't any built-in candidates of record type, and a user-defined operator 8399 // must have an operand of record or enumeration type. Also, the only other 8400 // overloaded operator with enumeration arguments, operator=, 8401 // cannot be overloaded for enumeration types, so this is the only place 8402 // where we must suppress candidates like this. 8403 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8404 UserDefinedBinaryOperators; 8405 8406 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8407 if (CandidateTypes[ArgIdx].enumeration_begin() != 8408 CandidateTypes[ArgIdx].enumeration_end()) { 8409 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8410 CEnd = CandidateSet.end(); 8411 C != CEnd; ++C) { 8412 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8413 continue; 8414 8415 if (C->Function->isFunctionTemplateSpecialization()) 8416 continue; 8417 8418 // We interpret "same parameter-type-list" as applying to the 8419 // "synthesized candidate, with the order of the two parameters 8420 // reversed", not to the original function. 8421 bool Reversed = C->isReversed(); 8422 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0) 8423 ->getType() 8424 .getUnqualifiedType(); 8425 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1) 8426 ->getType() 8427 .getUnqualifiedType(); 8428 8429 // Skip if either parameter isn't of enumeral type. 8430 if (!FirstParamType->isEnumeralType() || 8431 !SecondParamType->isEnumeralType()) 8432 continue; 8433 8434 // Add this operator to the set of known user-defined operators. 8435 UserDefinedBinaryOperators.insert( 8436 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8437 S.Context.getCanonicalType(SecondParamType))); 8438 } 8439 } 8440 } 8441 8442 /// Set of (canonical) types that we've already handled. 8443 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8444 8445 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8446 for (BuiltinCandidateTypeSet::iterator 8447 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8448 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8449 Ptr != PtrEnd; ++Ptr) { 8450 // Don't add the same builtin candidate twice. 8451 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8452 continue; 8453 8454 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8455 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8456 } 8457 for (BuiltinCandidateTypeSet::iterator 8458 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8459 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8460 Enum != EnumEnd; ++Enum) { 8461 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8462 8463 // Don't add the same builtin candidate twice, or if a user defined 8464 // candidate exists. 8465 if (!AddedTypes.insert(CanonType).second || 8466 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8467 CanonType))) 8468 continue; 8469 QualType ParamTypes[2] = { *Enum, *Enum }; 8470 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8471 } 8472 } 8473 } 8474 8475 // C++ [over.built]p13: 8476 // 8477 // For every cv-qualified or cv-unqualified object type T 8478 // there exist candidate operator functions of the form 8479 // 8480 // T* operator+(T*, ptrdiff_t); 8481 // T& operator[](T*, ptrdiff_t); [BELOW] 8482 // T* operator-(T*, ptrdiff_t); 8483 // T* operator+(ptrdiff_t, T*); 8484 // T& operator[](ptrdiff_t, T*); [BELOW] 8485 // 8486 // C++ [over.built]p14: 8487 // 8488 // For every T, where T is a pointer to object type, there 8489 // exist candidate operator functions of the form 8490 // 8491 // ptrdiff_t operator-(T, T); 8492 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8493 /// Set of (canonical) types that we've already handled. 8494 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8495 8496 for (int Arg = 0; Arg < 2; ++Arg) { 8497 QualType AsymmetricParamTypes[2] = { 8498 S.Context.getPointerDiffType(), 8499 S.Context.getPointerDiffType(), 8500 }; 8501 for (BuiltinCandidateTypeSet::iterator 8502 Ptr = CandidateTypes[Arg].pointer_begin(), 8503 PtrEnd = CandidateTypes[Arg].pointer_end(); 8504 Ptr != PtrEnd; ++Ptr) { 8505 QualType PointeeTy = (*Ptr)->getPointeeType(); 8506 if (!PointeeTy->isObjectType()) 8507 continue; 8508 8509 AsymmetricParamTypes[Arg] = *Ptr; 8510 if (Arg == 0 || Op == OO_Plus) { 8511 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8512 // T* operator+(ptrdiff_t, T*); 8513 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8514 } 8515 if (Op == OO_Minus) { 8516 // ptrdiff_t operator-(T, T); 8517 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8518 continue; 8519 8520 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8521 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8522 } 8523 } 8524 } 8525 } 8526 8527 // C++ [over.built]p12: 8528 // 8529 // For every pair of promoted arithmetic types L and R, there 8530 // exist candidate operator functions of the form 8531 // 8532 // LR operator*(L, R); 8533 // LR operator/(L, R); 8534 // LR operator+(L, R); 8535 // LR operator-(L, R); 8536 // bool operator<(L, R); 8537 // bool operator>(L, R); 8538 // bool operator<=(L, R); 8539 // bool operator>=(L, R); 8540 // bool operator==(L, R); 8541 // bool operator!=(L, R); 8542 // 8543 // where LR is the result of the usual arithmetic conversions 8544 // between types L and R. 8545 // 8546 // C++ [over.built]p24: 8547 // 8548 // For every pair of promoted arithmetic types L and R, there exist 8549 // candidate operator functions of the form 8550 // 8551 // LR operator?(bool, L, R); 8552 // 8553 // where LR is the result of the usual arithmetic conversions 8554 // between types L and R. 8555 // Our candidates ignore the first parameter. 8556 void addGenericBinaryArithmeticOverloads() { 8557 if (!HasArithmeticOrEnumeralCandidateType) 8558 return; 8559 8560 for (unsigned Left = FirstPromotedArithmeticType; 8561 Left < LastPromotedArithmeticType; ++Left) { 8562 for (unsigned Right = FirstPromotedArithmeticType; 8563 Right < LastPromotedArithmeticType; ++Right) { 8564 QualType LandR[2] = { ArithmeticTypes[Left], 8565 ArithmeticTypes[Right] }; 8566 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8567 } 8568 } 8569 8570 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8571 // conditional operator for vector types. 8572 for (BuiltinCandidateTypeSet::iterator 8573 Vec1 = CandidateTypes[0].vector_begin(), 8574 Vec1End = CandidateTypes[0].vector_end(); 8575 Vec1 != Vec1End; ++Vec1) { 8576 for (BuiltinCandidateTypeSet::iterator 8577 Vec2 = CandidateTypes[1].vector_begin(), 8578 Vec2End = CandidateTypes[1].vector_end(); 8579 Vec2 != Vec2End; ++Vec2) { 8580 QualType LandR[2] = { *Vec1, *Vec2 }; 8581 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8582 } 8583 } 8584 } 8585 8586 /// Add binary operator overloads for each candidate matrix type M1, M2: 8587 /// * (M1, M1) -> M1 8588 /// * (M1, M1.getElementType()) -> M1 8589 /// * (M2.getElementType(), M2) -> M2 8590 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0]. 8591 void addMatrixBinaryArithmeticOverloads() { 8592 if (!HasArithmeticOrEnumeralCandidateType) 8593 return; 8594 8595 for (QualType M1 : CandidateTypes[0].matrix_types()) { 8596 AddCandidate(M1, cast<MatrixType>(M1)->getElementType()); 8597 AddCandidate(M1, M1); 8598 } 8599 8600 for (QualType M2 : CandidateTypes[1].matrix_types()) { 8601 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2); 8602 if (!CandidateTypes[0].containsMatrixType(M2)) 8603 AddCandidate(M2, M2); 8604 } 8605 } 8606 8607 // C++2a [over.built]p14: 8608 // 8609 // For every integral type T there exists a candidate operator function 8610 // of the form 8611 // 8612 // std::strong_ordering operator<=>(T, T) 8613 // 8614 // C++2a [over.built]p15: 8615 // 8616 // For every pair of floating-point types L and R, there exists a candidate 8617 // operator function of the form 8618 // 8619 // std::partial_ordering operator<=>(L, R); 8620 // 8621 // FIXME: The current specification for integral types doesn't play nice with 8622 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8623 // comparisons. Under the current spec this can lead to ambiguity during 8624 // overload resolution. For example: 8625 // 8626 // enum A : int {a}; 8627 // auto x = (a <=> (long)42); 8628 // 8629 // error: call is ambiguous for arguments 'A' and 'long'. 8630 // note: candidate operator<=>(int, int) 8631 // note: candidate operator<=>(long, long) 8632 // 8633 // To avoid this error, this function deviates from the specification and adds 8634 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8635 // arithmetic types (the same as the generic relational overloads). 8636 // 8637 // For now this function acts as a placeholder. 8638 void addThreeWayArithmeticOverloads() { 8639 addGenericBinaryArithmeticOverloads(); 8640 } 8641 8642 // C++ [over.built]p17: 8643 // 8644 // For every pair of promoted integral types L and R, there 8645 // exist candidate operator functions of the form 8646 // 8647 // LR operator%(L, R); 8648 // LR operator&(L, R); 8649 // LR operator^(L, R); 8650 // LR operator|(L, R); 8651 // L operator<<(L, R); 8652 // L operator>>(L, R); 8653 // 8654 // where LR is the result of the usual arithmetic conversions 8655 // between types L and R. 8656 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8657 if (!HasArithmeticOrEnumeralCandidateType) 8658 return; 8659 8660 for (unsigned Left = FirstPromotedIntegralType; 8661 Left < LastPromotedIntegralType; ++Left) { 8662 for (unsigned Right = FirstPromotedIntegralType; 8663 Right < LastPromotedIntegralType; ++Right) { 8664 QualType LandR[2] = { ArithmeticTypes[Left], 8665 ArithmeticTypes[Right] }; 8666 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8667 } 8668 } 8669 } 8670 8671 // C++ [over.built]p20: 8672 // 8673 // For every pair (T, VQ), where T is an enumeration or 8674 // pointer to member type and VQ is either volatile or 8675 // empty, there exist candidate operator functions of the form 8676 // 8677 // VQ T& operator=(VQ T&, T); 8678 void addAssignmentMemberPointerOrEnumeralOverloads() { 8679 /// Set of (canonical) types that we've already handled. 8680 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8681 8682 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8683 for (BuiltinCandidateTypeSet::iterator 8684 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8685 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8686 Enum != EnumEnd; ++Enum) { 8687 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8688 continue; 8689 8690 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8691 } 8692 8693 for (BuiltinCandidateTypeSet::iterator 8694 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8695 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8696 MemPtr != MemPtrEnd; ++MemPtr) { 8697 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8698 continue; 8699 8700 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8701 } 8702 } 8703 } 8704 8705 // C++ [over.built]p19: 8706 // 8707 // For every pair (T, VQ), where T is any type and VQ is either 8708 // volatile or empty, there exist candidate operator functions 8709 // of the form 8710 // 8711 // T*VQ& operator=(T*VQ&, T*); 8712 // 8713 // C++ [over.built]p21: 8714 // 8715 // For every pair (T, VQ), where T is a cv-qualified or 8716 // cv-unqualified object type and VQ is either volatile or 8717 // empty, there exist candidate operator functions of the form 8718 // 8719 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8720 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8721 void addAssignmentPointerOverloads(bool isEqualOp) { 8722 /// Set of (canonical) types that we've already handled. 8723 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8724 8725 for (BuiltinCandidateTypeSet::iterator 8726 Ptr = CandidateTypes[0].pointer_begin(), 8727 PtrEnd = CandidateTypes[0].pointer_end(); 8728 Ptr != PtrEnd; ++Ptr) { 8729 // If this is operator=, keep track of the builtin candidates we added. 8730 if (isEqualOp) 8731 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8732 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8733 continue; 8734 8735 // non-volatile version 8736 QualType ParamTypes[2] = { 8737 S.Context.getLValueReferenceType(*Ptr), 8738 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8739 }; 8740 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8741 /*IsAssignmentOperator=*/ isEqualOp); 8742 8743 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8744 VisibleTypeConversionsQuals.hasVolatile(); 8745 if (NeedVolatile) { 8746 // volatile version 8747 ParamTypes[0] = 8748 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8749 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8750 /*IsAssignmentOperator=*/isEqualOp); 8751 } 8752 8753 if (!(*Ptr).isRestrictQualified() && 8754 VisibleTypeConversionsQuals.hasRestrict()) { 8755 // restrict version 8756 ParamTypes[0] 8757 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8758 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8759 /*IsAssignmentOperator=*/isEqualOp); 8760 8761 if (NeedVolatile) { 8762 // volatile restrict version 8763 ParamTypes[0] 8764 = S.Context.getLValueReferenceType( 8765 S.Context.getCVRQualifiedType(*Ptr, 8766 (Qualifiers::Volatile | 8767 Qualifiers::Restrict))); 8768 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8769 /*IsAssignmentOperator=*/isEqualOp); 8770 } 8771 } 8772 } 8773 8774 if (isEqualOp) { 8775 for (BuiltinCandidateTypeSet::iterator 8776 Ptr = CandidateTypes[1].pointer_begin(), 8777 PtrEnd = CandidateTypes[1].pointer_end(); 8778 Ptr != PtrEnd; ++Ptr) { 8779 // Make sure we don't add the same candidate twice. 8780 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8781 continue; 8782 8783 QualType ParamTypes[2] = { 8784 S.Context.getLValueReferenceType(*Ptr), 8785 *Ptr, 8786 }; 8787 8788 // non-volatile version 8789 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8790 /*IsAssignmentOperator=*/true); 8791 8792 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8793 VisibleTypeConversionsQuals.hasVolatile(); 8794 if (NeedVolatile) { 8795 // volatile version 8796 ParamTypes[0] = 8797 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8798 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8799 /*IsAssignmentOperator=*/true); 8800 } 8801 8802 if (!(*Ptr).isRestrictQualified() && 8803 VisibleTypeConversionsQuals.hasRestrict()) { 8804 // restrict version 8805 ParamTypes[0] 8806 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8807 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8808 /*IsAssignmentOperator=*/true); 8809 8810 if (NeedVolatile) { 8811 // volatile restrict version 8812 ParamTypes[0] 8813 = S.Context.getLValueReferenceType( 8814 S.Context.getCVRQualifiedType(*Ptr, 8815 (Qualifiers::Volatile | 8816 Qualifiers::Restrict))); 8817 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8818 /*IsAssignmentOperator=*/true); 8819 } 8820 } 8821 } 8822 } 8823 } 8824 8825 // C++ [over.built]p18: 8826 // 8827 // For every triple (L, VQ, R), where L is an arithmetic type, 8828 // VQ is either volatile or empty, and R is a promoted 8829 // arithmetic type, there exist candidate operator functions of 8830 // the form 8831 // 8832 // VQ L& operator=(VQ L&, R); 8833 // VQ L& operator*=(VQ L&, R); 8834 // VQ L& operator/=(VQ L&, R); 8835 // VQ L& operator+=(VQ L&, R); 8836 // VQ L& operator-=(VQ L&, R); 8837 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8838 if (!HasArithmeticOrEnumeralCandidateType) 8839 return; 8840 8841 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8842 for (unsigned Right = FirstPromotedArithmeticType; 8843 Right < LastPromotedArithmeticType; ++Right) { 8844 QualType ParamTypes[2]; 8845 ParamTypes[1] = ArithmeticTypes[Right]; 8846 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8847 S, ArithmeticTypes[Left], Args[0]); 8848 // Add this built-in operator as a candidate (VQ is empty). 8849 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8850 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8851 /*IsAssignmentOperator=*/isEqualOp); 8852 8853 // Add this built-in operator as a candidate (VQ is 'volatile'). 8854 if (VisibleTypeConversionsQuals.hasVolatile()) { 8855 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy); 8856 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8857 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8858 /*IsAssignmentOperator=*/isEqualOp); 8859 } 8860 } 8861 } 8862 8863 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8864 for (BuiltinCandidateTypeSet::iterator 8865 Vec1 = CandidateTypes[0].vector_begin(), 8866 Vec1End = CandidateTypes[0].vector_end(); 8867 Vec1 != Vec1End; ++Vec1) { 8868 for (BuiltinCandidateTypeSet::iterator 8869 Vec2 = CandidateTypes[1].vector_begin(), 8870 Vec2End = CandidateTypes[1].vector_end(); 8871 Vec2 != Vec2End; ++Vec2) { 8872 QualType ParamTypes[2]; 8873 ParamTypes[1] = *Vec2; 8874 // Add this built-in operator as a candidate (VQ is empty). 8875 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 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(*Vec1); 8882 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8883 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8884 /*IsAssignmentOperator=*/isEqualOp); 8885 } 8886 } 8887 } 8888 } 8889 8890 // C++ [over.built]p22: 8891 // 8892 // For every triple (L, VQ, R), where L is an integral type, VQ 8893 // is either volatile or empty, and R is a promoted integral 8894 // type, there exist candidate operator functions of the form 8895 // 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 // VQ L& operator|=(VQ L&, R); 8902 void addAssignmentIntegralOverloads() { 8903 if (!HasArithmeticOrEnumeralCandidateType) 8904 return; 8905 8906 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8907 for (unsigned Right = FirstPromotedIntegralType; 8908 Right < LastPromotedIntegralType; ++Right) { 8909 QualType ParamTypes[2]; 8910 ParamTypes[1] = ArithmeticTypes[Right]; 8911 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType( 8912 S, ArithmeticTypes[Left], Args[0]); 8913 // Add this built-in operator as a candidate (VQ is empty). 8914 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy); 8915 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8916 if (VisibleTypeConversionsQuals.hasVolatile()) { 8917 // Add this built-in operator as a candidate (VQ is 'volatile'). 8918 ParamTypes[0] = LeftBaseTy; 8919 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8920 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8921 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8922 } 8923 } 8924 } 8925 } 8926 8927 // C++ [over.operator]p23: 8928 // 8929 // There also exist candidate operator functions of the form 8930 // 8931 // bool operator!(bool); 8932 // bool operator&&(bool, bool); 8933 // bool operator||(bool, bool); 8934 void addExclaimOverload() { 8935 QualType ParamTy = S.Context.BoolTy; 8936 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8937 /*IsAssignmentOperator=*/false, 8938 /*NumContextualBoolArguments=*/1); 8939 } 8940 void addAmpAmpOrPipePipeOverload() { 8941 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8942 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8943 /*IsAssignmentOperator=*/false, 8944 /*NumContextualBoolArguments=*/2); 8945 } 8946 8947 // C++ [over.built]p13: 8948 // 8949 // For every cv-qualified or cv-unqualified object type T there 8950 // exist candidate operator functions of the form 8951 // 8952 // T* operator+(T*, ptrdiff_t); [ABOVE] 8953 // T& operator[](T*, ptrdiff_t); 8954 // T* operator-(T*, ptrdiff_t); [ABOVE] 8955 // T* operator+(ptrdiff_t, T*); [ABOVE] 8956 // T& operator[](ptrdiff_t, T*); 8957 void addSubscriptOverloads() { 8958 for (BuiltinCandidateTypeSet::iterator 8959 Ptr = CandidateTypes[0].pointer_begin(), 8960 PtrEnd = CandidateTypes[0].pointer_end(); 8961 Ptr != PtrEnd; ++Ptr) { 8962 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8963 QualType PointeeType = (*Ptr)->getPointeeType(); 8964 if (!PointeeType->isObjectType()) 8965 continue; 8966 8967 // T& operator[](T*, ptrdiff_t) 8968 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8969 } 8970 8971 for (BuiltinCandidateTypeSet::iterator 8972 Ptr = CandidateTypes[1].pointer_begin(), 8973 PtrEnd = CandidateTypes[1].pointer_end(); 8974 Ptr != PtrEnd; ++Ptr) { 8975 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8976 QualType PointeeType = (*Ptr)->getPointeeType(); 8977 if (!PointeeType->isObjectType()) 8978 continue; 8979 8980 // T& operator[](ptrdiff_t, T*) 8981 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8982 } 8983 } 8984 8985 // C++ [over.built]p11: 8986 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8987 // C1 is the same type as C2 or is a derived class of C2, T is an object 8988 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8989 // there exist candidate operator functions of the form 8990 // 8991 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8992 // 8993 // where CV12 is the union of CV1 and CV2. 8994 void addArrowStarOverloads() { 8995 for (BuiltinCandidateTypeSet::iterator 8996 Ptr = CandidateTypes[0].pointer_begin(), 8997 PtrEnd = CandidateTypes[0].pointer_end(); 8998 Ptr != PtrEnd; ++Ptr) { 8999 QualType C1Ty = (*Ptr); 9000 QualType C1; 9001 QualifierCollector Q1; 9002 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 9003 if (!isa<RecordType>(C1)) 9004 continue; 9005 // heuristic to reduce number of builtin candidates in the set. 9006 // Add volatile/restrict version only if there are conversions to a 9007 // volatile/restrict type. 9008 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 9009 continue; 9010 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 9011 continue; 9012 for (BuiltinCandidateTypeSet::iterator 9013 MemPtr = CandidateTypes[1].member_pointer_begin(), 9014 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 9015 MemPtr != MemPtrEnd; ++MemPtr) { 9016 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 9017 QualType C2 = QualType(mptr->getClass(), 0); 9018 C2 = C2.getUnqualifiedType(); 9019 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 9020 break; 9021 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 9022 // build CV12 T& 9023 QualType T = mptr->getPointeeType(); 9024 if (!VisibleTypeConversionsQuals.hasVolatile() && 9025 T.isVolatileQualified()) 9026 continue; 9027 if (!VisibleTypeConversionsQuals.hasRestrict() && 9028 T.isRestrictQualified()) 9029 continue; 9030 T = Q1.apply(S.Context, T); 9031 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9032 } 9033 } 9034 } 9035 9036 // Note that we don't consider the first argument, since it has been 9037 // contextually converted to bool long ago. The candidates below are 9038 // therefore added as binary. 9039 // 9040 // C++ [over.built]p25: 9041 // For every type T, where T is a pointer, pointer-to-member, or scoped 9042 // enumeration type, there exist candidate operator functions of the form 9043 // 9044 // T operator?(bool, T, T); 9045 // 9046 void addConditionalOperatorOverloads() { 9047 /// Set of (canonical) types that we've already handled. 9048 llvm::SmallPtrSet<QualType, 8> AddedTypes; 9049 9050 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 9051 for (BuiltinCandidateTypeSet::iterator 9052 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 9053 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 9054 Ptr != PtrEnd; ++Ptr) { 9055 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 9056 continue; 9057 9058 QualType ParamTypes[2] = { *Ptr, *Ptr }; 9059 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9060 } 9061 9062 for (BuiltinCandidateTypeSet::iterator 9063 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 9064 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 9065 MemPtr != MemPtrEnd; ++MemPtr) { 9066 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 9067 continue; 9068 9069 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 9070 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9071 } 9072 9073 if (S.getLangOpts().CPlusPlus11) { 9074 for (BuiltinCandidateTypeSet::iterator 9075 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 9076 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 9077 Enum != EnumEnd; ++Enum) { 9078 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped()) 9079 continue; 9080 9081 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 9082 continue; 9083 9084 QualType ParamTypes[2] = { *Enum, *Enum }; 9085 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 9086 } 9087 } 9088 } 9089 } 9090 }; 9091 9092 } // end anonymous namespace 9093 9094 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 9095 /// operator overloads to the candidate set (C++ [over.built]), based 9096 /// on the operator @p Op and the arguments given. For example, if the 9097 /// operator is a binary '+', this routine might add "int 9098 /// operator+(int, int)" to cover integer addition. 9099 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 9100 SourceLocation OpLoc, 9101 ArrayRef<Expr *> Args, 9102 OverloadCandidateSet &CandidateSet) { 9103 // Find all of the types that the arguments can convert to, but only 9104 // if the operator we're looking at has built-in operator candidates 9105 // that make use of these types. Also record whether we encounter non-record 9106 // candidate types or either arithmetic or enumeral candidate types. 9107 Qualifiers VisibleTypeConversionsQuals; 9108 VisibleTypeConversionsQuals.addConst(); 9109 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 9110 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 9111 9112 bool HasNonRecordCandidateType = false; 9113 bool HasArithmeticOrEnumeralCandidateType = false; 9114 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 9115 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 9116 CandidateTypes.emplace_back(*this); 9117 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 9118 OpLoc, 9119 true, 9120 (Op == OO_Exclaim || 9121 Op == OO_AmpAmp || 9122 Op == OO_PipePipe), 9123 VisibleTypeConversionsQuals); 9124 HasNonRecordCandidateType = HasNonRecordCandidateType || 9125 CandidateTypes[ArgIdx].hasNonRecordTypes(); 9126 HasArithmeticOrEnumeralCandidateType = 9127 HasArithmeticOrEnumeralCandidateType || 9128 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 9129 } 9130 9131 // Exit early when no non-record types have been added to the candidate set 9132 // for any of the arguments to the operator. 9133 // 9134 // We can't exit early for !, ||, or &&, since there we have always have 9135 // 'bool' overloads. 9136 if (!HasNonRecordCandidateType && 9137 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 9138 return; 9139 9140 // Setup an object to manage the common state for building overloads. 9141 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 9142 VisibleTypeConversionsQuals, 9143 HasArithmeticOrEnumeralCandidateType, 9144 CandidateTypes, CandidateSet); 9145 9146 // Dispatch over the operation to add in only those overloads which apply. 9147 switch (Op) { 9148 case OO_None: 9149 case NUM_OVERLOADED_OPERATORS: 9150 llvm_unreachable("Expected an overloaded operator"); 9151 9152 case OO_New: 9153 case OO_Delete: 9154 case OO_Array_New: 9155 case OO_Array_Delete: 9156 case OO_Call: 9157 llvm_unreachable( 9158 "Special operators don't use AddBuiltinOperatorCandidates"); 9159 9160 case OO_Comma: 9161 case OO_Arrow: 9162 case OO_Coawait: 9163 // C++ [over.match.oper]p3: 9164 // -- For the operator ',', the unary operator '&', the 9165 // operator '->', or the operator 'co_await', the 9166 // built-in candidates set is empty. 9167 break; 9168 9169 case OO_Plus: // '+' is either unary or binary 9170 if (Args.size() == 1) 9171 OpBuilder.addUnaryPlusPointerOverloads(); 9172 LLVM_FALLTHROUGH; 9173 9174 case OO_Minus: // '-' is either unary or binary 9175 if (Args.size() == 1) { 9176 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 9177 } else { 9178 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 9179 OpBuilder.addGenericBinaryArithmeticOverloads(); 9180 OpBuilder.addMatrixBinaryArithmeticOverloads(); 9181 } 9182 break; 9183 9184 case OO_Star: // '*' is either unary or binary 9185 if (Args.size() == 1) 9186 OpBuilder.addUnaryStarPointerOverloads(); 9187 else 9188 OpBuilder.addGenericBinaryArithmeticOverloads(); 9189 break; 9190 9191 case OO_Slash: 9192 OpBuilder.addGenericBinaryArithmeticOverloads(); 9193 break; 9194 9195 case OO_PlusPlus: 9196 case OO_MinusMinus: 9197 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 9198 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 9199 break; 9200 9201 case OO_EqualEqual: 9202 case OO_ExclaimEqual: 9203 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 9204 LLVM_FALLTHROUGH; 9205 9206 case OO_Less: 9207 case OO_Greater: 9208 case OO_LessEqual: 9209 case OO_GreaterEqual: 9210 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9211 OpBuilder.addGenericBinaryArithmeticOverloads(); 9212 break; 9213 9214 case OO_Spaceship: 9215 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 9216 OpBuilder.addThreeWayArithmeticOverloads(); 9217 break; 9218 9219 case OO_Percent: 9220 case OO_Caret: 9221 case OO_Pipe: 9222 case OO_LessLess: 9223 case OO_GreaterGreater: 9224 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9225 break; 9226 9227 case OO_Amp: // '&' is either unary or binary 9228 if (Args.size() == 1) 9229 // C++ [over.match.oper]p3: 9230 // -- For the operator ',', the unary operator '&', or the 9231 // operator '->', the built-in candidates set is empty. 9232 break; 9233 9234 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 9235 break; 9236 9237 case OO_Tilde: 9238 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 9239 break; 9240 9241 case OO_Equal: 9242 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 9243 LLVM_FALLTHROUGH; 9244 9245 case OO_PlusEqual: 9246 case OO_MinusEqual: 9247 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 9248 LLVM_FALLTHROUGH; 9249 9250 case OO_StarEqual: 9251 case OO_SlashEqual: 9252 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 9253 break; 9254 9255 case OO_PercentEqual: 9256 case OO_LessLessEqual: 9257 case OO_GreaterGreaterEqual: 9258 case OO_AmpEqual: 9259 case OO_CaretEqual: 9260 case OO_PipeEqual: 9261 OpBuilder.addAssignmentIntegralOverloads(); 9262 break; 9263 9264 case OO_Exclaim: 9265 OpBuilder.addExclaimOverload(); 9266 break; 9267 9268 case OO_AmpAmp: 9269 case OO_PipePipe: 9270 OpBuilder.addAmpAmpOrPipePipeOverload(); 9271 break; 9272 9273 case OO_Subscript: 9274 OpBuilder.addSubscriptOverloads(); 9275 break; 9276 9277 case OO_ArrowStar: 9278 OpBuilder.addArrowStarOverloads(); 9279 break; 9280 9281 case OO_Conditional: 9282 OpBuilder.addConditionalOperatorOverloads(); 9283 OpBuilder.addGenericBinaryArithmeticOverloads(); 9284 break; 9285 } 9286 } 9287 9288 /// Add function candidates found via argument-dependent lookup 9289 /// to the set of overloading candidates. 9290 /// 9291 /// This routine performs argument-dependent name lookup based on the 9292 /// given function name (which may also be an operator name) and adds 9293 /// all of the overload candidates found by ADL to the overload 9294 /// candidate set (C++ [basic.lookup.argdep]). 9295 void 9296 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 9297 SourceLocation Loc, 9298 ArrayRef<Expr *> Args, 9299 TemplateArgumentListInfo *ExplicitTemplateArgs, 9300 OverloadCandidateSet& CandidateSet, 9301 bool PartialOverloading) { 9302 ADLResult Fns; 9303 9304 // FIXME: This approach for uniquing ADL results (and removing 9305 // redundant candidates from the set) relies on pointer-equality, 9306 // which means we need to key off the canonical decl. However, 9307 // always going back to the canonical decl might not get us the 9308 // right set of default arguments. What default arguments are 9309 // we supposed to consider on ADL candidates, anyway? 9310 9311 // FIXME: Pass in the explicit template arguments? 9312 ArgumentDependentLookup(Name, Loc, Args, Fns); 9313 9314 // Erase all of the candidates we already knew about. 9315 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 9316 CandEnd = CandidateSet.end(); 9317 Cand != CandEnd; ++Cand) 9318 if (Cand->Function) { 9319 Fns.erase(Cand->Function); 9320 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 9321 Fns.erase(FunTmpl); 9322 } 9323 9324 // For each of the ADL candidates we found, add it to the overload 9325 // set. 9326 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 9327 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 9328 9329 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9330 if (ExplicitTemplateArgs) 9331 continue; 9332 9333 AddOverloadCandidate( 9334 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false, 9335 PartialOverloading, /*AllowExplicit=*/true, 9336 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL); 9337 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) { 9338 AddOverloadCandidate( 9339 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet, 9340 /*SuppressUserConversions=*/false, PartialOverloading, 9341 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false, 9342 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed); 9343 } 9344 } else { 9345 auto *FTD = cast<FunctionTemplateDecl>(*I); 9346 AddTemplateOverloadCandidate( 9347 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet, 9348 /*SuppressUserConversions=*/false, PartialOverloading, 9349 /*AllowExplicit=*/true, ADLCallKind::UsesADL); 9350 if (CandidateSet.getRewriteInfo().shouldAddReversed( 9351 Context, FTD->getTemplatedDecl())) { 9352 AddTemplateOverloadCandidate( 9353 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]}, 9354 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading, 9355 /*AllowExplicit=*/true, ADLCallKind::UsesADL, 9356 OverloadCandidateParamOrder::Reversed); 9357 } 9358 } 9359 } 9360 } 9361 9362 namespace { 9363 enum class Comparison { Equal, Better, Worse }; 9364 } 9365 9366 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9367 /// overload resolution. 9368 /// 9369 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9370 /// Cand1's first N enable_if attributes have precisely the same conditions as 9371 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9372 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9373 /// 9374 /// Note that you can have a pair of candidates such that Cand1's enable_if 9375 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9376 /// worse than Cand1's. 9377 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9378 const FunctionDecl *Cand2) { 9379 // Common case: One (or both) decls don't have enable_if attrs. 9380 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9381 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9382 if (!Cand1Attr || !Cand2Attr) { 9383 if (Cand1Attr == Cand2Attr) 9384 return Comparison::Equal; 9385 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9386 } 9387 9388 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9389 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9390 9391 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9392 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9393 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9394 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9395 9396 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9397 // has fewer enable_if attributes than Cand2, and vice versa. 9398 if (!Cand1A) 9399 return Comparison::Worse; 9400 if (!Cand2A) 9401 return Comparison::Better; 9402 9403 Cand1ID.clear(); 9404 Cand2ID.clear(); 9405 9406 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9407 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9408 if (Cand1ID != Cand2ID) 9409 return Comparison::Worse; 9410 } 9411 9412 return Comparison::Equal; 9413 } 9414 9415 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9416 const OverloadCandidate &Cand2) { 9417 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9418 !Cand2.Function->isMultiVersion()) 9419 return false; 9420 9421 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9422 // is obviously better. 9423 if (Cand1.Function->isInvalidDecl()) return false; 9424 if (Cand2.Function->isInvalidDecl()) return true; 9425 9426 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9427 // cpu_dispatch, else arbitrarily based on the identifiers. 9428 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9429 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9430 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9431 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9432 9433 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9434 return false; 9435 9436 if (Cand1CPUDisp && !Cand2CPUDisp) 9437 return true; 9438 if (Cand2CPUDisp && !Cand1CPUDisp) 9439 return false; 9440 9441 if (Cand1CPUSpec && Cand2CPUSpec) { 9442 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9443 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9444 9445 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9446 FirstDiff = std::mismatch( 9447 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9448 Cand2CPUSpec->cpus_begin(), 9449 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9450 return LHS->getName() == RHS->getName(); 9451 }); 9452 9453 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9454 "Two different cpu-specific versions should not have the same " 9455 "identifier list, otherwise they'd be the same decl!"); 9456 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9457 } 9458 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9459 } 9460 9461 /// Compute the type of the implicit object parameter for the given function, 9462 /// if any. Returns None if there is no implicit object parameter, and a null 9463 /// QualType if there is a 'matches anything' implicit object parameter. 9464 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context, 9465 const FunctionDecl *F) { 9466 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F)) 9467 return llvm::None; 9468 9469 auto *M = cast<CXXMethodDecl>(F); 9470 // Static member functions' object parameters match all types. 9471 if (M->isStatic()) 9472 return QualType(); 9473 9474 QualType T = M->getThisObjectType(); 9475 if (M->getRefQualifier() == RQ_RValue) 9476 return Context.getRValueReferenceType(T); 9477 return Context.getLValueReferenceType(T); 9478 } 9479 9480 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1, 9481 const FunctionDecl *F2, unsigned NumParams) { 9482 if (declaresSameEntity(F1, F2)) 9483 return true; 9484 9485 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) { 9486 if (First) { 9487 if (Optional<QualType> T = getImplicitObjectParamType(Context, F)) 9488 return *T; 9489 } 9490 assert(I < F->getNumParams()); 9491 return F->getParamDecl(I++)->getType(); 9492 }; 9493 9494 unsigned I1 = 0, I2 = 0; 9495 for (unsigned I = 0; I != NumParams; ++I) { 9496 QualType T1 = NextParam(F1, I1, I == 0); 9497 QualType T2 = NextParam(F2, I2, I == 0); 9498 if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2)) 9499 return false; 9500 } 9501 return true; 9502 } 9503 9504 /// isBetterOverloadCandidate - Determines whether the first overload 9505 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9506 bool clang::isBetterOverloadCandidate( 9507 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9508 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9509 // Define viable functions to be better candidates than non-viable 9510 // functions. 9511 if (!Cand2.Viable) 9512 return Cand1.Viable; 9513 else if (!Cand1.Viable) 9514 return false; 9515 9516 // C++ [over.match.best]p1: 9517 // 9518 // -- if F is a static member function, ICS1(F) is defined such 9519 // that ICS1(F) is neither better nor worse than ICS1(G) for 9520 // any function G, and, symmetrically, ICS1(G) is neither 9521 // better nor worse than ICS1(F). 9522 unsigned StartArg = 0; 9523 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9524 StartArg = 1; 9525 9526 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9527 // We don't allow incompatible pointer conversions in C++. 9528 if (!S.getLangOpts().CPlusPlus) 9529 return ICS.isStandard() && 9530 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9531 9532 // The only ill-formed conversion we allow in C++ is the string literal to 9533 // char* conversion, which is only considered ill-formed after C++11. 9534 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9535 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9536 }; 9537 9538 // Define functions that don't require ill-formed conversions for a given 9539 // argument to be better candidates than functions that do. 9540 unsigned NumArgs = Cand1.Conversions.size(); 9541 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9542 bool HasBetterConversion = false; 9543 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9544 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9545 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9546 if (Cand1Bad != Cand2Bad) { 9547 if (Cand1Bad) 9548 return false; 9549 HasBetterConversion = true; 9550 } 9551 } 9552 9553 if (HasBetterConversion) 9554 return true; 9555 9556 // C++ [over.match.best]p1: 9557 // A viable function F1 is defined to be a better function than another 9558 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9559 // conversion sequence than ICSi(F2), and then... 9560 bool HasWorseConversion = false; 9561 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9562 switch (CompareImplicitConversionSequences(S, Loc, 9563 Cand1.Conversions[ArgIdx], 9564 Cand2.Conversions[ArgIdx])) { 9565 case ImplicitConversionSequence::Better: 9566 // Cand1 has a better conversion sequence. 9567 HasBetterConversion = true; 9568 break; 9569 9570 case ImplicitConversionSequence::Worse: 9571 if (Cand1.Function && Cand2.Function && 9572 Cand1.isReversed() != Cand2.isReversed() && 9573 haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function, 9574 NumArgs)) { 9575 // Work around large-scale breakage caused by considering reversed 9576 // forms of operator== in C++20: 9577 // 9578 // When comparing a function against a reversed function with the same 9579 // parameter types, if we have a better conversion for one argument and 9580 // a worse conversion for the other, the implicit conversion sequences 9581 // are treated as being equally good. 9582 // 9583 // This prevents a comparison function from being considered ambiguous 9584 // with a reversed form that is written in the same way. 9585 // 9586 // We diagnose this as an extension from CreateOverloadedBinOp. 9587 HasWorseConversion = true; 9588 break; 9589 } 9590 9591 // Cand1 can't be better than Cand2. 9592 return false; 9593 9594 case ImplicitConversionSequence::Indistinguishable: 9595 // Do nothing. 9596 break; 9597 } 9598 } 9599 9600 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9601 // ICSj(F2), or, if not that, 9602 if (HasBetterConversion && !HasWorseConversion) 9603 return true; 9604 9605 // -- the context is an initialization by user-defined conversion 9606 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9607 // from the return type of F1 to the destination type (i.e., 9608 // the type of the entity being initialized) is a better 9609 // conversion sequence than the standard conversion sequence 9610 // from the return type of F2 to the destination type. 9611 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9612 Cand1.Function && Cand2.Function && 9613 isa<CXXConversionDecl>(Cand1.Function) && 9614 isa<CXXConversionDecl>(Cand2.Function)) { 9615 // First check whether we prefer one of the conversion functions over the 9616 // other. This only distinguishes the results in non-standard, extension 9617 // cases such as the conversion from a lambda closure type to a function 9618 // pointer or block. 9619 ImplicitConversionSequence::CompareKind Result = 9620 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9621 if (Result == ImplicitConversionSequence::Indistinguishable) 9622 Result = CompareStandardConversionSequences(S, Loc, 9623 Cand1.FinalConversion, 9624 Cand2.FinalConversion); 9625 9626 if (Result != ImplicitConversionSequence::Indistinguishable) 9627 return Result == ImplicitConversionSequence::Better; 9628 9629 // FIXME: Compare kind of reference binding if conversion functions 9630 // convert to a reference type used in direct reference binding, per 9631 // C++14 [over.match.best]p1 section 2 bullet 3. 9632 } 9633 9634 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9635 // as combined with the resolution to CWG issue 243. 9636 // 9637 // When the context is initialization by constructor ([over.match.ctor] or 9638 // either phase of [over.match.list]), a constructor is preferred over 9639 // a conversion function. 9640 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9641 Cand1.Function && Cand2.Function && 9642 isa<CXXConstructorDecl>(Cand1.Function) != 9643 isa<CXXConstructorDecl>(Cand2.Function)) 9644 return isa<CXXConstructorDecl>(Cand1.Function); 9645 9646 // -- F1 is a non-template function and F2 is a function template 9647 // specialization, or, if not that, 9648 bool Cand1IsSpecialization = Cand1.Function && 9649 Cand1.Function->getPrimaryTemplate(); 9650 bool Cand2IsSpecialization = Cand2.Function && 9651 Cand2.Function->getPrimaryTemplate(); 9652 if (Cand1IsSpecialization != Cand2IsSpecialization) 9653 return Cand2IsSpecialization; 9654 9655 // -- F1 and F2 are function template specializations, and the function 9656 // template for F1 is more specialized than the template for F2 9657 // according to the partial ordering rules described in 14.5.5.2, or, 9658 // if not that, 9659 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9660 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate( 9661 Cand1.Function->getPrimaryTemplate(), 9662 Cand2.Function->getPrimaryTemplate(), Loc, 9663 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion 9664 : TPOC_Call, 9665 Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments, 9666 Cand1.isReversed() ^ Cand2.isReversed())) 9667 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9668 } 9669 9670 // -— F1 and F2 are non-template functions with the same 9671 // parameter-type-lists, and F1 is more constrained than F2 [...], 9672 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization && 9673 !Cand2IsSpecialization && Cand1.Function->hasPrototype() && 9674 Cand2.Function->hasPrototype()) { 9675 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType()); 9676 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType()); 9677 if (PT1->getNumParams() == PT2->getNumParams() && 9678 PT1->isVariadic() == PT2->isVariadic() && 9679 S.FunctionParamTypesAreEqual(PT1, PT2)) { 9680 Expr *RC1 = Cand1.Function->getTrailingRequiresClause(); 9681 Expr *RC2 = Cand2.Function->getTrailingRequiresClause(); 9682 if (RC1 && RC2) { 9683 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 9684 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, 9685 {RC2}, AtLeastAsConstrained1) || 9686 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, 9687 {RC1}, AtLeastAsConstrained2)) 9688 return false; 9689 if (AtLeastAsConstrained1 != AtLeastAsConstrained2) 9690 return AtLeastAsConstrained1; 9691 } else if (RC1 || RC2) { 9692 return RC1 != nullptr; 9693 } 9694 } 9695 } 9696 9697 // -- F1 is a constructor for a class D, F2 is a constructor for a base 9698 // class B of D, and for all arguments the corresponding parameters of 9699 // F1 and F2 have the same type. 9700 // FIXME: Implement the "all parameters have the same type" check. 9701 bool Cand1IsInherited = 9702 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9703 bool Cand2IsInherited = 9704 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9705 if (Cand1IsInherited != Cand2IsInherited) 9706 return Cand2IsInherited; 9707 else if (Cand1IsInherited) { 9708 assert(Cand2IsInherited); 9709 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9710 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9711 if (Cand1Class->isDerivedFrom(Cand2Class)) 9712 return true; 9713 if (Cand2Class->isDerivedFrom(Cand1Class)) 9714 return false; 9715 // Inherited from sibling base classes: still ambiguous. 9716 } 9717 9718 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not 9719 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate 9720 // with reversed order of parameters and F1 is not 9721 // 9722 // We rank reversed + different operator as worse than just reversed, but 9723 // that comparison can never happen, because we only consider reversing for 9724 // the maximally-rewritten operator (== or <=>). 9725 if (Cand1.RewriteKind != Cand2.RewriteKind) 9726 return Cand1.RewriteKind < Cand2.RewriteKind; 9727 9728 // Check C++17 tie-breakers for deduction guides. 9729 { 9730 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9731 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9732 if (Guide1 && Guide2) { 9733 // -- F1 is generated from a deduction-guide and F2 is not 9734 if (Guide1->isImplicit() != Guide2->isImplicit()) 9735 return Guide2->isImplicit(); 9736 9737 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9738 if (Guide1->isCopyDeductionCandidate()) 9739 return true; 9740 } 9741 } 9742 9743 // Check for enable_if value-based overload resolution. 9744 if (Cand1.Function && Cand2.Function) { 9745 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9746 if (Cmp != Comparison::Equal) 9747 return Cmp == Comparison::Better; 9748 } 9749 9750 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9751 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9752 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9753 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9754 } 9755 9756 bool HasPS1 = Cand1.Function != nullptr && 9757 functionHasPassObjectSizeParams(Cand1.Function); 9758 bool HasPS2 = Cand2.Function != nullptr && 9759 functionHasPassObjectSizeParams(Cand2.Function); 9760 if (HasPS1 != HasPS2 && HasPS1) 9761 return true; 9762 9763 return isBetterMultiversionCandidate(Cand1, Cand2); 9764 } 9765 9766 /// Determine whether two declarations are "equivalent" for the purposes of 9767 /// name lookup and overload resolution. This applies when the same internal/no 9768 /// linkage entity is defined by two modules (probably by textually including 9769 /// the same header). In such a case, we don't consider the declarations to 9770 /// declare the same entity, but we also don't want lookups with both 9771 /// declarations visible to be ambiguous in some cases (this happens when using 9772 /// a modularized libstdc++). 9773 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9774 const NamedDecl *B) { 9775 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9776 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9777 if (!VA || !VB) 9778 return false; 9779 9780 // The declarations must be declaring the same name as an internal linkage 9781 // entity in different modules. 9782 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9783 VB->getDeclContext()->getRedeclContext()) || 9784 getOwningModule(VA) == getOwningModule(VB) || 9785 VA->isExternallyVisible() || VB->isExternallyVisible()) 9786 return false; 9787 9788 // Check that the declarations appear to be equivalent. 9789 // 9790 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9791 // For constants and functions, we should check the initializer or body is 9792 // the same. For non-constant variables, we shouldn't allow it at all. 9793 if (Context.hasSameType(VA->getType(), VB->getType())) 9794 return true; 9795 9796 // Enum constants within unnamed enumerations will have different types, but 9797 // may still be similar enough to be interchangeable for our purposes. 9798 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9799 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9800 // Only handle anonymous enums. If the enumerations were named and 9801 // equivalent, they would have been merged to the same type. 9802 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9803 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9804 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9805 !Context.hasSameType(EnumA->getIntegerType(), 9806 EnumB->getIntegerType())) 9807 return false; 9808 // Allow this only if the value is the same for both enumerators. 9809 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9810 } 9811 } 9812 9813 // Nothing else is sufficiently similar. 9814 return false; 9815 } 9816 9817 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9818 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9819 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9820 9821 Module *M = getOwningModule(D); 9822 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9823 << !M << (M ? M->getFullModuleName() : ""); 9824 9825 for (auto *E : Equiv) { 9826 Module *M = getOwningModule(E); 9827 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9828 << !M << (M ? M->getFullModuleName() : ""); 9829 } 9830 } 9831 9832 /// Computes the best viable function (C++ 13.3.3) 9833 /// within an overload candidate set. 9834 /// 9835 /// \param Loc The location of the function name (or operator symbol) for 9836 /// which overload resolution occurs. 9837 /// 9838 /// \param Best If overload resolution was successful or found a deleted 9839 /// function, \p Best points to the candidate function found. 9840 /// 9841 /// \returns The result of overload resolution. 9842 OverloadingResult 9843 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9844 iterator &Best) { 9845 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9846 std::transform(begin(), end(), std::back_inserter(Candidates), 9847 [](OverloadCandidate &Cand) { return &Cand; }); 9848 9849 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9850 // are accepted by both clang and NVCC. However, during a particular 9851 // compilation mode only one call variant is viable. We need to 9852 // exclude non-viable overload candidates from consideration based 9853 // only on their host/device attributes. Specifically, if one 9854 // candidate call is WrongSide and the other is SameSide, we ignore 9855 // the WrongSide candidate. 9856 if (S.getLangOpts().CUDA) { 9857 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9858 bool ContainsSameSideCandidate = 9859 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9860 // Check viable function only. 9861 return Cand->Viable && Cand->Function && 9862 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9863 Sema::CFP_SameSide; 9864 }); 9865 if (ContainsSameSideCandidate) { 9866 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9867 // Check viable function only to avoid unnecessary data copying/moving. 9868 return Cand->Viable && Cand->Function && 9869 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9870 Sema::CFP_WrongSide; 9871 }; 9872 llvm::erase_if(Candidates, IsWrongSideCandidate); 9873 } 9874 } 9875 9876 // Find the best viable function. 9877 Best = end(); 9878 for (auto *Cand : Candidates) { 9879 Cand->Best = false; 9880 if (Cand->Viable) 9881 if (Best == end() || 9882 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9883 Best = Cand; 9884 } 9885 9886 // If we didn't find any viable functions, abort. 9887 if (Best == end()) 9888 return OR_No_Viable_Function; 9889 9890 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9891 9892 llvm::SmallVector<OverloadCandidate*, 4> PendingBest; 9893 PendingBest.push_back(&*Best); 9894 Best->Best = true; 9895 9896 // Make sure that this function is better than every other viable 9897 // function. If not, we have an ambiguity. 9898 while (!PendingBest.empty()) { 9899 auto *Curr = PendingBest.pop_back_val(); 9900 for (auto *Cand : Candidates) { 9901 if (Cand->Viable && !Cand->Best && 9902 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) { 9903 PendingBest.push_back(Cand); 9904 Cand->Best = true; 9905 9906 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function, 9907 Curr->Function)) 9908 EquivalentCands.push_back(Cand->Function); 9909 else 9910 Best = end(); 9911 } 9912 } 9913 } 9914 9915 // If we found more than one best candidate, this is ambiguous. 9916 if (Best == end()) 9917 return OR_Ambiguous; 9918 9919 // Best is the best viable function. 9920 if (Best->Function && Best->Function->isDeleted()) 9921 return OR_Deleted; 9922 9923 if (!EquivalentCands.empty()) 9924 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9925 EquivalentCands); 9926 9927 return OR_Success; 9928 } 9929 9930 namespace { 9931 9932 enum OverloadCandidateKind { 9933 oc_function, 9934 oc_method, 9935 oc_reversed_binary_operator, 9936 oc_constructor, 9937 oc_implicit_default_constructor, 9938 oc_implicit_copy_constructor, 9939 oc_implicit_move_constructor, 9940 oc_implicit_copy_assignment, 9941 oc_implicit_move_assignment, 9942 oc_implicit_equality_comparison, 9943 oc_inherited_constructor 9944 }; 9945 9946 enum OverloadCandidateSelect { 9947 ocs_non_template, 9948 ocs_template, 9949 ocs_described_template, 9950 }; 9951 9952 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9953 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9954 OverloadCandidateRewriteKind CRK, 9955 std::string &Description) { 9956 9957 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9958 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9959 isTemplate = true; 9960 Description = S.getTemplateArgumentBindingsText( 9961 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9962 } 9963 9964 OverloadCandidateSelect Select = [&]() { 9965 if (!Description.empty()) 9966 return ocs_described_template; 9967 return isTemplate ? ocs_template : ocs_non_template; 9968 }(); 9969 9970 OverloadCandidateKind Kind = [&]() { 9971 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual) 9972 return oc_implicit_equality_comparison; 9973 9974 if (CRK & CRK_Reversed) 9975 return oc_reversed_binary_operator; 9976 9977 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9978 if (!Ctor->isImplicit()) { 9979 if (isa<ConstructorUsingShadowDecl>(Found)) 9980 return oc_inherited_constructor; 9981 else 9982 return oc_constructor; 9983 } 9984 9985 if (Ctor->isDefaultConstructor()) 9986 return oc_implicit_default_constructor; 9987 9988 if (Ctor->isMoveConstructor()) 9989 return oc_implicit_move_constructor; 9990 9991 assert(Ctor->isCopyConstructor() && 9992 "unexpected sort of implicit constructor"); 9993 return oc_implicit_copy_constructor; 9994 } 9995 9996 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9997 // This actually gets spelled 'candidate function' for now, but 9998 // it doesn't hurt to split it out. 9999 if (!Meth->isImplicit()) 10000 return oc_method; 10001 10002 if (Meth->isMoveAssignmentOperator()) 10003 return oc_implicit_move_assignment; 10004 10005 if (Meth->isCopyAssignmentOperator()) 10006 return oc_implicit_copy_assignment; 10007 10008 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 10009 return oc_method; 10010 } 10011 10012 return oc_function; 10013 }(); 10014 10015 return std::make_pair(Kind, Select); 10016 } 10017 10018 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 10019 // FIXME: It'd be nice to only emit a note once per using-decl per overload 10020 // set. 10021 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 10022 S.Diag(FoundDecl->getLocation(), 10023 diag::note_ovl_candidate_inherited_constructor) 10024 << Shadow->getNominatedBaseClass(); 10025 } 10026 10027 } // end anonymous namespace 10028 10029 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 10030 const FunctionDecl *FD) { 10031 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 10032 bool AlwaysTrue; 10033 if (EnableIf->getCond()->isValueDependent() || 10034 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 10035 return false; 10036 if (!AlwaysTrue) 10037 return false; 10038 } 10039 return true; 10040 } 10041 10042 /// Returns true if we can take the address of the function. 10043 /// 10044 /// \param Complain - If true, we'll emit a diagnostic 10045 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 10046 /// we in overload resolution? 10047 /// \param Loc - The location of the statement we're complaining about. Ignored 10048 /// if we're not complaining, or if we're in overload resolution. 10049 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 10050 bool Complain, 10051 bool InOverloadResolution, 10052 SourceLocation Loc) { 10053 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 10054 if (Complain) { 10055 if (InOverloadResolution) 10056 S.Diag(FD->getBeginLoc(), 10057 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 10058 else 10059 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 10060 } 10061 return false; 10062 } 10063 10064 if (FD->getTrailingRequiresClause()) { 10065 ConstraintSatisfaction Satisfaction; 10066 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc)) 10067 return false; 10068 if (!Satisfaction.IsSatisfied) { 10069 if (Complain) { 10070 if (InOverloadResolution) 10071 S.Diag(FD->getBeginLoc(), 10072 diag::note_ovl_candidate_unsatisfied_constraints); 10073 else 10074 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied) 10075 << FD; 10076 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 10077 } 10078 return false; 10079 } 10080 } 10081 10082 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 10083 return P->hasAttr<PassObjectSizeAttr>(); 10084 }); 10085 if (I == FD->param_end()) 10086 return true; 10087 10088 if (Complain) { 10089 // Add one to ParamNo because it's user-facing 10090 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 10091 if (InOverloadResolution) 10092 S.Diag(FD->getLocation(), 10093 diag::note_ovl_candidate_has_pass_object_size_params) 10094 << ParamNo; 10095 else 10096 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 10097 << FD << ParamNo; 10098 } 10099 return false; 10100 } 10101 10102 static bool checkAddressOfCandidateIsAvailable(Sema &S, 10103 const FunctionDecl *FD) { 10104 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 10105 /*InOverloadResolution=*/true, 10106 /*Loc=*/SourceLocation()); 10107 } 10108 10109 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10110 bool Complain, 10111 SourceLocation Loc) { 10112 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 10113 /*InOverloadResolution=*/false, 10114 Loc); 10115 } 10116 10117 // Notes the location of an overload candidate. 10118 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 10119 OverloadCandidateRewriteKind RewriteKind, 10120 QualType DestType, bool TakingAddress) { 10121 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 10122 return; 10123 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 10124 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 10125 return; 10126 10127 std::string FnDesc; 10128 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 10129 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc); 10130 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 10131 << (unsigned)KSPair.first << (unsigned)KSPair.second 10132 << Fn << FnDesc; 10133 10134 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 10135 Diag(Fn->getLocation(), PD); 10136 MaybeEmitInheritedConstructorNote(*this, Found); 10137 } 10138 10139 static void 10140 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) { 10141 // Perhaps the ambiguity was caused by two atomic constraints that are 10142 // 'identical' but not equivalent: 10143 // 10144 // void foo() requires (sizeof(T) > 4) { } // #1 10145 // void foo() requires (sizeof(T) > 4) && T::value { } // #2 10146 // 10147 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause 10148 // #2 to subsume #1, but these constraint are not considered equivalent 10149 // according to the subsumption rules because they are not the same 10150 // source-level construct. This behavior is quite confusing and we should try 10151 // to help the user figure out what happened. 10152 10153 SmallVector<const Expr *, 3> FirstAC, SecondAC; 10154 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr; 10155 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10156 if (!I->Function) 10157 continue; 10158 SmallVector<const Expr *, 3> AC; 10159 if (auto *Template = I->Function->getPrimaryTemplate()) 10160 Template->getAssociatedConstraints(AC); 10161 else 10162 I->Function->getAssociatedConstraints(AC); 10163 if (AC.empty()) 10164 continue; 10165 if (FirstCand == nullptr) { 10166 FirstCand = I->Function; 10167 FirstAC = AC; 10168 } else if (SecondCand == nullptr) { 10169 SecondCand = I->Function; 10170 SecondAC = AC; 10171 } else { 10172 // We have more than one pair of constrained functions - this check is 10173 // expensive and we'd rather not try to diagnose it. 10174 return; 10175 } 10176 } 10177 if (!SecondCand) 10178 return; 10179 // The diagnostic can only happen if there are associated constraints on 10180 // both sides (there needs to be some identical atomic constraint). 10181 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC, 10182 SecondCand, SecondAC)) 10183 // Just show the user one diagnostic, they'll probably figure it out 10184 // from here. 10185 return; 10186 } 10187 10188 // Notes the location of all overload candidates designated through 10189 // OverloadedExpr 10190 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 10191 bool TakingAddress) { 10192 assert(OverloadedExpr->getType() == Context.OverloadTy); 10193 10194 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 10195 OverloadExpr *OvlExpr = Ovl.Expression; 10196 10197 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10198 IEnd = OvlExpr->decls_end(); 10199 I != IEnd; ++I) { 10200 if (FunctionTemplateDecl *FunTmpl = 10201 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 10202 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType, 10203 TakingAddress); 10204 } else if (FunctionDecl *Fun 10205 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 10206 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress); 10207 } 10208 } 10209 } 10210 10211 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 10212 /// "lead" diagnostic; it will be given two arguments, the source and 10213 /// target types of the conversion. 10214 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 10215 Sema &S, 10216 SourceLocation CaretLoc, 10217 const PartialDiagnostic &PDiag) const { 10218 S.Diag(CaretLoc, PDiag) 10219 << Ambiguous.getFromType() << Ambiguous.getToType(); 10220 // FIXME: The note limiting machinery is borrowed from 10221 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 10222 // refactoring here. 10223 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10224 unsigned CandsShown = 0; 10225 AmbiguousConversionSequence::const_iterator I, E; 10226 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 10227 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10228 break; 10229 ++CandsShown; 10230 S.NoteOverloadCandidate(I->first, I->second); 10231 } 10232 if (I != E) 10233 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 10234 } 10235 10236 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 10237 unsigned I, bool TakingCandidateAddress) { 10238 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 10239 assert(Conv.isBad()); 10240 assert(Cand->Function && "for now, candidate must be a function"); 10241 FunctionDecl *Fn = Cand->Function; 10242 10243 // There's a conversion slot for the object argument if this is a 10244 // non-constructor method. Note that 'I' corresponds the 10245 // conversion-slot index. 10246 bool isObjectArgument = false; 10247 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 10248 if (I == 0) 10249 isObjectArgument = true; 10250 else 10251 I--; 10252 } 10253 10254 std::string FnDesc; 10255 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10256 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(), 10257 FnDesc); 10258 10259 Expr *FromExpr = Conv.Bad.FromExpr; 10260 QualType FromTy = Conv.Bad.getFromType(); 10261 QualType ToTy = Conv.Bad.getToType(); 10262 10263 if (FromTy == S.Context.OverloadTy) { 10264 assert(FromExpr && "overload set argument came from implicit argument?"); 10265 Expr *E = FromExpr->IgnoreParens(); 10266 if (isa<UnaryOperator>(E)) 10267 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 10268 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 10269 10270 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 10271 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10272 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 10273 << Name << I + 1; 10274 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10275 return; 10276 } 10277 10278 // Do some hand-waving analysis to see if the non-viability is due 10279 // to a qualifier mismatch. 10280 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 10281 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 10282 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 10283 CToTy = RT->getPointeeType(); 10284 else { 10285 // TODO: detect and diagnose the full richness of const mismatches. 10286 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 10287 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 10288 CFromTy = FromPT->getPointeeType(); 10289 CToTy = ToPT->getPointeeType(); 10290 } 10291 } 10292 10293 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 10294 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 10295 Qualifiers FromQs = CFromTy.getQualifiers(); 10296 Qualifiers ToQs = CToTy.getQualifiers(); 10297 10298 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 10299 if (isObjectArgument) 10300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this) 10301 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10302 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10303 << FromQs.getAddressSpace() << ToQs.getAddressSpace(); 10304 else 10305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 10306 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10307 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10308 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 10309 << ToTy->isReferenceType() << I + 1; 10310 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10311 return; 10312 } 10313 10314 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 10316 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10318 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 10319 << (unsigned)isObjectArgument << I + 1; 10320 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10321 return; 10322 } 10323 10324 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 10325 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 10326 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10327 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10328 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 10329 << (unsigned)isObjectArgument << I + 1; 10330 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10331 return; 10332 } 10333 10334 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 10335 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 10336 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10337 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10338 << FromQs.hasUnaligned() << I + 1; 10339 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10340 return; 10341 } 10342 10343 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 10344 assert(CVR && "unexpected qualifiers mismatch"); 10345 10346 if (isObjectArgument) { 10347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 10348 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10349 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10350 << (CVR - 1); 10351 } else { 10352 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 10353 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10354 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10355 << (CVR - 1) << I + 1; 10356 } 10357 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10358 return; 10359 } 10360 10361 // Special diagnostic for failure to convert an initializer list, since 10362 // telling the user that it has type void is not useful. 10363 if (FromExpr && isa<InitListExpr>(FromExpr)) { 10364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 10365 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10366 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10367 << ToTy << (unsigned)isObjectArgument << I + 1; 10368 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10369 return; 10370 } 10371 10372 // Diagnose references or pointers to incomplete types differently, 10373 // since it's far from impossible that the incompleteness triggered 10374 // the failure. 10375 QualType TempFromTy = FromTy.getNonReferenceType(); 10376 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 10377 TempFromTy = PTy->getPointeeType(); 10378 if (TempFromTy->isIncompleteType()) { 10379 // Emit the generic diagnostic and, optionally, add the hints to it. 10380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 10381 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10382 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10383 << ToTy << (unsigned)isObjectArgument << I + 1 10384 << (unsigned)(Cand->Fix.Kind); 10385 10386 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10387 return; 10388 } 10389 10390 // Diagnose base -> derived pointer conversions. 10391 unsigned BaseToDerivedConversion = 0; 10392 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 10393 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 10394 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10395 FromPtrTy->getPointeeType()) && 10396 !FromPtrTy->getPointeeType()->isIncompleteType() && 10397 !ToPtrTy->getPointeeType()->isIncompleteType() && 10398 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 10399 FromPtrTy->getPointeeType())) 10400 BaseToDerivedConversion = 1; 10401 } 10402 } else if (const ObjCObjectPointerType *FromPtrTy 10403 = FromTy->getAs<ObjCObjectPointerType>()) { 10404 if (const ObjCObjectPointerType *ToPtrTy 10405 = ToTy->getAs<ObjCObjectPointerType>()) 10406 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 10407 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 10408 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 10409 FromPtrTy->getPointeeType()) && 10410 FromIface->isSuperClassOf(ToIface)) 10411 BaseToDerivedConversion = 2; 10412 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 10413 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 10414 !FromTy->isIncompleteType() && 10415 !ToRefTy->getPointeeType()->isIncompleteType() && 10416 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 10417 BaseToDerivedConversion = 3; 10418 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 10419 ToTy.getNonReferenceType().getCanonicalType() == 10420 FromTy.getNonReferenceType().getCanonicalType()) { 10421 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 10422 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10423 << (unsigned)isObjectArgument << I + 1 10424 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 10425 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10426 return; 10427 } 10428 } 10429 10430 if (BaseToDerivedConversion) { 10431 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 10432 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10433 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10434 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 10435 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10436 return; 10437 } 10438 10439 if (isa<ObjCObjectPointerType>(CFromTy) && 10440 isa<PointerType>(CToTy)) { 10441 Qualifiers FromQs = CFromTy.getQualifiers(); 10442 Qualifiers ToQs = CToTy.getQualifiers(); 10443 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 10444 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 10445 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10446 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 10447 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 10448 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10449 return; 10450 } 10451 } 10452 10453 if (TakingCandidateAddress && 10454 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 10455 return; 10456 10457 // Emit the generic diagnostic and, optionally, add the hints to it. 10458 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 10459 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 10461 << ToTy << (unsigned)isObjectArgument << I + 1 10462 << (unsigned)(Cand->Fix.Kind); 10463 10464 // If we can fix the conversion, suggest the FixIts. 10465 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 10466 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 10467 FDiag << *HI; 10468 S.Diag(Fn->getLocation(), FDiag); 10469 10470 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10471 } 10472 10473 /// Additional arity mismatch diagnosis specific to a function overload 10474 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 10475 /// over a candidate in any candidate set. 10476 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 10477 unsigned NumArgs) { 10478 FunctionDecl *Fn = Cand->Function; 10479 unsigned MinParams = Fn->getMinRequiredArguments(); 10480 10481 // With invalid overloaded operators, it's possible that we think we 10482 // have an arity mismatch when in fact it looks like we have the 10483 // right number of arguments, because only overloaded operators have 10484 // the weird behavior of overloading member and non-member functions. 10485 // Just don't report anything. 10486 if (Fn->isInvalidDecl() && 10487 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 10488 return true; 10489 10490 if (NumArgs < MinParams) { 10491 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 10492 (Cand->FailureKind == ovl_fail_bad_deduction && 10493 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 10494 } else { 10495 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 10496 (Cand->FailureKind == ovl_fail_bad_deduction && 10497 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 10498 } 10499 10500 return false; 10501 } 10502 10503 /// General arity mismatch diagnosis over a candidate in a candidate set. 10504 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 10505 unsigned NumFormalArgs) { 10506 assert(isa<FunctionDecl>(D) && 10507 "The templated declaration should at least be a function" 10508 " when diagnosing bad template argument deduction due to too many" 10509 " or too few arguments"); 10510 10511 FunctionDecl *Fn = cast<FunctionDecl>(D); 10512 10513 // TODO: treat calls to a missing default constructor as a special case 10514 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>(); 10515 unsigned MinParams = Fn->getMinRequiredArguments(); 10516 10517 // at least / at most / exactly 10518 unsigned mode, modeCount; 10519 if (NumFormalArgs < MinParams) { 10520 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 10521 FnTy->isTemplateVariadic()) 10522 mode = 0; // "at least" 10523 else 10524 mode = 2; // "exactly" 10525 modeCount = MinParams; 10526 } else { 10527 if (MinParams != FnTy->getNumParams()) 10528 mode = 1; // "at most" 10529 else 10530 mode = 2; // "exactly" 10531 modeCount = FnTy->getNumParams(); 10532 } 10533 10534 std::string Description; 10535 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10536 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description); 10537 10538 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 10539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 10540 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10541 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 10542 else 10543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 10544 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 10545 << Description << mode << modeCount << NumFormalArgs; 10546 10547 MaybeEmitInheritedConstructorNote(S, Found); 10548 } 10549 10550 /// Arity mismatch diagnosis specific to a function overload candidate. 10551 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10552 unsigned NumFormalArgs) { 10553 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10554 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10555 } 10556 10557 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10558 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10559 return TD; 10560 llvm_unreachable("Unsupported: Getting the described template declaration" 10561 " for bad deduction diagnosis"); 10562 } 10563 10564 /// Diagnose a failed template-argument deduction. 10565 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10566 DeductionFailureInfo &DeductionFailure, 10567 unsigned NumArgs, 10568 bool TakingCandidateAddress) { 10569 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10570 NamedDecl *ParamD; 10571 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10572 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10573 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10574 switch (DeductionFailure.Result) { 10575 case Sema::TDK_Success: 10576 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10577 10578 case Sema::TDK_Incomplete: { 10579 assert(ParamD && "no parameter found for incomplete deduction result"); 10580 S.Diag(Templated->getLocation(), 10581 diag::note_ovl_candidate_incomplete_deduction) 10582 << ParamD->getDeclName(); 10583 MaybeEmitInheritedConstructorNote(S, Found); 10584 return; 10585 } 10586 10587 case Sema::TDK_IncompletePack: { 10588 assert(ParamD && "no parameter found for incomplete deduction result"); 10589 S.Diag(Templated->getLocation(), 10590 diag::note_ovl_candidate_incomplete_deduction_pack) 10591 << ParamD->getDeclName() 10592 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10593 << *DeductionFailure.getFirstArg(); 10594 MaybeEmitInheritedConstructorNote(S, Found); 10595 return; 10596 } 10597 10598 case Sema::TDK_Underqualified: { 10599 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10600 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10601 10602 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10603 10604 // Param will have been canonicalized, but it should just be a 10605 // qualified version of ParamD, so move the qualifiers to that. 10606 QualifierCollector Qs; 10607 Qs.strip(Param); 10608 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10609 assert(S.Context.hasSameType(Param, NonCanonParam)); 10610 10611 // Arg has also been canonicalized, but there's nothing we can do 10612 // about that. It also doesn't matter as much, because it won't 10613 // have any template parameters in it (because deduction isn't 10614 // done on dependent types). 10615 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10616 10617 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10618 << ParamD->getDeclName() << Arg << NonCanonParam; 10619 MaybeEmitInheritedConstructorNote(S, Found); 10620 return; 10621 } 10622 10623 case Sema::TDK_Inconsistent: { 10624 assert(ParamD && "no parameter found for inconsistent deduction result"); 10625 int which = 0; 10626 if (isa<TemplateTypeParmDecl>(ParamD)) 10627 which = 0; 10628 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10629 // Deduction might have failed because we deduced arguments of two 10630 // different types for a non-type template parameter. 10631 // FIXME: Use a different TDK value for this. 10632 QualType T1 = 10633 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10634 QualType T2 = 10635 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10636 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10637 S.Diag(Templated->getLocation(), 10638 diag::note_ovl_candidate_inconsistent_deduction_types) 10639 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10640 << *DeductionFailure.getSecondArg() << T2; 10641 MaybeEmitInheritedConstructorNote(S, Found); 10642 return; 10643 } 10644 10645 which = 1; 10646 } else { 10647 which = 2; 10648 } 10649 10650 // Tweak the diagnostic if the problem is that we deduced packs of 10651 // different arities. We'll print the actual packs anyway in case that 10652 // includes additional useful information. 10653 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack && 10654 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack && 10655 DeductionFailure.getFirstArg()->pack_size() != 10656 DeductionFailure.getSecondArg()->pack_size()) { 10657 which = 3; 10658 } 10659 10660 S.Diag(Templated->getLocation(), 10661 diag::note_ovl_candidate_inconsistent_deduction) 10662 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10663 << *DeductionFailure.getSecondArg(); 10664 MaybeEmitInheritedConstructorNote(S, Found); 10665 return; 10666 } 10667 10668 case Sema::TDK_InvalidExplicitArguments: 10669 assert(ParamD && "no parameter found for invalid explicit arguments"); 10670 if (ParamD->getDeclName()) 10671 S.Diag(Templated->getLocation(), 10672 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10673 << ParamD->getDeclName(); 10674 else { 10675 int index = 0; 10676 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10677 index = TTP->getIndex(); 10678 else if (NonTypeTemplateParmDecl *NTTP 10679 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10680 index = NTTP->getIndex(); 10681 else 10682 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10683 S.Diag(Templated->getLocation(), 10684 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10685 << (index + 1); 10686 } 10687 MaybeEmitInheritedConstructorNote(S, Found); 10688 return; 10689 10690 case Sema::TDK_ConstraintsNotSatisfied: { 10691 // Format the template argument list into the argument string. 10692 SmallString<128> TemplateArgString; 10693 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList(); 10694 TemplateArgString = " "; 10695 TemplateArgString += S.getTemplateArgumentBindingsText( 10696 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10697 if (TemplateArgString.size() == 1) 10698 TemplateArgString.clear(); 10699 S.Diag(Templated->getLocation(), 10700 diag::note_ovl_candidate_unsatisfied_constraints) 10701 << TemplateArgString; 10702 10703 S.DiagnoseUnsatisfiedConstraint( 10704 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction); 10705 return; 10706 } 10707 case Sema::TDK_TooManyArguments: 10708 case Sema::TDK_TooFewArguments: 10709 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10710 return; 10711 10712 case Sema::TDK_InstantiationDepth: 10713 S.Diag(Templated->getLocation(), 10714 diag::note_ovl_candidate_instantiation_depth); 10715 MaybeEmitInheritedConstructorNote(S, Found); 10716 return; 10717 10718 case Sema::TDK_SubstitutionFailure: { 10719 // Format the template argument list into the argument string. 10720 SmallString<128> TemplateArgString; 10721 if (TemplateArgumentList *Args = 10722 DeductionFailure.getTemplateArgumentList()) { 10723 TemplateArgString = " "; 10724 TemplateArgString += S.getTemplateArgumentBindingsText( 10725 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10726 if (TemplateArgString.size() == 1) 10727 TemplateArgString.clear(); 10728 } 10729 10730 // If this candidate was disabled by enable_if, say so. 10731 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10732 if (PDiag && PDiag->second.getDiagID() == 10733 diag::err_typename_nested_not_found_enable_if) { 10734 // FIXME: Use the source range of the condition, and the fully-qualified 10735 // name of the enable_if template. These are both present in PDiag. 10736 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10737 << "'enable_if'" << TemplateArgString; 10738 return; 10739 } 10740 10741 // We found a specific requirement that disabled the enable_if. 10742 if (PDiag && PDiag->second.getDiagID() == 10743 diag::err_typename_nested_not_found_requirement) { 10744 S.Diag(Templated->getLocation(), 10745 diag::note_ovl_candidate_disabled_by_requirement) 10746 << PDiag->second.getStringArg(0) << TemplateArgString; 10747 return; 10748 } 10749 10750 // Format the SFINAE diagnostic into the argument string. 10751 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10752 // formatted message in another diagnostic. 10753 SmallString<128> SFINAEArgString; 10754 SourceRange R; 10755 if (PDiag) { 10756 SFINAEArgString = ": "; 10757 R = SourceRange(PDiag->first, PDiag->first); 10758 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10759 } 10760 10761 S.Diag(Templated->getLocation(), 10762 diag::note_ovl_candidate_substitution_failure) 10763 << TemplateArgString << SFINAEArgString << R; 10764 MaybeEmitInheritedConstructorNote(S, Found); 10765 return; 10766 } 10767 10768 case Sema::TDK_DeducedMismatch: 10769 case Sema::TDK_DeducedMismatchNested: { 10770 // Format the template argument list into the argument string. 10771 SmallString<128> TemplateArgString; 10772 if (TemplateArgumentList *Args = 10773 DeductionFailure.getTemplateArgumentList()) { 10774 TemplateArgString = " "; 10775 TemplateArgString += S.getTemplateArgumentBindingsText( 10776 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10777 if (TemplateArgString.size() == 1) 10778 TemplateArgString.clear(); 10779 } 10780 10781 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10782 << (*DeductionFailure.getCallArgIndex() + 1) 10783 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10784 << TemplateArgString 10785 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10786 break; 10787 } 10788 10789 case Sema::TDK_NonDeducedMismatch: { 10790 // FIXME: Provide a source location to indicate what we couldn't match. 10791 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10792 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10793 if (FirstTA.getKind() == TemplateArgument::Template && 10794 SecondTA.getKind() == TemplateArgument::Template) { 10795 TemplateName FirstTN = FirstTA.getAsTemplate(); 10796 TemplateName SecondTN = SecondTA.getAsTemplate(); 10797 if (FirstTN.getKind() == TemplateName::Template && 10798 SecondTN.getKind() == TemplateName::Template) { 10799 if (FirstTN.getAsTemplateDecl()->getName() == 10800 SecondTN.getAsTemplateDecl()->getName()) { 10801 // FIXME: This fixes a bad diagnostic where both templates are named 10802 // the same. This particular case is a bit difficult since: 10803 // 1) It is passed as a string to the diagnostic printer. 10804 // 2) The diagnostic printer only attempts to find a better 10805 // name for types, not decls. 10806 // Ideally, this should folded into the diagnostic printer. 10807 S.Diag(Templated->getLocation(), 10808 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10809 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10810 return; 10811 } 10812 } 10813 } 10814 10815 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10816 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10817 return; 10818 10819 // FIXME: For generic lambda parameters, check if the function is a lambda 10820 // call operator, and if so, emit a prettier and more informative 10821 // diagnostic that mentions 'auto' and lambda in addition to 10822 // (or instead of?) the canonical template type parameters. 10823 S.Diag(Templated->getLocation(), 10824 diag::note_ovl_candidate_non_deduced_mismatch) 10825 << FirstTA << SecondTA; 10826 return; 10827 } 10828 // TODO: diagnose these individually, then kill off 10829 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10830 case Sema::TDK_MiscellaneousDeductionFailure: 10831 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10832 MaybeEmitInheritedConstructorNote(S, Found); 10833 return; 10834 case Sema::TDK_CUDATargetMismatch: 10835 S.Diag(Templated->getLocation(), 10836 diag::note_cuda_ovl_candidate_target_mismatch); 10837 return; 10838 } 10839 } 10840 10841 /// Diagnose a failed template-argument deduction, for function calls. 10842 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10843 unsigned NumArgs, 10844 bool TakingCandidateAddress) { 10845 unsigned TDK = Cand->DeductionFailure.Result; 10846 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10847 if (CheckArityMismatch(S, Cand, NumArgs)) 10848 return; 10849 } 10850 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10851 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10852 } 10853 10854 /// CUDA: diagnose an invalid call across targets. 10855 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10856 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10857 FunctionDecl *Callee = Cand->Function; 10858 10859 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10860 CalleeTarget = S.IdentifyCUDATarget(Callee); 10861 10862 std::string FnDesc; 10863 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10864 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, 10865 Cand->getRewriteKind(), FnDesc); 10866 10867 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10868 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10869 << FnDesc /* Ignored */ 10870 << CalleeTarget << CallerTarget; 10871 10872 // This could be an implicit constructor for which we could not infer the 10873 // target due to a collsion. Diagnose that case. 10874 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10875 if (Meth != nullptr && Meth->isImplicit()) { 10876 CXXRecordDecl *ParentClass = Meth->getParent(); 10877 Sema::CXXSpecialMember CSM; 10878 10879 switch (FnKindPair.first) { 10880 default: 10881 return; 10882 case oc_implicit_default_constructor: 10883 CSM = Sema::CXXDefaultConstructor; 10884 break; 10885 case oc_implicit_copy_constructor: 10886 CSM = Sema::CXXCopyConstructor; 10887 break; 10888 case oc_implicit_move_constructor: 10889 CSM = Sema::CXXMoveConstructor; 10890 break; 10891 case oc_implicit_copy_assignment: 10892 CSM = Sema::CXXCopyAssignment; 10893 break; 10894 case oc_implicit_move_assignment: 10895 CSM = Sema::CXXMoveAssignment; 10896 break; 10897 }; 10898 10899 bool ConstRHS = false; 10900 if (Meth->getNumParams()) { 10901 if (const ReferenceType *RT = 10902 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10903 ConstRHS = RT->getPointeeType().isConstQualified(); 10904 } 10905 } 10906 10907 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10908 /* ConstRHS */ ConstRHS, 10909 /* Diagnose */ true); 10910 } 10911 } 10912 10913 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10914 FunctionDecl *Callee = Cand->Function; 10915 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10916 10917 S.Diag(Callee->getLocation(), 10918 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10919 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10920 } 10921 10922 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) { 10923 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function); 10924 assert(ES.isExplicit() && "not an explicit candidate"); 10925 10926 unsigned Kind; 10927 switch (Cand->Function->getDeclKind()) { 10928 case Decl::Kind::CXXConstructor: 10929 Kind = 0; 10930 break; 10931 case Decl::Kind::CXXConversion: 10932 Kind = 1; 10933 break; 10934 case Decl::Kind::CXXDeductionGuide: 10935 Kind = Cand->Function->isImplicit() ? 0 : 2; 10936 break; 10937 default: 10938 llvm_unreachable("invalid Decl"); 10939 } 10940 10941 // Note the location of the first (in-class) declaration; a redeclaration 10942 // (particularly an out-of-class definition) will typically lack the 10943 // 'explicit' specifier. 10944 // FIXME: This is probably a good thing to do for all 'candidate' notes. 10945 FunctionDecl *First = Cand->Function->getFirstDecl(); 10946 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern()) 10947 First = Pattern->getFirstDecl(); 10948 10949 S.Diag(First->getLocation(), 10950 diag::note_ovl_candidate_explicit) 10951 << Kind << (ES.getExpr() ? 1 : 0) 10952 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange()); 10953 } 10954 10955 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10956 FunctionDecl *Callee = Cand->Function; 10957 10958 S.Diag(Callee->getLocation(), 10959 diag::note_ovl_candidate_disabled_by_extension) 10960 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10961 } 10962 10963 /// Generates a 'note' diagnostic for an overload candidate. We've 10964 /// already generated a primary error at the call site. 10965 /// 10966 /// It really does need to be a single diagnostic with its caret 10967 /// pointed at the candidate declaration. Yes, this creates some 10968 /// major challenges of technical writing. Yes, this makes pointing 10969 /// out problems with specific arguments quite awkward. It's still 10970 /// better than generating twenty screens of text for every failed 10971 /// overload. 10972 /// 10973 /// It would be great to be able to express per-candidate problems 10974 /// more richly for those diagnostic clients that cared, but we'd 10975 /// still have to be just as careful with the default diagnostics. 10976 /// \param CtorDestAS Addr space of object being constructed (for ctor 10977 /// candidates only). 10978 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10979 unsigned NumArgs, 10980 bool TakingCandidateAddress, 10981 LangAS CtorDestAS = LangAS::Default) { 10982 FunctionDecl *Fn = Cand->Function; 10983 10984 // Note deleted candidates, but only if they're viable. 10985 if (Cand->Viable) { 10986 if (Fn->isDeleted()) { 10987 std::string FnDesc; 10988 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10989 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 10990 Cand->getRewriteKind(), FnDesc); 10991 10992 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10993 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10994 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10995 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10996 return; 10997 } 10998 10999 // We don't really have anything else to say about viable candidates. 11000 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11001 return; 11002 } 11003 11004 switch (Cand->FailureKind) { 11005 case ovl_fail_too_many_arguments: 11006 case ovl_fail_too_few_arguments: 11007 return DiagnoseArityMismatch(S, Cand, NumArgs); 11008 11009 case ovl_fail_bad_deduction: 11010 return DiagnoseBadDeduction(S, Cand, NumArgs, 11011 TakingCandidateAddress); 11012 11013 case ovl_fail_illegal_constructor: { 11014 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 11015 << (Fn->getPrimaryTemplate() ? 1 : 0); 11016 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11017 return; 11018 } 11019 11020 case ovl_fail_object_addrspace_mismatch: { 11021 Qualifiers QualsForPrinting; 11022 QualsForPrinting.setAddressSpace(CtorDestAS); 11023 S.Diag(Fn->getLocation(), 11024 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch) 11025 << QualsForPrinting; 11026 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11027 return; 11028 } 11029 11030 case ovl_fail_trivial_conversion: 11031 case ovl_fail_bad_final_conversion: 11032 case ovl_fail_final_conversion_not_exact: 11033 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11034 11035 case ovl_fail_bad_conversion: { 11036 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 11037 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 11038 if (Cand->Conversions[I].isBad()) 11039 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 11040 11041 // FIXME: this currently happens when we're called from SemaInit 11042 // when user-conversion overload fails. Figure out how to handle 11043 // those conditions and diagnose them well. 11044 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind()); 11045 } 11046 11047 case ovl_fail_bad_target: 11048 return DiagnoseBadTarget(S, Cand); 11049 11050 case ovl_fail_enable_if: 11051 return DiagnoseFailedEnableIfAttr(S, Cand); 11052 11053 case ovl_fail_explicit: 11054 return DiagnoseFailedExplicitSpec(S, Cand); 11055 11056 case ovl_fail_ext_disabled: 11057 return DiagnoseOpenCLExtensionDisabled(S, Cand); 11058 11059 case ovl_fail_inhctor_slice: 11060 // It's generally not interesting to note copy/move constructors here. 11061 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 11062 return; 11063 S.Diag(Fn->getLocation(), 11064 diag::note_ovl_candidate_inherited_constructor_slice) 11065 << (Fn->getPrimaryTemplate() ? 1 : 0) 11066 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 11067 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 11068 return; 11069 11070 case ovl_fail_addr_not_available: { 11071 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 11072 (void)Available; 11073 assert(!Available); 11074 break; 11075 } 11076 case ovl_non_default_multiversion_function: 11077 // Do nothing, these should simply be ignored. 11078 break; 11079 11080 case ovl_fail_constraints_not_satisfied: { 11081 std::string FnDesc; 11082 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 11083 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, 11084 Cand->getRewriteKind(), FnDesc); 11085 11086 S.Diag(Fn->getLocation(), 11087 diag::note_ovl_candidate_constraints_not_satisfied) 11088 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 11089 << FnDesc /* Ignored */; 11090 ConstraintSatisfaction Satisfaction; 11091 if (S.CheckFunctionConstraints(Fn, Satisfaction)) 11092 break; 11093 S.DiagnoseUnsatisfiedConstraint(Satisfaction); 11094 } 11095 } 11096 } 11097 11098 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 11099 // Desugar the type of the surrogate down to a function type, 11100 // retaining as many typedefs as possible while still showing 11101 // the function type (and, therefore, its parameter types). 11102 QualType FnType = Cand->Surrogate->getConversionType(); 11103 bool isLValueReference = false; 11104 bool isRValueReference = false; 11105 bool isPointer = false; 11106 if (const LValueReferenceType *FnTypeRef = 11107 FnType->getAs<LValueReferenceType>()) { 11108 FnType = FnTypeRef->getPointeeType(); 11109 isLValueReference = true; 11110 } else if (const RValueReferenceType *FnTypeRef = 11111 FnType->getAs<RValueReferenceType>()) { 11112 FnType = FnTypeRef->getPointeeType(); 11113 isRValueReference = true; 11114 } 11115 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 11116 FnType = FnTypePtr->getPointeeType(); 11117 isPointer = true; 11118 } 11119 // Desugar down to a function type. 11120 FnType = QualType(FnType->getAs<FunctionType>(), 0); 11121 // Reconstruct the pointer/reference as appropriate. 11122 if (isPointer) FnType = S.Context.getPointerType(FnType); 11123 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 11124 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 11125 11126 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 11127 << FnType; 11128 } 11129 11130 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 11131 SourceLocation OpLoc, 11132 OverloadCandidate *Cand) { 11133 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 11134 std::string TypeStr("operator"); 11135 TypeStr += Opc; 11136 TypeStr += "("; 11137 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 11138 if (Cand->Conversions.size() == 1) { 11139 TypeStr += ")"; 11140 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11141 } else { 11142 TypeStr += ", "; 11143 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 11144 TypeStr += ")"; 11145 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr; 11146 } 11147 } 11148 11149 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 11150 OverloadCandidate *Cand) { 11151 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 11152 if (ICS.isBad()) break; // all meaningless after first invalid 11153 if (!ICS.isAmbiguous()) continue; 11154 11155 ICS.DiagnoseAmbiguousConversion( 11156 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 11157 } 11158 } 11159 11160 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 11161 if (Cand->Function) 11162 return Cand->Function->getLocation(); 11163 if (Cand->IsSurrogate) 11164 return Cand->Surrogate->getLocation(); 11165 return SourceLocation(); 11166 } 11167 11168 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 11169 switch ((Sema::TemplateDeductionResult)DFI.Result) { 11170 case Sema::TDK_Success: 11171 case Sema::TDK_NonDependentConversionFailure: 11172 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 11173 11174 case Sema::TDK_Invalid: 11175 case Sema::TDK_Incomplete: 11176 case Sema::TDK_IncompletePack: 11177 return 1; 11178 11179 case Sema::TDK_Underqualified: 11180 case Sema::TDK_Inconsistent: 11181 return 2; 11182 11183 case Sema::TDK_SubstitutionFailure: 11184 case Sema::TDK_DeducedMismatch: 11185 case Sema::TDK_ConstraintsNotSatisfied: 11186 case Sema::TDK_DeducedMismatchNested: 11187 case Sema::TDK_NonDeducedMismatch: 11188 case Sema::TDK_MiscellaneousDeductionFailure: 11189 case Sema::TDK_CUDATargetMismatch: 11190 return 3; 11191 11192 case Sema::TDK_InstantiationDepth: 11193 return 4; 11194 11195 case Sema::TDK_InvalidExplicitArguments: 11196 return 5; 11197 11198 case Sema::TDK_TooManyArguments: 11199 case Sema::TDK_TooFewArguments: 11200 return 6; 11201 } 11202 llvm_unreachable("Unhandled deduction result"); 11203 } 11204 11205 namespace { 11206 struct CompareOverloadCandidatesForDisplay { 11207 Sema &S; 11208 SourceLocation Loc; 11209 size_t NumArgs; 11210 OverloadCandidateSet::CandidateSetKind CSK; 11211 11212 CompareOverloadCandidatesForDisplay( 11213 Sema &S, SourceLocation Loc, size_t NArgs, 11214 OverloadCandidateSet::CandidateSetKind CSK) 11215 : S(S), NumArgs(NArgs), CSK(CSK) {} 11216 11217 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const { 11218 // If there are too many or too few arguments, that's the high-order bit we 11219 // want to sort by, even if the immediate failure kind was something else. 11220 if (C->FailureKind == ovl_fail_too_many_arguments || 11221 C->FailureKind == ovl_fail_too_few_arguments) 11222 return static_cast<OverloadFailureKind>(C->FailureKind); 11223 11224 if (C->Function) { 11225 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic()) 11226 return ovl_fail_too_many_arguments; 11227 if (NumArgs < C->Function->getMinRequiredArguments()) 11228 return ovl_fail_too_few_arguments; 11229 } 11230 11231 return static_cast<OverloadFailureKind>(C->FailureKind); 11232 } 11233 11234 bool operator()(const OverloadCandidate *L, 11235 const OverloadCandidate *R) { 11236 // Fast-path this check. 11237 if (L == R) return false; 11238 11239 // Order first by viability. 11240 if (L->Viable) { 11241 if (!R->Viable) return true; 11242 11243 // TODO: introduce a tri-valued comparison for overload 11244 // candidates. Would be more worthwhile if we had a sort 11245 // that could exploit it. 11246 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 11247 return true; 11248 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 11249 return false; 11250 } else if (R->Viable) 11251 return false; 11252 11253 assert(L->Viable == R->Viable); 11254 11255 // Criteria by which we can sort non-viable candidates: 11256 if (!L->Viable) { 11257 OverloadFailureKind LFailureKind = EffectiveFailureKind(L); 11258 OverloadFailureKind RFailureKind = EffectiveFailureKind(R); 11259 11260 // 1. Arity mismatches come after other candidates. 11261 if (LFailureKind == ovl_fail_too_many_arguments || 11262 LFailureKind == ovl_fail_too_few_arguments) { 11263 if (RFailureKind == ovl_fail_too_many_arguments || 11264 RFailureKind == ovl_fail_too_few_arguments) { 11265 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 11266 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 11267 if (LDist == RDist) { 11268 if (LFailureKind == RFailureKind) 11269 // Sort non-surrogates before surrogates. 11270 return !L->IsSurrogate && R->IsSurrogate; 11271 // Sort candidates requiring fewer parameters than there were 11272 // arguments given after candidates requiring more parameters 11273 // than there were arguments given. 11274 return LFailureKind == ovl_fail_too_many_arguments; 11275 } 11276 return LDist < RDist; 11277 } 11278 return false; 11279 } 11280 if (RFailureKind == ovl_fail_too_many_arguments || 11281 RFailureKind == ovl_fail_too_few_arguments) 11282 return true; 11283 11284 // 2. Bad conversions come first and are ordered by the number 11285 // of bad conversions and quality of good conversions. 11286 if (LFailureKind == ovl_fail_bad_conversion) { 11287 if (RFailureKind != ovl_fail_bad_conversion) 11288 return true; 11289 11290 // The conversion that can be fixed with a smaller number of changes, 11291 // comes first. 11292 unsigned numLFixes = L->Fix.NumConversionsFixed; 11293 unsigned numRFixes = R->Fix.NumConversionsFixed; 11294 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 11295 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 11296 if (numLFixes != numRFixes) { 11297 return numLFixes < numRFixes; 11298 } 11299 11300 // If there's any ordering between the defined conversions... 11301 // FIXME: this might not be transitive. 11302 assert(L->Conversions.size() == R->Conversions.size()); 11303 11304 int leftBetter = 0; 11305 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 11306 for (unsigned E = L->Conversions.size(); I != E; ++I) { 11307 switch (CompareImplicitConversionSequences(S, Loc, 11308 L->Conversions[I], 11309 R->Conversions[I])) { 11310 case ImplicitConversionSequence::Better: 11311 leftBetter++; 11312 break; 11313 11314 case ImplicitConversionSequence::Worse: 11315 leftBetter--; 11316 break; 11317 11318 case ImplicitConversionSequence::Indistinguishable: 11319 break; 11320 } 11321 } 11322 if (leftBetter > 0) return true; 11323 if (leftBetter < 0) return false; 11324 11325 } else if (RFailureKind == ovl_fail_bad_conversion) 11326 return false; 11327 11328 if (LFailureKind == ovl_fail_bad_deduction) { 11329 if (RFailureKind != ovl_fail_bad_deduction) 11330 return true; 11331 11332 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11333 return RankDeductionFailure(L->DeductionFailure) 11334 < RankDeductionFailure(R->DeductionFailure); 11335 } else if (RFailureKind == ovl_fail_bad_deduction) 11336 return false; 11337 11338 // TODO: others? 11339 } 11340 11341 // Sort everything else by location. 11342 SourceLocation LLoc = GetLocationForCandidate(L); 11343 SourceLocation RLoc = GetLocationForCandidate(R); 11344 11345 // Put candidates without locations (e.g. builtins) at the end. 11346 if (LLoc.isInvalid()) return false; 11347 if (RLoc.isInvalid()) return true; 11348 11349 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11350 } 11351 }; 11352 } 11353 11354 /// CompleteNonViableCandidate - Normally, overload resolution only 11355 /// computes up to the first bad conversion. Produces the FixIt set if 11356 /// possible. 11357 static void 11358 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 11359 ArrayRef<Expr *> Args, 11360 OverloadCandidateSet::CandidateSetKind CSK) { 11361 assert(!Cand->Viable); 11362 11363 // Don't do anything on failures other than bad conversion. 11364 if (Cand->FailureKind != ovl_fail_bad_conversion) 11365 return; 11366 11367 // We only want the FixIts if all the arguments can be corrected. 11368 bool Unfixable = false; 11369 // Use a implicit copy initialization to check conversion fixes. 11370 Cand->Fix.setConversionChecker(TryCopyInitialization); 11371 11372 // Attempt to fix the bad conversion. 11373 unsigned ConvCount = Cand->Conversions.size(); 11374 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 11375 ++ConvIdx) { 11376 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 11377 if (Cand->Conversions[ConvIdx].isInitialized() && 11378 Cand->Conversions[ConvIdx].isBad()) { 11379 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11380 break; 11381 } 11382 } 11383 11384 // FIXME: this should probably be preserved from the overload 11385 // operation somehow. 11386 bool SuppressUserConversions = false; 11387 11388 unsigned ConvIdx = 0; 11389 unsigned ArgIdx = 0; 11390 ArrayRef<QualType> ParamTypes; 11391 bool Reversed = Cand->isReversed(); 11392 11393 if (Cand->IsSurrogate) { 11394 QualType ConvType 11395 = Cand->Surrogate->getConversionType().getNonReferenceType(); 11396 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11397 ConvType = ConvPtrType->getPointeeType(); 11398 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes(); 11399 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11400 ConvIdx = 1; 11401 } else if (Cand->Function) { 11402 ParamTypes = 11403 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes(); 11404 if (isa<CXXMethodDecl>(Cand->Function) && 11405 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) { 11406 // Conversion 0 is 'this', which doesn't have a corresponding parameter. 11407 ConvIdx = 1; 11408 if (CSK == OverloadCandidateSet::CSK_Operator && 11409 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call) 11410 // Argument 0 is 'this', which doesn't have a corresponding parameter. 11411 ArgIdx = 1; 11412 } 11413 } else { 11414 // Builtin operator. 11415 assert(ConvCount <= 3); 11416 ParamTypes = Cand->BuiltinParamTypes; 11417 } 11418 11419 // Fill in the rest of the conversions. 11420 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0; 11421 ConvIdx != ConvCount; 11422 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) { 11423 assert(ArgIdx < Args.size() && "no argument for this arg conversion"); 11424 if (Cand->Conversions[ConvIdx].isInitialized()) { 11425 // We've already checked this conversion. 11426 } else if (ParamIdx < ParamTypes.size()) { 11427 if (ParamTypes[ParamIdx]->isDependentType()) 11428 Cand->Conversions[ConvIdx].setAsIdentityConversion( 11429 Args[ArgIdx]->getType()); 11430 else { 11431 Cand->Conversions[ConvIdx] = 11432 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx], 11433 SuppressUserConversions, 11434 /*InOverloadResolution=*/true, 11435 /*AllowObjCWritebackConversion=*/ 11436 S.getLangOpts().ObjCAutoRefCount); 11437 // Store the FixIt in the candidate if it exists. 11438 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 11439 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 11440 } 11441 } else 11442 Cand->Conversions[ConvIdx].setEllipsis(); 11443 } 11444 } 11445 11446 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates( 11447 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11448 SourceLocation OpLoc, 11449 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11450 // Sort the candidates by viability and position. Sorting directly would 11451 // be prohibitive, so we make a set of pointers and sort those. 11452 SmallVector<OverloadCandidate*, 32> Cands; 11453 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 11454 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11455 if (!Filter(*Cand)) 11456 continue; 11457 switch (OCD) { 11458 case OCD_AllCandidates: 11459 if (!Cand->Viable) { 11460 if (!Cand->Function && !Cand->IsSurrogate) { 11461 // This a non-viable builtin candidate. We do not, in general, 11462 // want to list every possible builtin candidate. 11463 continue; 11464 } 11465 CompleteNonViableCandidate(S, Cand, Args, Kind); 11466 } 11467 break; 11468 11469 case OCD_ViableCandidates: 11470 if (!Cand->Viable) 11471 continue; 11472 break; 11473 11474 case OCD_AmbiguousCandidates: 11475 if (!Cand->Best) 11476 continue; 11477 break; 11478 } 11479 11480 Cands.push_back(Cand); 11481 } 11482 11483 llvm::stable_sort( 11484 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 11485 11486 return Cands; 11487 } 11488 11489 /// When overload resolution fails, prints diagnostic messages containing the 11490 /// candidates in the candidate set. 11491 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD, 11492 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 11493 StringRef Opc, SourceLocation OpLoc, 11494 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 11495 11496 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter); 11497 11498 S.Diag(PD.first, PD.second); 11499 11500 NoteCandidates(S, Args, Cands, Opc, OpLoc); 11501 11502 if (OCD == OCD_AmbiguousCandidates) 11503 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()}); 11504 } 11505 11506 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args, 11507 ArrayRef<OverloadCandidate *> Cands, 11508 StringRef Opc, SourceLocation OpLoc) { 11509 bool ReportedAmbiguousConversions = false; 11510 11511 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11512 unsigned CandsShown = 0; 11513 auto I = Cands.begin(), E = Cands.end(); 11514 for (; I != E; ++I) { 11515 OverloadCandidate *Cand = *I; 11516 11517 // Set an arbitrary limit on the number of candidate functions we'll spam 11518 // the user with. FIXME: This limit should depend on details of the 11519 // candidate list. 11520 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 11521 break; 11522 } 11523 ++CandsShown; 11524 11525 if (Cand->Function) 11526 NoteFunctionCandidate(S, Cand, Args.size(), 11527 /*TakingCandidateAddress=*/false, DestAS); 11528 else if (Cand->IsSurrogate) 11529 NoteSurrogateCandidate(S, Cand); 11530 else { 11531 assert(Cand->Viable && 11532 "Non-viable built-in candidates are not added to Cands."); 11533 // Generally we only see ambiguities including viable builtin 11534 // operators if overload resolution got screwed up by an 11535 // ambiguous user-defined conversion. 11536 // 11537 // FIXME: It's quite possible for different conversions to see 11538 // different ambiguities, though. 11539 if (!ReportedAmbiguousConversions) { 11540 NoteAmbiguousUserConversions(S, OpLoc, Cand); 11541 ReportedAmbiguousConversions = true; 11542 } 11543 11544 // If this is a viable builtin, print it. 11545 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 11546 } 11547 } 11548 11549 if (I != E) 11550 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 11551 } 11552 11553 static SourceLocation 11554 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 11555 return Cand->Specialization ? Cand->Specialization->getLocation() 11556 : SourceLocation(); 11557 } 11558 11559 namespace { 11560 struct CompareTemplateSpecCandidatesForDisplay { 11561 Sema &S; 11562 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 11563 11564 bool operator()(const TemplateSpecCandidate *L, 11565 const TemplateSpecCandidate *R) { 11566 // Fast-path this check. 11567 if (L == R) 11568 return false; 11569 11570 // Assuming that both candidates are not matches... 11571 11572 // Sort by the ranking of deduction failures. 11573 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 11574 return RankDeductionFailure(L->DeductionFailure) < 11575 RankDeductionFailure(R->DeductionFailure); 11576 11577 // Sort everything else by location. 11578 SourceLocation LLoc = GetLocationForCandidate(L); 11579 SourceLocation RLoc = GetLocationForCandidate(R); 11580 11581 // Put candidates without locations (e.g. builtins) at the end. 11582 if (LLoc.isInvalid()) 11583 return false; 11584 if (RLoc.isInvalid()) 11585 return true; 11586 11587 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 11588 } 11589 }; 11590 } 11591 11592 /// Diagnose a template argument deduction failure. 11593 /// We are treating these failures as overload failures due to bad 11594 /// deductions. 11595 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 11596 bool ForTakingAddress) { 11597 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 11598 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 11599 } 11600 11601 void TemplateSpecCandidateSet::destroyCandidates() { 11602 for (iterator i = begin(), e = end(); i != e; ++i) { 11603 i->DeductionFailure.Destroy(); 11604 } 11605 } 11606 11607 void TemplateSpecCandidateSet::clear() { 11608 destroyCandidates(); 11609 Candidates.clear(); 11610 } 11611 11612 /// NoteCandidates - When no template specialization match is found, prints 11613 /// diagnostic messages containing the non-matching specializations that form 11614 /// the candidate set. 11615 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 11616 /// OCD == OCD_AllCandidates and Cand->Viable == false. 11617 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 11618 // Sort the candidates by position (assuming no candidate is a match). 11619 // Sorting directly would be prohibitive, so we make a set of pointers 11620 // and sort those. 11621 SmallVector<TemplateSpecCandidate *, 32> Cands; 11622 Cands.reserve(size()); 11623 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 11624 if (Cand->Specialization) 11625 Cands.push_back(Cand); 11626 // Otherwise, this is a non-matching builtin candidate. We do not, 11627 // in general, want to list every possible builtin candidate. 11628 } 11629 11630 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 11631 11632 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 11633 // for generalization purposes (?). 11634 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 11635 11636 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 11637 unsigned CandsShown = 0; 11638 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 11639 TemplateSpecCandidate *Cand = *I; 11640 11641 // Set an arbitrary limit on the number of candidates we'll spam 11642 // the user with. FIXME: This limit should depend on details of the 11643 // candidate list. 11644 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 11645 break; 11646 ++CandsShown; 11647 11648 assert(Cand->Specialization && 11649 "Non-matching built-in candidates are not added to Cands."); 11650 Cand->NoteDeductionFailure(S, ForTakingAddress); 11651 } 11652 11653 if (I != E) 11654 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 11655 } 11656 11657 // [PossiblyAFunctionType] --> [Return] 11658 // NonFunctionType --> NonFunctionType 11659 // R (A) --> R(A) 11660 // R (*)(A) --> R (A) 11661 // R (&)(A) --> R (A) 11662 // R (S::*)(A) --> R (A) 11663 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 11664 QualType Ret = PossiblyAFunctionType; 11665 if (const PointerType *ToTypePtr = 11666 PossiblyAFunctionType->getAs<PointerType>()) 11667 Ret = ToTypePtr->getPointeeType(); 11668 else if (const ReferenceType *ToTypeRef = 11669 PossiblyAFunctionType->getAs<ReferenceType>()) 11670 Ret = ToTypeRef->getPointeeType(); 11671 else if (const MemberPointerType *MemTypePtr = 11672 PossiblyAFunctionType->getAs<MemberPointerType>()) 11673 Ret = MemTypePtr->getPointeeType(); 11674 Ret = 11675 Context.getCanonicalType(Ret).getUnqualifiedType(); 11676 return Ret; 11677 } 11678 11679 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 11680 bool Complain = true) { 11681 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 11682 S.DeduceReturnType(FD, Loc, Complain)) 11683 return true; 11684 11685 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 11686 if (S.getLangOpts().CPlusPlus17 && 11687 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 11688 !S.ResolveExceptionSpec(Loc, FPT)) 11689 return true; 11690 11691 return false; 11692 } 11693 11694 namespace { 11695 // A helper class to help with address of function resolution 11696 // - allows us to avoid passing around all those ugly parameters 11697 class AddressOfFunctionResolver { 11698 Sema& S; 11699 Expr* SourceExpr; 11700 const QualType& TargetType; 11701 QualType TargetFunctionType; // Extracted function type from target type 11702 11703 bool Complain; 11704 //DeclAccessPair& ResultFunctionAccessPair; 11705 ASTContext& Context; 11706 11707 bool TargetTypeIsNonStaticMemberFunction; 11708 bool FoundNonTemplateFunction; 11709 bool StaticMemberFunctionFromBoundPointer; 11710 bool HasComplained; 11711 11712 OverloadExpr::FindResult OvlExprInfo; 11713 OverloadExpr *OvlExpr; 11714 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11715 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11716 TemplateSpecCandidateSet FailedCandidates; 11717 11718 public: 11719 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11720 const QualType &TargetType, bool Complain) 11721 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11722 Complain(Complain), Context(S.getASTContext()), 11723 TargetTypeIsNonStaticMemberFunction( 11724 !!TargetType->getAs<MemberPointerType>()), 11725 FoundNonTemplateFunction(false), 11726 StaticMemberFunctionFromBoundPointer(false), 11727 HasComplained(false), 11728 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11729 OvlExpr(OvlExprInfo.Expression), 11730 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11731 ExtractUnqualifiedFunctionTypeFromTargetType(); 11732 11733 if (TargetFunctionType->isFunctionType()) { 11734 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11735 if (!UME->isImplicitAccess() && 11736 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11737 StaticMemberFunctionFromBoundPointer = true; 11738 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11739 DeclAccessPair dap; 11740 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11741 OvlExpr, false, &dap)) { 11742 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11743 if (!Method->isStatic()) { 11744 // If the target type is a non-function type and the function found 11745 // is a non-static member function, pretend as if that was the 11746 // target, it's the only possible type to end up with. 11747 TargetTypeIsNonStaticMemberFunction = true; 11748 11749 // And skip adding the function if its not in the proper form. 11750 // We'll diagnose this due to an empty set of functions. 11751 if (!OvlExprInfo.HasFormOfMemberPointer) 11752 return; 11753 } 11754 11755 Matches.push_back(std::make_pair(dap, Fn)); 11756 } 11757 return; 11758 } 11759 11760 if (OvlExpr->hasExplicitTemplateArgs()) 11761 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11762 11763 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11764 // C++ [over.over]p4: 11765 // If more than one function is selected, [...] 11766 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11767 if (FoundNonTemplateFunction) 11768 EliminateAllTemplateMatches(); 11769 else 11770 EliminateAllExceptMostSpecializedTemplate(); 11771 } 11772 } 11773 11774 if (S.getLangOpts().CUDA && Matches.size() > 1) 11775 EliminateSuboptimalCudaMatches(); 11776 } 11777 11778 bool hasComplained() const { return HasComplained; } 11779 11780 private: 11781 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11782 QualType Discard; 11783 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11784 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11785 } 11786 11787 /// \return true if A is considered a better overload candidate for the 11788 /// desired type than B. 11789 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11790 // If A doesn't have exactly the correct type, we don't want to classify it 11791 // as "better" than anything else. This way, the user is required to 11792 // disambiguate for us if there are multiple candidates and no exact match. 11793 return candidateHasExactlyCorrectType(A) && 11794 (!candidateHasExactlyCorrectType(B) || 11795 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11796 } 11797 11798 /// \return true if we were able to eliminate all but one overload candidate, 11799 /// false otherwise. 11800 bool eliminiateSuboptimalOverloadCandidates() { 11801 // Same algorithm as overload resolution -- one pass to pick the "best", 11802 // another pass to be sure that nothing is better than the best. 11803 auto Best = Matches.begin(); 11804 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11805 if (isBetterCandidate(I->second, Best->second)) 11806 Best = I; 11807 11808 const FunctionDecl *BestFn = Best->second; 11809 auto IsBestOrInferiorToBest = [this, BestFn]( 11810 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11811 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11812 }; 11813 11814 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11815 // option, so we can potentially give the user a better error 11816 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11817 return false; 11818 Matches[0] = *Best; 11819 Matches.resize(1); 11820 return true; 11821 } 11822 11823 bool isTargetTypeAFunction() const { 11824 return TargetFunctionType->isFunctionType(); 11825 } 11826 11827 // [ToType] [Return] 11828 11829 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11830 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11831 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11832 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11833 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11834 } 11835 11836 // return true if any matching specializations were found 11837 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11838 const DeclAccessPair& CurAccessFunPair) { 11839 if (CXXMethodDecl *Method 11840 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11841 // Skip non-static function templates when converting to pointer, and 11842 // static when converting to member pointer. 11843 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11844 return false; 11845 } 11846 else if (TargetTypeIsNonStaticMemberFunction) 11847 return false; 11848 11849 // C++ [over.over]p2: 11850 // If the name is a function template, template argument deduction is 11851 // done (14.8.2.2), and if the argument deduction succeeds, the 11852 // resulting template argument list is used to generate a single 11853 // function template specialization, which is added to the set of 11854 // overloaded functions considered. 11855 FunctionDecl *Specialization = nullptr; 11856 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11857 if (Sema::TemplateDeductionResult Result 11858 = S.DeduceTemplateArguments(FunctionTemplate, 11859 &OvlExplicitTemplateArgs, 11860 TargetFunctionType, Specialization, 11861 Info, /*IsAddressOfFunction*/true)) { 11862 // Make a note of the failed deduction for diagnostics. 11863 FailedCandidates.addCandidate() 11864 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11865 MakeDeductionFailureInfo(Context, Result, Info)); 11866 return false; 11867 } 11868 11869 // Template argument deduction ensures that we have an exact match or 11870 // compatible pointer-to-function arguments that would be adjusted by ICS. 11871 // This function template specicalization works. 11872 assert(S.isSameOrCompatibleFunctionType( 11873 Context.getCanonicalType(Specialization->getType()), 11874 Context.getCanonicalType(TargetFunctionType))); 11875 11876 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11877 return false; 11878 11879 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11880 return true; 11881 } 11882 11883 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11884 const DeclAccessPair& CurAccessFunPair) { 11885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11886 // Skip non-static functions when converting to pointer, and static 11887 // when converting to member pointer. 11888 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11889 return false; 11890 } 11891 else if (TargetTypeIsNonStaticMemberFunction) 11892 return false; 11893 11894 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11895 if (S.getLangOpts().CUDA) 11896 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11897 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11898 return false; 11899 if (FunDecl->isMultiVersion()) { 11900 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11901 if (TA && !TA->isDefaultVersion()) 11902 return false; 11903 } 11904 11905 // If any candidate has a placeholder return type, trigger its deduction 11906 // now. 11907 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11908 Complain)) { 11909 HasComplained |= Complain; 11910 return false; 11911 } 11912 11913 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11914 return false; 11915 11916 // If we're in C, we need to support types that aren't exactly identical. 11917 if (!S.getLangOpts().CPlusPlus || 11918 candidateHasExactlyCorrectType(FunDecl)) { 11919 Matches.push_back(std::make_pair( 11920 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11921 FoundNonTemplateFunction = true; 11922 return true; 11923 } 11924 } 11925 11926 return false; 11927 } 11928 11929 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11930 bool Ret = false; 11931 11932 // If the overload expression doesn't have the form of a pointer to 11933 // member, don't try to convert it to a pointer-to-member type. 11934 if (IsInvalidFormOfPointerToMemberFunction()) 11935 return false; 11936 11937 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11938 E = OvlExpr->decls_end(); 11939 I != E; ++I) { 11940 // Look through any using declarations to find the underlying function. 11941 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11942 11943 // C++ [over.over]p3: 11944 // Non-member functions and static member functions match 11945 // targets of type "pointer-to-function" or "reference-to-function." 11946 // Nonstatic member functions match targets of 11947 // type "pointer-to-member-function." 11948 // Note that according to DR 247, the containing class does not matter. 11949 if (FunctionTemplateDecl *FunctionTemplate 11950 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11951 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11952 Ret = true; 11953 } 11954 // If we have explicit template arguments supplied, skip non-templates. 11955 else if (!OvlExpr->hasExplicitTemplateArgs() && 11956 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11957 Ret = true; 11958 } 11959 assert(Ret || Matches.empty()); 11960 return Ret; 11961 } 11962 11963 void EliminateAllExceptMostSpecializedTemplate() { 11964 // [...] and any given function template specialization F1 is 11965 // eliminated if the set contains a second function template 11966 // specialization whose function template is more specialized 11967 // than the function template of F1 according to the partial 11968 // ordering rules of 14.5.5.2. 11969 11970 // The algorithm specified above is quadratic. We instead use a 11971 // two-pass algorithm (similar to the one used to identify the 11972 // best viable function in an overload set) that identifies the 11973 // best function template (if it exists). 11974 11975 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11976 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11977 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11978 11979 // TODO: It looks like FailedCandidates does not serve much purpose 11980 // here, since the no_viable diagnostic has index 0. 11981 UnresolvedSetIterator Result = S.getMostSpecialized( 11982 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11983 SourceExpr->getBeginLoc(), S.PDiag(), 11984 S.PDiag(diag::err_addr_ovl_ambiguous) 11985 << Matches[0].second->getDeclName(), 11986 S.PDiag(diag::note_ovl_candidate) 11987 << (unsigned)oc_function << (unsigned)ocs_described_template, 11988 Complain, TargetFunctionType); 11989 11990 if (Result != MatchesCopy.end()) { 11991 // Make it the first and only element 11992 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11993 Matches[0].second = cast<FunctionDecl>(*Result); 11994 Matches.resize(1); 11995 } else 11996 HasComplained |= Complain; 11997 } 11998 11999 void EliminateAllTemplateMatches() { 12000 // [...] any function template specializations in the set are 12001 // eliminated if the set also contains a non-template function, [...] 12002 for (unsigned I = 0, N = Matches.size(); I != N; ) { 12003 if (Matches[I].second->getPrimaryTemplate() == nullptr) 12004 ++I; 12005 else { 12006 Matches[I] = Matches[--N]; 12007 Matches.resize(N); 12008 } 12009 } 12010 } 12011 12012 void EliminateSuboptimalCudaMatches() { 12013 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 12014 } 12015 12016 public: 12017 void ComplainNoMatchesFound() const { 12018 assert(Matches.empty()); 12019 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 12020 << OvlExpr->getName() << TargetFunctionType 12021 << OvlExpr->getSourceRange(); 12022 if (FailedCandidates.empty()) 12023 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12024 /*TakingAddress=*/true); 12025 else { 12026 // We have some deduction failure messages. Use them to diagnose 12027 // the function templates, and diagnose the non-template candidates 12028 // normally. 12029 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 12030 IEnd = OvlExpr->decls_end(); 12031 I != IEnd; ++I) 12032 if (FunctionDecl *Fun = 12033 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 12034 if (!functionHasPassObjectSizeParams(Fun)) 12035 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType, 12036 /*TakingAddress=*/true); 12037 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 12038 } 12039 } 12040 12041 bool IsInvalidFormOfPointerToMemberFunction() const { 12042 return TargetTypeIsNonStaticMemberFunction && 12043 !OvlExprInfo.HasFormOfMemberPointer; 12044 } 12045 12046 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 12047 // TODO: Should we condition this on whether any functions might 12048 // have matched, or is it more appropriate to do that in callers? 12049 // TODO: a fixit wouldn't hurt. 12050 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 12051 << TargetType << OvlExpr->getSourceRange(); 12052 } 12053 12054 bool IsStaticMemberFunctionFromBoundPointer() const { 12055 return StaticMemberFunctionFromBoundPointer; 12056 } 12057 12058 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 12059 S.Diag(OvlExpr->getBeginLoc(), 12060 diag::err_invalid_form_pointer_member_function) 12061 << OvlExpr->getSourceRange(); 12062 } 12063 12064 void ComplainOfInvalidConversion() const { 12065 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 12066 << OvlExpr->getName() << TargetType; 12067 } 12068 12069 void ComplainMultipleMatchesFound() const { 12070 assert(Matches.size() > 1); 12071 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 12072 << OvlExpr->getName() << OvlExpr->getSourceRange(); 12073 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 12074 /*TakingAddress=*/true); 12075 } 12076 12077 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 12078 12079 int getNumMatches() const { return Matches.size(); } 12080 12081 FunctionDecl* getMatchingFunctionDecl() const { 12082 if (Matches.size() != 1) return nullptr; 12083 return Matches[0].second; 12084 } 12085 12086 const DeclAccessPair* getMatchingFunctionAccessPair() const { 12087 if (Matches.size() != 1) return nullptr; 12088 return &Matches[0].first; 12089 } 12090 }; 12091 } 12092 12093 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 12094 /// an overloaded function (C++ [over.over]), where @p From is an 12095 /// expression with overloaded function type and @p ToType is the type 12096 /// we're trying to resolve to. For example: 12097 /// 12098 /// @code 12099 /// int f(double); 12100 /// int f(int); 12101 /// 12102 /// int (*pfd)(double) = f; // selects f(double) 12103 /// @endcode 12104 /// 12105 /// This routine returns the resulting FunctionDecl if it could be 12106 /// resolved, and NULL otherwise. When @p Complain is true, this 12107 /// routine will emit diagnostics if there is an error. 12108 FunctionDecl * 12109 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 12110 QualType TargetType, 12111 bool Complain, 12112 DeclAccessPair &FoundResult, 12113 bool *pHadMultipleCandidates) { 12114 assert(AddressOfExpr->getType() == Context.OverloadTy); 12115 12116 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 12117 Complain); 12118 int NumMatches = Resolver.getNumMatches(); 12119 FunctionDecl *Fn = nullptr; 12120 bool ShouldComplain = Complain && !Resolver.hasComplained(); 12121 if (NumMatches == 0 && ShouldComplain) { 12122 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 12123 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 12124 else 12125 Resolver.ComplainNoMatchesFound(); 12126 } 12127 else if (NumMatches > 1 && ShouldComplain) 12128 Resolver.ComplainMultipleMatchesFound(); 12129 else if (NumMatches == 1) { 12130 Fn = Resolver.getMatchingFunctionDecl(); 12131 assert(Fn); 12132 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 12133 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 12134 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 12135 if (Complain) { 12136 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 12137 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 12138 else 12139 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 12140 } 12141 } 12142 12143 if (pHadMultipleCandidates) 12144 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 12145 return Fn; 12146 } 12147 12148 /// Given an expression that refers to an overloaded function, try to 12149 /// resolve that function to a single function that can have its address taken. 12150 /// This will modify `Pair` iff it returns non-null. 12151 /// 12152 /// This routine can only succeed if from all of the candidates in the overload 12153 /// set for SrcExpr that can have their addresses taken, there is one candidate 12154 /// that is more constrained than the rest. 12155 FunctionDecl * 12156 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) { 12157 OverloadExpr::FindResult R = OverloadExpr::find(E); 12158 OverloadExpr *Ovl = R.Expression; 12159 bool IsResultAmbiguous = false; 12160 FunctionDecl *Result = nullptr; 12161 DeclAccessPair DAP; 12162 SmallVector<FunctionDecl *, 2> AmbiguousDecls; 12163 12164 auto CheckMoreConstrained = 12165 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> { 12166 SmallVector<const Expr *, 1> AC1, AC2; 12167 FD1->getAssociatedConstraints(AC1); 12168 FD2->getAssociatedConstraints(AC2); 12169 bool AtLeastAsConstrained1, AtLeastAsConstrained2; 12170 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1)) 12171 return None; 12172 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2)) 12173 return None; 12174 if (AtLeastAsConstrained1 == AtLeastAsConstrained2) 12175 return None; 12176 return AtLeastAsConstrained1; 12177 }; 12178 12179 // Don't use the AddressOfResolver because we're specifically looking for 12180 // cases where we have one overload candidate that lacks 12181 // enable_if/pass_object_size/... 12182 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 12183 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 12184 if (!FD) 12185 return nullptr; 12186 12187 if (!checkAddressOfFunctionIsAvailable(FD)) 12188 continue; 12189 12190 // We have more than one result - see if it is more constrained than the 12191 // previous one. 12192 if (Result) { 12193 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD, 12194 Result); 12195 if (!MoreConstrainedThanPrevious) { 12196 IsResultAmbiguous = true; 12197 AmbiguousDecls.push_back(FD); 12198 continue; 12199 } 12200 if (!*MoreConstrainedThanPrevious) 12201 continue; 12202 // FD is more constrained - replace Result with it. 12203 } 12204 IsResultAmbiguous = false; 12205 DAP = I.getPair(); 12206 Result = FD; 12207 } 12208 12209 if (IsResultAmbiguous) 12210 return nullptr; 12211 12212 if (Result) { 12213 SmallVector<const Expr *, 1> ResultAC; 12214 // We skipped over some ambiguous declarations which might be ambiguous with 12215 // the selected result. 12216 for (FunctionDecl *Skipped : AmbiguousDecls) 12217 if (!CheckMoreConstrained(Skipped, Result).hasValue()) 12218 return nullptr; 12219 Pair = DAP; 12220 } 12221 return Result; 12222 } 12223 12224 /// Given an overloaded function, tries to turn it into a non-overloaded 12225 /// function reference using resolveAddressOfSingleOverloadCandidate. This 12226 /// will perform access checks, diagnose the use of the resultant decl, and, if 12227 /// requested, potentially perform a function-to-pointer decay. 12228 /// 12229 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 12230 /// Otherwise, returns true. This may emit diagnostics and return true. 12231 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate( 12232 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 12233 Expr *E = SrcExpr.get(); 12234 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 12235 12236 DeclAccessPair DAP; 12237 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP); 12238 if (!Found || Found->isCPUDispatchMultiVersion() || 12239 Found->isCPUSpecificMultiVersion()) 12240 return false; 12241 12242 // Emitting multiple diagnostics for a function that is both inaccessible and 12243 // unavailable is consistent with our behavior elsewhere. So, always check 12244 // for both. 12245 DiagnoseUseOfDecl(Found, E->getExprLoc()); 12246 CheckAddressOfMemberAccess(E, DAP); 12247 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 12248 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 12249 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 12250 else 12251 SrcExpr = Fixed; 12252 return true; 12253 } 12254 12255 /// Given an expression that refers to an overloaded function, try to 12256 /// resolve that overloaded function expression down to a single function. 12257 /// 12258 /// This routine can only resolve template-ids that refer to a single function 12259 /// template, where that template-id refers to a single template whose template 12260 /// arguments are either provided by the template-id or have defaults, 12261 /// as described in C++0x [temp.arg.explicit]p3. 12262 /// 12263 /// If no template-ids are found, no diagnostics are emitted and NULL is 12264 /// returned. 12265 FunctionDecl * 12266 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 12267 bool Complain, 12268 DeclAccessPair *FoundResult) { 12269 // C++ [over.over]p1: 12270 // [...] [Note: any redundant set of parentheses surrounding the 12271 // overloaded function name is ignored (5.1). ] 12272 // C++ [over.over]p1: 12273 // [...] The overloaded function name can be preceded by the & 12274 // operator. 12275 12276 // If we didn't actually find any template-ids, we're done. 12277 if (!ovl->hasExplicitTemplateArgs()) 12278 return nullptr; 12279 12280 TemplateArgumentListInfo ExplicitTemplateArgs; 12281 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 12282 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 12283 12284 // Look through all of the overloaded functions, searching for one 12285 // whose type matches exactly. 12286 FunctionDecl *Matched = nullptr; 12287 for (UnresolvedSetIterator I = ovl->decls_begin(), 12288 E = ovl->decls_end(); I != E; ++I) { 12289 // C++0x [temp.arg.explicit]p3: 12290 // [...] In contexts where deduction is done and fails, or in contexts 12291 // where deduction is not done, if a template argument list is 12292 // specified and it, along with any default template arguments, 12293 // identifies a single function template specialization, then the 12294 // template-id is an lvalue for the function template specialization. 12295 FunctionTemplateDecl *FunctionTemplate 12296 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 12297 12298 // C++ [over.over]p2: 12299 // If the name is a function template, template argument deduction is 12300 // done (14.8.2.2), and if the argument deduction succeeds, the 12301 // resulting template argument list is used to generate a single 12302 // function template specialization, which is added to the set of 12303 // overloaded functions considered. 12304 FunctionDecl *Specialization = nullptr; 12305 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 12306 if (TemplateDeductionResult Result 12307 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 12308 Specialization, Info, 12309 /*IsAddressOfFunction*/true)) { 12310 // Make a note of the failed deduction for diagnostics. 12311 // TODO: Actually use the failed-deduction info? 12312 FailedCandidates.addCandidate() 12313 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 12314 MakeDeductionFailureInfo(Context, Result, Info)); 12315 continue; 12316 } 12317 12318 assert(Specialization && "no specialization and no error?"); 12319 12320 // Multiple matches; we can't resolve to a single declaration. 12321 if (Matched) { 12322 if (Complain) { 12323 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 12324 << ovl->getName(); 12325 NoteAllOverloadCandidates(ovl); 12326 } 12327 return nullptr; 12328 } 12329 12330 Matched = Specialization; 12331 if (FoundResult) *FoundResult = I.getPair(); 12332 } 12333 12334 if (Matched && 12335 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 12336 return nullptr; 12337 12338 return Matched; 12339 } 12340 12341 // Resolve and fix an overloaded expression that can be resolved 12342 // because it identifies a single function template specialization. 12343 // 12344 // Last three arguments should only be supplied if Complain = true 12345 // 12346 // Return true if it was logically possible to so resolve the 12347 // expression, regardless of whether or not it succeeded. Always 12348 // returns true if 'complain' is set. 12349 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 12350 ExprResult &SrcExpr, bool doFunctionPointerConverion, 12351 bool complain, SourceRange OpRangeForComplaining, 12352 QualType DestTypeForComplaining, 12353 unsigned DiagIDForComplaining) { 12354 assert(SrcExpr.get()->getType() == Context.OverloadTy); 12355 12356 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 12357 12358 DeclAccessPair found; 12359 ExprResult SingleFunctionExpression; 12360 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 12361 ovl.Expression, /*complain*/ false, &found)) { 12362 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 12363 SrcExpr = ExprError(); 12364 return true; 12365 } 12366 12367 // It is only correct to resolve to an instance method if we're 12368 // resolving a form that's permitted to be a pointer to member. 12369 // Otherwise we'll end up making a bound member expression, which 12370 // is illegal in all the contexts we resolve like this. 12371 if (!ovl.HasFormOfMemberPointer && 12372 isa<CXXMethodDecl>(fn) && 12373 cast<CXXMethodDecl>(fn)->isInstance()) { 12374 if (!complain) return false; 12375 12376 Diag(ovl.Expression->getExprLoc(), 12377 diag::err_bound_member_function) 12378 << 0 << ovl.Expression->getSourceRange(); 12379 12380 // TODO: I believe we only end up here if there's a mix of 12381 // static and non-static candidates (otherwise the expression 12382 // would have 'bound member' type, not 'overload' type). 12383 // Ideally we would note which candidate was chosen and why 12384 // the static candidates were rejected. 12385 SrcExpr = ExprError(); 12386 return true; 12387 } 12388 12389 // Fix the expression to refer to 'fn'. 12390 SingleFunctionExpression = 12391 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 12392 12393 // If desired, do function-to-pointer decay. 12394 if (doFunctionPointerConverion) { 12395 SingleFunctionExpression = 12396 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 12397 if (SingleFunctionExpression.isInvalid()) { 12398 SrcExpr = ExprError(); 12399 return true; 12400 } 12401 } 12402 } 12403 12404 if (!SingleFunctionExpression.isUsable()) { 12405 if (complain) { 12406 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 12407 << ovl.Expression->getName() 12408 << DestTypeForComplaining 12409 << OpRangeForComplaining 12410 << ovl.Expression->getQualifierLoc().getSourceRange(); 12411 NoteAllOverloadCandidates(SrcExpr.get()); 12412 12413 SrcExpr = ExprError(); 12414 return true; 12415 } 12416 12417 return false; 12418 } 12419 12420 SrcExpr = SingleFunctionExpression; 12421 return true; 12422 } 12423 12424 /// Add a single candidate to the overload set. 12425 static void AddOverloadedCallCandidate(Sema &S, 12426 DeclAccessPair FoundDecl, 12427 TemplateArgumentListInfo *ExplicitTemplateArgs, 12428 ArrayRef<Expr *> Args, 12429 OverloadCandidateSet &CandidateSet, 12430 bool PartialOverloading, 12431 bool KnownValid) { 12432 NamedDecl *Callee = FoundDecl.getDecl(); 12433 if (isa<UsingShadowDecl>(Callee)) 12434 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 12435 12436 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 12437 if (ExplicitTemplateArgs) { 12438 assert(!KnownValid && "Explicit template arguments?"); 12439 return; 12440 } 12441 // Prevent ill-formed function decls to be added as overload candidates. 12442 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 12443 return; 12444 12445 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 12446 /*SuppressUserConversions=*/false, 12447 PartialOverloading); 12448 return; 12449 } 12450 12451 if (FunctionTemplateDecl *FuncTemplate 12452 = dyn_cast<FunctionTemplateDecl>(Callee)) { 12453 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 12454 ExplicitTemplateArgs, Args, CandidateSet, 12455 /*SuppressUserConversions=*/false, 12456 PartialOverloading); 12457 return; 12458 } 12459 12460 assert(!KnownValid && "unhandled case in overloaded call candidate"); 12461 } 12462 12463 /// Add the overload candidates named by callee and/or found by argument 12464 /// dependent lookup to the given overload set. 12465 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 12466 ArrayRef<Expr *> Args, 12467 OverloadCandidateSet &CandidateSet, 12468 bool PartialOverloading) { 12469 12470 #ifndef NDEBUG 12471 // Verify that ArgumentDependentLookup is consistent with the rules 12472 // in C++0x [basic.lookup.argdep]p3: 12473 // 12474 // Let X be the lookup set produced by unqualified lookup (3.4.1) 12475 // and let Y be the lookup set produced by argument dependent 12476 // lookup (defined as follows). If X contains 12477 // 12478 // -- a declaration of a class member, or 12479 // 12480 // -- a block-scope function declaration that is not a 12481 // using-declaration, or 12482 // 12483 // -- a declaration that is neither a function or a function 12484 // template 12485 // 12486 // then Y is empty. 12487 12488 if (ULE->requiresADL()) { 12489 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12490 E = ULE->decls_end(); I != E; ++I) { 12491 assert(!(*I)->getDeclContext()->isRecord()); 12492 assert(isa<UsingShadowDecl>(*I) || 12493 !(*I)->getDeclContext()->isFunctionOrMethod()); 12494 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 12495 } 12496 } 12497 #endif 12498 12499 // It would be nice to avoid this copy. 12500 TemplateArgumentListInfo TABuffer; 12501 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12502 if (ULE->hasExplicitTemplateArgs()) { 12503 ULE->copyTemplateArgumentsInto(TABuffer); 12504 ExplicitTemplateArgs = &TABuffer; 12505 } 12506 12507 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 12508 E = ULE->decls_end(); I != E; ++I) 12509 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 12510 CandidateSet, PartialOverloading, 12511 /*KnownValid*/ true); 12512 12513 if (ULE->requiresADL()) 12514 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 12515 Args, ExplicitTemplateArgs, 12516 CandidateSet, PartialOverloading); 12517 } 12518 12519 /// Determine whether a declaration with the specified name could be moved into 12520 /// a different namespace. 12521 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 12522 switch (Name.getCXXOverloadedOperator()) { 12523 case OO_New: case OO_Array_New: 12524 case OO_Delete: case OO_Array_Delete: 12525 return false; 12526 12527 default: 12528 return true; 12529 } 12530 } 12531 12532 /// Attempt to recover from an ill-formed use of a non-dependent name in a 12533 /// template, where the non-dependent name was declared after the template 12534 /// was defined. This is common in code written for a compilers which do not 12535 /// correctly implement two-stage name lookup. 12536 /// 12537 /// Returns true if a viable candidate was found and a diagnostic was issued. 12538 static bool 12539 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 12540 const CXXScopeSpec &SS, LookupResult &R, 12541 OverloadCandidateSet::CandidateSetKind CSK, 12542 TemplateArgumentListInfo *ExplicitTemplateArgs, 12543 ArrayRef<Expr *> Args, 12544 bool *DoDiagnoseEmptyLookup = nullptr) { 12545 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 12546 return false; 12547 12548 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 12549 if (DC->isTransparentContext()) 12550 continue; 12551 12552 SemaRef.LookupQualifiedName(R, DC); 12553 12554 if (!R.empty()) { 12555 R.suppressDiagnostics(); 12556 12557 if (isa<CXXRecordDecl>(DC)) { 12558 // Don't diagnose names we find in classes; we get much better 12559 // diagnostics for these from DiagnoseEmptyLookup. 12560 R.clear(); 12561 if (DoDiagnoseEmptyLookup) 12562 *DoDiagnoseEmptyLookup = true; 12563 return false; 12564 } 12565 12566 OverloadCandidateSet Candidates(FnLoc, CSK); 12567 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12568 AddOverloadedCallCandidate(SemaRef, I.getPair(), 12569 ExplicitTemplateArgs, Args, 12570 Candidates, false, /*KnownValid*/ false); 12571 12572 OverloadCandidateSet::iterator Best; 12573 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 12574 // No viable functions. Don't bother the user with notes for functions 12575 // which don't work and shouldn't be found anyway. 12576 R.clear(); 12577 return false; 12578 } 12579 12580 // Find the namespaces where ADL would have looked, and suggest 12581 // declaring the function there instead. 12582 Sema::AssociatedNamespaceSet AssociatedNamespaces; 12583 Sema::AssociatedClassSet AssociatedClasses; 12584 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 12585 AssociatedNamespaces, 12586 AssociatedClasses); 12587 Sema::AssociatedNamespaceSet SuggestedNamespaces; 12588 if (canBeDeclaredInNamespace(R.getLookupName())) { 12589 DeclContext *Std = SemaRef.getStdNamespace(); 12590 for (Sema::AssociatedNamespaceSet::iterator 12591 it = AssociatedNamespaces.begin(), 12592 end = AssociatedNamespaces.end(); it != end; ++it) { 12593 // Never suggest declaring a function within namespace 'std'. 12594 if (Std && Std->Encloses(*it)) 12595 continue; 12596 12597 // Never suggest declaring a function within a namespace with a 12598 // reserved name, like __gnu_cxx. 12599 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 12600 if (NS && 12601 NS->getQualifiedNameAsString().find("__") != std::string::npos) 12602 continue; 12603 12604 SuggestedNamespaces.insert(*it); 12605 } 12606 } 12607 12608 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 12609 << R.getLookupName(); 12610 if (SuggestedNamespaces.empty()) { 12611 SemaRef.Diag(Best->Function->getLocation(), 12612 diag::note_not_found_by_two_phase_lookup) 12613 << R.getLookupName() << 0; 12614 } else if (SuggestedNamespaces.size() == 1) { 12615 SemaRef.Diag(Best->Function->getLocation(), 12616 diag::note_not_found_by_two_phase_lookup) 12617 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 12618 } else { 12619 // FIXME: It would be useful to list the associated namespaces here, 12620 // but the diagnostics infrastructure doesn't provide a way to produce 12621 // a localized representation of a list of items. 12622 SemaRef.Diag(Best->Function->getLocation(), 12623 diag::note_not_found_by_two_phase_lookup) 12624 << R.getLookupName() << 2; 12625 } 12626 12627 // Try to recover by calling this function. 12628 return true; 12629 } 12630 12631 R.clear(); 12632 } 12633 12634 return false; 12635 } 12636 12637 /// Attempt to recover from ill-formed use of a non-dependent operator in a 12638 /// template, where the non-dependent operator was declared after the template 12639 /// was defined. 12640 /// 12641 /// Returns true if a viable candidate was found and a diagnostic was issued. 12642 static bool 12643 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 12644 SourceLocation OpLoc, 12645 ArrayRef<Expr *> Args) { 12646 DeclarationName OpName = 12647 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 12648 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 12649 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 12650 OverloadCandidateSet::CSK_Operator, 12651 /*ExplicitTemplateArgs=*/nullptr, Args); 12652 } 12653 12654 namespace { 12655 class BuildRecoveryCallExprRAII { 12656 Sema &SemaRef; 12657 public: 12658 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 12659 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 12660 SemaRef.IsBuildingRecoveryCallExpr = true; 12661 } 12662 12663 ~BuildRecoveryCallExprRAII() { 12664 SemaRef.IsBuildingRecoveryCallExpr = false; 12665 } 12666 }; 12667 12668 } 12669 12670 /// Attempts to recover from a call where no functions were found. 12671 /// 12672 /// Returns true if new candidates were found. 12673 static ExprResult 12674 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12675 UnresolvedLookupExpr *ULE, 12676 SourceLocation LParenLoc, 12677 MutableArrayRef<Expr *> Args, 12678 SourceLocation RParenLoc, 12679 bool EmptyLookup, bool AllowTypoCorrection) { 12680 // Do not try to recover if it is already building a recovery call. 12681 // This stops infinite loops for template instantiations like 12682 // 12683 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 12684 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 12685 // 12686 if (SemaRef.IsBuildingRecoveryCallExpr) 12687 return ExprError(); 12688 BuildRecoveryCallExprRAII RCE(SemaRef); 12689 12690 CXXScopeSpec SS; 12691 SS.Adopt(ULE->getQualifierLoc()); 12692 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 12693 12694 TemplateArgumentListInfo TABuffer; 12695 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 12696 if (ULE->hasExplicitTemplateArgs()) { 12697 ULE->copyTemplateArgumentsInto(TABuffer); 12698 ExplicitTemplateArgs = &TABuffer; 12699 } 12700 12701 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 12702 Sema::LookupOrdinaryName); 12703 bool DoDiagnoseEmptyLookup = EmptyLookup; 12704 if (!DiagnoseTwoPhaseLookup( 12705 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal, 12706 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) { 12707 NoTypoCorrectionCCC NoTypoValidator{}; 12708 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(), 12709 ExplicitTemplateArgs != nullptr, 12710 dyn_cast<MemberExpr>(Fn)); 12711 CorrectionCandidateCallback &Validator = 12712 AllowTypoCorrection 12713 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator) 12714 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator); 12715 if (!DoDiagnoseEmptyLookup || 12716 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs, 12717 Args)) 12718 return ExprError(); 12719 } 12720 12721 assert(!R.empty() && "lookup results empty despite recovery"); 12722 12723 // If recovery created an ambiguity, just bail out. 12724 if (R.isAmbiguous()) { 12725 R.suppressDiagnostics(); 12726 return ExprError(); 12727 } 12728 12729 // Build an implicit member call if appropriate. Just drop the 12730 // casts and such from the call, we don't really care. 12731 ExprResult NewFn = ExprError(); 12732 if ((*R.begin())->isCXXClassMember()) 12733 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 12734 ExplicitTemplateArgs, S); 12735 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 12736 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 12737 ExplicitTemplateArgs); 12738 else 12739 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 12740 12741 if (NewFn.isInvalid()) 12742 return ExprError(); 12743 12744 // This shouldn't cause an infinite loop because we're giving it 12745 // an expression with viable lookup results, which should never 12746 // end up here. 12747 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 12748 MultiExprArg(Args.data(), Args.size()), 12749 RParenLoc); 12750 } 12751 12752 /// Constructs and populates an OverloadedCandidateSet from 12753 /// the given function. 12754 /// \returns true when an the ExprResult output parameter has been set. 12755 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12756 UnresolvedLookupExpr *ULE, 12757 MultiExprArg Args, 12758 SourceLocation RParenLoc, 12759 OverloadCandidateSet *CandidateSet, 12760 ExprResult *Result) { 12761 #ifndef NDEBUG 12762 if (ULE->requiresADL()) { 12763 // To do ADL, we must have found an unqualified name. 12764 assert(!ULE->getQualifier() && "qualified name with ADL"); 12765 12766 // We don't perform ADL for implicit declarations of builtins. 12767 // Verify that this was correctly set up. 12768 FunctionDecl *F; 12769 if (ULE->decls_begin() != ULE->decls_end() && 12770 ULE->decls_begin() + 1 == ULE->decls_end() && 12771 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12772 F->getBuiltinID() && F->isImplicit()) 12773 llvm_unreachable("performing ADL for builtin"); 12774 12775 // We don't perform ADL in C. 12776 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12777 } 12778 #endif 12779 12780 UnbridgedCastsSet UnbridgedCasts; 12781 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12782 *Result = ExprError(); 12783 return true; 12784 } 12785 12786 // Add the functions denoted by the callee to the set of candidate 12787 // functions, including those from argument-dependent lookup. 12788 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12789 12790 if (getLangOpts().MSVCCompat && 12791 CurContext->isDependentContext() && !isSFINAEContext() && 12792 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12793 12794 OverloadCandidateSet::iterator Best; 12795 if (CandidateSet->empty() || 12796 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12797 OR_No_Viable_Function) { 12798 // In Microsoft mode, if we are inside a template class member function 12799 // then create a type dependent CallExpr. The goal is to postpone name 12800 // lookup to instantiation time to be able to search into type dependent 12801 // base classes. 12802 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12803 VK_RValue, RParenLoc); 12804 CE->markDependentForPostponedNameLookup(); 12805 *Result = CE; 12806 return true; 12807 } 12808 } 12809 12810 if (CandidateSet->empty()) 12811 return false; 12812 12813 UnbridgedCasts.restore(); 12814 return false; 12815 } 12816 12817 // Guess at what the return type for an unresolvable overload should be. 12818 static QualType chooseRecoveryType(OverloadCandidateSet &CS, 12819 OverloadCandidateSet::iterator *Best) { 12820 llvm::Optional<QualType> Result; 12821 // Adjust Type after seeing a candidate. 12822 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) { 12823 if (!Candidate.Function) 12824 return; 12825 QualType T = Candidate.Function->getCallResultType(); 12826 if (T.isNull()) 12827 return; 12828 if (!Result) 12829 Result = T; 12830 else if (Result != T) 12831 Result = QualType(); 12832 }; 12833 12834 // Look for an unambiguous type from a progressively larger subset. 12835 // e.g. if types disagree, but all *viable* overloads return int, choose int. 12836 // 12837 // First, consider only the best candidate. 12838 if (Best && *Best != CS.end()) 12839 ConsiderCandidate(**Best); 12840 // Next, consider only viable candidates. 12841 if (!Result) 12842 for (const auto &C : CS) 12843 if (C.Viable) 12844 ConsiderCandidate(C); 12845 // Finally, consider all candidates. 12846 if (!Result) 12847 for (const auto &C : CS) 12848 ConsiderCandidate(C); 12849 12850 return Result.getValueOr(QualType()); 12851 } 12852 12853 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12854 /// the completed call expression. If overload resolution fails, emits 12855 /// diagnostics and returns ExprError() 12856 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12857 UnresolvedLookupExpr *ULE, 12858 SourceLocation LParenLoc, 12859 MultiExprArg Args, 12860 SourceLocation RParenLoc, 12861 Expr *ExecConfig, 12862 OverloadCandidateSet *CandidateSet, 12863 OverloadCandidateSet::iterator *Best, 12864 OverloadingResult OverloadResult, 12865 bool AllowTypoCorrection) { 12866 if (CandidateSet->empty()) 12867 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12868 RParenLoc, /*EmptyLookup=*/true, 12869 AllowTypoCorrection); 12870 12871 switch (OverloadResult) { 12872 case OR_Success: { 12873 FunctionDecl *FDecl = (*Best)->Function; 12874 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12875 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12876 return ExprError(); 12877 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12878 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12879 ExecConfig, /*IsExecConfig=*/false, 12880 (*Best)->IsADLCandidate); 12881 } 12882 12883 case OR_No_Viable_Function: { 12884 // Try to recover by looking for viable functions which the user might 12885 // have meant to call. 12886 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12887 Args, RParenLoc, 12888 /*EmptyLookup=*/false, 12889 AllowTypoCorrection); 12890 if (!Recovery.isInvalid()) 12891 return Recovery; 12892 12893 // If the user passes in a function that we can't take the address of, we 12894 // generally end up emitting really bad error messages. Here, we attempt to 12895 // emit better ones. 12896 for (const Expr *Arg : Args) { 12897 if (!Arg->getType()->isFunctionType()) 12898 continue; 12899 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12900 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12901 if (FD && 12902 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12903 Arg->getExprLoc())) 12904 return ExprError(); 12905 } 12906 } 12907 12908 CandidateSet->NoteCandidates( 12909 PartialDiagnosticAt( 12910 Fn->getBeginLoc(), 12911 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call) 12912 << ULE->getName() << Fn->getSourceRange()), 12913 SemaRef, OCD_AllCandidates, Args); 12914 break; 12915 } 12916 12917 case OR_Ambiguous: 12918 CandidateSet->NoteCandidates( 12919 PartialDiagnosticAt(Fn->getBeginLoc(), 12920 SemaRef.PDiag(diag::err_ovl_ambiguous_call) 12921 << ULE->getName() << Fn->getSourceRange()), 12922 SemaRef, OCD_AmbiguousCandidates, Args); 12923 break; 12924 12925 case OR_Deleted: { 12926 CandidateSet->NoteCandidates( 12927 PartialDiagnosticAt(Fn->getBeginLoc(), 12928 SemaRef.PDiag(diag::err_ovl_deleted_call) 12929 << ULE->getName() << Fn->getSourceRange()), 12930 SemaRef, OCD_AllCandidates, Args); 12931 12932 // We emitted an error for the unavailable/deleted function call but keep 12933 // the call in the AST. 12934 FunctionDecl *FDecl = (*Best)->Function; 12935 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12936 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12937 ExecConfig, /*IsExecConfig=*/false, 12938 (*Best)->IsADLCandidate); 12939 } 12940 } 12941 12942 // Overload resolution failed, try to recover. 12943 SmallVector<Expr *, 8> SubExprs = {Fn}; 12944 SubExprs.append(Args.begin(), Args.end()); 12945 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs, 12946 chooseRecoveryType(*CandidateSet, Best)); 12947 } 12948 12949 static void markUnaddressableCandidatesUnviable(Sema &S, 12950 OverloadCandidateSet &CS) { 12951 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12952 if (I->Viable && 12953 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12954 I->Viable = false; 12955 I->FailureKind = ovl_fail_addr_not_available; 12956 } 12957 } 12958 } 12959 12960 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12961 /// (which eventually refers to the declaration Func) and the call 12962 /// arguments Args/NumArgs, attempt to resolve the function call down 12963 /// to a specific function. If overload resolution succeeds, returns 12964 /// the call expression produced by overload resolution. 12965 /// Otherwise, emits diagnostics and returns ExprError. 12966 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12967 UnresolvedLookupExpr *ULE, 12968 SourceLocation LParenLoc, 12969 MultiExprArg Args, 12970 SourceLocation RParenLoc, 12971 Expr *ExecConfig, 12972 bool AllowTypoCorrection, 12973 bool CalleesAddressIsTaken) { 12974 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12975 OverloadCandidateSet::CSK_Normal); 12976 ExprResult result; 12977 12978 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12979 &result)) 12980 return result; 12981 12982 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12983 // functions that aren't addressible are considered unviable. 12984 if (CalleesAddressIsTaken) 12985 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12986 12987 OverloadCandidateSet::iterator Best; 12988 OverloadingResult OverloadResult = 12989 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12990 12991 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc, 12992 ExecConfig, &CandidateSet, &Best, 12993 OverloadResult, AllowTypoCorrection); 12994 } 12995 12996 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12997 return Functions.size() > 1 || 12998 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12999 } 13000 13001 /// Create a unary operation that may resolve to an overloaded 13002 /// operator. 13003 /// 13004 /// \param OpLoc The location of the operator itself (e.g., '*'). 13005 /// 13006 /// \param Opc The UnaryOperatorKind that describes this operator. 13007 /// 13008 /// \param Fns The set of non-member functions that will be 13009 /// considered by overload resolution. The caller needs to build this 13010 /// set based on the context using, e.g., 13011 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13012 /// set should not contain any member functions; those will be added 13013 /// by CreateOverloadedUnaryOp(). 13014 /// 13015 /// \param Input The input argument. 13016 ExprResult 13017 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 13018 const UnresolvedSetImpl &Fns, 13019 Expr *Input, bool PerformADL) { 13020 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 13021 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 13022 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13023 // TODO: provide better source location info. 13024 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13025 13026 if (checkPlaceholderForOverload(*this, Input)) 13027 return ExprError(); 13028 13029 Expr *Args[2] = { Input, nullptr }; 13030 unsigned NumArgs = 1; 13031 13032 // For post-increment and post-decrement, add the implicit '0' as 13033 // the second argument, so that we know this is a post-increment or 13034 // post-decrement. 13035 if (Opc == UO_PostInc || Opc == UO_PostDec) { 13036 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13037 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 13038 SourceLocation()); 13039 NumArgs = 2; 13040 } 13041 13042 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 13043 13044 if (Input->isTypeDependent()) { 13045 if (Fns.empty()) 13046 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, 13047 VK_RValue, OK_Ordinary, OpLoc, false, 13048 CurFPFeatures); 13049 13050 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13051 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13052 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13053 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13054 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 13055 Context.DependentTy, VK_RValue, OpLoc, 13056 CurFPFeatures); 13057 } 13058 13059 // Build an empty overload set. 13060 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 13061 13062 // Add the candidates from the given function set. 13063 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet); 13064 13065 // Add operator candidates that are member functions. 13066 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13067 13068 // Add candidates from ADL. 13069 if (PerformADL) { 13070 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 13071 /*ExplicitTemplateArgs*/nullptr, 13072 CandidateSet); 13073 } 13074 13075 // Add builtin operator candidates. 13076 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 13077 13078 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13079 13080 // Perform overload resolution. 13081 OverloadCandidateSet::iterator Best; 13082 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13083 case OR_Success: { 13084 // We found a built-in operator or an overloaded operator. 13085 FunctionDecl *FnDecl = Best->Function; 13086 13087 if (FnDecl) { 13088 Expr *Base = nullptr; 13089 // We matched an overloaded operator. Build a call to that 13090 // operator. 13091 13092 // Convert the arguments. 13093 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13094 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 13095 13096 ExprResult InputRes = 13097 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 13098 Best->FoundDecl, Method); 13099 if (InputRes.isInvalid()) 13100 return ExprError(); 13101 Base = Input = InputRes.get(); 13102 } else { 13103 // Convert the arguments. 13104 ExprResult InputInit 13105 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13106 Context, 13107 FnDecl->getParamDecl(0)), 13108 SourceLocation(), 13109 Input); 13110 if (InputInit.isInvalid()) 13111 return ExprError(); 13112 Input = InputInit.get(); 13113 } 13114 13115 // Build the actual expression node. 13116 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 13117 Base, HadMultipleCandidates, 13118 OpLoc); 13119 if (FnExpr.isInvalid()) 13120 return ExprError(); 13121 13122 // Determine the result type. 13123 QualType ResultTy = FnDecl->getReturnType(); 13124 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13125 ResultTy = ResultTy.getNonLValueExprType(Context); 13126 13127 Args[0] = Input; 13128 CallExpr *TheCall = CXXOperatorCallExpr::Create( 13129 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 13130 CurFPFeatures, Best->IsADLCandidate); 13131 13132 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 13133 return ExprError(); 13134 13135 if (CheckFunctionCall(FnDecl, TheCall, 13136 FnDecl->getType()->castAs<FunctionProtoType>())) 13137 return ExprError(); 13138 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl); 13139 } else { 13140 // We matched a built-in operator. Convert the arguments, then 13141 // break out so that we will build the appropriate built-in 13142 // operator node. 13143 ExprResult InputRes = PerformImplicitConversion( 13144 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 13145 CCK_ForBuiltinOverloadedOp); 13146 if (InputRes.isInvalid()) 13147 return ExprError(); 13148 Input = InputRes.get(); 13149 break; 13150 } 13151 } 13152 13153 case OR_No_Viable_Function: 13154 // This is an erroneous use of an operator which can be overloaded by 13155 // a non-member function. Check for non-member operators which were 13156 // defined too late to be candidates. 13157 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 13158 // FIXME: Recover by calling the found function. 13159 return ExprError(); 13160 13161 // No viable function; fall through to handling this as a 13162 // built-in operator, which will produce an error message for us. 13163 break; 13164 13165 case OR_Ambiguous: 13166 CandidateSet.NoteCandidates( 13167 PartialDiagnosticAt(OpLoc, 13168 PDiag(diag::err_ovl_ambiguous_oper_unary) 13169 << UnaryOperator::getOpcodeStr(Opc) 13170 << Input->getType() << Input->getSourceRange()), 13171 *this, OCD_AmbiguousCandidates, ArgsArray, 13172 UnaryOperator::getOpcodeStr(Opc), OpLoc); 13173 return ExprError(); 13174 13175 case OR_Deleted: 13176 CandidateSet.NoteCandidates( 13177 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 13178 << UnaryOperator::getOpcodeStr(Opc) 13179 << Input->getSourceRange()), 13180 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc), 13181 OpLoc); 13182 return ExprError(); 13183 } 13184 13185 // Either we found no viable overloaded operator or we matched a 13186 // built-in operator. In either case, fall through to trying to 13187 // build a built-in operation. 13188 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13189 } 13190 13191 /// Perform lookup for an overloaded binary operator. 13192 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 13193 OverloadedOperatorKind Op, 13194 const UnresolvedSetImpl &Fns, 13195 ArrayRef<Expr *> Args, bool PerformADL) { 13196 SourceLocation OpLoc = CandidateSet.getLocation(); 13197 13198 OverloadedOperatorKind ExtraOp = 13199 CandidateSet.getRewriteInfo().AllowRewrittenCandidates 13200 ? getRewrittenOverloadedOperator(Op) 13201 : OO_None; 13202 13203 // Add the candidates from the given function set. This also adds the 13204 // rewritten candidates using these functions if necessary. 13205 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet); 13206 13207 // Add operator candidates that are member functions. 13208 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13209 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op)) 13210 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet, 13211 OverloadCandidateParamOrder::Reversed); 13212 13213 // In C++20, also add any rewritten member candidates. 13214 if (ExtraOp) { 13215 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet); 13216 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp)) 13217 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]}, 13218 CandidateSet, 13219 OverloadCandidateParamOrder::Reversed); 13220 } 13221 13222 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 13223 // performed for an assignment operator (nor for operator[] nor operator->, 13224 // which don't get here). 13225 if (Op != OO_Equal && PerformADL) { 13226 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13227 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 13228 /*ExplicitTemplateArgs*/ nullptr, 13229 CandidateSet); 13230 if (ExtraOp) { 13231 DeclarationName ExtraOpName = 13232 Context.DeclarationNames.getCXXOperatorName(ExtraOp); 13233 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args, 13234 /*ExplicitTemplateArgs*/ nullptr, 13235 CandidateSet); 13236 } 13237 } 13238 13239 // Add builtin operator candidates. 13240 // 13241 // FIXME: We don't add any rewritten candidates here. This is strictly 13242 // incorrect; a builtin candidate could be hidden by a non-viable candidate, 13243 // resulting in our selecting a rewritten builtin candidate. For example: 13244 // 13245 // enum class E { e }; 13246 // bool operator!=(E, E) requires false; 13247 // bool k = E::e != E::e; 13248 // 13249 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But 13250 // it seems unreasonable to consider rewritten builtin candidates. A core 13251 // issue has been filed proposing to removed this requirement. 13252 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 13253 } 13254 13255 /// Create a binary operation that may resolve to an overloaded 13256 /// operator. 13257 /// 13258 /// \param OpLoc The location of the operator itself (e.g., '+'). 13259 /// 13260 /// \param Opc The BinaryOperatorKind that describes this operator. 13261 /// 13262 /// \param Fns The set of non-member functions that will be 13263 /// considered by overload resolution. The caller needs to build this 13264 /// set based on the context using, e.g., 13265 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 13266 /// set should not contain any member functions; those will be added 13267 /// by CreateOverloadedBinOp(). 13268 /// 13269 /// \param LHS Left-hand argument. 13270 /// \param RHS Right-hand argument. 13271 /// \param PerformADL Whether to consider operator candidates found by ADL. 13272 /// \param AllowRewrittenCandidates Whether to consider candidates found by 13273 /// C++20 operator rewrites. 13274 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 13275 /// the function in question. Such a function is never a candidate in 13276 /// our overload resolution. This also enables synthesizing a three-way 13277 /// comparison from < and == as described in C++20 [class.spaceship]p1. 13278 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 13279 BinaryOperatorKind Opc, 13280 const UnresolvedSetImpl &Fns, Expr *LHS, 13281 Expr *RHS, bool PerformADL, 13282 bool AllowRewrittenCandidates, 13283 FunctionDecl *DefaultedFn) { 13284 Expr *Args[2] = { LHS, RHS }; 13285 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 13286 13287 if (!getLangOpts().CPlusPlus20) 13288 AllowRewrittenCandidates = false; 13289 13290 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 13291 13292 // If either side is type-dependent, create an appropriate dependent 13293 // expression. 13294 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13295 if (Fns.empty()) { 13296 // If there are no functions to store, just build a dependent 13297 // BinaryOperator or CompoundAssignment. 13298 if (Opc <= BO_Assign || Opc > BO_OrAssign) 13299 return BinaryOperator::Create(Context, Args[0], Args[1], Opc, 13300 Context.DependentTy, VK_RValue, 13301 OK_Ordinary, OpLoc, CurFPFeatures); 13302 return CompoundAssignOperator::Create( 13303 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, 13304 OK_Ordinary, OpLoc, CurFPFeatures, Context.DependentTy, 13305 Context.DependentTy); 13306 } 13307 13308 // FIXME: save results of ADL from here? 13309 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13310 // TODO: provide better source location info in DNLoc component. 13311 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 13312 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 13313 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 13314 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 13315 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 13316 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 13317 Context.DependentTy, VK_RValue, OpLoc, 13318 CurFPFeatures); 13319 } 13320 13321 // Always do placeholder-like conversions on the RHS. 13322 if (checkPlaceholderForOverload(*this, Args[1])) 13323 return ExprError(); 13324 13325 // Do placeholder-like conversion on the LHS; note that we should 13326 // not get here with a PseudoObject LHS. 13327 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 13328 if (checkPlaceholderForOverload(*this, Args[0])) 13329 return ExprError(); 13330 13331 // If this is the assignment operator, we only perform overload resolution 13332 // if the left-hand side is a class or enumeration type. This is actually 13333 // a hack. The standard requires that we do overload resolution between the 13334 // various built-in candidates, but as DR507 points out, this can lead to 13335 // problems. So we do it this way, which pretty much follows what GCC does. 13336 // Note that we go the traditional code path for compound assignment forms. 13337 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 13338 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13339 13340 // If this is the .* operator, which is not overloadable, just 13341 // create a built-in binary operator. 13342 if (Opc == BO_PtrMemD) 13343 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13344 13345 // Build the overload set. 13346 OverloadCandidateSet CandidateSet( 13347 OpLoc, OverloadCandidateSet::CSK_Operator, 13348 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates)); 13349 if (DefaultedFn) 13350 CandidateSet.exclude(DefaultedFn); 13351 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL); 13352 13353 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13354 13355 // Perform overload resolution. 13356 OverloadCandidateSet::iterator Best; 13357 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13358 case OR_Success: { 13359 // We found a built-in operator or an overloaded operator. 13360 FunctionDecl *FnDecl = Best->Function; 13361 13362 bool IsReversed = Best->isReversed(); 13363 if (IsReversed) 13364 std::swap(Args[0], Args[1]); 13365 13366 if (FnDecl) { 13367 Expr *Base = nullptr; 13368 // We matched an overloaded operator. Build a call to that 13369 // operator. 13370 13371 OverloadedOperatorKind ChosenOp = 13372 FnDecl->getDeclName().getCXXOverloadedOperator(); 13373 13374 // C++2a [over.match.oper]p9: 13375 // If a rewritten operator== candidate is selected by overload 13376 // resolution for an operator@, its return type shall be cv bool 13377 if (Best->RewriteKind && ChosenOp == OO_EqualEqual && 13378 !FnDecl->getReturnType()->isBooleanType()) { 13379 bool IsExtension = 13380 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType(); 13381 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool 13382 : diag::err_ovl_rewrite_equalequal_not_bool) 13383 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc) 13384 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13385 Diag(FnDecl->getLocation(), diag::note_declared_at); 13386 if (!IsExtension) 13387 return ExprError(); 13388 } 13389 13390 if (AllowRewrittenCandidates && !IsReversed && 13391 CandidateSet.getRewriteInfo().isReversible()) { 13392 // We could have reversed this operator, but didn't. Check if some 13393 // reversed form was a viable candidate, and if so, if it had a 13394 // better conversion for either parameter. If so, this call is 13395 // formally ambiguous, and allowing it is an extension. 13396 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith; 13397 for (OverloadCandidate &Cand : CandidateSet) { 13398 if (Cand.Viable && Cand.Function && Cand.isReversed() && 13399 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) { 13400 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 13401 if (CompareImplicitConversionSequences( 13402 *this, OpLoc, Cand.Conversions[ArgIdx], 13403 Best->Conversions[ArgIdx]) == 13404 ImplicitConversionSequence::Better) { 13405 AmbiguousWith.push_back(Cand.Function); 13406 break; 13407 } 13408 } 13409 } 13410 } 13411 13412 if (!AmbiguousWith.empty()) { 13413 bool AmbiguousWithSelf = 13414 AmbiguousWith.size() == 1 && 13415 declaresSameEntity(AmbiguousWith.front(), FnDecl); 13416 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed) 13417 << BinaryOperator::getOpcodeStr(Opc) 13418 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf 13419 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13420 if (AmbiguousWithSelf) { 13421 Diag(FnDecl->getLocation(), 13422 diag::note_ovl_ambiguous_oper_binary_reversed_self); 13423 } else { 13424 Diag(FnDecl->getLocation(), 13425 diag::note_ovl_ambiguous_oper_binary_selected_candidate); 13426 for (auto *F : AmbiguousWith) 13427 Diag(F->getLocation(), 13428 diag::note_ovl_ambiguous_oper_binary_reversed_candidate); 13429 } 13430 } 13431 } 13432 13433 // Convert the arguments. 13434 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 13435 // Best->Access is only meaningful for class members. 13436 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 13437 13438 ExprResult Arg1 = 13439 PerformCopyInitialization( 13440 InitializedEntity::InitializeParameter(Context, 13441 FnDecl->getParamDecl(0)), 13442 SourceLocation(), Args[1]); 13443 if (Arg1.isInvalid()) 13444 return ExprError(); 13445 13446 ExprResult Arg0 = 13447 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13448 Best->FoundDecl, Method); 13449 if (Arg0.isInvalid()) 13450 return ExprError(); 13451 Base = Args[0] = Arg0.getAs<Expr>(); 13452 Args[1] = RHS = Arg1.getAs<Expr>(); 13453 } else { 13454 // Convert the arguments. 13455 ExprResult Arg0 = PerformCopyInitialization( 13456 InitializedEntity::InitializeParameter(Context, 13457 FnDecl->getParamDecl(0)), 13458 SourceLocation(), Args[0]); 13459 if (Arg0.isInvalid()) 13460 return ExprError(); 13461 13462 ExprResult Arg1 = 13463 PerformCopyInitialization( 13464 InitializedEntity::InitializeParameter(Context, 13465 FnDecl->getParamDecl(1)), 13466 SourceLocation(), Args[1]); 13467 if (Arg1.isInvalid()) 13468 return ExprError(); 13469 Args[0] = LHS = Arg0.getAs<Expr>(); 13470 Args[1] = RHS = Arg1.getAs<Expr>(); 13471 } 13472 13473 // Build the actual expression node. 13474 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13475 Best->FoundDecl, Base, 13476 HadMultipleCandidates, OpLoc); 13477 if (FnExpr.isInvalid()) 13478 return ExprError(); 13479 13480 // Determine the result type. 13481 QualType ResultTy = FnDecl->getReturnType(); 13482 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13483 ResultTy = ResultTy.getNonLValueExprType(Context); 13484 13485 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13486 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc, 13487 CurFPFeatures, Best->IsADLCandidate); 13488 13489 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 13490 FnDecl)) 13491 return ExprError(); 13492 13493 ArrayRef<const Expr *> ArgsArray(Args, 2); 13494 const Expr *ImplicitThis = nullptr; 13495 // Cut off the implicit 'this'. 13496 if (isa<CXXMethodDecl>(FnDecl)) { 13497 ImplicitThis = ArgsArray[0]; 13498 ArgsArray = ArgsArray.slice(1); 13499 } 13500 13501 // Check for a self move. 13502 if (Op == OO_Equal) 13503 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 13504 13505 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 13506 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 13507 VariadicDoesNotApply); 13508 13509 ExprResult R = MaybeBindToTemporary(TheCall); 13510 if (R.isInvalid()) 13511 return ExprError(); 13512 13513 // For a rewritten candidate, we've already reversed the arguments 13514 // if needed. Perform the rest of the rewrite now. 13515 if ((Best->RewriteKind & CRK_DifferentOperator) || 13516 (Op == OO_Spaceship && IsReversed)) { 13517 if (Op == OO_ExclaimEqual) { 13518 assert(ChosenOp == OO_EqualEqual && "unexpected operator name"); 13519 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get()); 13520 } else { 13521 assert(ChosenOp == OO_Spaceship && "unexpected operator name"); 13522 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 13523 Expr *ZeroLiteral = 13524 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc); 13525 13526 Sema::CodeSynthesisContext Ctx; 13527 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship; 13528 Ctx.Entity = FnDecl; 13529 pushCodeSynthesisContext(Ctx); 13530 13531 R = CreateOverloadedBinOp( 13532 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(), 13533 IsReversed ? R.get() : ZeroLiteral, PerformADL, 13534 /*AllowRewrittenCandidates=*/false); 13535 13536 popCodeSynthesisContext(); 13537 } 13538 if (R.isInvalid()) 13539 return ExprError(); 13540 } else { 13541 assert(ChosenOp == Op && "unexpected operator name"); 13542 } 13543 13544 // Make a note in the AST if we did any rewriting. 13545 if (Best->RewriteKind != CRK_None) 13546 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed); 13547 13548 return CheckForImmediateInvocation(R, FnDecl); 13549 } else { 13550 // We matched a built-in operator. Convert the arguments, then 13551 // break out so that we will build the appropriate built-in 13552 // operator node. 13553 ExprResult ArgsRes0 = PerformImplicitConversion( 13554 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13555 AA_Passing, CCK_ForBuiltinOverloadedOp); 13556 if (ArgsRes0.isInvalid()) 13557 return ExprError(); 13558 Args[0] = ArgsRes0.get(); 13559 13560 ExprResult ArgsRes1 = PerformImplicitConversion( 13561 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13562 AA_Passing, CCK_ForBuiltinOverloadedOp); 13563 if (ArgsRes1.isInvalid()) 13564 return ExprError(); 13565 Args[1] = ArgsRes1.get(); 13566 break; 13567 } 13568 } 13569 13570 case OR_No_Viable_Function: { 13571 // C++ [over.match.oper]p9: 13572 // If the operator is the operator , [...] and there are no 13573 // viable functions, then the operator is assumed to be the 13574 // built-in operator and interpreted according to clause 5. 13575 if (Opc == BO_Comma) 13576 break; 13577 13578 // When defaulting an 'operator<=>', we can try to synthesize a three-way 13579 // compare result using '==' and '<'. 13580 if (DefaultedFn && Opc == BO_Cmp) { 13581 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0], 13582 Args[1], DefaultedFn); 13583 if (E.isInvalid() || E.isUsable()) 13584 return E; 13585 } 13586 13587 // For class as left operand for assignment or compound assignment 13588 // operator do not fall through to handling in built-in, but report that 13589 // no overloaded assignment operator found 13590 ExprResult Result = ExprError(); 13591 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc); 13592 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, 13593 Args, OpLoc); 13594 if (Args[0]->getType()->isRecordType() && 13595 Opc >= BO_Assign && Opc <= BO_OrAssign) { 13596 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13597 << BinaryOperator::getOpcodeStr(Opc) 13598 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13599 if (Args[0]->getType()->isIncompleteType()) { 13600 Diag(OpLoc, diag::note_assign_lhs_incomplete) 13601 << Args[0]->getType() 13602 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 13603 } 13604 } else { 13605 // This is an erroneous use of an operator which can be overloaded by 13606 // a non-member function. Check for non-member operators which were 13607 // defined too late to be candidates. 13608 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 13609 // FIXME: Recover by calling the found function. 13610 return ExprError(); 13611 13612 // No viable function; try to create a built-in operation, which will 13613 // produce an error. Then, show the non-viable candidates. 13614 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13615 } 13616 assert(Result.isInvalid() && 13617 "C++ binary operator overloading is missing candidates!"); 13618 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc); 13619 return Result; 13620 } 13621 13622 case OR_Ambiguous: 13623 CandidateSet.NoteCandidates( 13624 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13625 << BinaryOperator::getOpcodeStr(Opc) 13626 << Args[0]->getType() 13627 << Args[1]->getType() 13628 << Args[0]->getSourceRange() 13629 << Args[1]->getSourceRange()), 13630 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13631 OpLoc); 13632 return ExprError(); 13633 13634 case OR_Deleted: 13635 if (isImplicitlyDeleted(Best->Function)) { 13636 FunctionDecl *DeletedFD = Best->Function; 13637 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD); 13638 if (DFK.isSpecialMember()) { 13639 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 13640 << Args[0]->getType() << DFK.asSpecialMember(); 13641 } else { 13642 assert(DFK.isComparison()); 13643 Diag(OpLoc, diag::err_ovl_deleted_comparison) 13644 << Args[0]->getType() << DeletedFD; 13645 } 13646 13647 // The user probably meant to call this special member. Just 13648 // explain why it's deleted. 13649 NoteDeletedFunction(DeletedFD); 13650 return ExprError(); 13651 } 13652 CandidateSet.NoteCandidates( 13653 PartialDiagnosticAt( 13654 OpLoc, PDiag(diag::err_ovl_deleted_oper) 13655 << getOperatorSpelling(Best->Function->getDeclName() 13656 .getCXXOverloadedOperator()) 13657 << Args[0]->getSourceRange() 13658 << Args[1]->getSourceRange()), 13659 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc), 13660 OpLoc); 13661 return ExprError(); 13662 } 13663 13664 // We matched a built-in operator; build it. 13665 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 13666 } 13667 13668 ExprResult Sema::BuildSynthesizedThreeWayComparison( 13669 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, 13670 FunctionDecl *DefaultedFn) { 13671 const ComparisonCategoryInfo *Info = 13672 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType()); 13673 // If we're not producing a known comparison category type, we can't 13674 // synthesize a three-way comparison. Let the caller diagnose this. 13675 if (!Info) 13676 return ExprResult((Expr*)nullptr); 13677 13678 // If we ever want to perform this synthesis more generally, we will need to 13679 // apply the temporary materialization conversion to the operands. 13680 assert(LHS->isGLValue() && RHS->isGLValue() && 13681 "cannot use prvalue expressions more than once"); 13682 Expr *OrigLHS = LHS; 13683 Expr *OrigRHS = RHS; 13684 13685 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to 13686 // each of them multiple times below. 13687 LHS = new (Context) 13688 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(), 13689 LHS->getObjectKind(), LHS); 13690 RHS = new (Context) 13691 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(), 13692 RHS->getObjectKind(), RHS); 13693 13694 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true, 13695 DefaultedFn); 13696 if (Eq.isInvalid()) 13697 return ExprError(); 13698 13699 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true, 13700 true, DefaultedFn); 13701 if (Less.isInvalid()) 13702 return ExprError(); 13703 13704 ExprResult Greater; 13705 if (Info->isPartial()) { 13706 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true, 13707 DefaultedFn); 13708 if (Greater.isInvalid()) 13709 return ExprError(); 13710 } 13711 13712 // Form the list of comparisons we're going to perform. 13713 struct Comparison { 13714 ExprResult Cmp; 13715 ComparisonCategoryResult Result; 13716 } Comparisons[4] = 13717 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal 13718 : ComparisonCategoryResult::Equivalent}, 13719 {Less, ComparisonCategoryResult::Less}, 13720 {Greater, ComparisonCategoryResult::Greater}, 13721 {ExprResult(), ComparisonCategoryResult::Unordered}, 13722 }; 13723 13724 int I = Info->isPartial() ? 3 : 2; 13725 13726 // Combine the comparisons with suitable conditional expressions. 13727 ExprResult Result; 13728 for (; I >= 0; --I) { 13729 // Build a reference to the comparison category constant. 13730 auto *VI = Info->lookupValueInfo(Comparisons[I].Result); 13731 // FIXME: Missing a constant for a comparison category. Diagnose this? 13732 if (!VI) 13733 return ExprResult((Expr*)nullptr); 13734 ExprResult ThisResult = 13735 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD); 13736 if (ThisResult.isInvalid()) 13737 return ExprError(); 13738 13739 // Build a conditional unless this is the final case. 13740 if (Result.get()) { 13741 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(), 13742 ThisResult.get(), Result.get()); 13743 if (Result.isInvalid()) 13744 return ExprError(); 13745 } else { 13746 Result = ThisResult; 13747 } 13748 } 13749 13750 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to 13751 // bind the OpaqueValueExprs before they're (repeatedly) used. 13752 Expr *SyntacticForm = BinaryOperator::Create( 13753 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(), 13754 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc, 13755 CurFPFeatures); 13756 Expr *SemanticForm[] = {LHS, RHS, Result.get()}; 13757 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2); 13758 } 13759 13760 ExprResult 13761 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 13762 SourceLocation RLoc, 13763 Expr *Base, Expr *Idx) { 13764 Expr *Args[2] = { Base, Idx }; 13765 DeclarationName OpName = 13766 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 13767 13768 // If either side is type-dependent, create an appropriate dependent 13769 // expression. 13770 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 13771 13772 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 13773 // CHECKME: no 'operator' keyword? 13774 DeclarationNameInfo OpNameInfo(OpName, LLoc); 13775 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13776 UnresolvedLookupExpr *Fn 13777 = UnresolvedLookupExpr::Create(Context, NamingClass, 13778 NestedNameSpecifierLoc(), OpNameInfo, 13779 /*ADL*/ true, /*Overloaded*/ false, 13780 UnresolvedSetIterator(), 13781 UnresolvedSetIterator()); 13782 // Can't add any actual overloads yet 13783 13784 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 13785 Context.DependentTy, VK_RValue, RLoc, 13786 CurFPFeatures); 13787 } 13788 13789 // Handle placeholders on both operands. 13790 if (checkPlaceholderForOverload(*this, Args[0])) 13791 return ExprError(); 13792 if (checkPlaceholderForOverload(*this, Args[1])) 13793 return ExprError(); 13794 13795 // Build an empty overload set. 13796 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 13797 13798 // Subscript can only be overloaded as a member function. 13799 13800 // Add operator candidates that are member functions. 13801 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13802 13803 // Add builtin operator candidates. 13804 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 13805 13806 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13807 13808 // Perform overload resolution. 13809 OverloadCandidateSet::iterator Best; 13810 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 13811 case OR_Success: { 13812 // We found a built-in operator or an overloaded operator. 13813 FunctionDecl *FnDecl = Best->Function; 13814 13815 if (FnDecl) { 13816 // We matched an overloaded operator. Build a call to that 13817 // operator. 13818 13819 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 13820 13821 // Convert the arguments. 13822 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 13823 ExprResult Arg0 = 13824 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 13825 Best->FoundDecl, Method); 13826 if (Arg0.isInvalid()) 13827 return ExprError(); 13828 Args[0] = Arg0.get(); 13829 13830 // Convert the arguments. 13831 ExprResult InputInit 13832 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13833 Context, 13834 FnDecl->getParamDecl(0)), 13835 SourceLocation(), 13836 Args[1]); 13837 if (InputInit.isInvalid()) 13838 return ExprError(); 13839 13840 Args[1] = InputInit.getAs<Expr>(); 13841 13842 // Build the actual expression node. 13843 DeclarationNameInfo OpLocInfo(OpName, LLoc); 13844 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 13845 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 13846 Best->FoundDecl, 13847 Base, 13848 HadMultipleCandidates, 13849 OpLocInfo.getLoc(), 13850 OpLocInfo.getInfo()); 13851 if (FnExpr.isInvalid()) 13852 return ExprError(); 13853 13854 // Determine the result type 13855 QualType ResultTy = FnDecl->getReturnType(); 13856 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13857 ResultTy = ResultTy.getNonLValueExprType(Context); 13858 13859 CXXOperatorCallExpr *TheCall = 13860 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 13861 Args, ResultTy, VK, RLoc, CurFPFeatures); 13862 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 13863 return ExprError(); 13864 13865 if (CheckFunctionCall(Method, TheCall, 13866 Method->getType()->castAs<FunctionProtoType>())) 13867 return ExprError(); 13868 13869 return MaybeBindToTemporary(TheCall); 13870 } else { 13871 // We matched a built-in operator. Convert the arguments, then 13872 // break out so that we will build the appropriate built-in 13873 // operator node. 13874 ExprResult ArgsRes0 = PerformImplicitConversion( 13875 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 13876 AA_Passing, CCK_ForBuiltinOverloadedOp); 13877 if (ArgsRes0.isInvalid()) 13878 return ExprError(); 13879 Args[0] = ArgsRes0.get(); 13880 13881 ExprResult ArgsRes1 = PerformImplicitConversion( 13882 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 13883 AA_Passing, CCK_ForBuiltinOverloadedOp); 13884 if (ArgsRes1.isInvalid()) 13885 return ExprError(); 13886 Args[1] = ArgsRes1.get(); 13887 13888 break; 13889 } 13890 } 13891 13892 case OR_No_Viable_Function: { 13893 PartialDiagnostic PD = CandidateSet.empty() 13894 ? (PDiag(diag::err_ovl_no_oper) 13895 << Args[0]->getType() << /*subscript*/ 0 13896 << Args[0]->getSourceRange() << Args[1]->getSourceRange()) 13897 : (PDiag(diag::err_ovl_no_viable_subscript) 13898 << Args[0]->getType() << Args[0]->getSourceRange() 13899 << Args[1]->getSourceRange()); 13900 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this, 13901 OCD_AllCandidates, Args, "[]", LLoc); 13902 return ExprError(); 13903 } 13904 13905 case OR_Ambiguous: 13906 CandidateSet.NoteCandidates( 13907 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary) 13908 << "[]" << Args[0]->getType() 13909 << Args[1]->getType() 13910 << Args[0]->getSourceRange() 13911 << Args[1]->getSourceRange()), 13912 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc); 13913 return ExprError(); 13914 13915 case OR_Deleted: 13916 CandidateSet.NoteCandidates( 13917 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper) 13918 << "[]" << Args[0]->getSourceRange() 13919 << Args[1]->getSourceRange()), 13920 *this, OCD_AllCandidates, Args, "[]", LLoc); 13921 return ExprError(); 13922 } 13923 13924 // We matched a built-in operator; build it. 13925 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 13926 } 13927 13928 /// BuildCallToMemberFunction - Build a call to a member 13929 /// function. MemExpr is the expression that refers to the member 13930 /// function (and includes the object parameter), Args/NumArgs are the 13931 /// arguments to the function call (not including the object 13932 /// parameter). The caller needs to validate that the member 13933 /// expression refers to a non-static member function or an overloaded 13934 /// member function. 13935 ExprResult 13936 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 13937 SourceLocation LParenLoc, 13938 MultiExprArg Args, 13939 SourceLocation RParenLoc) { 13940 assert(MemExprE->getType() == Context.BoundMemberTy || 13941 MemExprE->getType() == Context.OverloadTy); 13942 13943 // Dig out the member expression. This holds both the object 13944 // argument and the member function we're referring to. 13945 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 13946 13947 // Determine whether this is a call to a pointer-to-member function. 13948 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 13949 assert(op->getType() == Context.BoundMemberTy); 13950 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 13951 13952 QualType fnType = 13953 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 13954 13955 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 13956 QualType resultType = proto->getCallResultType(Context); 13957 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 13958 13959 // Check that the object type isn't more qualified than the 13960 // member function we're calling. 13961 Qualifiers funcQuals = proto->getMethodQuals(); 13962 13963 QualType objectType = op->getLHS()->getType(); 13964 if (op->getOpcode() == BO_PtrMemI) 13965 objectType = objectType->castAs<PointerType>()->getPointeeType(); 13966 Qualifiers objectQuals = objectType.getQualifiers(); 13967 13968 Qualifiers difference = objectQuals - funcQuals; 13969 difference.removeObjCGCAttr(); 13970 difference.removeAddressSpace(); 13971 if (difference) { 13972 std::string qualsString = difference.getAsString(); 13973 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 13974 << fnType.getUnqualifiedType() 13975 << qualsString 13976 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 13977 } 13978 13979 CXXMemberCallExpr *call = 13980 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 13981 valueKind, RParenLoc, proto->getNumParams()); 13982 13983 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 13984 call, nullptr)) 13985 return ExprError(); 13986 13987 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 13988 return ExprError(); 13989 13990 if (CheckOtherCall(call, proto)) 13991 return ExprError(); 13992 13993 return MaybeBindToTemporary(call); 13994 } 13995 13996 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 13997 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 13998 RParenLoc); 13999 14000 UnbridgedCastsSet UnbridgedCasts; 14001 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14002 return ExprError(); 14003 14004 MemberExpr *MemExpr; 14005 CXXMethodDecl *Method = nullptr; 14006 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 14007 NestedNameSpecifier *Qualifier = nullptr; 14008 if (isa<MemberExpr>(NakedMemExpr)) { 14009 MemExpr = cast<MemberExpr>(NakedMemExpr); 14010 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 14011 FoundDecl = MemExpr->getFoundDecl(); 14012 Qualifier = MemExpr->getQualifier(); 14013 UnbridgedCasts.restore(); 14014 } else { 14015 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 14016 Qualifier = UnresExpr->getQualifier(); 14017 14018 QualType ObjectType = UnresExpr->getBaseType(); 14019 Expr::Classification ObjectClassification 14020 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 14021 : UnresExpr->getBase()->Classify(Context); 14022 14023 // Add overload candidates 14024 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 14025 OverloadCandidateSet::CSK_Normal); 14026 14027 // FIXME: avoid copy. 14028 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14029 if (UnresExpr->hasExplicitTemplateArgs()) { 14030 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14031 TemplateArgs = &TemplateArgsBuffer; 14032 } 14033 14034 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 14035 E = UnresExpr->decls_end(); I != E; ++I) { 14036 14037 NamedDecl *Func = *I; 14038 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 14039 if (isa<UsingShadowDecl>(Func)) 14040 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 14041 14042 14043 // Microsoft supports direct constructor calls. 14044 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 14045 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, 14046 CandidateSet, 14047 /*SuppressUserConversions*/ false); 14048 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 14049 // If explicit template arguments were provided, we can't call a 14050 // non-template member function. 14051 if (TemplateArgs) 14052 continue; 14053 14054 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 14055 ObjectClassification, Args, CandidateSet, 14056 /*SuppressUserConversions=*/false); 14057 } else { 14058 AddMethodTemplateCandidate( 14059 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 14060 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 14061 /*SuppressUserConversions=*/false); 14062 } 14063 } 14064 14065 DeclarationName DeclName = UnresExpr->getMemberName(); 14066 14067 UnbridgedCasts.restore(); 14068 14069 OverloadCandidateSet::iterator Best; 14070 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 14071 Best)) { 14072 case OR_Success: 14073 Method = cast<CXXMethodDecl>(Best->Function); 14074 FoundDecl = Best->FoundDecl; 14075 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 14076 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 14077 return ExprError(); 14078 // If FoundDecl is different from Method (such as if one is a template 14079 // and the other a specialization), make sure DiagnoseUseOfDecl is 14080 // called on both. 14081 // FIXME: This would be more comprehensively addressed by modifying 14082 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 14083 // being used. 14084 if (Method != FoundDecl.getDecl() && 14085 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 14086 return ExprError(); 14087 break; 14088 14089 case OR_No_Viable_Function: 14090 CandidateSet.NoteCandidates( 14091 PartialDiagnosticAt( 14092 UnresExpr->getMemberLoc(), 14093 PDiag(diag::err_ovl_no_viable_member_function_in_call) 14094 << DeclName << MemExprE->getSourceRange()), 14095 *this, OCD_AllCandidates, Args); 14096 // FIXME: Leaking incoming expressions! 14097 return ExprError(); 14098 14099 case OR_Ambiguous: 14100 CandidateSet.NoteCandidates( 14101 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14102 PDiag(diag::err_ovl_ambiguous_member_call) 14103 << DeclName << MemExprE->getSourceRange()), 14104 *this, OCD_AmbiguousCandidates, Args); 14105 // FIXME: Leaking incoming expressions! 14106 return ExprError(); 14107 14108 case OR_Deleted: 14109 CandidateSet.NoteCandidates( 14110 PartialDiagnosticAt(UnresExpr->getMemberLoc(), 14111 PDiag(diag::err_ovl_deleted_member_call) 14112 << DeclName << MemExprE->getSourceRange()), 14113 *this, OCD_AllCandidates, Args); 14114 // FIXME: Leaking incoming expressions! 14115 return ExprError(); 14116 } 14117 14118 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 14119 14120 // If overload resolution picked a static member, build a 14121 // non-member call based on that function. 14122 if (Method->isStatic()) { 14123 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 14124 RParenLoc); 14125 } 14126 14127 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 14128 } 14129 14130 QualType ResultType = Method->getReturnType(); 14131 ExprValueKind VK = Expr::getValueKindForType(ResultType); 14132 ResultType = ResultType.getNonLValueExprType(Context); 14133 14134 assert(Method && "Member call to something that isn't a method?"); 14135 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14136 CXXMemberCallExpr *TheCall = 14137 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 14138 RParenLoc, Proto->getNumParams()); 14139 14140 // Check for a valid return type. 14141 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 14142 TheCall, Method)) 14143 return ExprError(); 14144 14145 // Convert the object argument (for a non-static member function call). 14146 // We only need to do this if there was actually an overload; otherwise 14147 // it was done at lookup. 14148 if (!Method->isStatic()) { 14149 ExprResult ObjectArg = 14150 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 14151 FoundDecl, Method); 14152 if (ObjectArg.isInvalid()) 14153 return ExprError(); 14154 MemExpr->setBase(ObjectArg.get()); 14155 } 14156 14157 // Convert the rest of the arguments 14158 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 14159 RParenLoc)) 14160 return ExprError(); 14161 14162 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14163 14164 if (CheckFunctionCall(Method, TheCall, Proto)) 14165 return ExprError(); 14166 14167 // In the case the method to call was not selected by the overloading 14168 // resolution process, we still need to handle the enable_if attribute. Do 14169 // that here, so it will not hide previous -- and more relevant -- errors. 14170 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 14171 if (const EnableIfAttr *Attr = 14172 CheckEnableIf(Method, LParenLoc, Args, true)) { 14173 Diag(MemE->getMemberLoc(), 14174 diag::err_ovl_no_viable_member_function_in_call) 14175 << Method << Method->getSourceRange(); 14176 Diag(Method->getLocation(), 14177 diag::note_ovl_candidate_disabled_by_function_cond_attr) 14178 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 14179 return ExprError(); 14180 } 14181 } 14182 14183 if ((isa<CXXConstructorDecl>(CurContext) || 14184 isa<CXXDestructorDecl>(CurContext)) && 14185 TheCall->getMethodDecl()->isPure()) { 14186 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 14187 14188 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 14189 MemExpr->performsVirtualDispatch(getLangOpts())) { 14190 Diag(MemExpr->getBeginLoc(), 14191 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 14192 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 14193 << MD->getParent()->getDeclName(); 14194 14195 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 14196 if (getLangOpts().AppleKext) 14197 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 14198 << MD->getParent()->getDeclName() << MD->getDeclName(); 14199 } 14200 } 14201 14202 if (CXXDestructorDecl *DD = 14203 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 14204 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 14205 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 14206 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 14207 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 14208 MemExpr->getMemberLoc()); 14209 } 14210 14211 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), 14212 TheCall->getMethodDecl()); 14213 } 14214 14215 /// BuildCallToObjectOfClassType - Build a call to an object of class 14216 /// type (C++ [over.call.object]), which can end up invoking an 14217 /// overloaded function call operator (@c operator()) or performing a 14218 /// user-defined conversion on the object argument. 14219 ExprResult 14220 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 14221 SourceLocation LParenLoc, 14222 MultiExprArg Args, 14223 SourceLocation RParenLoc) { 14224 if (checkPlaceholderForOverload(*this, Obj)) 14225 return ExprError(); 14226 ExprResult Object = Obj; 14227 14228 UnbridgedCastsSet UnbridgedCasts; 14229 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 14230 return ExprError(); 14231 14232 assert(Object.get()->getType()->isRecordType() && 14233 "Requires object type argument"); 14234 14235 // C++ [over.call.object]p1: 14236 // If the primary-expression E in the function call syntax 14237 // evaluates to a class object of type "cv T", then the set of 14238 // candidate functions includes at least the function call 14239 // operators of T. The function call operators of T are obtained by 14240 // ordinary lookup of the name operator() in the context of 14241 // (E).operator(). 14242 OverloadCandidateSet CandidateSet(LParenLoc, 14243 OverloadCandidateSet::CSK_Operator); 14244 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 14245 14246 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 14247 diag::err_incomplete_object_call, Object.get())) 14248 return true; 14249 14250 const auto *Record = Object.get()->getType()->castAs<RecordType>(); 14251 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 14252 LookupQualifiedName(R, Record->getDecl()); 14253 R.suppressDiagnostics(); 14254 14255 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14256 Oper != OperEnd; ++Oper) { 14257 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 14258 Object.get()->Classify(Context), Args, CandidateSet, 14259 /*SuppressUserConversion=*/false); 14260 } 14261 14262 // C++ [over.call.object]p2: 14263 // In addition, for each (non-explicit in C++0x) conversion function 14264 // declared in T of the form 14265 // 14266 // operator conversion-type-id () cv-qualifier; 14267 // 14268 // where cv-qualifier is the same cv-qualification as, or a 14269 // greater cv-qualification than, cv, and where conversion-type-id 14270 // denotes the type "pointer to function of (P1,...,Pn) returning 14271 // R", or the type "reference to pointer to function of 14272 // (P1,...,Pn) returning R", or the type "reference to function 14273 // of (P1,...,Pn) returning R", a surrogate call function [...] 14274 // is also considered as a candidate function. Similarly, 14275 // surrogate call functions are added to the set of candidate 14276 // functions for each conversion function declared in an 14277 // accessible base class provided the function is not hidden 14278 // within T by another intervening declaration. 14279 const auto &Conversions = 14280 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 14281 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 14282 NamedDecl *D = *I; 14283 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 14284 if (isa<UsingShadowDecl>(D)) 14285 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 14286 14287 // Skip over templated conversion functions; they aren't 14288 // surrogates. 14289 if (isa<FunctionTemplateDecl>(D)) 14290 continue; 14291 14292 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 14293 if (!Conv->isExplicit()) { 14294 // Strip the reference type (if any) and then the pointer type (if 14295 // any) to get down to what might be a function type. 14296 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 14297 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 14298 ConvType = ConvPtrType->getPointeeType(); 14299 14300 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 14301 { 14302 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 14303 Object.get(), Args, CandidateSet); 14304 } 14305 } 14306 } 14307 14308 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14309 14310 // Perform overload resolution. 14311 OverloadCandidateSet::iterator Best; 14312 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 14313 Best)) { 14314 case OR_Success: 14315 // Overload resolution succeeded; we'll build the appropriate call 14316 // below. 14317 break; 14318 14319 case OR_No_Viable_Function: { 14320 PartialDiagnostic PD = 14321 CandidateSet.empty() 14322 ? (PDiag(diag::err_ovl_no_oper) 14323 << Object.get()->getType() << /*call*/ 1 14324 << Object.get()->getSourceRange()) 14325 : (PDiag(diag::err_ovl_no_viable_object_call) 14326 << Object.get()->getType() << Object.get()->getSourceRange()); 14327 CandidateSet.NoteCandidates( 14328 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this, 14329 OCD_AllCandidates, Args); 14330 break; 14331 } 14332 case OR_Ambiguous: 14333 CandidateSet.NoteCandidates( 14334 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14335 PDiag(diag::err_ovl_ambiguous_object_call) 14336 << Object.get()->getType() 14337 << Object.get()->getSourceRange()), 14338 *this, OCD_AmbiguousCandidates, Args); 14339 break; 14340 14341 case OR_Deleted: 14342 CandidateSet.NoteCandidates( 14343 PartialDiagnosticAt(Object.get()->getBeginLoc(), 14344 PDiag(diag::err_ovl_deleted_object_call) 14345 << Object.get()->getType() 14346 << Object.get()->getSourceRange()), 14347 *this, OCD_AllCandidates, Args); 14348 break; 14349 } 14350 14351 if (Best == CandidateSet.end()) 14352 return true; 14353 14354 UnbridgedCasts.restore(); 14355 14356 if (Best->Function == nullptr) { 14357 // Since there is no function declaration, this is one of the 14358 // surrogate candidates. Dig out the conversion function. 14359 CXXConversionDecl *Conv 14360 = cast<CXXConversionDecl>( 14361 Best->Conversions[0].UserDefined.ConversionFunction); 14362 14363 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 14364 Best->FoundDecl); 14365 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 14366 return ExprError(); 14367 assert(Conv == Best->FoundDecl.getDecl() && 14368 "Found Decl & conversion-to-functionptr should be same, right?!"); 14369 // We selected one of the surrogate functions that converts the 14370 // object parameter to a function pointer. Perform the conversion 14371 // on the object argument, then let BuildCallExpr finish the job. 14372 14373 // Create an implicit member expr to refer to the conversion operator. 14374 // and then call it. 14375 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 14376 Conv, HadMultipleCandidates); 14377 if (Call.isInvalid()) 14378 return ExprError(); 14379 // Record usage of conversion in an implicit cast. 14380 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 14381 CK_UserDefinedConversion, Call.get(), 14382 nullptr, VK_RValue); 14383 14384 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 14385 } 14386 14387 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 14388 14389 // We found an overloaded operator(). Build a CXXOperatorCallExpr 14390 // that calls this method, using Object for the implicit object 14391 // parameter and passing along the remaining arguments. 14392 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14393 14394 // An error diagnostic has already been printed when parsing the declaration. 14395 if (Method->isInvalidDecl()) 14396 return ExprError(); 14397 14398 const auto *Proto = Method->getType()->castAs<FunctionProtoType>(); 14399 unsigned NumParams = Proto->getNumParams(); 14400 14401 DeclarationNameInfo OpLocInfo( 14402 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 14403 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 14404 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14405 Obj, HadMultipleCandidates, 14406 OpLocInfo.getLoc(), 14407 OpLocInfo.getInfo()); 14408 if (NewFn.isInvalid()) 14409 return true; 14410 14411 // The number of argument slots to allocate in the call. If we have default 14412 // arguments we need to allocate space for them as well. We additionally 14413 // need one more slot for the object parameter. 14414 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 14415 14416 // Build the full argument list for the method call (the implicit object 14417 // parameter is placed at the beginning of the list). 14418 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 14419 14420 bool IsError = false; 14421 14422 // Initialize the implicit object parameter. 14423 ExprResult ObjRes = 14424 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 14425 Best->FoundDecl, Method); 14426 if (ObjRes.isInvalid()) 14427 IsError = true; 14428 else 14429 Object = ObjRes; 14430 MethodArgs[0] = Object.get(); 14431 14432 // Check the argument types. 14433 for (unsigned i = 0; i != NumParams; i++) { 14434 Expr *Arg; 14435 if (i < Args.size()) { 14436 Arg = Args[i]; 14437 14438 // Pass the argument. 14439 14440 ExprResult InputInit 14441 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 14442 Context, 14443 Method->getParamDecl(i)), 14444 SourceLocation(), Arg); 14445 14446 IsError |= InputInit.isInvalid(); 14447 Arg = InputInit.getAs<Expr>(); 14448 } else { 14449 ExprResult DefArg 14450 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 14451 if (DefArg.isInvalid()) { 14452 IsError = true; 14453 break; 14454 } 14455 14456 Arg = DefArg.getAs<Expr>(); 14457 } 14458 14459 MethodArgs[i + 1] = Arg; 14460 } 14461 14462 // If this is a variadic call, handle args passed through "...". 14463 if (Proto->isVariadic()) { 14464 // Promote the arguments (C99 6.5.2.2p7). 14465 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 14466 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 14467 nullptr); 14468 IsError |= Arg.isInvalid(); 14469 MethodArgs[i + 1] = Arg.get(); 14470 } 14471 } 14472 14473 if (IsError) 14474 return true; 14475 14476 DiagnoseSentinelCalls(Method, LParenLoc, Args); 14477 14478 // Once we've built TheCall, all of the expressions are properly owned. 14479 QualType ResultTy = Method->getReturnType(); 14480 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14481 ResultTy = ResultTy.getNonLValueExprType(Context); 14482 14483 CXXOperatorCallExpr *TheCall = 14484 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 14485 ResultTy, VK, RParenLoc, CurFPFeatures); 14486 14487 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 14488 return true; 14489 14490 if (CheckFunctionCall(Method, TheCall, Proto)) 14491 return true; 14492 14493 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method); 14494 } 14495 14496 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 14497 /// (if one exists), where @c Base is an expression of class type and 14498 /// @c Member is the name of the member we're trying to find. 14499 ExprResult 14500 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 14501 bool *NoArrowOperatorFound) { 14502 assert(Base->getType()->isRecordType() && 14503 "left-hand side must have class type"); 14504 14505 if (checkPlaceholderForOverload(*this, Base)) 14506 return ExprError(); 14507 14508 SourceLocation Loc = Base->getExprLoc(); 14509 14510 // C++ [over.ref]p1: 14511 // 14512 // [...] An expression x->m is interpreted as (x.operator->())->m 14513 // for a class object x of type T if T::operator->() exists and if 14514 // the operator is selected as the best match function by the 14515 // overload resolution mechanism (13.3). 14516 DeclarationName OpName = 14517 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 14518 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 14519 14520 if (RequireCompleteType(Loc, Base->getType(), 14521 diag::err_typecheck_incomplete_tag, Base)) 14522 return ExprError(); 14523 14524 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 14525 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl()); 14526 R.suppressDiagnostics(); 14527 14528 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 14529 Oper != OperEnd; ++Oper) { 14530 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 14531 None, CandidateSet, /*SuppressUserConversion=*/false); 14532 } 14533 14534 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14535 14536 // Perform overload resolution. 14537 OverloadCandidateSet::iterator Best; 14538 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 14539 case OR_Success: 14540 // Overload resolution succeeded; we'll build the call below. 14541 break; 14542 14543 case OR_No_Viable_Function: { 14544 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base); 14545 if (CandidateSet.empty()) { 14546 QualType BaseType = Base->getType(); 14547 if (NoArrowOperatorFound) { 14548 // Report this specific error to the caller instead of emitting a 14549 // diagnostic, as requested. 14550 *NoArrowOperatorFound = true; 14551 return ExprError(); 14552 } 14553 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 14554 << BaseType << Base->getSourceRange(); 14555 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 14556 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 14557 << FixItHint::CreateReplacement(OpLoc, "."); 14558 } 14559 } else 14560 Diag(OpLoc, diag::err_ovl_no_viable_oper) 14561 << "operator->" << Base->getSourceRange(); 14562 CandidateSet.NoteCandidates(*this, Base, Cands); 14563 return ExprError(); 14564 } 14565 case OR_Ambiguous: 14566 CandidateSet.NoteCandidates( 14567 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary) 14568 << "->" << Base->getType() 14569 << Base->getSourceRange()), 14570 *this, OCD_AmbiguousCandidates, Base); 14571 return ExprError(); 14572 14573 case OR_Deleted: 14574 CandidateSet.NoteCandidates( 14575 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper) 14576 << "->" << Base->getSourceRange()), 14577 *this, OCD_AllCandidates, Base); 14578 return ExprError(); 14579 } 14580 14581 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 14582 14583 // Convert the object parameter. 14584 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 14585 ExprResult BaseResult = 14586 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 14587 Best->FoundDecl, Method); 14588 if (BaseResult.isInvalid()) 14589 return ExprError(); 14590 Base = BaseResult.get(); 14591 14592 // Build the operator call. 14593 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 14594 Base, HadMultipleCandidates, OpLoc); 14595 if (FnExpr.isInvalid()) 14596 return ExprError(); 14597 14598 QualType ResultTy = Method->getReturnType(); 14599 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14600 ResultTy = ResultTy.getNonLValueExprType(Context); 14601 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 14602 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, CurFPFeatures); 14603 14604 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 14605 return ExprError(); 14606 14607 if (CheckFunctionCall(Method, TheCall, 14608 Method->getType()->castAs<FunctionProtoType>())) 14609 return ExprError(); 14610 14611 return MaybeBindToTemporary(TheCall); 14612 } 14613 14614 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 14615 /// a literal operator described by the provided lookup results. 14616 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 14617 DeclarationNameInfo &SuffixInfo, 14618 ArrayRef<Expr*> Args, 14619 SourceLocation LitEndLoc, 14620 TemplateArgumentListInfo *TemplateArgs) { 14621 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 14622 14623 OverloadCandidateSet CandidateSet(UDSuffixLoc, 14624 OverloadCandidateSet::CSK_Normal); 14625 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet, 14626 TemplateArgs); 14627 14628 bool HadMultipleCandidates = (CandidateSet.size() > 1); 14629 14630 // Perform overload resolution. This will usually be trivial, but might need 14631 // to perform substitutions for a literal operator template. 14632 OverloadCandidateSet::iterator Best; 14633 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 14634 case OR_Success: 14635 case OR_Deleted: 14636 break; 14637 14638 case OR_No_Viable_Function: 14639 CandidateSet.NoteCandidates( 14640 PartialDiagnosticAt(UDSuffixLoc, 14641 PDiag(diag::err_ovl_no_viable_function_in_call) 14642 << R.getLookupName()), 14643 *this, OCD_AllCandidates, Args); 14644 return ExprError(); 14645 14646 case OR_Ambiguous: 14647 CandidateSet.NoteCandidates( 14648 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call) 14649 << R.getLookupName()), 14650 *this, OCD_AmbiguousCandidates, Args); 14651 return ExprError(); 14652 } 14653 14654 FunctionDecl *FD = Best->Function; 14655 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 14656 nullptr, HadMultipleCandidates, 14657 SuffixInfo.getLoc(), 14658 SuffixInfo.getInfo()); 14659 if (Fn.isInvalid()) 14660 return true; 14661 14662 // Check the argument types. This should almost always be a no-op, except 14663 // that array-to-pointer decay is applied to string literals. 14664 Expr *ConvArgs[2]; 14665 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 14666 ExprResult InputInit = PerformCopyInitialization( 14667 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 14668 SourceLocation(), Args[ArgIdx]); 14669 if (InputInit.isInvalid()) 14670 return true; 14671 ConvArgs[ArgIdx] = InputInit.get(); 14672 } 14673 14674 QualType ResultTy = FD->getReturnType(); 14675 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 14676 ResultTy = ResultTy.getNonLValueExprType(Context); 14677 14678 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 14679 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 14680 VK, LitEndLoc, UDSuffixLoc); 14681 14682 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 14683 return ExprError(); 14684 14685 if (CheckFunctionCall(FD, UDL, nullptr)) 14686 return ExprError(); 14687 14688 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD); 14689 } 14690 14691 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 14692 /// given LookupResult is non-empty, it is assumed to describe a member which 14693 /// will be invoked. Otherwise, the function will be found via argument 14694 /// dependent lookup. 14695 /// CallExpr is set to a valid expression and FRS_Success returned on success, 14696 /// otherwise CallExpr is set to ExprError() and some non-success value 14697 /// is returned. 14698 Sema::ForRangeStatus 14699 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 14700 SourceLocation RangeLoc, 14701 const DeclarationNameInfo &NameInfo, 14702 LookupResult &MemberLookup, 14703 OverloadCandidateSet *CandidateSet, 14704 Expr *Range, ExprResult *CallExpr) { 14705 Scope *S = nullptr; 14706 14707 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 14708 if (!MemberLookup.empty()) { 14709 ExprResult MemberRef = 14710 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 14711 /*IsPtr=*/false, CXXScopeSpec(), 14712 /*TemplateKWLoc=*/SourceLocation(), 14713 /*FirstQualifierInScope=*/nullptr, 14714 MemberLookup, 14715 /*TemplateArgs=*/nullptr, S); 14716 if (MemberRef.isInvalid()) { 14717 *CallExpr = ExprError(); 14718 return FRS_DiagnosticIssued; 14719 } 14720 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 14721 if (CallExpr->isInvalid()) { 14722 *CallExpr = ExprError(); 14723 return FRS_DiagnosticIssued; 14724 } 14725 } else { 14726 UnresolvedSet<0> FoundNames; 14727 UnresolvedLookupExpr *Fn = 14728 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 14729 NestedNameSpecifierLoc(), NameInfo, 14730 /*NeedsADL=*/true, /*Overloaded=*/false, 14731 FoundNames.begin(), FoundNames.end()); 14732 14733 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 14734 CandidateSet, CallExpr); 14735 if (CandidateSet->empty() || CandidateSetError) { 14736 *CallExpr = ExprError(); 14737 return FRS_NoViableFunction; 14738 } 14739 OverloadCandidateSet::iterator Best; 14740 OverloadingResult OverloadResult = 14741 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 14742 14743 if (OverloadResult == OR_No_Viable_Function) { 14744 *CallExpr = ExprError(); 14745 return FRS_NoViableFunction; 14746 } 14747 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 14748 Loc, nullptr, CandidateSet, &Best, 14749 OverloadResult, 14750 /*AllowTypoCorrection=*/false); 14751 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 14752 *CallExpr = ExprError(); 14753 return FRS_DiagnosticIssued; 14754 } 14755 } 14756 return FRS_Success; 14757 } 14758 14759 14760 /// FixOverloadedFunctionReference - E is an expression that refers to 14761 /// a C++ overloaded function (possibly with some parentheses and 14762 /// perhaps a '&' around it). We have resolved the overloaded function 14763 /// to the function declaration Fn, so patch up the expression E to 14764 /// refer (possibly indirectly) to Fn. Returns the new expr. 14765 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 14766 FunctionDecl *Fn) { 14767 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 14768 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 14769 Found, Fn); 14770 if (SubExpr == PE->getSubExpr()) 14771 return PE; 14772 14773 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 14774 } 14775 14776 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 14777 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 14778 Found, Fn); 14779 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 14780 SubExpr->getType()) && 14781 "Implicit cast type cannot be determined from overload"); 14782 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 14783 if (SubExpr == ICE->getSubExpr()) 14784 return ICE; 14785 14786 return ImplicitCastExpr::Create(Context, ICE->getType(), 14787 ICE->getCastKind(), 14788 SubExpr, nullptr, 14789 ICE->getValueKind()); 14790 } 14791 14792 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 14793 if (!GSE->isResultDependent()) { 14794 Expr *SubExpr = 14795 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 14796 if (SubExpr == GSE->getResultExpr()) 14797 return GSE; 14798 14799 // Replace the resulting type information before rebuilding the generic 14800 // selection expression. 14801 ArrayRef<Expr *> A = GSE->getAssocExprs(); 14802 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 14803 unsigned ResultIdx = GSE->getResultIndex(); 14804 AssocExprs[ResultIdx] = SubExpr; 14805 14806 return GenericSelectionExpr::Create( 14807 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 14808 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 14809 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 14810 ResultIdx); 14811 } 14812 // Rather than fall through to the unreachable, return the original generic 14813 // selection expression. 14814 return GSE; 14815 } 14816 14817 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 14818 assert(UnOp->getOpcode() == UO_AddrOf && 14819 "Can only take the address of an overloaded function"); 14820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 14821 if (Method->isStatic()) { 14822 // Do nothing: static member functions aren't any different 14823 // from non-member functions. 14824 } else { 14825 // Fix the subexpression, which really has to be an 14826 // UnresolvedLookupExpr holding an overloaded member function 14827 // or template. 14828 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14829 Found, Fn); 14830 if (SubExpr == UnOp->getSubExpr()) 14831 return UnOp; 14832 14833 assert(isa<DeclRefExpr>(SubExpr) 14834 && "fixed to something other than a decl ref"); 14835 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 14836 && "fixed to a member ref with no nested name qualifier"); 14837 14838 // We have taken the address of a pointer to member 14839 // function. Perform the computation here so that we get the 14840 // appropriate pointer to member type. 14841 QualType ClassType 14842 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 14843 QualType MemPtrType 14844 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 14845 // Under the MS ABI, lock down the inheritance model now. 14846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14847 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 14848 14849 return UnaryOperator::Create( 14850 Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary, 14851 UnOp->getOperatorLoc(), false, CurFPFeatures); 14852 } 14853 } 14854 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 14855 Found, Fn); 14856 if (SubExpr == UnOp->getSubExpr()) 14857 return UnOp; 14858 14859 return UnaryOperator::Create( 14860 Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()), 14861 VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), false, CurFPFeatures); 14862 } 14863 14864 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14865 // FIXME: avoid copy. 14866 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14867 if (ULE->hasExplicitTemplateArgs()) { 14868 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 14869 TemplateArgs = &TemplateArgsBuffer; 14870 } 14871 14872 DeclRefExpr *DRE = 14873 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(), 14874 ULE->getQualifierLoc(), Found.getDecl(), 14875 ULE->getTemplateKeywordLoc(), TemplateArgs); 14876 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 14877 return DRE; 14878 } 14879 14880 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 14881 // FIXME: avoid copy. 14882 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 14883 if (MemExpr->hasExplicitTemplateArgs()) { 14884 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 14885 TemplateArgs = &TemplateArgsBuffer; 14886 } 14887 14888 Expr *Base; 14889 14890 // If we're filling in a static method where we used to have an 14891 // implicit member access, rewrite to a simple decl ref. 14892 if (MemExpr->isImplicitAccess()) { 14893 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14894 DeclRefExpr *DRE = BuildDeclRefExpr( 14895 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(), 14896 MemExpr->getQualifierLoc(), Found.getDecl(), 14897 MemExpr->getTemplateKeywordLoc(), TemplateArgs); 14898 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 14899 return DRE; 14900 } else { 14901 SourceLocation Loc = MemExpr->getMemberLoc(); 14902 if (MemExpr->getQualifier()) 14903 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 14904 Base = 14905 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true); 14906 } 14907 } else 14908 Base = MemExpr->getBase(); 14909 14910 ExprValueKind valueKind; 14911 QualType type; 14912 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 14913 valueKind = VK_LValue; 14914 type = Fn->getType(); 14915 } else { 14916 valueKind = VK_RValue; 14917 type = Context.BoundMemberTy; 14918 } 14919 14920 return BuildMemberExpr( 14921 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 14922 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 14923 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(), 14924 type, valueKind, OK_Ordinary, TemplateArgs); 14925 } 14926 14927 llvm_unreachable("Invalid reference to overloaded function"); 14928 } 14929 14930 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 14931 DeclAccessPair Found, 14932 FunctionDecl *Fn) { 14933 return FixOverloadedFunctionReference(E.get(), Found, Fn); 14934 } 14935